[Freeswitch-svn] [commit] r5009 - in freeswitch/branches/cparker: . build build/config conf docs libs libs/apr libs/apr-util libs/apr-util/build libs/apr-util/include libs/apr-util/include/private libs/apr-util/xml/expat libs/apr-util/xml/expat/conftools libs/apr-util/xml/expat/lib libs/apr/build libs/apr/include libs/apr/include/arch/unix libs/codec/g726 libs/codec/g726/build libs/codec/g726/build/config libs/codec/g7xx libs/codec/g7xx/build libs/codec/gsm libs/codec/ilbc libs/codec/ilbc/build libs/codec/ilbc/src libs/codec/lpc10 libs/codec/lpc10/build libs/codec/lpc10/build/config libs/codec/lpc10/src libs/curl libs/curl/docs libs/curl/include libs/curl/include/curl libs/curl/lib libs/curl/packages libs/curl/packages/AIX libs/curl/packages/AIX/RPM libs/curl/packages/DOS libs/curl/packages/EPM libs/curl/packages/Linux libs/curl/packages/Linux/RPM libs/curl/packages/Solaris libs/curl/packages/Win32 libs/curl/packages/Win32/cygwin libs/curl/packages/vms libs/curl/src libs/curl/tests libs/iax libs/iax/build libs/iax/src libs/iksemel libs/iksemel/build libs/iksemel/doc libs/iksemel/include libs/iksemel/src libs/iksemel/test libs/iksemel/tools libs/js libs/js/nsprpub libs/js/nsprpub/build/autoconf libs/js/nsprpub/config libs/js/nsprpub/lib/ds libs/js/nsprpub/lib/libc/src libs/js/nsprpub/pr/include libs/js/nsprpub/pr/src libs/js/nsprpub/pr/src/io libs/js/nsprpub/pr/src/malloc libs/js/nsprpub/pr/src/md/unix libs/js/nsprpub/pr/src/memory libs/js/nsprpub/pr/src/misc libs/js/nsprpub/pr/src/pthreads libs/js/nsprpub/pr/src/threads libs/js/src libs/libdingaling libs/libdingaling/build libs/libdingaling/src libs/libetpan libs/libresample libs/libresample/build libs/libresample/src libs/libsndfile libs/libsndfile/Octave libs/libsndfile/Win32 libs/libsndfile/doc libs/libsndfile/examples libs/libsndfile/man libs/libsndfile/regtest libs/libsndfile/src libs/libsndfile/src/G72x libs/libsndfile/src/GSM610 libs/libsndfile/tests libs/libspeakup libs/libspeakup/build libs/libteletone libs/libteletone/build libs/libteletone/src libs/pcre libs/portaudio libs/portaudio/bindings/cpp libs/portaudio/bindings/cpp/build/gnu libs/portaudio/build/msvc libs/portaudio/src/common libs/portaudio/test libs/sofia-sip libs/sofia-sip/docs libs/sofia-sip/libsofia-sip-ua libs/sofia-sip/libsofia-sip-ua-glib libs/sofia-sip/libsofia-sip-ua-glib/su-glib libs/sofia-sip/libsofia-sip-ua-glib/su-glib/sofia-sip libs/sofia-sip/libsofia-sip-ua/bnf libs/sofia-sip/libsofia-sip-ua/docs libs/sofia-sip/libsofia-sip-ua/features libs/sofia-sip/libsofia-sip-ua/http libs/sofia-sip/libsofia-sip-ua/http/sofia-sip libs/sofia-sip/libsofia-sip-ua/ipt libs/sofia-sip/libsofia-sip-ua/ipt/sofia-sip libs/sofia-sip/libsofia-sip-ua/iptsec libs/sofia-sip/libsofia-sip-ua/iptsec/sofia-sip libs/sofia-sip/libsofia-sip-ua/msg libs/sofia-sip/libsofia-sip-ua/msg/sofia-sip libs/sofia-sip/libsofia-sip-ua/nea libs/sofia-sip/libsofia-sip-ua/nta libs/sofia-sip/libsofia-sip-ua/nta/sofia-sip libs/sofia-sip/libsofia-sip-ua/nth libs/sofia-sip/libsofia-sip-ua/nth/sofia-sip libs/sofia-sip/libsofia-sip-ua/nua libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip libs/sofia-sip/libsofia-sip-ua/sdp libs/sofia-sip/libsofia-sip-ua/sip libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip libs/sofia-sip/libsofia-sip-ua/sip/tests libs/sofia-sip/libsofia-sip-ua/soa libs/sofia-sip/libsofia-sip-ua/soa/sofia-sip libs/sofia-sip/libsofia-sip-ua/sresolv libs/sofia-sip/libsofia-sip-ua/stun libs/sofia-sip/libsofia-sip-ua/su libs/sofia-sip/libsofia-sip-ua/su/sofia-sip libs/sofia-sip/libsofia-sip-ua/tport libs/sofia-sip/libsofia-sip-ua/tport/sofia-sip libs/sofia-sip/libsofia-sip-ua/url libs/sofia-sip/libsofia-sip-ua/url/sofia-sip libs/sofia-sip/m4 libs/sofia-sip/packages libs/sofia-sip/rules libs/sofia-sip/utils libs/sofia-sip/win32 libs/sofia-sip/win32/libsofia-sip-ua libs/sofia-sip/win32/libsofia-sip-ua-static libs/sofia-sip/win32/tests/test_htable libs/sofia-sip/win32/tests/test_memmem libs/sofia-sip/win32/tests/test_nta libs/sofia-sip/win32/tests/test_nua libs/sofia-sip/win32/tests/test_su libs/sofia-sip/win32/tests/test_tport libs/sofia-sip/win32/tests/torture_rbtree libs/sofia-sip/win32/tests/torture_su libs/sofia-sip/win32/tests/torture_su_alloc libs/sofia-sip/win32/tests/torture_su_bm libs/sofia-sip/win32/tests/torture_su_port libs/sofia-sip/win32/tests/torture_su_root libs/sofia-sip/win32/tests/torture_su_tag libs/sofia-sip/win32/tests/torture_su_time libs/sofia-sip/win32/tests/torture_su_timer libs/sofia-sip/win32/utils/localinfo libs/sofia-sip/win32/utils/sip_dig libs/sofia-sip/win32/utils/sip_options libs/sofia-sip/win32/utils/sip_options_static libs/sofia-sip/win32/utils/stunc libs/speex libs/speex/doc libs/speex/include libs/speex/include/speex libs/speex/libspeex libs/speex/src libs/speex/symbian libs/speex/ti libs/speex/ti/speex_C54_test libs/speex/ti/speex_C55_test libs/speex/ti/speex_C64_test libs/speex/win32 libs/speex/win32/VS2003 libs/speex/win32/VS2003/libspeex libs/speex/win32/VS2003/speexdec libs/speex/win32/VS2003/speexenc libs/speex/win32/VS2005 libs/speex/win32/VS2005/libspeex libs/speex/win32/VS2005/speexdec libs/speex/win32/VS2005/speexenc libs/speex/win32/libspeex libs/speex/win32/speexdec libs/speex/win32/speexenc libs/sqlite libs/srtp libs/srtp/build libs/srtp/crypto/rng libs/srtp/doc libs/srtp/test libs/udns libs/win32/js libs/win32/pcre libs/win32/sofia libs/win32/sqlite libs/win32/xmlrpc libs/xmlrpc-c libs/xmlrpc-c/autom4te.cache libs/xmlrpc-c/src scripts/socket/FreeSWITCH scripts/socket/socket2me src src/include src/include/private src/mod src/mod/applications src/mod/applications/mod_bridgecall src/mod/applications/mod_commands src/mod/applications/mod_conference src/mod/applications/mod_dptools src/mod/applications/mod_echo src/mod/applications/mod_enum src/mod/applications/mod_ivrtest src/mod/applications/mod_park src/mod/applications/mod_playback src/mod/applications/mod_rss src/mod/applications/mod_skel src/mod/asr_tts src/mod/asr_tts/mod_cepstral src/mod/asr_tts/mod_lumenvox src/mod/codecs src/mod/codecs/mod_amr src/mod/codecs/mod_g711 src/mod/codecs/mod_g722 src/mod/codecs/mod_g723_1 src/mod/codecs/mod_g726 src/mod/codecs/mod_g729 src/mod/codecs/mod_gsm src/mod/codecs/mod_h26x src/mod/codecs/mod_ilbc src/mod/codecs/mod_l16 src/mod/codecs/mod_lpc10 src/mod/codecs/mod_speex src/mod/dialplans src/mod/dialplans/mod_dialplan_directory src/mod/dialplans/mod_dialplan_xml src/mod/directories src/mod/directories/mod_ldap src/mod/dotnet src/mod/endpoints src/mod/endpoints/mod_dingaling src/mod/endpoints/mod_iax src/mod/endpoints/mod_opal src/mod/endpoints/mod_portaudio src/mod/endpoints/mod_sofia src/mod/endpoints/mod_wanpipe src/mod/endpoints/mod_wanpipe/libsangoma src/mod/endpoints/mod_woomera src/mod/event_handlers src/mod/event_handlers/mod_cdr src/mod/event_handlers/mod_event_multicast src/mod/event_handlers/mod_event_socket src/mod/event_handlers/mod_event_test src/mod/event_handlers/mod_radius_cdr src/mod/event_handlers/mod_xmpp_event src/mod/event_handlers/mod_zeroconf src/mod/formats src/mod/formats/mod_native_file src/mod/formats/mod_shout src/mod/formats/mod_sndfile src/mod/languages src/mod/languages/mod_mono src/mod/languages/mod_perl src/mod/languages/mod_python src/mod/languages/mod_spidermonkey src/mod/languages/mod_spidermonkey_core_db src/mod/languages/mod_spidermonkey_etpan src/mod/languages/mod_spidermonkey_odbc src/mod/languages/mod_spidermonkey_skel src/mod/languages/mod_spidermonkey_teletone src/mod/loggers src/mod/loggers/mod_console src/mod/loggers/mod_syslog src/mod/say src/mod/say/mod_say_en src/mod/timers src/mod/timers/mod_softtimer src/mod/xml_int src/mod/xml_int/mod_xml_cdr src/mod/xml_int/mod_xml_curl src/mod/xml_int/mod_xml_rpc w32/Library

Freeswitch SVN cparker at freeswitch.org
Tue Apr 24 10:14:53 EDT 2007


Author: cparker
Date: Tue Apr 24 10:14:28 2007
New Revision: 5009

Added:
   freeswitch/branches/cparker/acinclude.m4
      - copied unchanged from r5008, /freeswitch/trunk/acinclude.m4
   freeswitch/branches/cparker/bootstrap.sh
      - copied unchanged from r5008, /freeswitch/trunk/bootstrap.sh
   freeswitch/branches/cparker/build/config/ax_lib_mysql.m4
      - copied unchanged from r5008, /freeswitch/trunk/build/config/ax_lib_mysql.m4
   freeswitch/branches/cparker/build/config/libcurl.m4
      - copied unchanged from r5008, /freeswitch/trunk/build/config/libcurl.m4
   freeswitch/branches/cparker/build/fixautomake.sh
      - copied unchanged from r5008, /freeswitch/trunk/build/fixautomake.sh
   freeswitch/branches/cparker/build/fixlibtool.sh
      - copied unchanged from r5008, /freeswitch/trunk/build/fixlibtool.sh
   freeswitch/branches/cparker/build/getlib.sh.in
      - copied unchanged from r5008, /freeswitch/trunk/build/getlib.sh.in
   freeswitch/branches/cparker/build/indent_options.sh
      - copied unchanged from r5008, /freeswitch/trunk/build/indent_options.sh
   freeswitch/branches/cparker/build/modmake.rules.in
      - copied unchanged from r5008, /freeswitch/trunk/build/modmake.rules.in
   freeswitch/branches/cparker/build/modules.conf.in
      - copied unchanged from r5008, /freeswitch/trunk/build/modules.conf.in
   freeswitch/branches/cparker/build/turbo_build.sh
      - copied unchanged from r5008, /freeswitch/trunk/build/turbo_build.sh
   freeswitch/branches/cparker/conf/mod_cdr.conf.xml
      - copied unchanged from r5008, /freeswitch/trunk/conf/mod_cdr.conf.xml
   freeswitch/branches/cparker/docs/AUTHORS
      - copied unchanged from r5008, /freeswitch/trunk/docs/AUTHORS
   freeswitch/branches/cparker/docs/COPYING
      - copied unchanged from r5008, /freeswitch/trunk/docs/COPYING
   freeswitch/branches/cparker/libs/apr-util/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/apr-util/.update
   freeswitch/branches/cparker/libs/apr-util/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/apr-util/configure.gnu
   freeswitch/branches/cparker/libs/apr/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/apr/.update
   freeswitch/branches/cparker/libs/apr/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/apr/configure.gnu
   freeswitch/branches/cparker/libs/codec/g726/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/.update
   freeswitch/branches/cparker/libs/codec/g726/acsite.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/acsite.m4
   freeswitch/branches/cparker/libs/codec/g726/build/   (props changed)
      - copied from r5008, /freeswitch/trunk/libs/codec/g726/build/
   freeswitch/branches/cparker/libs/codec/g726/build/config/
      - copied from r5008, /freeswitch/trunk/libs/codec/g726/build/config/
   freeswitch/branches/cparker/libs/codec/g726/build/config/ac_cflags_gcc_option.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ac_cflags_gcc_option.m4
   freeswitch/branches/cparker/libs/codec/g726/build/config/ac_cflags_sun_option.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ac_cflags_sun_option.m4
   freeswitch/branches/cparker/libs/codec/g726/build/config/ac_gcc_archflag.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ac_gcc_archflag.m4
   freeswitch/branches/cparker/libs/codec/g726/build/config/ac_gcc_x86_cpuid.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ac_gcc_x86_cpuid.m4
   freeswitch/branches/cparker/libs/codec/g726/build/config/ac_prog_gzip.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ac_prog_gzip.m4
   freeswitch/branches/cparker/libs/codec/g726/build/config/ac_prog_wget.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ac_prog_wget.m4
   freeswitch/branches/cparker/libs/codec/g726/build/config/ax_cc_maxopt.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ax_cc_maxopt.m4
   freeswitch/branches/cparker/libs/codec/g726/build/config/ax_cflags_warn_all_ansi.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ax_cflags_warn_all_ansi.m4
   freeswitch/branches/cparker/libs/codec/g726/build/config/ax_check_compiler_flags.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ax_check_compiler_flags.m4
   freeswitch/branches/cparker/libs/codec/g726/build/config/ax_compiler_vendor.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/build/config/ax_compiler_vendor.m4
   freeswitch/branches/cparker/libs/codec/g726/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g726/configure.gnu
   freeswitch/branches/cparker/libs/codec/g7xx/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g7xx/.update
   freeswitch/branches/cparker/libs/codec/g7xx/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/g7xx/configure.gnu
   freeswitch/branches/cparker/libs/codec/gsm/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/gsm/.update
   freeswitch/branches/cparker/libs/codec/gsm/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/gsm/configure.gnu
   freeswitch/branches/cparker/libs/codec/ilbc/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/ilbc/.update
   freeswitch/branches/cparker/libs/codec/ilbc/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/ilbc/configure.gnu
   freeswitch/branches/cparker/libs/codec/lpc10/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/.update
   freeswitch/branches/cparker/libs/codec/lpc10/build/   (props changed)
      - copied from r5008, /freeswitch/trunk/libs/codec/lpc10/build/
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/
      - copied from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ac_cflags_gcc_option.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ac_cflags_gcc_option.m4
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ac_cflags_sun_option.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ac_cflags_sun_option.m4
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ac_gcc_archflag.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ac_gcc_archflag.m4
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ac_gcc_x86_cpuid.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ac_gcc_x86_cpuid.m4
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ac_prog_gzip.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ac_prog_gzip.m4
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ac_prog_wget.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ac_prog_wget.m4
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ax_cc_maxopt.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ax_cc_maxopt.m4
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ax_cflags_warn_all_ansi.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ax_cflags_warn_all_ansi.m4
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ax_check_compiler_flags.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ax_check_compiler_flags.m4
   freeswitch/branches/cparker/libs/codec/lpc10/build/config/ax_compiler_vendor.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/build/config/ax_compiler_vendor.m4
   freeswitch/branches/cparker/libs/codec/lpc10/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/configure.gnu
   freeswitch/branches/cparker/libs/codec/lpc10/src/
      - copied from r5008, /freeswitch/trunk/libs/codec/lpc10/src/
   freeswitch/branches/cparker/libs/codec/lpc10/src/analys.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/analys.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/bsynz.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/bsynz.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/chanwr.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/chanwr.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/dcbias.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/dcbias.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/decode.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/decode.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/deemp.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/deemp.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/difmag.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/difmag.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/dyptrk.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/dyptrk.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/encode.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/encode.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/energy.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/energy.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/f2c.h
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/f2c.h
   freeswitch/branches/cparker/libs/codec/lpc10/src/f2clib.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/f2clib.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/ham84.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/ham84.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/hp100.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/hp100.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/invert.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/invert.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/irc2pc.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/irc2pc.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/ivfilt.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/ivfilt.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/lpc10.h
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/lpc10.h
   freeswitch/branches/cparker/libs/codec/lpc10/src/lpcdec.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/lpcdec.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/lpcenc.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/lpcenc.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/lpcini.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/lpcini.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/lpfilt.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/lpfilt.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/median.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/median.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/mload.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/mload.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/onset.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/onset.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/pitsyn.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/pitsyn.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/placea.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/placea.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/placev.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/placev.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/preemp.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/preemp.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/prepro.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/prepro.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/random.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/random.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/rcchk.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/rcchk.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/synths.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/synths.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/tbdm.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/tbdm.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/voicin.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/voicin.c
   freeswitch/branches/cparker/libs/codec/lpc10/src/vparms.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/codec/lpc10/src/vparms.c
   freeswitch/branches/cparker/libs/curl/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/curl/.update
   freeswitch/branches/cparker/libs/curl/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/curl/configure.gnu
   freeswitch/branches/cparker/libs/iax/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/iax/configure.gnu
   freeswitch/branches/cparker/libs/iksemel/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/iksemel/.update
   freeswitch/branches/cparker/libs/iksemel/acsite.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/iksemel/acsite.m4
   freeswitch/branches/cparker/libs/iksemel/build/   (props changed)
      - copied from r5008, /freeswitch/trunk/libs/iksemel/build/
   freeswitch/branches/cparker/libs/iksemel/build/libgnutls.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/iksemel/build/libgnutls.m4
   freeswitch/branches/cparker/libs/iksemel/build/texinfo.tex
      - copied unchanged from r5008, /freeswitch/trunk/libs/iksemel/build/texinfo.tex
   freeswitch/branches/cparker/libs/iksemel/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/iksemel/configure.gnu
   freeswitch/branches/cparker/libs/js/acsite.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/js/acsite.m4
   freeswitch/branches/cparker/libs/js/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/js/configure.gnu
   freeswitch/branches/cparker/libs/js/nsprpub/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/js/nsprpub/.update
   freeswitch/branches/cparker/libs/js/nsprpub/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/js/nsprpub/configure.gnu
   freeswitch/branches/cparker/libs/libdingaling/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/libdingaling/configure.gnu
   freeswitch/branches/cparker/libs/libetpan/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/libetpan/.update
   freeswitch/branches/cparker/libs/libetpan/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/libetpan/configure.gnu
   freeswitch/branches/cparker/libs/libresample/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/libresample/.update
   freeswitch/branches/cparker/libs/libresample/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/libresample/configure.gnu
   freeswitch/branches/cparker/libs/libsndfile/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/libsndfile/.update
   freeswitch/branches/cparker/libs/libsndfile/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/libsndfile/configure.gnu
   freeswitch/branches/cparker/libs/libspeakup/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/libspeakup/.update
   freeswitch/branches/cparker/libs/libteletone/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/libteletone/.update
   freeswitch/branches/cparker/libs/libteletone/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/libteletone/configure.gnu
   freeswitch/branches/cparker/libs/pcre/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/pcre/.update
   freeswitch/branches/cparker/libs/pcre/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/pcre/configure.gnu
   freeswitch/branches/cparker/libs/portaudio/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/portaudio/.update
   freeswitch/branches/cparker/libs/portaudio/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/portaudio/configure.gnu
   freeswitch/branches/cparker/libs/sofia-sip/acinclude.m4
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/acinclude.m4
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/torture_su_glib_timer.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/torture_su_glib_timer.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/bnf/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/features/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/features/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/http/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/http_inlined.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/http/http_inlined.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/ipt/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/iptsec/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/msg/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/msg_inlined.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/msg/msg_inlined.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/test_inlined.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/msg/test_inlined.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/nea/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/nta/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/nth/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/nua/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_offer_answer.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/nua/test_offer_answer.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/sdp/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/sip/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/run_test_date
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/sip/run_test_date
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/run_test_sip_msg
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/sip/run_test_sip_msg
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_inlined.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/sip/sip_inlined.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/tests/10052.txt
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/sip/tests/10052.txt
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/soa/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/sresolv/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/stun/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/poll.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/poll.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/run_test_su_osx
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/run_test_su_osx
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_base_port.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/su_base_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_devpoll_port.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/su_devpoll_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_epoll_port.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/su_epoll_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_kqueue_port.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/su_kqueue_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_poll_port.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/su_poll_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_pthread_port.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/su_pthread_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_select_port.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/su_select_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_socket_port.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/su_socket_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_win32_port.c
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/su/su_win32_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/tport/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/libsofia-sip-ua/url/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/rules/
      - copied from r5008, /freeswitch/trunk/libs/sofia-sip/rules/
   freeswitch/branches/cparker/libs/sofia-sip/rules/recursive.am
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/rules/recursive.am
   freeswitch/branches/cparker/libs/sofia-sip/rules/sofia.am
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/rules/sofia.am
   freeswitch/branches/cparker/libs/sofia-sip/rules/valcheck.am
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/rules/valcheck.am
   freeswitch/branches/cparker/libs/sofia-sip/utils/Doxyfile.in
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/utils/Doxyfile.in
   freeswitch/branches/cparker/libs/sofia-sip/win32/SofiaSIP.sln
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/SofiaSIP.sln
   freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua-static/libsofia_sip_ua_static.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/libsofia-sip-ua-static/libsofia_sip_ua_static.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua/libsofia_sip_ua.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/libsofia-sip-ua/libsofia_sip_ua.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_htable/test_htable.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/test_htable/test_htable.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_memmem/test_memmem.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/test_memmem/test_memmem.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_nta/test_nta.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/test_nta/test_nta.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_nua/test_nua.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/test_nua/test_nua.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_su/test_su.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/test_su/test_su.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_tport/test_tport.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/test_tport/test_tport.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/torture_rbtree/torture_rbtree.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/torture_rbtree/torture_rbtree.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/torture_su/torture_su.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/torture_su/torture_su.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/torture_su_alloc/torture_su_alloc.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/torture_su_alloc/torture_su_alloc.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/torture_su_bm/torture_su_bm.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/torture_su_bm/torture_su_bm.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/torture_su_port/torture_su_port.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/torture_su_port/torture_su_port.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/torture_su_root/torture_su_root.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/torture_su_root/torture_su_root.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/torture_su_tag/torture_su_tag.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/torture_su_tag/torture_su_tag.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/torture_su_time/torture_su_time.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/torture_su_time/torture_su_time.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/torture_su_timer/torture_su_timer.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/tests/torture_su_timer/torture_su_timer.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/utils/localinfo/localinfo.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/utils/localinfo/localinfo.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/utils/sip_dig/sip_dig.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/utils/sip_dig/sip_dig.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/utils/sip_options/sip_options.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/utils/sip_options/sip_options.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/utils/sip_options_static/sip_options_static.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/utils/sip_options_static/sip_options_static.vcproj
   freeswitch/branches/cparker/libs/sofia-sip/win32/utils/stunc/stunc.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/libs/sofia-sip/win32/utils/stunc/stunc.vcproj
   freeswitch/branches/cparker/libs/speex/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/speex/.update
   freeswitch/branches/cparker/libs/speex/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/speex/configure.gnu
   freeswitch/branches/cparker/libs/sqlite/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/sqlite/configure.gnu
   freeswitch/branches/cparker/libs/srtp/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/srtp/.update
   freeswitch/branches/cparker/libs/srtp/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/srtp/configure.gnu
   freeswitch/branches/cparker/libs/udns/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/udns/.update
   freeswitch/branches/cparker/libs/xmlrpc-c/.update
      - copied unchanged from r5008, /freeswitch/trunk/libs/xmlrpc-c/.update
   freeswitch/branches/cparker/libs/xmlrpc-c/configure.gnu
      - copied unchanged from r5008, /freeswitch/trunk/libs/xmlrpc-c/configure.gnu
   freeswitch/branches/cparker/scripts/socket/socket2me/
      - copied from r5008, /freeswitch/trunk/scripts/socket/socket2me/
   freeswitch/branches/cparker/scripts/socket/socket2me/Makefile
      - copied unchanged from r5008, /freeswitch/trunk/scripts/socket/socket2me/Makefile
   freeswitch/branches/cparker/scripts/socket/socket2me/README
      - copied unchanged from r5008, /freeswitch/trunk/scripts/socket/socket2me/README
   freeswitch/branches/cparker/scripts/socket/socket2me/socket2me.c
      - copied unchanged from r5008, /freeswitch/trunk/scripts/socket/socket2me/socket2me.c
   freeswitch/branches/cparker/src/Makefile.am
      - copied unchanged from r5008, /freeswitch/trunk/src/Makefile.am
   freeswitch/branches/cparker/src/include/private/
      - copied from r5008, /freeswitch/trunk/src/include/private/
   freeswitch/branches/cparker/src/include/private/switch_core.h
      - copied unchanged from r5008, /freeswitch/trunk/src/include/private/switch_core.h
   freeswitch/branches/cparker/src/include/switch_core_db.h
      - copied unchanged from r5008, /freeswitch/trunk/src/include/switch_core_db.h
   freeswitch/branches/cparker/src/include/switch_core_event_hook.h
      - copied unchanged from r5008, /freeswitch/trunk/src/include/switch_core_event_hook.h
   freeswitch/branches/cparker/src/include/switch_odbc.h
      - copied unchanged from r5008, /freeswitch/trunk/src/include/switch_odbc.h
   freeswitch/branches/cparker/src/include/switch_regex.h
      - copied unchanged from r5008, /freeswitch/trunk/src/include/switch_regex.h
   freeswitch/branches/cparker/src/include/switch_scheduler.h
      - copied unchanged from r5008, /freeswitch/trunk/src/include/switch_scheduler.h
   freeswitch/branches/cparker/src/mod/Makefile.am
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/Makefile.am
   freeswitch/branches/cparker/src/mod/codecs/mod_h26x/
      - copied from r5008, /freeswitch/trunk/src/mod/codecs/mod_h26x/
   freeswitch/branches/cparker/src/mod/codecs/mod_h26x/Makefile
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/codecs/mod_h26x/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_h26x/mod_h26x.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/codecs/mod_h26x/mod_h26x.c
   freeswitch/branches/cparker/src/mod/codecs/mod_h26x/mod_h26x.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/codecs/mod_h26x/mod_h26x.vcproj
   freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/mod_sofia.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_sofia/mod_sofia.h
   freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/sofia.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_sofia/sofia.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/sofia_glue.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_sofia/sofia_glue.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/sofia_presence.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_sofia/sofia_presence.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/sofia_reg.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_sofia/sofia_reg.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/lib_api.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/lib_api.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/
      - copied from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/g711.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/g711.h
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.dsp
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.dsp
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.dsw
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.dsw
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.h
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.so.conf
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.so.conf
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.vcproj
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/libsangoma.vcproj
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/sangoma_pri.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/sangoma_pri.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/sangoma_pri.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/sangoma_pri.h
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/libsangoma/win_api_common.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/libsangoma/win_api_common.h
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/sigboost.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/sigboost.h
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/ss7boost_client.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/ss7boost_client.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/ss7boost_client.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/ss7boost_client.h
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/testapp.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/endpoints/mod_wanpipe/testapp.c
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/Makefile.am
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/event_handlers/mod_cdr/Makefile.am
   freeswitch/branches/cparker/src/mod/formats/mod_shout/   (props changed)
      - copied from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/
   freeswitch/branches/cparker/src/mod/formats/mod_shout/MPGLIB_README
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/MPGLIB_README
   freeswitch/branches/cparker/src/mod/formats/mod_shout/MPGLIB_TODO
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/MPGLIB_TODO
   freeswitch/branches/cparker/src/mod/formats/mod_shout/Makefile
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/Makefile
   freeswitch/branches/cparker/src/mod/formats/mod_shout/common.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/common.c
   freeswitch/branches/cparker/src/mod/formats/mod_shout/dct64_i386.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/dct64_i386.c
   freeswitch/branches/cparker/src/mod/formats/mod_shout/decode_i386.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/decode_i386.c
   freeswitch/branches/cparker/src/mod/formats/mod_shout/decode_ntom.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/decode_ntom.c
   freeswitch/branches/cparker/src/mod/formats/mod_shout/huffman.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/huffman.h
   freeswitch/branches/cparker/src/mod/formats/mod_shout/interface.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/interface.c
   freeswitch/branches/cparker/src/mod/formats/mod_shout/layer3.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/layer3.c
   freeswitch/branches/cparker/src/mod/formats/mod_shout/mod_shout.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/mod_shout.c
   freeswitch/branches/cparker/src/mod/formats/mod_shout/mpg123.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/mpg123.h
   freeswitch/branches/cparker/src/mod/formats/mod_shout/mpglib.h
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/mpglib.h
   freeswitch/branches/cparker/src/mod/formats/mod_shout/tabinit.c
      - copied unchanged from r5008, /freeswitch/trunk/src/mod/formats/mod_shout/tabinit.c
   freeswitch/branches/cparker/src/switch_apr.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_apr.c
   freeswitch/branches/cparker/src/switch_core_asr.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_asr.c
   freeswitch/branches/cparker/src/switch_core_codec.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_codec.c
   freeswitch/branches/cparker/src/switch_core_db.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_db.c
   freeswitch/branches/cparker/src/switch_core_directory.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_directory.c
   freeswitch/branches/cparker/src/switch_core_event_hook.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_event_hook.c
   freeswitch/branches/cparker/src/switch_core_file.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_file.c
   freeswitch/branches/cparker/src/switch_core_hash.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_hash.c
   freeswitch/branches/cparker/src/switch_core_io.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_io.c
   freeswitch/branches/cparker/src/switch_core_media_bug.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_media_bug.c
   freeswitch/branches/cparker/src/switch_core_memory.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_memory.c
   freeswitch/branches/cparker/src/switch_core_port_allocator.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_port_allocator.c
   freeswitch/branches/cparker/src/switch_core_rwlock.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_rwlock.c
   freeswitch/branches/cparker/src/switch_core_session.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_session.c
   freeswitch/branches/cparker/src/switch_core_speech.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_speech.c
   freeswitch/branches/cparker/src/switch_core_sqldb.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_sqldb.c
   freeswitch/branches/cparker/src/switch_core_state_machine.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_state_machine.c
   freeswitch/branches/cparker/src/switch_core_timer.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_core_timer.c
   freeswitch/branches/cparker/src/switch_ivr_async.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_ivr_async.c
   freeswitch/branches/cparker/src/switch_ivr_bridge.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_ivr_bridge.c
   freeswitch/branches/cparker/src/switch_ivr_menu.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_ivr_menu.c
   freeswitch/branches/cparker/src/switch_ivr_originate.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_ivr_originate.c
   freeswitch/branches/cparker/src/switch_ivr_play_say.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_ivr_play_say.c
   freeswitch/branches/cparker/src/switch_odbc.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_odbc.c
   freeswitch/branches/cparker/src/switch_regex.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_regex.c
   freeswitch/branches/cparker/src/switch_scheduler.c
      - copied unchanged from r5008, /freeswitch/trunk/src/switch_scheduler.c
Removed:
   freeswitch/branches/cparker/.indent.pro
   freeswitch/branches/cparker/AUTHORS
   freeswitch/branches/cparker/COPYING
   freeswitch/branches/cparker/ChangeLog
   freeswitch/branches/cparker/NEWS
   freeswitch/branches/cparker/README
   freeswitch/branches/cparker/acsite.m4
   freeswitch/branches/cparker/build.sh
   freeswitch/branches/cparker/build/addenv.sh
   freeswitch/branches/cparker/build/build.sh
   freeswitch/branches/cparker/build/checkversion.sh
   freeswitch/branches/cparker/build/config/compile
   freeswitch/branches/cparker/build/config/config.guess
   freeswitch/branches/cparker/build/config/depcomp
   freeswitch/branches/cparker/build/config/install-sh
   freeswitch/branches/cparker/build/config/ltmain.sh
   freeswitch/branches/cparker/build/config/missing
   freeswitch/branches/cparker/build/modmake.sh
   freeswitch/branches/cparker/generic_mod.mk
   freeswitch/branches/cparker/indent_options.sh
   freeswitch/branches/cparker/libs/apr-util/build/apr_common.m4
   freeswitch/branches/cparker/libs/apr-util/build/config.guess
   freeswitch/branches/cparker/libs/apr-util/build/config.sub
   freeswitch/branches/cparker/libs/apr-util/build/find_apr.m4
   freeswitch/branches/cparker/libs/apr-util/build/get-version.sh
   freeswitch/branches/cparker/libs/apr-util/build/install.sh
   freeswitch/branches/cparker/libs/apr-util/configure
   freeswitch/branches/cparker/libs/apr-util/include/private/apu_config.h.in
   freeswitch/branches/cparker/libs/apr-util/xml/expat/acconfig.h
   freeswitch/branches/cparker/libs/apr-util/xml/expat/aclocal.m4
   freeswitch/branches/cparker/libs/apr-util/xml/expat/config.h.in
   freeswitch/branches/cparker/libs/apr-util/xml/expat/configure
   freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/ltmain.sh
   freeswitch/branches/cparker/libs/apr/build/config.guess
   freeswitch/branches/cparker/libs/apr/build/libtool.m4
   freeswitch/branches/cparker/libs/apr/build/ltmain.sh
   freeswitch/branches/cparker/libs/apr/configure
   freeswitch/branches/cparker/libs/apr/include/arch/unix/apr_private.h.in
   freeswitch/branches/cparker/libs/codec/g726/Makefile.in
   freeswitch/branches/cparker/libs/codec/g726/aclocal.m4
   freeswitch/branches/cparker/libs/codec/g726/compile
   freeswitch/branches/cparker/libs/codec/g726/config.guess
   freeswitch/branches/cparker/libs/codec/g726/config.sub
   freeswitch/branches/cparker/libs/codec/g726/configure
   freeswitch/branches/cparker/libs/codec/g726/depcomp
   freeswitch/branches/cparker/libs/codec/g726/install-sh
   freeswitch/branches/cparker/libs/codec/g726/ltmain.sh
   freeswitch/branches/cparker/libs/codec/g726/missing
   freeswitch/branches/cparker/libs/codec/g7xx/Makefile.in
   freeswitch/branches/cparker/libs/codec/g7xx/aclocal.m4
   freeswitch/branches/cparker/libs/codec/g7xx/build/compile
   freeswitch/branches/cparker/libs/codec/g7xx/build/config.guess
   freeswitch/branches/cparker/libs/codec/g7xx/build/config.sub
   freeswitch/branches/cparker/libs/codec/g7xx/build/depcomp
   freeswitch/branches/cparker/libs/codec/g7xx/build/install-sh
   freeswitch/branches/cparker/libs/codec/g7xx/build/ltmain.sh
   freeswitch/branches/cparker/libs/codec/g7xx/build/missing
   freeswitch/branches/cparker/libs/codec/g7xx/configure
   freeswitch/branches/cparker/libs/codec/gsm/Makefile.in
   freeswitch/branches/cparker/libs/codec/gsm/aclocal.m4
   freeswitch/branches/cparker/libs/codec/gsm/compile
   freeswitch/branches/cparker/libs/codec/gsm/config.guess
   freeswitch/branches/cparker/libs/codec/gsm/config.sub
   freeswitch/branches/cparker/libs/codec/gsm/configure
   freeswitch/branches/cparker/libs/codec/gsm/depcomp
   freeswitch/branches/cparker/libs/codec/gsm/install-sh
   freeswitch/branches/cparker/libs/codec/gsm/ltmain.sh
   freeswitch/branches/cparker/libs/codec/gsm/missing
   freeswitch/branches/cparker/libs/codec/ilbc/Makefile.in
   freeswitch/branches/cparker/libs/codec/ilbc/aclocal.m4
   freeswitch/branches/cparker/libs/codec/ilbc/build/compile
   freeswitch/branches/cparker/libs/codec/ilbc/build/config.guess
   freeswitch/branches/cparker/libs/codec/ilbc/build/config.sub
   freeswitch/branches/cparker/libs/codec/ilbc/build/depcomp
   freeswitch/branches/cparker/libs/codec/ilbc/build/install-sh
   freeswitch/branches/cparker/libs/codec/ilbc/build/ltmain.sh
   freeswitch/branches/cparker/libs/codec/ilbc/build/missing
   freeswitch/branches/cparker/libs/codec/ilbc/configure
   freeswitch/branches/cparker/libs/codec/lpc10/Makefile.in
   freeswitch/branches/cparker/libs/codec/lpc10/aclocal.m4
   freeswitch/branches/cparker/libs/codec/lpc10/analys.c
   freeswitch/branches/cparker/libs/codec/lpc10/bsynz.c
   freeswitch/branches/cparker/libs/codec/lpc10/chanwr.c
   freeswitch/branches/cparker/libs/codec/lpc10/compile
   freeswitch/branches/cparker/libs/codec/lpc10/config.guess
   freeswitch/branches/cparker/libs/codec/lpc10/config.sub
   freeswitch/branches/cparker/libs/codec/lpc10/configure
   freeswitch/branches/cparker/libs/codec/lpc10/dcbias.c
   freeswitch/branches/cparker/libs/codec/lpc10/decode.c
   freeswitch/branches/cparker/libs/codec/lpc10/deemp.c
   freeswitch/branches/cparker/libs/codec/lpc10/depcomp
   freeswitch/branches/cparker/libs/codec/lpc10/difmag.c
   freeswitch/branches/cparker/libs/codec/lpc10/dyptrk.c
   freeswitch/branches/cparker/libs/codec/lpc10/encode.c
   freeswitch/branches/cparker/libs/codec/lpc10/energy.c
   freeswitch/branches/cparker/libs/codec/lpc10/f2c.h
   freeswitch/branches/cparker/libs/codec/lpc10/f2clib.c
   freeswitch/branches/cparker/libs/codec/lpc10/ham84.c
   freeswitch/branches/cparker/libs/codec/lpc10/hp100.c
   freeswitch/branches/cparker/libs/codec/lpc10/install-sh
   freeswitch/branches/cparker/libs/codec/lpc10/invert.c
   freeswitch/branches/cparker/libs/codec/lpc10/irc2pc.c
   freeswitch/branches/cparker/libs/codec/lpc10/ivfilt.c
   freeswitch/branches/cparker/libs/codec/lpc10/lpc10.h
   freeswitch/branches/cparker/libs/codec/lpc10/lpcdec.c
   freeswitch/branches/cparker/libs/codec/lpc10/lpcenc.c
   freeswitch/branches/cparker/libs/codec/lpc10/lpcini.c
   freeswitch/branches/cparker/libs/codec/lpc10/lpfilt.c
   freeswitch/branches/cparker/libs/codec/lpc10/ltmain.sh
   freeswitch/branches/cparker/libs/codec/lpc10/median.c
   freeswitch/branches/cparker/libs/codec/lpc10/missing
   freeswitch/branches/cparker/libs/codec/lpc10/mload.c
   freeswitch/branches/cparker/libs/codec/lpc10/onset.c
   freeswitch/branches/cparker/libs/codec/lpc10/pitsyn.c
   freeswitch/branches/cparker/libs/codec/lpc10/placea.c
   freeswitch/branches/cparker/libs/codec/lpc10/placev.c
   freeswitch/branches/cparker/libs/codec/lpc10/preemp.c
   freeswitch/branches/cparker/libs/codec/lpc10/prepro.c
   freeswitch/branches/cparker/libs/codec/lpc10/random.c
   freeswitch/branches/cparker/libs/codec/lpc10/rcchk.c
   freeswitch/branches/cparker/libs/codec/lpc10/synths.c
   freeswitch/branches/cparker/libs/codec/lpc10/tbdm.c
   freeswitch/branches/cparker/libs/codec/lpc10/voicin.c
   freeswitch/branches/cparker/libs/codec/lpc10/vparms.c
   freeswitch/branches/cparker/libs/curl/Makefile.in
   freeswitch/branches/cparker/libs/curl/aclocal.m4
   freeswitch/branches/cparker/libs/curl/compile
   freeswitch/branches/cparker/libs/curl/config.guess
   freeswitch/branches/cparker/libs/curl/config.sub
   freeswitch/branches/cparker/libs/curl/configure
   freeswitch/branches/cparker/libs/curl/depcomp
   freeswitch/branches/cparker/libs/curl/docs/
   freeswitch/branches/cparker/libs/curl/include/Makefile.in
   freeswitch/branches/cparker/libs/curl/include/curl/Makefile.in
   freeswitch/branches/cparker/libs/curl/install-sh
   freeswitch/branches/cparker/libs/curl/lib/Makefile.in
   freeswitch/branches/cparker/libs/curl/ltmain.sh
   freeswitch/branches/cparker/libs/curl/missing
   freeswitch/branches/cparker/libs/curl/packages/AIX/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/AIX/RPM/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/DOS/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/EPM/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/Linux/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/Linux/RPM/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/Solaris/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/Win32/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/Win32/cygwin/Makefile.in
   freeswitch/branches/cparker/libs/curl/packages/vms/Makefile.in
   freeswitch/branches/cparker/libs/curl/src/Makefile.in
   freeswitch/branches/cparker/libs/curl/tests/
   freeswitch/branches/cparker/libs/iax/Makefile.in
   freeswitch/branches/cparker/libs/iax/aclocal.m4
   freeswitch/branches/cparker/libs/iax/build/config.guess
   freeswitch/branches/cparker/libs/iax/build/config.sub
   freeswitch/branches/cparker/libs/iax/build/depcomp
   freeswitch/branches/cparker/libs/iax/build/install-sh
   freeswitch/branches/cparker/libs/iax/build/ltmain.sh
   freeswitch/branches/cparker/libs/iax/build/missing
   freeswitch/branches/cparker/libs/iax/configure
   freeswitch/branches/cparker/libs/iax/src/Makefile.in
   freeswitch/branches/cparker/libs/iksemel/Makefile.in
   freeswitch/branches/cparker/libs/iksemel/aclocal.m4
   freeswitch/branches/cparker/libs/iksemel/config.guess
   freeswitch/branches/cparker/libs/iksemel/config.sub
   freeswitch/branches/cparker/libs/iksemel/configure
   freeswitch/branches/cparker/libs/iksemel/doc/Makefile.in
   freeswitch/branches/cparker/libs/iksemel/doc/texinfo.tex
   freeswitch/branches/cparker/libs/iksemel/include/Makefile.in
   freeswitch/branches/cparker/libs/iksemel/include/config.h.in
   freeswitch/branches/cparker/libs/iksemel/install-sh
   freeswitch/branches/cparker/libs/iksemel/missing
   freeswitch/branches/cparker/libs/iksemel/mkinstalldirs
   freeswitch/branches/cparker/libs/iksemel/src/Makefile.in
   freeswitch/branches/cparker/libs/iksemel/test/Makefile.in
   freeswitch/branches/cparker/libs/iksemel/tools/Makefile.in
   freeswitch/branches/cparker/libs/js/aclocal.m4
   freeswitch/branches/cparker/libs/js/config.guess
   freeswitch/branches/cparker/libs/js/config.h.in
   freeswitch/branches/cparker/libs/js/config.sub
   freeswitch/branches/cparker/libs/js/configure
   freeswitch/branches/cparker/libs/js/ltmain.sh
   freeswitch/branches/cparker/libs/js/nsprpub/build/autoconf/config.guess
   freeswitch/branches/cparker/libs/js/nsprpub/build/autoconf/config.sub
   freeswitch/branches/cparker/libs/js/nsprpub/configure
   freeswitch/branches/cparker/libs/libdingaling/Makefile.in
   freeswitch/branches/cparker/libs/libdingaling/aclocal.m4
   freeswitch/branches/cparker/libs/libdingaling/build/compile
   freeswitch/branches/cparker/libs/libdingaling/build/config.guess
   freeswitch/branches/cparker/libs/libdingaling/build/config.sub
   freeswitch/branches/cparker/libs/libdingaling/build/depcomp
   freeswitch/branches/cparker/libs/libdingaling/build/install-sh
   freeswitch/branches/cparker/libs/libdingaling/build/ltmain.sh
   freeswitch/branches/cparker/libs/libdingaling/build/missing
   freeswitch/branches/cparker/libs/libdingaling/configure
   freeswitch/branches/cparker/libs/libdingaling/src/config.h.in
   freeswitch/branches/cparker/libs/libetpan/aclocal.m4
   freeswitch/branches/cparker/libs/libetpan/config.guess
   freeswitch/branches/cparker/libs/libetpan/config.h.in
   freeswitch/branches/cparker/libs/libetpan/config.sub
   freeswitch/branches/cparker/libs/libetpan/configure
   freeswitch/branches/cparker/libs/libetpan/ltmain.sh
   freeswitch/branches/cparker/libs/libresample-0.1.3.build.sh
   freeswitch/branches/cparker/libs/libresample/Makefile.in
   freeswitch/branches/cparker/libs/libresample/aclocal.m4
   freeswitch/branches/cparker/libs/libresample/build/compile
   freeswitch/branches/cparker/libs/libresample/build/config.guess
   freeswitch/branches/cparker/libs/libresample/build/config.sub
   freeswitch/branches/cparker/libs/libresample/build/depcomp
   freeswitch/branches/cparker/libs/libresample/build/install-sh
   freeswitch/branches/cparker/libs/libresample/build/ltmain.sh
   freeswitch/branches/cparker/libs/libresample/build/missing
   freeswitch/branches/cparker/libs/libresample/configure
   freeswitch/branches/cparker/libs/libresample/src/configtemplate.h
   freeswitch/branches/cparker/libs/libsndfile/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/Octave/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/Win32/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/aclocal.m4
   freeswitch/branches/cparker/libs/libsndfile/compile
   freeswitch/branches/cparker/libs/libsndfile/config.guess
   freeswitch/branches/cparker/libs/libsndfile/config.sub
   freeswitch/branches/cparker/libs/libsndfile/configure
   freeswitch/branches/cparker/libs/libsndfile/depcomp
   freeswitch/branches/cparker/libs/libsndfile/doc/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/examples/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/install-sh
   freeswitch/branches/cparker/libs/libsndfile/ltmain.sh
   freeswitch/branches/cparker/libs/libsndfile/man/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/missing
   freeswitch/branches/cparker/libs/libsndfile/regtest/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/src/G72x/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/src/GSM610/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/src/Makefile.in
   freeswitch/branches/cparker/libs/libsndfile/src/config.h.in
   freeswitch/branches/cparker/libs/libsndfile/tests/Makefile.in
   freeswitch/branches/cparker/libs/libspeakup/aclocal.m4
   freeswitch/branches/cparker/libs/libspeakup/build/compile
   freeswitch/branches/cparker/libs/libspeakup/build/config.guess
   freeswitch/branches/cparker/libs/libspeakup/build/config.sub
   freeswitch/branches/cparker/libs/libspeakup/build/depcomp
   freeswitch/branches/cparker/libs/libspeakup/build/install-sh
   freeswitch/branches/cparker/libs/libspeakup/build/ltmain.sh
   freeswitch/branches/cparker/libs/libspeakup/build/missing
   freeswitch/branches/cparker/libs/libteletone/Makefile.in
   freeswitch/branches/cparker/libs/libteletone/aclocal.m4
   freeswitch/branches/cparker/libs/libteletone/build/compile
   freeswitch/branches/cparker/libs/libteletone/build/config.guess
   freeswitch/branches/cparker/libs/libteletone/build/config.sub
   freeswitch/branches/cparker/libs/libteletone/build/depcomp
   freeswitch/branches/cparker/libs/libteletone/build/install-sh
   freeswitch/branches/cparker/libs/libteletone/build/ltmain.sh
   freeswitch/branches/cparker/libs/libteletone/build/missing
   freeswitch/branches/cparker/libs/libteletone/configure
   freeswitch/branches/cparker/libs/mozilla.build.sh
   freeswitch/branches/cparker/libs/openldap-2.3.19.build.sh
   freeswitch/branches/cparker/libs/pcre/config.guess
   freeswitch/branches/cparker/libs/pcre/config.sub
   freeswitch/branches/cparker/libs/pcre/configure
   freeswitch/branches/cparker/libs/pcre/ltmain.sh
   freeswitch/branches/cparker/libs/portaudio/aclocal.m4
   freeswitch/branches/cparker/libs/portaudio/bindings/cpp/aclocal.m4
   freeswitch/branches/cparker/libs/portaudio/bindings/cpp/build/gnu/aclocal.m4
   freeswitch/branches/cparker/libs/sofia-sip/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/aclocal.m4
   freeswitch/branches/cparker/libs/sofia-sip/compile
   freeswitch/branches/cparker/libs/sofia-sip/config.guess
   freeswitch/branches/cparker/libs/sofia-sip/config.h.in
   freeswitch/branches/cparker/libs/sofia-sip/config.sub
   freeswitch/branches/cparker/libs/sofia-sip/configure
   freeswitch/branches/cparker/libs/sofia-sip/depcomp
   freeswitch/branches/cparker/libs/sofia-sip/install-sh
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/features/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/features/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/ltmain.sh
   freeswitch/branches/cparker/libs/sofia-sip/missing
   freeswitch/branches/cparker/libs/sofia-sip/packages/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/utils/Doxyfile
   freeswitch/branches/cparker/libs/sofia-sip/utils/Doxyfile.build.in
   freeswitch/branches/cparker/libs/sofia-sip/utils/Makefile.in
   freeswitch/branches/cparker/libs/sofia-sip/win32/Makefile.in
   freeswitch/branches/cparker/libs/speex/Makefile.in
   freeswitch/branches/cparker/libs/speex/aclocal.m4
   freeswitch/branches/cparker/libs/speex/config.guess
   freeswitch/branches/cparker/libs/speex/config.sub
   freeswitch/branches/cparker/libs/speex/configure
   freeswitch/branches/cparker/libs/speex/depcomp
   freeswitch/branches/cparker/libs/speex/doc/Makefile.in
   freeswitch/branches/cparker/libs/speex/include/Makefile.in
   freeswitch/branches/cparker/libs/speex/include/speex/Makefile.in
   freeswitch/branches/cparker/libs/speex/install-sh
   freeswitch/branches/cparker/libs/speex/libspeex/Makefile.in
   freeswitch/branches/cparker/libs/speex/ltmain.sh
   freeswitch/branches/cparker/libs/speex/missing
   freeswitch/branches/cparker/libs/speex/src/Makefile.in
   freeswitch/branches/cparker/libs/speex/symbian/Makefile.in
   freeswitch/branches/cparker/libs/speex/ti/Makefile.in
   freeswitch/branches/cparker/libs/speex/ti/speex_C54_test/Makefile.in
   freeswitch/branches/cparker/libs/speex/ti/speex_C55_test/Makefile.in
   freeswitch/branches/cparker/libs/speex/ti/speex_C64_test/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/VS2003/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/VS2003/libspeex/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/VS2003/speexdec/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/VS2003/speexenc/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/VS2005/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/VS2005/libspeex/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/VS2005/speexdec/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/VS2005/speexenc/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/libspeex/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/speexdec/Makefile.in
   freeswitch/branches/cparker/libs/speex/win32/speexenc/Makefile.in
   freeswitch/branches/cparker/libs/sqlite-3.3.6.build.sh
   freeswitch/branches/cparker/libs/sqlite/aclocal.m4
   freeswitch/branches/cparker/libs/sqlite/config.guess
   freeswitch/branches/cparker/libs/sqlite/config.sub
   freeswitch/branches/cparker/libs/sqlite/configure
   freeswitch/branches/cparker/libs/sqlite/ltmain.sh
   freeswitch/branches/cparker/libs/srtp.build.sh
   freeswitch/branches/cparker/libs/srtp/Makefile.in
   freeswitch/branches/cparker/libs/srtp/aclocal.m4
   freeswitch/branches/cparker/libs/srtp/build/config.guess
   freeswitch/branches/cparker/libs/srtp/build/config.sub
   freeswitch/branches/cparker/libs/srtp/build/ltmain.sh
   freeswitch/branches/cparker/libs/srtp/config.guess
   freeswitch/branches/cparker/libs/srtp/config.sub
   freeswitch/branches/cparker/libs/srtp/config_in.h
   freeswitch/branches/cparker/libs/srtp/configure
   freeswitch/branches/cparker/libs/srtp/doc/Makefile
   freeswitch/branches/cparker/libs/srtp/install-sh
   freeswitch/branches/cparker/libs/srtp/test/Makefile.in
   freeswitch/branches/cparker/libs/udns.build.sh
   freeswitch/branches/cparker/libs/xmlrpc-c/aclocal.m4
   freeswitch/branches/cparker/libs/xmlrpc-c/autom4te.cache/
   freeswitch/branches/cparker/libs/xmlrpc-c/config.guess
   freeswitch/branches/cparker/libs/xmlrpc-c/config.sub
   freeswitch/branches/cparker/libs/xmlrpc-c/configure
   freeswitch/branches/cparker/libs/xmlrpc-c/ltmain.sh
   freeswitch/branches/cparker/libs/xmlrpc-c/missing
   freeswitch/branches/cparker/modules.conf.in
   freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_xml/Makefile
Modified:
   freeswitch/branches/cparker/   (props changed)
   freeswitch/branches/cparker/Freeswitch.sln
   freeswitch/branches/cparker/Makefile.am
   freeswitch/branches/cparker/Makefile.in
   freeswitch/branches/cparker/aclocal.m4
   freeswitch/branches/cparker/build/   (props changed)
   freeswitch/branches/cparker/build/buildlib.sh
   freeswitch/branches/cparker/build/config/   (props changed)
   freeswitch/branches/cparker/conf/default_context.xml
   freeswitch/branches/cparker/conf/dingaling.conf.xml
   freeswitch/branches/cparker/conf/freeswitch.xml
   freeswitch/branches/cparker/conf/freeswitch_combined.xml
   freeswitch/branches/cparker/conf/modules.conf.xml
   freeswitch/branches/cparker/conf/sofia.conf.xml
   freeswitch/branches/cparker/conf/switch.conf.xml
   freeswitch/branches/cparker/conf/wanpipe.conf.xml
   freeswitch/branches/cparker/configure
   freeswitch/branches/cparker/configure.in
   freeswitch/branches/cparker/libs/   (props changed)
   freeswitch/branches/cparker/libs/apr/   (props changed)
   freeswitch/branches/cparker/libs/apr-util/   (props changed)
   freeswitch/branches/cparker/libs/apr-util/build/   (props changed)
   freeswitch/branches/cparker/libs/apr-util/build-outputs.mk
   freeswitch/branches/cparker/libs/apr-util/build.conf
   freeswitch/branches/cparker/libs/apr-util/buildconf
   freeswitch/branches/cparker/libs/apr-util/configure.in
   freeswitch/branches/cparker/libs/apr-util/include/   (props changed)
   freeswitch/branches/cparker/libs/apr-util/include/private/   (props changed)
   freeswitch/branches/cparker/libs/apr-util/xml/expat/   (props changed)
   freeswitch/branches/cparker/libs/apr-util/xml/expat/configure.in
   freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/   (props changed)
   freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/config.guess
   freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/config.sub
   freeswitch/branches/cparker/libs/apr-util/xml/expat/lib/winconfig.h
   freeswitch/branches/cparker/libs/apr-util/xml/expat/lib/xmlparse.c
   freeswitch/branches/cparker/libs/apr/build/   (props changed)
   freeswitch/branches/cparker/libs/apr/build/apr_common.m4
   freeswitch/branches/cparker/libs/apr/configure.in
   freeswitch/branches/cparker/libs/apr/include/apr.h.in
   freeswitch/branches/cparker/libs/apr/include/arch/unix/   (props changed)
   freeswitch/branches/cparker/libs/codec/g726/   (props changed)
   freeswitch/branches/cparker/libs/codec/g726/Makefile.am
   freeswitch/branches/cparker/libs/codec/g726/configure.in
   freeswitch/branches/cparker/libs/codec/g7xx/   (props changed)
   freeswitch/branches/cparker/libs/codec/g7xx/build/   (props changed)
   freeswitch/branches/cparker/libs/codec/gsm/   (props changed)
   freeswitch/branches/cparker/libs/codec/gsm/Makefile.am
   freeswitch/branches/cparker/libs/codec/gsm/configure.in
   freeswitch/branches/cparker/libs/codec/ilbc/   (props changed)
   freeswitch/branches/cparker/libs/codec/ilbc/build/   (props changed)
   freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_decode.h
   freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_define.h
   freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_encode.h
   freeswitch/branches/cparker/libs/codec/lpc10/   (props changed)
   freeswitch/branches/cparker/libs/codec/lpc10/Makefile.am
   freeswitch/branches/cparker/libs/codec/lpc10/configure.ac
   freeswitch/branches/cparker/libs/curl/   (props changed)
   freeswitch/branches/cparker/libs/curl/Makefile.am
   freeswitch/branches/cparker/libs/curl/configure.ac
   freeswitch/branches/cparker/libs/curl/include/   (props changed)
   freeswitch/branches/cparker/libs/curl/include/curl/   (props changed)
   freeswitch/branches/cparker/libs/curl/lib/   (props changed)
   freeswitch/branches/cparker/libs/curl/lib/config.h.in
   freeswitch/branches/cparker/libs/curl/packages/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/AIX/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/AIX/RPM/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/DOS/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/EPM/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/Linux/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/Linux/RPM/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/Solaris/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/Win32/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/Win32/cygwin/   (props changed)
   freeswitch/branches/cparker/libs/curl/packages/vms/   (props changed)
   freeswitch/branches/cparker/libs/curl/src/   (props changed)
   freeswitch/branches/cparker/libs/curl/src/Makefile.am
   freeswitch/branches/cparker/libs/curl/src/Makefile.inc
   freeswitch/branches/cparker/libs/iax/   (props changed)
   freeswitch/branches/cparker/libs/iax/.update
   freeswitch/branches/cparker/libs/iax/build/   (props changed)
   freeswitch/branches/cparker/libs/iax/src/   (props changed)
   freeswitch/branches/cparker/libs/iax/src/iax-mutex.c
   freeswitch/branches/cparker/libs/iax/src/iax-mutex.h
   freeswitch/branches/cparker/libs/iksemel/   (props changed)
   freeswitch/branches/cparker/libs/iksemel/configure.ac
   freeswitch/branches/cparker/libs/iksemel/doc/   (props changed)
   freeswitch/branches/cparker/libs/iksemel/include/   (props changed)
   freeswitch/branches/cparker/libs/iksemel/include/iksemel.h
   freeswitch/branches/cparker/libs/iksemel/ltmain.sh
   freeswitch/branches/cparker/libs/iksemel/src/   (props changed)
   freeswitch/branches/cparker/libs/iksemel/src/filter.c
   freeswitch/branches/cparker/libs/iksemel/src/iks.c
   freeswitch/branches/cparker/libs/iksemel/src/ikstack.c
   freeswitch/branches/cparker/libs/iksemel/src/io-posix.c
   freeswitch/branches/cparker/libs/iksemel/src/sax.c
   freeswitch/branches/cparker/libs/iksemel/src/utility.c
   freeswitch/branches/cparker/libs/iksemel/test/   (props changed)
   freeswitch/branches/cparker/libs/iksemel/tools/   (props changed)
   freeswitch/branches/cparker/libs/js/   (props changed)
   freeswitch/branches/cparker/libs/js/.update
   freeswitch/branches/cparker/libs/js/Makefile.in
   freeswitch/branches/cparker/libs/js/configure.ac
   freeswitch/branches/cparker/libs/js/nsprpub/   (props changed)
   freeswitch/branches/cparker/libs/js/nsprpub/build/autoconf/   (props changed)
   freeswitch/branches/cparker/libs/js/nsprpub/config/nspr.m4
   freeswitch/branches/cparker/libs/js/nsprpub/configure.in
   freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plarena.c
   freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plds.def
   freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plhash.c
   freeswitch/branches/cparker/libs/js/nsprpub/lib/libc/src/plc.def
   freeswitch/branches/cparker/libs/js/nsprpub/lib/libc/src/plerror.c
   freeswitch/branches/cparker/libs/js/nsprpub/pr/include/   (props changed)
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/Makefile.in
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/Makefile.in
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/prfdcach.c
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/pripv6.c
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/prlog.c
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/malloc/Makefile.in
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/malloc/prmem.c
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/Makefile.in
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/objs.mk
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/os_Linux_x86_64.s
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/memory/Makefile.in
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/misc/Makefile.in
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/misc/prinit.c
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/nspr.def
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/Makefile.in
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/ptio.c
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/ptthread.c
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/threads/Makefile.in
   freeswitch/branches/cparker/libs/js/nsprpub/pr/src/threads/prcthr.c
   freeswitch/branches/cparker/libs/js/src/jspubtd.h
   freeswitch/branches/cparker/libs/libdingaling/   (props changed)
   freeswitch/branches/cparker/libs/libdingaling/.update
   freeswitch/branches/cparker/libs/libdingaling/Makefile.am
   freeswitch/branches/cparker/libs/libdingaling/build/   (props changed)
   freeswitch/branches/cparker/libs/libdingaling/configure.in
   freeswitch/branches/cparker/libs/libdingaling/src/   (props changed)
   freeswitch/branches/cparker/libs/libdingaling/src/libdingaling.c
   freeswitch/branches/cparker/libs/libdingaling/src/libdingaling.h
   freeswitch/branches/cparker/libs/libetpan/   (props changed)
   freeswitch/branches/cparker/libs/libetpan/configure.in
   freeswitch/branches/cparker/libs/libresample/   (props changed)
   freeswitch/branches/cparker/libs/libresample/build/   (props changed)
   freeswitch/branches/cparker/libs/libresample/configure.in
   freeswitch/branches/cparker/libs/libresample/src/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/Makefile.am
   freeswitch/branches/cparker/libs/libsndfile/Octave/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/Win32/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/acinclude.m4
   freeswitch/branches/cparker/libs/libsndfile/doc/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/examples/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/man/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/regtest/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/src/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/src/G72x/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/src/GSM610/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/tests/   (props changed)
   freeswitch/branches/cparker/libs/libsndfile/tests/utils.h
   freeswitch/branches/cparker/libs/libspeakup/configure.in
   freeswitch/branches/cparker/libs/libteletone/   (props changed)
   freeswitch/branches/cparker/libs/libteletone/build/   (props changed)
   freeswitch/branches/cparker/libs/libteletone/configure.in
   freeswitch/branches/cparker/libs/libteletone/src/libteletone.h
   freeswitch/branches/cparker/libs/libteletone/src/libteletone_detect.c
   freeswitch/branches/cparker/libs/libteletone/src/libteletone_detect.h
   freeswitch/branches/cparker/libs/pcre/   (props changed)
   freeswitch/branches/cparker/libs/pcre/INSTALL
   freeswitch/branches/cparker/libs/portaudio/Makefile.in
   freeswitch/branches/cparker/libs/portaudio/build/msvc/   (props changed)
   freeswitch/branches/cparker/libs/portaudio/configure
   freeswitch/branches/cparker/libs/portaudio/configure.in
   freeswitch/branches/cparker/libs/portaudio/src/common/pa_ringbuffer.c
   freeswitch/branches/cparker/libs/portaudio/test/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/.update
   freeswitch/branches/cparker/libs/sofia-sip/AUTHORS
   freeswitch/branches/cparker/libs/sofia-sip/COPYRIGHTS
   freeswitch/branches/cparker/libs/sofia-sip/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/README
   freeswitch/branches/cparker/libs/sofia-sip/RELEASE
   freeswitch/branches/cparker/libs/sofia-sip/RELEASE.template
   freeswitch/branches/cparker/libs/sofia-sip/configure.ac
   freeswitch/branches/cparker/libs/sofia-sip/configure.gnu
   freeswitch/branches/cparker/libs/sofia-sip/docs/build_system.txt
   freeswitch/branches/cparker/libs/sofia-sip/docs/devel_platform_notes.txt
   freeswitch/branches/cparker/libs/sofia-sip/docs/release_management.txt
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/sofia-sip/su_glib.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/su_source.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ChangeLog
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/bnf.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/torture_bnf.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.aliases
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.conf
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.version.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/conformance.docs
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/hide_emails.sh
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/features/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/features/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/http_basic.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/http_parser.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/sofia-sip/http_header.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/test_http.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/sofia-sip/base64.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/sofia-sip/string0.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/torture_base64.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_client.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_module.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_plugin_delayed.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/sofia-sip/auth_client_plugin.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/sofia-sip/auth_plugin.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/test_auth_digest.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/msg_parser.awk
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/msg_parser_util.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/sofia-sip/msg_parser.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/test_msg.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/nea_server.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_check.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_internal.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_tag.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/run_test_nta
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/run_test_nta_api
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/sofia-sip/nta.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/sofia-sip/nta_tag.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/test_nta.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/test_nta_api.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/http-server.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/nth_client.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/nth_server.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/sofia-sip/nth_tag.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/test_nth.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua.docs
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_common.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_dialog.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_dialog.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_event_server.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_extension.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_message.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_notifier.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_options.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_params.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_params.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_publish.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_register.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_registrar.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_session.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_stack.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_stack.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_subnotref.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_tag.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/outbound.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/outbound.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua_tag.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_100rel.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_basic_call.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_call_hold.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_call_reject.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_cancel_bye.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_extension.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_init.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nat.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nat.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua_api.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua_params.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_ops.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_proxy.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_proxy.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_refer.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_register.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_session_timer.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_simple.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_sip_events.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/run_test_sdp
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/sdp.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/sdp_print.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/torture_sdp.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_basic.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_event.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_extra.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_extra_headers.txt
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_feature.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_mime.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_parser.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_prack.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_pref_util.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_reason.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_refer.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_tag_class.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_util.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_header.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_parser.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_util.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/test_date.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/test_sip_msg.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/torture_sip.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/validator.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/soa.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/soa_static.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/sofia-sip/soa_session.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/test_soa.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/run_test_sresolv
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres_blocking.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres_cache.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sresolv.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sresolv.docs
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/test_sresolv.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/stun.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/stun_internal.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/addrinfo.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/run_test_su
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/htable.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/htable2.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_bm.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_configure.h.in
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_debug.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_tag.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_time.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_wait.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/tstdef.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_addrinfo.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_alloc.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_alloc_lock.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_bm.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_localinfo.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_log.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_os_nw.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_osx_runloop.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_port.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_root.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_time.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_timer.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_wait.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/tag_dll.awk
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_htable.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_memmem.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_su.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_rbtree.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_alloc.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_bm.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_port.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_root.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_root_osx.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_tag.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_time.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_timer.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/sofia-sip/tport_tag.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/test_tport.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_internal.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_logging.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_stub_stun.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_tls.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_sctp.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_tcp.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_tls.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_udp.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/sofia-sip/url.h
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/torture_url.c
   freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/url.c
   freeswitch/branches/cparker/libs/sofia-sip/m4/sac-general.m4
   freeswitch/branches/cparker/libs/sofia-sip/m4/sac-openssl.m4
   freeswitch/branches/cparker/libs/sofia-sip/m4/sac-su.m4
   freeswitch/branches/cparker/libs/sofia-sip/m4/sac-su2.m4
   freeswitch/branches/cparker/libs/sofia-sip/m4/sac-tport.m4
   freeswitch/branches/cparker/libs/sofia-sip/packages/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/packages/sofia-sip.spec.in
   freeswitch/branches/cparker/libs/sofia-sip/utils/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/utils/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/utils/sip-options.c
   freeswitch/branches/cparker/libs/sofia-sip/win32/   (props changed)
   freeswitch/branches/cparker/libs/sofia-sip/win32/Makefile.am
   freeswitch/branches/cparker/libs/sofia-sip/win32/SofiaSIP.dsw
   freeswitch/branches/cparker/libs/sofia-sip/win32/build_sources.cmd
   freeswitch/branches/cparker/libs/sofia-sip/win32/check.cmd
   freeswitch/branches/cparker/libs/sofia-sip/win32/config.h.in
   freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua-static/libsofia_sip_ua_static.dsp
   freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua/libsofia_sip_ua.dsp
   freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_nua/test_nua.dsp
   freeswitch/branches/cparker/libs/sofia-sip/win32/version_files.cmd
   freeswitch/branches/cparker/libs/speex/   (props changed)
   freeswitch/branches/cparker/libs/speex/Makefile.am
   freeswitch/branches/cparker/libs/speex/doc/   (props changed)
   freeswitch/branches/cparker/libs/speex/include/   (props changed)
   freeswitch/branches/cparker/libs/speex/include/speex/   (props changed)
   freeswitch/branches/cparker/libs/speex/libspeex/   (props changed)
   freeswitch/branches/cparker/libs/speex/src/   (props changed)
   freeswitch/branches/cparker/libs/speex/symbian/   (props changed)
   freeswitch/branches/cparker/libs/speex/ti/   (props changed)
   freeswitch/branches/cparker/libs/speex/ti/speex_C54_test/   (props changed)
   freeswitch/branches/cparker/libs/speex/ti/speex_C55_test/   (props changed)
   freeswitch/branches/cparker/libs/speex/ti/speex_C64_test/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/VS2003/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/VS2003/libspeex/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/VS2003/speexdec/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/VS2003/speexenc/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/VS2005/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/VS2005/libspeex/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/VS2005/speexdec/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/VS2005/speexenc/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/libspeex/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/speexdec/   (props changed)
   freeswitch/branches/cparker/libs/speex/win32/speexenc/   (props changed)
   freeswitch/branches/cparker/libs/sqlite/   (props changed)
   freeswitch/branches/cparker/libs/sqlite/configure.ac
   freeswitch/branches/cparker/libs/srtp/   (props changed)
   freeswitch/branches/cparker/libs/srtp/Makefile.am
   freeswitch/branches/cparker/libs/srtp/build/   (props changed)
   freeswitch/branches/cparker/libs/srtp/configure.in
   freeswitch/branches/cparker/libs/srtp/crypto/rng/prng.c
   freeswitch/branches/cparker/libs/srtp/doc/   (props changed)
   freeswitch/branches/cparker/libs/srtp/test/   (props changed)
   freeswitch/branches/cparker/libs/udns/udns.h
   freeswitch/branches/cparker/libs/udns/udns_resolver.c
   freeswitch/branches/cparker/libs/win32/js/js.vcproj
   freeswitch/branches/cparker/libs/win32/pcre/libpcre.vcproj
   freeswitch/branches/cparker/libs/win32/sofia/libsofia_sip_ua_static.vcproj
   freeswitch/branches/cparker/libs/win32/sqlite/sqlite.vcproj
   freeswitch/branches/cparker/libs/win32/xmlrpc/xmlrpc.vcproj
   freeswitch/branches/cparker/libs/xmlrpc-c/   (props changed)
   freeswitch/branches/cparker/libs/xmlrpc-c/GNUmakefile
   freeswitch/branches/cparker/libs/xmlrpc-c/configure.in
   freeswitch/branches/cparker/libs/xmlrpc-c/src/Makefile
   freeswitch/branches/cparker/scripts/socket/FreeSWITCH/Client.pm
   freeswitch/branches/cparker/src/   (props changed)
   freeswitch/branches/cparker/src/include/   (props changed)
   freeswitch/branches/cparker/src/include/switch.h
   freeswitch/branches/cparker/src/include/switch_am_config.h.in
   freeswitch/branches/cparker/src/include/switch_apr.h
   freeswitch/branches/cparker/src/include/switch_bitpack.h
   freeswitch/branches/cparker/src/include/switch_buffer.h
   freeswitch/branches/cparker/src/include/switch_caller.h
   freeswitch/branches/cparker/src/include/switch_channel.h
   freeswitch/branches/cparker/src/include/switch_config.h
   freeswitch/branches/cparker/src/include/switch_console.h
   freeswitch/branches/cparker/src/include/switch_core.h
   freeswitch/branches/cparker/src/include/switch_event.h
   freeswitch/branches/cparker/src/include/switch_frame.h
   freeswitch/branches/cparker/src/include/switch_ivr.h
   freeswitch/branches/cparker/src/include/switch_loadable_module.h
   freeswitch/branches/cparker/src/include/switch_log.h
   freeswitch/branches/cparker/src/include/switch_module_interfaces.h
   freeswitch/branches/cparker/src/include/switch_platform.h
   freeswitch/branches/cparker/src/include/switch_resample.h
   freeswitch/branches/cparker/src/include/switch_rtp.h
   freeswitch/branches/cparker/src/include/switch_sqlite.h
   freeswitch/branches/cparker/src/include/switch_stun.h
   freeswitch/branches/cparker/src/include/switch_types.h
   freeswitch/branches/cparker/src/include/switch_utils.h
   freeswitch/branches/cparker/src/include/switch_xml.h
   freeswitch/branches/cparker/src/mod/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_bridgecall/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_bridgecall/mod_bridgecall.c
   freeswitch/branches/cparker/src/mod/applications/mod_commands/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_commands/mod_commands.c
   freeswitch/branches/cparker/src/mod/applications/mod_conference/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_conference/mod_conference.c
   freeswitch/branches/cparker/src/mod/applications/mod_dptools/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_dptools/mod_dptools.c
   freeswitch/branches/cparker/src/mod/applications/mod_echo/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_echo/mod_echo.c
   freeswitch/branches/cparker/src/mod/applications/mod_enum/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_enum/Makefile
   freeswitch/branches/cparker/src/mod/applications/mod_enum/mod_enum.c
   freeswitch/branches/cparker/src/mod/applications/mod_ivrtest/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_ivrtest/mod_ivrtest.c
   freeswitch/branches/cparker/src/mod/applications/mod_park/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_park/mod_park.c
   freeswitch/branches/cparker/src/mod/applications/mod_playback/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_playback/mod_playback.c
   freeswitch/branches/cparker/src/mod/applications/mod_rss/   (props changed)
   freeswitch/branches/cparker/src/mod/applications/mod_rss/mod_rss.c
   freeswitch/branches/cparker/src/mod/applications/mod_skel/   (props changed)
   freeswitch/branches/cparker/src/mod/asr_tts/   (props changed)
   freeswitch/branches/cparker/src/mod/asr_tts/mod_cepstral/   (props changed)
   freeswitch/branches/cparker/src/mod/asr_tts/mod_cepstral/Makefile
   freeswitch/branches/cparker/src/mod/asr_tts/mod_cepstral/mod_cepstral.c
   freeswitch/branches/cparker/src/mod/asr_tts/mod_lumenvox/   (props changed)
   freeswitch/branches/cparker/src/mod/asr_tts/mod_lumenvox/Makefile
   freeswitch/branches/cparker/src/mod/codecs/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_amr/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_amr/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_amr/mod_amr.c
   freeswitch/branches/cparker/src/mod/codecs/mod_g711/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_g711/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_g711/mod_g711.c
   freeswitch/branches/cparker/src/mod/codecs/mod_g722/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_g722/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_g722/mod_g722.c
   freeswitch/branches/cparker/src/mod/codecs/mod_g723_1/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_g723_1/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_g723_1/mod_g723_1.c
   freeswitch/branches/cparker/src/mod/codecs/mod_g726/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_g726/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_g726/mod_g726.c
   freeswitch/branches/cparker/src/mod/codecs/mod_g729/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_g729/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_g729/mod_g729.c
   freeswitch/branches/cparker/src/mod/codecs/mod_gsm/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_gsm/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_gsm/mod_gsm.c
   freeswitch/branches/cparker/src/mod/codecs/mod_ilbc/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_ilbc/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_ilbc/mod_ilbc.c
   freeswitch/branches/cparker/src/mod/codecs/mod_l16/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_l16/mod_l16.c
   freeswitch/branches/cparker/src/mod/codecs/mod_lpc10/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_lpc10/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_lpc10/mod_lpc10.c
   freeswitch/branches/cparker/src/mod/codecs/mod_speex/   (props changed)
   freeswitch/branches/cparker/src/mod/codecs/mod_speex/Makefile
   freeswitch/branches/cparker/src/mod/codecs/mod_speex/mod_speex.c
   freeswitch/branches/cparker/src/mod/dialplans/   (props changed)
   freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_directory/   (props changed)
   freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_directory/mod_dialplan_directory.c
   freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_xml/   (props changed)
   freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_xml/mod_dialplan_xml.c
   freeswitch/branches/cparker/src/mod/directories/   (props changed)
   freeswitch/branches/cparker/src/mod/directories/mod_ldap/   (props changed)
   freeswitch/branches/cparker/src/mod/directories/mod_ldap/Makefile
   freeswitch/branches/cparker/src/mod/directories/mod_ldap/mod_ldap.c
   freeswitch/branches/cparker/src/mod/dotnet/   (props changed)
   freeswitch/branches/cparker/src/mod/endpoints/   (props changed)
   freeswitch/branches/cparker/src/mod/endpoints/mod_dingaling/   (props changed)
   freeswitch/branches/cparker/src/mod/endpoints/mod_dingaling/Makefile
   freeswitch/branches/cparker/src/mod/endpoints/mod_dingaling/mod_dingaling.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_iax/   (props changed)
   freeswitch/branches/cparker/src/mod/endpoints/mod_iax/Makefile
   freeswitch/branches/cparker/src/mod/endpoints/mod_iax/mod_iax.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_opal/   (props changed)
   freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/   (props changed)
   freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/Makefile
   freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/mod_portaudio.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pa_ringbuffer.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pa_ringbuffer.h
   freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pablio.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pablio.h
   freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/   (props changed)
   freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/Makefile
   freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/mod_sofia.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/mod_sofia.vcproj
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/   (props changed)
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/Makefile
   freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/mod_wanpipe.c
   freeswitch/branches/cparker/src/mod/endpoints/mod_woomera/   (props changed)
   freeswitch/branches/cparker/src/mod/endpoints/mod_woomera/mod_woomera.c
   freeswitch/branches/cparker/src/mod/event_handlers/   (props changed)
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/   (props changed)
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/Makefile
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/basecdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/basecdr.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/baseregistry.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/cdrcontainer.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/cdrcontainer.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/csvcdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/csvcdr.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/curlcdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/curlcdr.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mod_cdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mod_cdr.vcproj
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mysqlcdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mysqlcdr.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/odbccdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/odbccdr.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/pddcdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/pddcdr.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/radiuscdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/sqlitecdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/sqlitecdr.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/xmlcdr.cpp
   freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/xmlcdr.h
   freeswitch/branches/cparker/src/mod/event_handlers/mod_event_multicast/   (props changed)
   freeswitch/branches/cparker/src/mod/event_handlers/mod_event_multicast/mod_event_multicast.c
   freeswitch/branches/cparker/src/mod/event_handlers/mod_event_socket/   (props changed)
   freeswitch/branches/cparker/src/mod/event_handlers/mod_event_socket/mod_event_socket.c
   freeswitch/branches/cparker/src/mod/event_handlers/mod_event_test/   (props changed)
   freeswitch/branches/cparker/src/mod/event_handlers/mod_event_test/mod_event_test.c
   freeswitch/branches/cparker/src/mod/event_handlers/mod_radius_cdr/mod_radius_cdr.c
   freeswitch/branches/cparker/src/mod/event_handlers/mod_xmpp_event/   (props changed)
   freeswitch/branches/cparker/src/mod/event_handlers/mod_xmpp_event/Makefile
   freeswitch/branches/cparker/src/mod/event_handlers/mod_xmpp_event/mod_xmpp_event.c
   freeswitch/branches/cparker/src/mod/event_handlers/mod_zeroconf/   (props changed)
   freeswitch/branches/cparker/src/mod/event_handlers/mod_zeroconf/Makefile
   freeswitch/branches/cparker/src/mod/event_handlers/mod_zeroconf/mod_zeroconf.c
   freeswitch/branches/cparker/src/mod/formats/   (props changed)
   freeswitch/branches/cparker/src/mod/formats/mod_native_file/   (props changed)
   freeswitch/branches/cparker/src/mod/formats/mod_native_file/mod_native_file.c
   freeswitch/branches/cparker/src/mod/formats/mod_sndfile/   (props changed)
   freeswitch/branches/cparker/src/mod/formats/mod_sndfile/Makefile
   freeswitch/branches/cparker/src/mod/formats/mod_sndfile/mod_sndfile.c
   freeswitch/branches/cparker/src/mod/languages/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_mono/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_mono/Makefile
   freeswitch/branches/cparker/src/mod/languages/mod_mono/mod_mono.c
   freeswitch/branches/cparker/src/mod/languages/mod_perl/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_perl/Makefile
   freeswitch/branches/cparker/src/mod/languages/mod_perl/fs_perl.pm
   freeswitch/branches/cparker/src/mod/languages/mod_perl/mod_perl.c
   freeswitch/branches/cparker/src/mod/languages/mod_perl/perlxsi.c
   freeswitch/branches/cparker/src/mod/languages/mod_perl/switch_swig_wrap.c
   freeswitch/branches/cparker/src/mod/languages/mod_python/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_python/Makefile
   freeswitch/branches/cparker/src/mod/languages/mod_python/freeswitch_python.h
   freeswitch/branches/cparker/src/mod/languages/mod_python/mod_python.c
   freeswitch/branches/cparker/src/mod/languages/mod_python/switch_swig_wrap.c
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/Makefile
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/mod_spidermonkey.c
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/mod_spidermonkey.h
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/sm.mak
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_core_db/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_core_db/Makefile
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_core_db/mod_spidermonkey_core_db.c
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_etpan/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_etpan/Makefile
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_etpan/mod_spidermonkey_etpan.c
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_odbc/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_odbc/Makefile
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_odbc/mod_spidermonkey_odbc.c
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_skel/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_skel/Makefile
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_skel/mod_spidermonkey_skel.c
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_teletone/   (props changed)
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_teletone/Makefile
   freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_teletone/mod_spidermonkey_teletone.c
   freeswitch/branches/cparker/src/mod/loggers/   (props changed)
   freeswitch/branches/cparker/src/mod/loggers/mod_console/   (props changed)
   freeswitch/branches/cparker/src/mod/loggers/mod_console/mod_console.c
   freeswitch/branches/cparker/src/mod/loggers/mod_syslog/   (props changed)
   freeswitch/branches/cparker/src/mod/loggers/mod_syslog/mod_syslog.c
   freeswitch/branches/cparker/src/mod/say/   (props changed)
   freeswitch/branches/cparker/src/mod/say/mod_say_en/   (props changed)
   freeswitch/branches/cparker/src/mod/say/mod_say_en/mod_say_en.c
   freeswitch/branches/cparker/src/mod/timers/   (props changed)
   freeswitch/branches/cparker/src/mod/timers/mod_softtimer/   (props changed)
   freeswitch/branches/cparker/src/mod/timers/mod_softtimer/mod_softtimer.c
   freeswitch/branches/cparker/src/mod/xml_int/   (props changed)
   freeswitch/branches/cparker/src/mod/xml_int/mod_xml_cdr/   (props changed)
   freeswitch/branches/cparker/src/mod/xml_int/mod_xml_cdr/mod_xml_cdr.c
   freeswitch/branches/cparker/src/mod/xml_int/mod_xml_cdr/mod_xml_cdr.vcproj
   freeswitch/branches/cparker/src/mod/xml_int/mod_xml_curl/   (props changed)
   freeswitch/branches/cparker/src/mod/xml_int/mod_xml_curl/Makefile
   freeswitch/branches/cparker/src/mod/xml_int/mod_xml_curl/mod_xml_curl.c
   freeswitch/branches/cparker/src/mod/xml_int/mod_xml_rpc/   (props changed)
   freeswitch/branches/cparker/src/mod/xml_int/mod_xml_rpc/Makefile
   freeswitch/branches/cparker/src/mod/xml_int/mod_xml_rpc/mod_xml_rpc.c
   freeswitch/branches/cparker/src/switch.c
   freeswitch/branches/cparker/src/switch_buffer.c
   freeswitch/branches/cparker/src/switch_caller.c
   freeswitch/branches/cparker/src/switch_channel.c
   freeswitch/branches/cparker/src/switch_config.c
   freeswitch/branches/cparker/src/switch_console.c
   freeswitch/branches/cparker/src/switch_core.c
   freeswitch/branches/cparker/src/switch_event.c
   freeswitch/branches/cparker/src/switch_ivr.c
   freeswitch/branches/cparker/src/switch_loadable_module.c
   freeswitch/branches/cparker/src/switch_log.c
   freeswitch/branches/cparker/src/switch_resample.c
   freeswitch/branches/cparker/src/switch_rtp.c
   freeswitch/branches/cparker/src/switch_stun.c
   freeswitch/branches/cparker/src/switch_swig.c
   freeswitch/branches/cparker/src/switch_utils.c
   freeswitch/branches/cparker/src/switch_xml.c
   freeswitch/branches/cparker/w32/Library/FreeSwitchCore.vcproj

Log:
Merge of trunk revisions 4419 to 5008 into cparker branch

Modified: freeswitch/branches/cparker/Freeswitch.sln
==============================================================================
--- freeswitch/branches/cparker/Freeswitch.sln	(original)
+++ freeswitch/branches/cparker/Freeswitch.sln	Tue Apr 24 10:14:28 2007
@@ -3,22 +3,20 @@
 # Visual Studio 2005
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeSwitchConsole", "w32\Console\FreeSwitchConsole.vcproj", "{1AF3A893-F7BE-43DD-B697-8AB2397C0D67}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeSwitchCoreLib", "w32\Library\FreeSwitchCore.vcproj", "{202D7A4E-760D-4D0E-AFA1-D7459CED30FF}"
 	ProjectSection(ProjectDependencies) = postProject
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{EEF031CB-FED8-451E-A471-91EC8D4F6750} = {EEF031CB-FED8-451E-A471-91EC8D4F6750}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{89385C74-5860-4174-9CAF-A39E7C48909C} = {89385C74-5860-4174-9CAF-A39E7C48909C}
-		{8D04B550-D240-4A44-8A18-35DA3F7038D9} = {8D04B550-D240-4A44-8A18-35DA3F7038D9}
 		{50AD0E28-B8D7-4FCC-8FC3-599F6AC69761} = {50AD0E28-B8D7-4FCC-8FC3-599F6AC69761}
+		{8D04B550-D240-4A44-8A18-35DA3F7038D9} = {8D04B550-D240-4A44-8A18-35DA3F7038D9}
+		{89385C74-5860-4174-9CAF-A39E7C48909C} = {89385C74-5860-4174-9CAF-A39E7C48909C}
+		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{EEF031CB-FED8-451E-A471-91EC8D4F6750} = {EEF031CB-FED8-451E-A471-91EC8D4F6750}
+		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
+		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_g729", "src\mod\codecs\mod_g729\mod_g729.vcproj", "{1D95CD95-0DE2-48C3-AC23-D5C7D1C9C0F0}"
@@ -28,42 +26,34 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_gsm", "src\mod\codecs\mod_gsm\mod_gsm.vcproj", "{4926323F-4EA8-4B7D-A3D3-65488725988F}"
 	ProjectSection(ProjectDependencies) = postProject
-		{8FD2E297-4096-47E5-9258-C48FF1841523} = {8FD2E297-4096-47E5-9258-C48FF1841523}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{8FD2E297-4096-47E5-9258-C48FF1841523} = {8FD2E297-4096-47E5-9258-C48FF1841523}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_xmpp_event", "src\mod\event_handlers\mod_xmpp_event\mod_xmpp_event.vcproj", "{F10BE67C-A8FF-4CB2-AF29-D46D2590DC59}"
 	ProjectSection(ProjectDependencies) = postProject
-		{E727E8F6-935D-46FE-8B0E-37834748A0E3} = {E727E8F6-935D-46FE-8B0E-37834748A0E3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{E727E8F6-935D-46FE-8B0E-37834748A0E3} = {E727E8F6-935D-46FE-8B0E-37834748A0E3}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_sndfile", "src\mod\formats\mod_sndfile\mod_sndfile.vcproj", "{AFAC0568-7548-42D5-9F6A-8D3400A1E4F6}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{3D0370CA-BED2-4657-A475-32375CBCB6E4} = {3D0370CA-BED2-4657-A475-32375CBCB6E4}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{3D0370CA-BED2-4657-A475-32375CBCB6E4} = {3D0370CA-BED2-4657-A475-32375CBCB6E4}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_bridgecall", "src\mod\applications\mod_bridgecall\mod_bridgecall.vcproj", "{E1794405-29D4-466D-9BE3-DD2344C2A663}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_event_test", "src\mod\event_handlers\mod_event_test\mod_event_test.vcproj", "{3A2A7795-C216-4FFF-B8EF-4D17A84BACCC}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_g711", "src\mod\codecs\mod_g711\mod_g711.vcproj", "{B1FE4613-3F4B-4DAF-9714-2472BF8F56AE}"
@@ -73,28 +63,22 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_iax", "src\mod\endpoints\mod_iax\mod_iax.vcproj", "{3A5B9131-F20C-4A85-9447-6C1610941CEE}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{5CC054B7-6DAA-46BF-9A08-3B33B83E8D3E} = {5CC054B7-6DAA-46BF-9A08-3B33B83E8D3E}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{5CC054B7-6DAA-46BF-9A08-3B33B83E8D3E} = {5CC054B7-6DAA-46BF-9A08-3B33B83E8D3E}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_playback", "src\mod\applications\mod_playback\mod_playback.vcproj", "{78100236-7CEA-4948-96CC-E8ED3160329C}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_PortAudio", "src\mod\endpoints\mod_portaudio\mod_PortAudio.vcproj", "{5FD31A25-5D83-4794-8BEE-904DAD84CE71}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{0A18A071-125E-442F-AFF7-A3F68ABECF99} = {0A18A071-125E-442F-AFF7-A3F68ABECF99}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{0A18A071-125E-442F-AFF7-A3F68ABECF99} = {0A18A071-125E-442F-AFF7-A3F68ABECF99}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_l16", "src\mod\codecs\mod_l16\mod_l16.vcproj", "{5844AFE1-AA3E-4BDB-A9EF-119AEF19DF88}"
@@ -104,24 +88,20 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_softtimer", "src\mod\timers\mod_softtimer\mod_softtimer.vcproj", "{DCC13474-28DF-47CA-A8EB-72F8CE9A78C5}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_speex", "src\mod\codecs\mod_speex\mod_speex.vcproj", "{5580D60E-0F77-4716-9CD4-B8E5986FA375}"
 	ProjectSection(ProjectDependencies) = postProject
-		{1C469CDD-A3AF-4A94-A592-B2CF12F2D918} = {1C469CDD-A3AF-4A94-A592-B2CF12F2D918}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{1C469CDD-A3AF-4A94-A592-B2CF12F2D918} = {1C469CDD-A3AF-4A94-A592-B2CF12F2D918}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_woomera", "src\mod\endpoints\mod_woomera\mod_woomera.vcproj", "{FE3540C5-3303-46E0-A69E-D92F775687F1}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Codecs", "Codecs", "{F881ADA2-2F1A-4046-9FEB-191D9422D781}"
@@ -144,19 +124,14 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_dialplan_xml", "src\mod\dialplans\mod_dialplan_xml\mod_dialplan_xml.vcproj", "{07113B25-D3AF-4E04-BA77-4CD1171F022C}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{8D04B550-D240-4A44-8A18-35DA3F7038D9} = {8D04B550-D240-4A44-8A18-35DA3F7038D9}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_ivrtest", "src\mod\applications\mod_ivrtest\mod_ivrtest.vcproj", "{419AA391-5F3F-4BFE-A869-9D154D62A792}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{54435603-DBB4-11D2-8724-00A0C9A8B90C}") = "FreeSwitchSetup", "w32\Setup\Setup.vdproj", "{B17FFBE6-A942-4056-8346-B624FB5D995B}"
@@ -170,28 +145,22 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_dialplan_directory", "src\mod\dialplans\mod_dialplan_directory\mod_dialplan_directory.vcproj", "{A27CCA23-1541-4337-81A4-F0A6413078A0}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_zeroconf", "src\mod\event_handlers\mod_zeroconf\mod_zeroconf.vcproj", "{C7705DC4-2088-493E-AF8D-65BC6D65C125}"
 	ProjectSection(ProjectDependencies) = postProject
-		{0D826AF5-0506-4C50-BB8B-7DB019AC21AE} = {0D826AF5-0506-4C50-BB8B-7DB019AC21AE}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{49C34584-B6DA-448F-83CF-27584DC9FC90} = {49C34584-B6DA-448F-83CF-27584DC9FC90}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{49C34584-B6DA-448F-83CF-27584DC9FC90} = {49C34584-B6DA-448F-83CF-27584DC9FC90}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{0D826AF5-0506-4C50-BB8B-7DB019AC21AE} = {0D826AF5-0506-4C50-BB8B-7DB019AC21AE}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_event_multicast", "src\mod\event_handlers\mod_event_multicast\mod_event_multicast.vcproj", "{784113EF-44D9-4949-835D-7065D3C7AD08}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libteletone", "libs\libteletone\libteletone.vcproj", "{89385C74-5860-4174-9CAF-A39E7C48909C}"
@@ -200,14 +169,10 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_spidermonkey", "src\mod\languages\mod_spidermonkey\mod_spidermonkey.vcproj", "{1AD3F51E-BBB6-4090-BA39-9DFAB1EF1F5F}"
 	ProjectSection(ProjectDependencies) = postProject
-		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{87EE9DA4-DE1E-4448-8324-183C98DCA588} = {87EE9DA4-DE1E-4448-8324-183C98DCA588}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{89385C74-5860-4174-9CAF-A39E7C48909C} = {89385C74-5860-4174-9CAF-A39E7C48909C}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{87EE9DA4-DE1E-4448-8324-183C98DCA588} = {87EE9DA4-DE1E-4448-8324-183C98DCA588}
+		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
 	EndProjectSection
 EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ASR-TTS", "ASR-TTS", "{4CF6A6AC-07DE-4B9E-ABE1-7F98B64E0BB0}"
@@ -229,36 +194,28 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_echo", "src\mod\applications\mod_echo\mod_echo.vcproj", "{0E2C6395-13B9-46E5-9264-8859D346018D}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_ilbc", "src\mod\codecs\mod_ilbc\mod_ilbc.vcproj", "{D3EC0AFF-76FC-4210-A825-9A17410660A3}"
 	ProjectSection(ProjectDependencies) = postProject
-		{989BB874-7AF1-44CB-8E5C-CC8113D267E8} = {989BB874-7AF1-44CB-8E5C-CC8113D267E8}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{989BB874-7AF1-44CB-8E5C-CC8113D267E8} = {989BB874-7AF1-44CB-8E5C-CC8113D267E8}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_dingaling", "src\mod\endpoints\mod_dingaling\mod_dingaling.vcproj", "{FFAA4C52-3A53-4F99-90C1-D59D1F0427F3}"
 	ProjectSection(ProjectDependencies) = postProject
-		{E727E8F6-935D-46FE-8B0E-37834748A0E3} = {E727E8F6-935D-46FE-8B0E-37834748A0E3}
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 		{1906D736-08BD-4EE1-924F-B536249B9A54} = {1906D736-08BD-4EE1-924F-B536249B9A54}
+		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{E727E8F6-935D-46FE-8B0E-37834748A0E3} = {E727E8F6-935D-46FE-8B0E-37834748A0E3}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_commands", "src\mod\applications\mod_commands\mod_commands.vcproj", "{30A5B29C-983E-4580-9FD0-D647CCDCC7EB}"
 	ProjectSection(ProjectDependencies) = postProject
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Loggers", "Loggers", "{A7AB4405-FDB7-4853-9FBB-1516B1C3D80A}"
@@ -272,58 +229,42 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_xml_rpc", "src\mod\xml_int\mod_xml_rpc\mod_xml_rpc.vcproj", "{CBEC7225-0C21-4DA8-978E-1F158F8AD950}"
 	ProjectSection(ProjectDependencies) = postProject
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{155844C3-EC5F-407F-97A4-A2DDADED9B2F} = {155844C3-EC5F-407F-97A4-A2DDADED9B2F}
-		{87EE9DA4-DE1E-4448-8324-183C98DCA588} = {87EE9DA4-DE1E-4448-8324-183C98DCA588}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{A3FE0076-B366-429D-A238-D7304DA7D3C1} = {A3FE0076-B366-429D-A238-D7304DA7D3C1}
-		{356EC96D-4C9F-47B5-9083-FC328B87BA94} = {356EC96D-4C9F-47B5-9083-FC328B87BA94}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{356EC96D-4C9F-47B5-9083-FC328B87BA94} = {356EC96D-4C9F-47B5-9083-FC328B87BA94}
+		{A3FE0076-B366-429D-A238-D7304DA7D3C1} = {A3FE0076-B366-429D-A238-D7304DA7D3C1}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{87EE9DA4-DE1E-4448-8324-183C98DCA588} = {87EE9DA4-DE1E-4448-8324-183C98DCA588}
+		{155844C3-EC5F-407F-97A4-A2DDADED9B2F} = {155844C3-EC5F-407F-97A4-A2DDADED9B2F}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_rss", "src\mod\applications\mod_rss\mod_rss.vcproj", "{B69247FA-ECD6-40ED-8E44-5CA6C3BAF9A4}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_conference", "src\mod\applications\mod_conference\mod_conference.vcproj", "{C24FB505-05D7-4319-8485-7540B44C8603}"
 	ProjectSection(ProjectDependencies) = postProject
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_dptools", "src\mod\applications\mod_dptools\mod_dptools.vcproj", "{B5881A85-FE70-4F64-8607-2CAAE52669C6}"
 	ProjectSection(ProjectDependencies) = postProject
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_event_socket", "src\mod\event_handlers\mod_event_socket\mod_event_socket.vcproj", "{05515420-16DE-4E63-BE73-85BE85BA5142}"
 	ProjectSection(ProjectDependencies) = postProject
-		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
 		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
+		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_cdr", "src\mod\event_handlers\mod_cdr\mod_cdr.vcproj", "{3D1EED36-A510-4EDB-B4D9-4E0F4A5EC2A8}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Libraries", "_Libraries", "{EB910B0D-F27D-4B62-B67B-DE834C99AC5B}"
@@ -336,6 +277,7 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libdingaling", "libs\libdingaling\libdingaling.vcproj", "{1906D736-08BD-4EE1-924F-B536249B9A54}"
 	ProjectSection(ProjectDependencies) = postProject
+		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{E727E8F6-935D-46FE-8B0E-37834748A0E3} = {E727E8F6-935D-46FE-8B0E-37834748A0E3}
 	EndProjectSection
 EndProject
@@ -361,8 +303,8 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libaprutil", "libs\win32\apr-util\libaprutil.vcproj", "{F057DA7F-79E5-4B00-845C-EF446EF055E3}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
 		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
 	EndProjectSection
 EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Downloads", "_Downloads", "{C120A020-773F-4EA3-923F-B67AF28B750D}"
@@ -380,8 +322,8 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mDNSResponder static library", "libs\win32\howl\libmDNSResponder.vcproj", "{49C34584-B6DA-448F-83CF-27584DC9FC90}"
 	ProjectSection(ProjectDependencies) = postProject
-		{0D826AF5-0506-4C50-BB8B-7DB019AC21AE} = {0D826AF5-0506-4C50-BB8B-7DB019AC21AE}
 		{5927104D-C14C-4AC8-925C-4AB681762E75} = {5927104D-C14C-4AC8-925C-4AB681762E75}
+		{0D826AF5-0506-4C50-BB8B-7DB019AC21AE} = {0D826AF5-0506-4C50-BB8B-7DB019AC21AE}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libsndfile", "libs\win32\libsndfile\libsndfile.vcproj", "{3D0370CA-BED2-4657-A475-32375CBCB6E4}"
@@ -401,49 +343,40 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_sofia", "src\mod\endpoints\mod_sofia\mod_sofia.vcproj", "{0DF3ABD0-DDC0-4265-B778-07C66780979B}"
 	ProjectSection(ProjectDependencies) = postProject
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{70A49BC2-7500-41D0-B75D-EDCC5BE987A0} = {70A49BC2-7500-41D0-B75D-EDCC5BE987A0}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 		{DF018947-0FFF-4EB3-BDEE-441DC81DA7A4} = {DF018947-0FFF-4EB3-BDEE-441DC81DA7A4}
+		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{70A49BC2-7500-41D0-B75D-EDCC5BE987A0} = {70A49BC2-7500-41D0-B75D-EDCC5BE987A0}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libg726", "libs\codec\g726\libg726.vcproj", "{5A6A281A-AA50-470A-8305-202BDA1CD1BF}"
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_g726", "src\mod\codecs\mod_g726\mod_g726.vcproj", "{486369EB-F150-4B56-BCC8-77B9E18FF5F5}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 		{5A6A281A-AA50-470A-8305-202BDA1CD1BF} = {5A6A281A-AA50-470A-8305-202BDA1CD1BF}
+		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libg7xx", "libs\codec\g7xx\libg7xx.vcproj", "{D71E7338-8D9C-4FE4-A15F-D5CC60202C7C}"
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_g722", "src\mod\codecs\mod_g722\mod_g722.vcproj", "{D42518CC-7475-454D-B392-0E132C07D761}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 		{D71E7338-8D9C-4FE4-A15F-D5CC60202C7C} = {D71E7338-8D9C-4FE4-A15F-D5CC60202C7C}
+		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_park", "src\mod\applications\mod_park\mod_park.vcproj", "{2740F45C-475A-4DE0-BCED-6E2E5F6C4B8B}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libsofia_sip_ua_static", "libs\win32\sofia\libsofia_sip_ua_static.vcproj", "{70A49BC2-7500-41D0-B75D-EDCC5BE987A0}"
 	ProjectSection(ProjectDependencies) = postProject
-		{8B3B4C4C-13C2-446C-BEB0-F412CC2CFB9A} = {8B3B4C4C-13C2-446C-BEB0-F412CC2CFB9A}
 		{DF018947-0FFF-4EB3-BDEE-441DC81DA7A4} = {DF018947-0FFF-4EB3-BDEE-441DC81DA7A4}
+		{8B3B4C4C-13C2-446C-BEB0-F412CC2CFB9A} = {8B3B4C4C-13C2-446C-BEB0-F412CC2CFB9A}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Download PTHREAD", "libs\win32\Download PTHREAD.vcproj", "{8B3B4C4C-13C2-446C-BEB0-F412CC2CFB9A}"
@@ -455,82 +388,67 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_g723_1", "src\mod\codecs\mod_g723_1\mod_g723_1.vcproj", "{FEA1EEF7-876F-48DE-88BF-C0E3E606D758}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_native_file", "src\mod\formats\mod_native_file\mod_native_file.vcproj", "{9254C4B0-6F60-42B6-BB3A-36D63FC001C7}"
 	ProjectSection(ProjectDependencies) = postProject
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FreeSwitch.NET", "src\dotnet\FreeSwitch.NET.csproj", "{251CAABC-16C3-4593-A491-603B908094E0}"
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_spidermonkey_core_db", "src\mod\languages\mod_spidermonkey_core_db\mod_spidermonkey_core_db.vcproj", "{ACFFF684-4D19-4D48-AF12-88EA1D778BDF}"
 	ProjectSection(ProjectDependencies) = postProject
-		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 		{1AD3F51E-BBB6-4090-BA39-9DFAB1EF1F5F} = {1AD3F51E-BBB6-4090-BA39-9DFAB1EF1F5F}
+		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_spidermonkey_teletone", "src\mod\languages\mod_spidermonkey_teletone\mod_spidermonkey_teletone.vcproj", "{8F992C49-6C51-412F-B2A3-34EAB708EB65}"
 	ProjectSection(ProjectDependencies) = postProject
-		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{89385C74-5860-4174-9CAF-A39E7C48909C} = {89385C74-5860-4174-9CAF-A39E7C48909C}
-		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 		{1AD3F51E-BBB6-4090-BA39-9DFAB1EF1F5F} = {1AD3F51E-BBB6-4090-BA39-9DFAB1EF1F5F}
+		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{89385C74-5860-4174-9CAF-A39E7C48909C} = {89385C74-5860-4174-9CAF-A39E7C48909C}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libudns", "libs\win32\udns\libudns.vcproj", "{4043FC6A-9A30-4577-8AD5-9B233C9575D8}"
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_enum", "src\mod\applications\mod_enum\mod_enum.vcproj", "{71A967D5-0E99-4CEF-A587-98836EE6F2EF}"
 	ProjectSection(ProjectDependencies) = postProject
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
-		{4043FC6A-9A30-4577-8AD5-9B233C9575D8} = {4043FC6A-9A30-4577-8AD5-9B233C9575D8}
-		{8D04B550-D240-4A44-8A18-35DA3F7038D9} = {8D04B550-D240-4A44-8A18-35DA3F7038D9}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{4043FC6A-9A30-4577-8AD5-9B233C9575D8} = {4043FC6A-9A30-4577-8AD5-9B233C9575D8}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_spidermonkey_etpan", "src\mod\languages\mod_spidermonkey_etpan\mod_spidermonkey_etpan.vcproj", "{D6C82F86-2B05-4A7F-8CC6-D2592E66FBB9}"
 	ProjectSection(ProjectDependencies) = postProject
-		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
-		{BA4DED3C-E56F-4484-BFC3-9C13E461A1BE} = {BA4DED3C-E56F-4484-BFC3-9C13E461A1BE}
 		{1AD3F51E-BBB6-4090-BA39-9DFAB1EF1F5F} = {1AD3F51E-BBB6-4090-BA39-9DFAB1EF1F5F}
+		{BA4DED3C-E56F-4484-BFC3-9C13E461A1BE} = {BA4DED3C-E56F-4484-BFC3-9C13E461A1BE}
+		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_spidermonkey_odbc", "src\mod\languages\mod_spidermonkey_odbc\mod_spidermonkey_odbc.vcproj", "{0A6B5EA5-6E9B-4A51-931F-ED25AA87B4DF}"
 	ProjectSection(ProjectDependencies) = postProject
-		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 		{1AD3F51E-BBB6-4090-BA39-9DFAB1EF1F5F} = {1AD3F51E-BBB6-4090-BA39-9DFAB1EF1F5F}
+		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
+		{204FA0DE-305D-4414-AE2E-F195A23F390D} = {204FA0DE-305D-4414-AE2E-F195A23F390D}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libetpan", "libs\win32\etpan\libetpan.vcproj", "{BA4DED3C-E56F-4484-BFC3-9C13E461A1BE}"
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_xml_curl", "src\mod\xml_int\mod_xml_curl\mod_xml_curl.vcproj", "{AB91A099-7690-4ECF-8994-E458F4EA1ED4}"
 	ProjectSection(ProjectDependencies) = postProject
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
-		{101130D1-3EA6-4ED2-B65D-CEB5243A20ED} = {101130D1-3EA6-4ED2-B65D-CEB5243A20ED}
 		{87EE9DA4-DE1E-4448-8324-183C98DCA588} = {87EE9DA4-DE1E-4448-8324-183C98DCA588}
 		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{F057DA7F-79E5-4B00-845C-EF446EF055E3} = {F057DA7F-79E5-4B00-845C-EF446EF055E3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 	EndProjectSection
 EndProject
@@ -538,17 +456,16 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_say_en", "src\mod\say\mod_say_en\mod_say_en.vcproj", "{988CACF7-3FCB-4992-BE69-77872AE67DC8}"
 	ProjectSection(ProjectDependencies) = postProject
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "portaudio", "libs\portaudio\build\msvc\portaudio.vcproj", "{0A18A071-125E-442F-AFF7-A3F68ABECF99}"
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_xml_cdr", "src\mod\xml_int\mod_xml_cdr\mod_xml_cdr.vcproj", "{08DAD348-9E0A-4A2E-97F1-F1E7E24A7836}"
 	ProjectSection(ProjectDependencies) = postProject
-		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3} = {6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
+		{F6C55D93-B927-4483-BB69-15AEF3DD2DFF} = {F6C55D93-B927-4483-BB69-15AEF3DD2DFF}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_amr", "src\mod\codecs\mod_amr\mod_amr.vcproj", "{8DEB383C-4091-4F42-A56F-C9E46D552D79}"
@@ -556,6 +473,135 @@
 		{202D7A4E-760D-4D0E-AFA1-D7459CED30FF} = {202D7A4E-760D-4D0E-AFA1-D7459CED30FF}
 	EndProjectSection
 EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Config", "_Config", "{57D119DC-484F-420F-B9E9-8589FD9A8DF8}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Default", "Default", "{3B08FEFD-4D3D-4C16-BA94-EE83509E32A0}"
+	ProjectSection(SolutionItems) = preProject
+		conf\conference.conf.xml = conf\conference.conf.xml
+		conf\console.conf.xml = conf\console.conf.xml
+		conf\default_context.xml = conf\default_context.xml
+		conf\dialplan_directory.conf.xml = conf\dialplan_directory.conf.xml
+		conf\dingaling.conf.xml = conf\dingaling.conf.xml
+		conf\directory.xml = conf\directory.xml
+		conf\enum.conf.xml = conf\enum.conf.xml
+		conf\event_multicast.conf.xml = conf\event_multicast.conf.xml
+		conf\event_socket.conf.xml = conf\event_socket.conf.xml
+		conf\freeswitch.xml = conf\freeswitch.xml
+		conf\freeswitch_combined.xml = conf\freeswitch_combined.xml
+		conf\iax.conf.xml = conf\iax.conf.xml
+		conf\ivr.conf.xml = conf\ivr.conf.xml
+		conf\lang_en.xml = conf\lang_en.xml
+		conf\lang_fr.xml = conf\lang_fr.xml
+		conf\mod_cdr.conf.xml = conf\mod_cdr.conf.xml
+		conf\modules.conf.xml = conf\modules.conf.xml
+		conf\portaudio.conf.xml = conf\portaudio.conf.xml
+		conf\rss.conf.xml = conf\rss.conf.xml
+		conf\sofia.conf.xml = conf\sofia.conf.xml
+		conf\spidermonkey.conf.xml = conf\spidermonkey.conf.xml
+		conf\switch.conf.xml = conf\switch.conf.xml
+		conf\syslog.conf.xml = conf\syslog.conf.xml
+		conf\wanpipe.conf.xml = conf\wanpipe.conf.xml
+		conf\woomera.conf.xml = conf\woomera.conf.xml
+		conf\xml_curl.conf.xml = conf\xml_curl.conf.xml
+		conf\xml_rpc.conf.xml = conf\xml_rpc.conf.xml
+		conf\xmpp_event.conf.xml = conf\xmpp_event.conf.xml
+		conf\zeroconf.conf.xml = conf\zeroconf.conf.xml
+	EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Release", "Release", "{7BFD517E-7F8F-4A40-A78E-8D3632738227}"
+	ProjectSection(SolutionItems) = preProject
+		release\conf\conference.conf.xml = release\conf\conference.conf.xml
+		release\conf\console.conf.xml = release\conf\console.conf.xml
+		release\conf\default_context.xml = release\conf\default_context.xml
+		release\conf\dialplan_directory.conf.xml = release\conf\dialplan_directory.conf.xml
+		release\conf\dingaling.conf.xml = release\conf\dingaling.conf.xml
+		release\conf\directory.xml = release\conf\directory.xml
+		release\conf\enum.conf.xml = release\conf\enum.conf.xml
+		release\conf\event_multicast.conf.xml = release\conf\event_multicast.conf.xml
+		release\conf\event_socket.conf.xml = release\conf\event_socket.conf.xml
+		release\conf\freeswitch.xml = release\conf\freeswitch.xml
+		release\conf\freeswitch_combined.xml = release\conf\freeswitch_combined.xml
+		release\conf\iax.conf.xml = release\conf\iax.conf.xml
+		release\conf\ivr.conf.xml = release\conf\ivr.conf.xml
+		release\conf\lang_en.xml = release\conf\lang_en.xml
+		release\conf\lang_fr.xml = release\conf\lang_fr.xml
+		release\conf\mod_cdr.conf.xml = release\conf\mod_cdr.conf.xml
+		release\conf\modules.conf.xml = release\conf\modules.conf.xml
+		release\conf\portaudio.conf.xml = release\conf\portaudio.conf.xml
+		release\conf\rss.conf.xml = release\conf\rss.conf.xml
+		release\conf\sofia.conf.xml = release\conf\sofia.conf.xml
+		release\conf\spidermonkey.conf.xml = release\conf\spidermonkey.conf.xml
+		release\conf\switch.conf.xml = release\conf\switch.conf.xml
+		release\conf\syslog.conf.xml = release\conf\syslog.conf.xml
+		release\conf\wanpipe.conf.xml = release\conf\wanpipe.conf.xml
+		release\conf\woomera.conf.xml = release\conf\woomera.conf.xml
+		release\conf\xml_curl.conf.xml = release\conf\xml_curl.conf.xml
+		release\conf\xml_rpc.conf.xml = release\conf\xml_rpc.conf.xml
+		release\conf\xmpp_event.conf.xml = release\conf\xmpp_event.conf.xml
+		release\conf\zeroconf.conf.xml = release\conf\zeroconf.conf.xml
+	EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Debug", "Debug", "{6374D55C-FABE-4A02-9CF1-4145308A56C5}"
+	ProjectSection(SolutionItems) = preProject
+		debug\conf\conference.conf.xml = debug\conf\conference.conf.xml
+		debug\conf\console.conf.xml = debug\conf\console.conf.xml
+		debug\conf\default_context.xml = debug\conf\default_context.xml
+		debug\conf\dialplan_directory.conf.xml = debug\conf\dialplan_directory.conf.xml
+		debug\conf\dingaling.conf.xml = debug\conf\dingaling.conf.xml
+		debug\conf\directory.xml = debug\conf\directory.xml
+		debug\conf\enum.conf.xml = debug\conf\enum.conf.xml
+		debug\conf\event_multicast.conf.xml = debug\conf\event_multicast.conf.xml
+		debug\conf\event_socket.conf.xml = debug\conf\event_socket.conf.xml
+		debug\conf\freeswitch.xml = debug\conf\freeswitch.xml
+		debug\conf\freeswitch_combined.xml = debug\conf\freeswitch_combined.xml
+		debug\conf\iax.conf.xml = debug\conf\iax.conf.xml
+		debug\conf\ivr.conf.xml = debug\conf\ivr.conf.xml
+		debug\conf\lang_en.xml = debug\conf\lang_en.xml
+		debug\conf\lang_fr.xml = debug\conf\lang_fr.xml
+		debug\conf\mod_cdr.conf.xml = debug\conf\mod_cdr.conf.xml
+		debug\conf\modules.conf.xml = debug\conf\modules.conf.xml
+		debug\conf\portaudio.conf.xml = debug\conf\portaudio.conf.xml
+		debug\conf\rss.conf.xml = debug\conf\rss.conf.xml
+		debug\conf\sofia.conf.xml = debug\conf\sofia.conf.xml
+		debug\conf\spidermonkey.conf.xml = debug\conf\spidermonkey.conf.xml
+		debug\conf\switch.conf.xml = debug\conf\switch.conf.xml
+		debug\conf\syslog.conf.xml = debug\conf\syslog.conf.xml
+		debug\conf\wanpipe.conf.xml = debug\conf\wanpipe.conf.xml
+		debug\conf\woomera.conf.xml = debug\conf\woomera.conf.xml
+		debug\conf\xml_curl.conf.xml = debug\conf\xml_curl.conf.xml
+		debug\conf\xml_rpc.conf.xml = debug\conf\xml_rpc.conf.xml
+		debug\conf\xmpp_event.conf.xml = debug\conf\xmpp_event.conf.xml
+		debug\conf\zeroconf.conf.xml = debug\conf\zeroconf.conf.xml
+	EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Build System", "_Build System", "{DB1024A8-41BF-4AD7-9AE6-13202230D1F3}"
+	ProjectSection(SolutionItems) = preProject
+		acsite.m4 = acsite.m4
+		build\addenv.sh = build\addenv.sh
+		build\build.sh = build\build.sh
+		build\buildlib.sh = build\buildlib.sh
+		build\checkversion.sh = build\checkversion.sh
+		configure.in = configure.in
+		Makefile.am = Makefile.am
+		build\modmake.sh = build\modmake.sh
+	EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "m4", "m4", "{CDE9B06A-3C27-4987-8FAE-DF1006BC705D}"
+	ProjectSection(SolutionItems) = preProject
+		build\config\ac_cflags_gcc_option.m4 = build\config\ac_cflags_gcc_option.m4
+		build\config\ac_cflags_sun_option.m4 = build\config\ac_cflags_sun_option.m4
+		build\config\ac_gcc_archflag.m4 = build\config\ac_gcc_archflag.m4
+		build\config\ac_gcc_x86_cpuid.m4 = build\config\ac_gcc_x86_cpuid.m4
+		build\config\ac_prog_gzip.m4 = build\config\ac_prog_gzip.m4
+		build\config\ac_prog_wget.m4 = build\config\ac_prog_wget.m4
+		build\config\ax_cc_maxopt.m4 = build\config\ax_cc_maxopt.m4
+		build\config\ax_cflags_warn_all_ansi.m4 = build\config\ax_cflags_warn_all_ansi.m4
+		build\config\ax_check_compiler_flags.m4 = build\config\ax_check_compiler_flags.m4
+		build\config\ax_compiler_vendor.m4 = build\config\ax_compiler_vendor.m4
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mod_h26x", "src\mod\codecs\mod_h26x\mod_h26x.vcproj", "{2C3C2423-234B-4772-8899-D3B137E5CA35}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Win32 = Debug|Win32
@@ -826,17 +872,17 @@
 		{EEF031CB-FED8-451E-A471-91EC8D4F6750}.Release|Win32.ActiveCfg = Release|Win32
 		{EEF031CB-FED8-451E-A471-91EC8D4F6750}.Release|Win32.Build.0 = Release|Win32
 		{EEF031CB-FED8-451E-A471-91EC8D4F6750}.Release|x64.ActiveCfg = Release|Win32
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Debug|Win32.ActiveCfg = Debug DLL|Win32
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Debug|Win32.Build.0 = Debug DLL|Win32
+		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Debug|Win32.ActiveCfg = Debug|Win32
+		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Debug|Win32.Build.0 = Debug|Win32
 		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Debug|x64.ActiveCfg = Debug|Win32
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Release|Win32.ActiveCfg = Release DLL|Win32
-		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Release|Win32.Build.0 = Release DLL|Win32
+		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Release|Win32.ActiveCfg = Release|Win32
+		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Release|Win32.Build.0 = Release|Win32
 		{6EDFEFD5-3596-4FA9-8EBA-B331547B35A3}.Release|x64.ActiveCfg = Release|Win32
-		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Debug|Win32.ActiveCfg = Debug DLL|Win32
-		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Debug|Win32.Build.0 = Debug DLL|Win32
+		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Debug|Win32.ActiveCfg = Debug|Win32
+		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Debug|Win32.Build.0 = Debug|Win32
 		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Debug|x64.ActiveCfg = Debug|Win32
-		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Release|Win32.ActiveCfg = Release DLL|Win32
-		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Release|Win32.Build.0 = Release DLL|Win32
+		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Release|Win32.ActiveCfg = Release|Win32
+		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Release|Win32.Build.0 = Release|Win32
 		{8D04B550-D240-4A44-8A18-35DA3F7038D9}.Release|x64.ActiveCfg = Release|Win32
 		{1CED5987-A529-46DC-B30F-870D85FF9C94}.Debug|Win32.ActiveCfg = Debug|Win32
 		{1CED5987-A529-46DC-B30F-870D85FF9C94}.Debug|Win32.Build.0 = Debug|Win32
@@ -1078,6 +1124,12 @@
 		{8DEB383C-4091-4F42-A56F-C9E46D552D79}.Release|Win32.ActiveCfg = Release Passthrough|Win32
 		{8DEB383C-4091-4F42-A56F-C9E46D552D79}.Release|Win32.Build.0 = Release Passthrough|Win32
 		{8DEB383C-4091-4F42-A56F-C9E46D552D79}.Release|x64.ActiveCfg = Release|Win32
+		{2C3C2423-234B-4772-8899-D3B137E5CA35}.Debug|Win32.ActiveCfg = Debug|Win32
+		{2C3C2423-234B-4772-8899-D3B137E5CA35}.Debug|Win32.Build.0 = Debug|Win32
+		{2C3C2423-234B-4772-8899-D3B137E5CA35}.Debug|x64.ActiveCfg = Debug|Win32
+		{2C3C2423-234B-4772-8899-D3B137E5CA35}.Release|Win32.ActiveCfg = Release|Win32
+		{2C3C2423-234B-4772-8899-D3B137E5CA35}.Release|Win32.Build.0 = Release|Win32
+		{2C3C2423-234B-4772-8899-D3B137E5CA35}.Release|x64.ActiveCfg = Release|Win32
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE
@@ -1093,6 +1145,7 @@
 		{D42518CC-7475-454D-B392-0E132C07D761} = {F881ADA2-2F1A-4046-9FEB-191D9422D781}
 		{FEA1EEF7-876F-48DE-88BF-C0E3E606D758} = {F881ADA2-2F1A-4046-9FEB-191D9422D781}
 		{8DEB383C-4091-4F42-A56F-C9E46D552D79} = {F881ADA2-2F1A-4046-9FEB-191D9422D781}
+		{2C3C2423-234B-4772-8899-D3B137E5CA35} = {F881ADA2-2F1A-4046-9FEB-191D9422D781}
 		{3A2A7795-C216-4FFF-B8EF-4D17A84BACCC} = {9ADF1E48-2F5C-4ED7-A893-596259FABFE0}
 		{F10BE67C-A8FF-4CB2-AF29-D46D2590DC59} = {9ADF1E48-2F5C-4ED7-A893-596259FABFE0}
 		{C7705DC4-2088-493E-AF8D-65BC6D65C125} = {9ADF1E48-2F5C-4ED7-A893-596259FABFE0}
@@ -1166,5 +1219,9 @@
 		{5927104D-C14C-4AC8-925C-4AB681762E75} = {C120A020-773F-4EA3-923F-B67AF28B750D}
 		{8B3B4C4C-13C2-446C-BEB0-F412CC2CFB9A} = {C120A020-773F-4EA3-923F-B67AF28B750D}
 		{988CACF7-3FCB-4992-BE69-77872AE67DC8} = {6CD61A1D-797C-470A-BE08-8C31B68BB336}
+		{3B08FEFD-4D3D-4C16-BA94-EE83509E32A0} = {57D119DC-484F-420F-B9E9-8589FD9A8DF8}
+		{7BFD517E-7F8F-4A40-A78E-8D3632738227} = {57D119DC-484F-420F-B9E9-8589FD9A8DF8}
+		{6374D55C-FABE-4A02-9CF1-4145308A56C5} = {57D119DC-484F-420F-B9E9-8589FD9A8DF8}
+		{CDE9B06A-3C27-4987-8FAE-DF1006BC705D} = {DB1024A8-41BF-4AD7-9AE6-13202230D1F3}
 	EndGlobalSection
 EndGlobal

Modified: freeswitch/branches/cparker/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/Makefile.am	(original)
+++ freeswitch/branches/cparker/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -1,85 +1,68 @@
 EXTRA_DIST =
-SUBDIRS = 
-AUTOMAKE_OPTS = gnu foreign
+SUBDIRS = . src
+AUTOMAKE_OPTS = foreign
 NAME=freeswitch
 PREFIX=$(prefix)
 
-AM_CFLAGS       = $(new_AM_CFLAGS)
-AM_CPPFLAGS = $(AM_CFLAGS)
-AM_LDFLAGS = $(new_AM_LDFLAGS)
-
-APR_CONFIG=$(prefix)/bin/apr-1-config
-APU_CONFIG=$(prefix)/bin/apu-1-config
-AM_CFLAGS  += -I$(PREFIX)/include $(shell $(APR_CONFIG) --cflags --cppflags --includes) -I${prefix}/include/srtp
-AM_LDFLAGS += -L$(PREFIX)/lib
-AM_LDFLAGS += $(shell $(APR_CONFIG) --link-ld --libs )
-AM_CFLAGS  += $(shell $(APU_CONFIG) --includes) 
-AM_LDFLAGS += $(shell $(APU_CONFIG) --link-ld --libs )
-AM_LDFLAGS += -lm -L/usr/local/lib/db42 -L/usr/local/lib
-AM_LDFLAGS += -lsqlite3 -lpcre
-OSARCH=$(shell uname -s)
+AM_CFLAGS   = $(SWITCH_AM_CFLAGS)
+AM_CPPFLAGS = $(SWITCH_AM_CXXFLAGS)
+AM_LDFLAGS  = $(SWITCH_AM_LDFLAGS)
+BASE        = $(switch_srcdir)
+OSARCH=`uname -s`
 
 if CRASHPROT
 AM_CFLAGS += -DCRASH_PROT
 endif
 
-AM_CFLAGS  +=-I$(PWD)/src/sqlite -I$(PWD) -I$(PWD)/src/include -I$(PREFIX)/include
-AM_CFLAGS 	+= -DSWITCH_MOD_DIR=\"$(PREFIX)/mod\"
-AM_CFLAGS	+= -DSWITCH_PREFIX_DIR=\"$(PREFIX)\"
-AM_CFLAGS	+= -DSWITCH_CONF_DIR=\"$(PREFIX)/conf\"
-AM_CFLAGS	+= -DSWITCH_DB_DIR=\"$(PREFIX)/db\"
-AM_CFLAGS	+= -DSWITCH_LOG_DIR=\"$(PREFIX)/log\"
-AM_CFLAGS	+= -DSWITCH_SCRIPT_DIR=\"$(PREFIX)/scripts\"
-AM_CFLAGS	+= -DSWITCH_HTDOCS_DIR=\"$(PREFIX)/htdocs\"
-AM_CFLAGS	+= -DSWITCH_GRAMMAR_DIR=\"$(PREFIX)/grammar\"
-
+.DEFAULT:
+	@cd src/mod && $(MAKE) $(AM_MAKEFLAGS) $@
 
 libfreeswitch_la_SOURCES	= \
-src/include/switch_am_config.h\
-src/include/switch.h\
-src/include/switch_apr.h\
-src/include/switch_buffer.h\
-src/include/switch_caller.h\
-src/include/switch_channel.h\
-src/include/switch_config.h\
-src/include/switch_console.h\
-src/include/switch_core.h\
-src/include/switch_event.h\
-src/include/switch_frame.h\
-src/include/switch_ivr.h\
-src/include/switch_loadable_module.h\
-src/include/switch_module_interfaces.h\
-src/include/switch_platform.h\
-src/include/switch_resample.h\
-src/include/switch_sqlite.h\
-src/include/switch_types.h\
-src/include/switch_utils.h\
-src/include/switch_version.h\
-src/include/switch_rtp.h\
-src/include/switch_stun.h\
-src/include/switch_log.h\
-src/include/switch_xml.h\
-src/switch_rtp.c\
+src/switch_apr.c \
 src/switch_buffer.c \
 src/switch_caller.c \
 src/switch_channel.c \
-src/switch_config.c \
 src/switch_console.c \
+src/switch_core_media_bug.c \
+src/switch_core_timer.c \
+src/switch_core_asr.c \
+src/switch_core_event_hook.c \
+src/switch_core_speech.c \
+src/switch_core_memory.c \
+src/switch_core_codec.c \
+src/switch_core_file.c \
+src/switch_core_hash.c \
+src/switch_core_sqldb.c \
+src/switch_core_session.c \
+src/switch_core_directory.c \
+src/switch_core_state_machine.c \
+src/switch_core_io.c \
+src/switch_core_rwlock.c \
+src/switch_core_port_allocator.c \
 src/switch_core.c \
+src/switch_scheduler.c \
+src/switch_core_db.c\
 src/switch_loadable_module.c \
 src/switch_utils.c \
 src/switch_event.c \
 src/switch_resample.c \
+src/switch_regex.c\
+src/switch_rtp.c\
+src/switch_ivr_bridge.c \
+src/switch_ivr_originate.c \
+src/switch_ivr_async.c \
+src/switch_ivr_play_say.c \
+src/switch_ivr_menu.c \
 src/switch_ivr.c \
 src/switch_stun.c\
 src/switch_log.c\
-src/switch_xml.c
+src/switch_xml.c\
+libs/libteletone/src/libteletone_detect.c\
+libs/libteletone/src/libteletone_generate.c
 
 
+library_includedir      = $(PREFIX)/include
 
-#bindir = $(PREFIX)/bin
-#libdir = $(PREFIX)/lib
-library_includedir	= $(PREFIX)/include
 library_include_HEADERS = \
 src/include/switch_am_config.h\
 src/include/switch.h\
@@ -87,9 +70,11 @@
 src/include/switch_buffer.h\
 src/include/switch_caller.h\
 src/include/switch_channel.h\
-src/include/switch_config.h\
 src/include/switch_console.h\
+src/include/switch_core_event_hook.h\
+src/include/switch_scheduler.h\
 src/include/switch_core.h\
+src/include/switch_core_db.h\
 src/include/switch_event.h\
 src/include/switch_frame.h\
 src/include/switch_ivr.h\
@@ -97,41 +82,87 @@
 src/include/switch_module_interfaces.h\
 src/include/switch_platform.h\
 src/include/switch_resample.h\
-src/include/switch_sqlite.h\
+src/include/switch_regex.h\
 src/include/switch_types.h\
 src/include/switch_utils.h\
 src/include/switch_rtp.h\
-src/include/switch_version.h\
 src/include/switch_stun.h\
 src/include/switch_log.h\
-src/include/switch_xml.h
-
-BUILT_SOURCES = version depends
-CLEANFILES = src/include/switch_version.h scripts/fsxs
-
+src/include/switch_xml.h\
+libs/libteletone/src/libteletone_detect.h\
+libs/libteletone/src/libteletone_generate.h\
+libs/libteletone/src/libteletone.h
+
+CORE_CFLAGS     = `$(switch_srcdir)/libs/apr/apr-1-config --cflags --cppflags --includes`
+CORE_CFLAGS    += `$(switch_srcdir)/libs/apr-util/apu-1-config --includes`
+CORE_CFLAGS    += -I$(switch_srcdir)/libs/sqlite
+CORE_CFLAGS    += -I$(switch_srcdir)/libs/pcre
+CORE_CFLAGS    += -I$(switch_srcdir)/libs/srtp/include
+CORE_CFLAGS    += -I$(switch_srcdir)/libs/srtp/crypto/include
+CORE_CFLAGS    += $(RESAMPLE_CFLAGS)
+
+CORE_LIBS      = libs/apr/libapr-1.la libs/apr-util/libaprutil-1.la
+CORE_LIBS     += libs/sqlite/libsqlite3.la libs/pcre/libpcre.la
+CORE_LIBS     += libs/srtp/libsrtp.la $(RESAMPLE_LIB)
+if ADD_ODBC
+libfreeswitch_la_SOURCES += src/switch_odbc.c
+library_include_HEADERS += src/include/switch_odbc.h
+CORE_LIBS     += -lodbc
+endif
 
-lib_LTLIBRARIES		= libfreeswitch.la
-libfreeswitch_la_CFLAGS	= $(AM_CFLAGS)
-libfreeswitch_la_LDFLAGS	= -version-info 1:0:0
-libfreeswitch_la_LIBADD  = -lteletone -lresample -lsrtp -lsqlite3 -lpcre
+lib_LTLIBRARIES	          = libfreeswitch.la
+libfreeswitch_la_CFLAGS   = $(CORE_CFLAGS) $(AM_CFLAGS)
+libfreeswitch_la_LDFLAGS  = -version-info 1:0:0 $(AM_LDFLAGS)
+libfreeswitch_la_LIBADD  = $(CORE_LIBS)
 nodist_libfreeswitch_la_SOURCES = src/include/switch_version.h
 
-bin_PROGRAMS =	freeswitch
-bin_SCRIPTS = scripts/fsxs
-freeswitch_SOURCES = 	src/switch.c\
-			src/include/switch_version.h
-freeswitch_CFLAGS = $(AM_CFLAGS)
-freeswitch_LDADD = ${top_builddir}/libfreeswitch.la 
+MOD_LINK       = $(BASE)/libfreeswitch.la
 
+CLEANFILES     = src/include/switch_version.h
+BUILT_SOURCES  = src/include/switch_version.h
 
+bin_PROGRAMS = freeswitch
+freeswitch_SOURCES = src/switch.c
+nodist_freeswitch_SOURCES = src/include/switch_version.h
+freeswitch_CFLAGS = $(AM_CFLAGS)
+freeswitch_LDFLAGS = $(AM_LDFLAGS) -rpath $(libdir)
+freeswitch_LDADD = libfreeswitch.la libs/apr/libapr-1.la
 
+$(libfreeswitch_la_SOURCES): $(CORE_LIBS) $(switch_builddir)/quiet_libtool modules.conf
 
-version: Makefile src/include/switch_version.h
-	MAKE=$(MAKE) ./build/checkversion.sh
+$(switch_builddir)/quiet_libtool: $(switch_builddir)/libtool
+	@cat libtool | sed -e 's|$$show "$$command"|if test -z "$$suppress_output" ; then $$show "Compiling $$srcfile ..." ; fi|' > quiet_libtool
 
-newversion: Makefile
-	MAKE=$(MAKE) ./build/checkversion.sh force
-	$(MAKE)
+install-data-local:
+	@echo Installing $(NAME)
+	@for x in conf mod db log log/xml_cdr bin scripts htdocs grammar ; do \
+		$(mkinstalldirs) $(DESTDIR)$(prefix)/$$x ; \
+	 done
+	@if [ ! -f $(DESTDIR)$(PREFIX)/conf/freeswitch.xml ] ; then \
+		$(INSTALL) conf/*.xml $(DESTDIR)$(PREFIX)/conf ; \
+	 fi
+
+.version:
+	touch .version
+
+src/include/switch_version.h: $(top_srcdir)/src/include/switch_version.h.in .version $(libfreeswitch_la_SOURCES) $(library_include_HEADERS)
+	@force=0 ; \
+	version=`svnversion . -n || echo hacked` ; \
+	oldversion=`cat .version 2>/dev/null || echo "0"` ; \
+	test ! -f src/include/switch_version.h || grep "@SVN_VERSION@" src/include/switch_version.h && force=1 ; \
+	if test "$$oldversion" != "$$version" || test $$force = 1 ; then \
+	  cat src/include/switch_version.h.in | sed "s/@SVN_VERSION@/$$version/g" > src/include/switch_version.h ; \
+	  echo $$version > .version ; \
+	fi ;
+
+update:
+	@if test -d .svn ; then \
+	  test ! -f .version || rm -f .version ; \
+	  echo Updating... ; \
+	  svn update ; \
+	else \
+	  echo "This source directory is not an svn working copy" ; \
+	fi
 
 .nodepends:
 	touch .nodepends
@@ -141,107 +172,68 @@
 yesdepends:
 	rm .nodepends
 
-depends:
-	@echo making depends
-	@rm -f build/freeswitch.env
-	@./build/addenv.sh build/freeswitch.env PREFIX $(PREFIX)
-	@./build/addenv.sh build/freeswitch.env MAKE $(MAKE)
-	mkdir -p $(PREFIX)
-	./build/buildlib.sh . install sqlite --prefix=$(PREFIX) --disable-tcl --enable-threadsafe
-	./build/buildlib.sh . install apr --prefix=$(PREFIX)
-	./build/buildlib.sh . install apr-util --with-apr=../apr --prefix=$(PREFIX)
-	./build/buildlib.sh . install libresample --prefix=$(PREFIX)
-	./build/buildlib.sh . install libteletone --prefix=$(PREFIX)
-	./build/buildlib.sh . install srtp --prefix=$(PREFIX)
-#	./build/buildlib.sh . install libspeakup --prefix=$(PREFIX)
-	./build/buildlib.sh . install pcre --prefix=$(PREFIX)
-	rm build/freeswitch.env
-
-
-modules: $(NAME)
-	@if [ ! -f $(PWD)/modules.conf ] ; then cp $(PWD)/modules.conf.in $(PWD)/modules.conf ; fi
-	@echo making modules
-	@rm -f build/freeswitch.env
-	@./build/addenv.sh build/freeswitch.env MAKE "$(MAKE)"
-	@./build/addenv.sh build/freeswitch.env DYLD_LIBRARY_PATH "$(PREFIX)/lib:$DYLD_LIBRARY_PATH"
-	@./build/addenv.sh build/freeswitch.env LD_LIBRARY_PATH "$(PREFIX)/lib:$LD_LIBRARY_PATH"
-	@./build/addenv.sh build/freeswitch.env PREFIX "$(PREFIX)"
-	@./build/addenv.sh build/freeswitch.env BASE "$(PWD)"
-	@./build/addenv.sh build/freeswitch.env OSARCH "$(OSARCH)"
-	@./build/addenv.sh build/freeswitch.env DYNAMIC_LIB_EXTEN "$(DYNAMIC_LIB_EXTEN)"
-	@./build/addenv.sh build/freeswitch.env SOLINK "$(SOLINK)"
-	@./build/addenv.sh build/freeswitch.env LDFLAGS "$(AM_LDFLAGS) -lfreeswitch"
-	@./build/addenv.sh build/freeswitch.env CFLAGS "$(AM_CFLAGS)"
-	@./build/addenv.sh build/freeswitch.env CC "$(CC)"
-	@./build/addenv.sh build/freeswitch.env CFGARGS "$(AM_CFGARGS)"
-	@cd src/mod && for i in `cat ../../modules.conf | grep -v \#` ; do echo making $$i ; $(PWD)/build/modmake.sh $(MAKE) $(PWD) $$i || exit 1; done
-	@rm -f build/freeswitch.env
+libs/apr/libapr-1.la: libs/apr libs/apr/.update
+	@cd libs/apr && $(MAKE)
+	@$(TOUCH_TARGET)
+
+libs/apr-util/libaprutil-1.la: libs/apr-util libs/apr-util/.update libs/apr/libapr-1.la
+	@cd libs/apr-util && $(MAKE)
+	@$(TOUCH_TARGET)
+
+libs/sqlite/libsqlite3.la: libs/sqlite libs/sqlite/.update
+	@cd libs/sqlite && $(MAKE)
+	@$(TOUCH_TARGET)
+
+libs/pcre/libpcre.la: libs/pcre libs/pcre/.update
+	@cd libs/pcre && $(MAKE)
+	@$(TOUCH_TARGET)
+
+libs/srtp/libsrtp.la: libs/srtp libs/srtp/.update
+	@cd libs/srtp && $(MAKE)
+	@$(TOUCH_TARGET)
+
+if USE_INTREE_RESAMPLE
+libs/libresample/libresample.la: libs/libresample libs/libresample/.update
+	@cd libs/libresample && $(MAKE)
+	@$(TOUCH_TARGET)
+endif
 
-modclean:
-	@rm -f build/freeswitch.env
-	@./build/addenv.sh build/freeswitch.env MAKE "$(MAKE)"
-	@./build/addenv.sh build/freeswitch.env CC "$(CC)"
-	@./build/addenv.sh build/freeswitch.env DYNAMIC_LIB_EXTEN "$(DYNAMIC_LIB_EXTEN)"
-	@cd src/mod && for i in `find . -type d -name mod_\*` ; do echo making clean $$i ; $(PWD)/build/modmake.sh $(MAKE) $(PWD) $$i clean || exit 1; done
-	@rm -f build/freeswitch.env
+core:  libfreeswitch.la  
+
+install_core: install-libLTLIBRARIES
+
+core_install: install_core
+
+everything: install
+
+installall: install
 
-everything: install install_mod
+sure: clean modwipe uninstall installall
 
-installall: install install_mod
+wayclean: clean
 
-sure: clean modclean modwipe uninstall installall
+modules: libfreeswitch.la
+	@cd src/mod && $(MAKE) $(AM_MAKEFLAGS)
 
-wayclean: clean modclean
+install_mod: libfreeswitch.la
+	@cd src/mod && $(MAKE) $(AM_MAKEFLAGS) install
+
+mod_install: install_mod
+
+uninstall_mod:
+	@cd src/mod && $(MAKE) $(AM_MAKEFLAGS) uninstall
+
+mod_uninstall: uninstall_mod
+
+modclean:
+	@cd src/mod && $(MAKE) $(AM_MAKEFLAGS) clean
 
 modwipe:
 	rm -f $(PREFIX)/mod/*.${DYNAMIC_LIB_EXTEN}
 
-install_mod: modules
-	@echo Installing $(NAME)
-	@mkdir -p $(PREFIX) $(PREFIX)/conf $(PREFIX)/mod $(PREFIX)/db $(PREFIX)/log $(PREFIX)/log/xml_cdr $(PREFIX)/bin $(PREFIX)/scripts $(PREFIX)/htdocs $(PREFIX)/grammar
-	@if [ ! -f $(PREFIX)/conf/freeswitch.xml ] ; then /bin/cp -p conf/*.xml $(PREFIX)/conf/; fi
-	@if [ -f .libs/$(NAME) ] ; then /bin/cp -p .libs/$(NAME) $(PREFIX)/bin ; else /bin/cp -p ./$(NAME) $(PREFIX)/bin ; fi
-	@echo Installing Modules
-	@rm -f build/freeswitch.env
-	@./build/addenv.sh build/freeswitch.env PREFIX "$(PREFIX)"
-	@./build/addenv.sh build/freeswitch.env MAKE "$(MAKE)"
-	@./build/addenv.sh build/freeswitch.env DYLD_LIBRARY_PATH "$(PREFIX)/lib:$DYLD_LIBRARY_PATH"
-	@./build/addenv.sh build/freeswitch.env LD_LIBRARY_PATH "$(PREFIX)/lib:$LD_LIBRARY_PATH"
-	@./build/addenv.sh build/freeswitch.env DYNAMIC_LIB_EXTEN "$(DYNAMIC_LIB_EXTEN)"
-	@./build/addenv.sh build/freeswitch.env BASE "$(PWD)"
-	@./build/addenv.sh build/freeswitch.env OSARCH "$(OSARCH)"
-	@./build/addenv.sh build/freeswitch.env SOLINK "$(SOLINK)"
-	@./build/addenv.sh build/freeswitch.env LDFLAGS "$(AM_LDFLAGS) -lfreeswitch"
-	@./build/addenv.sh build/freeswitch.env CFLAGS "$(AM_CFLAGS)"
-	@./build/addenv.sh build/freeswitch.env CC "$(CC)"
-	@cd src/mod && for i in `cat ../../modules.conf | grep -v \#` ; do echo making install $$i ; $(PWD)/build/modmake.sh $(MAKE) $(PWD) $$i install || exit 1; done
-	@rm -f build/freeswitch.env
-	@echo done
-
 dox:
 	cd docs && doxygen $(PWD)/docs/Doxygen.conf
 
-scripts/fsxs: scripts/fsxs.in
-	@echo creating fsxs
-	@sed -e "s, at MODULES_DIR\@,$(PREFIX)/mod," \
-	    -e "s, at LIB_DIR\@,$(PREFIX)/lib," \
-	    -e "s, at BIN_DIR\@,$(PREFIX)/bin," \
-	    -e "s, at INC_DIR\@,$(PREFIX)/include," \
-	    -e "s, at CFG_DIR\@,$(PREFIX)/conf," \
-	    -e "s, at DB_DIR\@,$(PREFIX)/db," \
-	    -e "s, at PREFIX\@,$(PREFIX)," \
-	    -e "s, at CC\@,$(CC)," \
-	    -e "s, at LD\@,$(CC)," \
-	    -e "s, at INSTALL\@,$(INSTALL)," \
-	    -e "s, at MKINSTALLDIRS\@,$(mkdir_p)," \
-	    \
-	    -e "s|@CFLAGS\@|$(CFLAGS) $(shell $(APR_CONFIG) --cflags --cppflags)|" \
-	    -e "s|@INCLUDES\@|-I$(PREFIX)/include $(shell $(APR_CONFIG) --includes) $(shell $(APU_CONFIG) --includes)|" \
-	    -e "s|@SOLINK\@|$(SOLINK)|" \
-	    -e "s|@LDFLAGS\@|-L$(PREFIX)/lib|" \
-	    -e "s|@LIBS\@|-lfreeswitch|" \
-	    scripts/fsxs.in > scripts/fsxs
-
 eclean: clean
 	rm -f `find . -type f -name \*~`
 	rm -f `find . -type f -name \.*~`
@@ -251,4 +243,18 @@
 	rm -f *.tar *.tgz *.gz 
 
 megaclean: eclean modclean
-	rm -fr .depend `find . -name .complete`
+	rm -f `find ./libs -name \*.la`
+
+modules.conf:
+	if test -f $@; then touch $@; else cp build/modules.conf.in $@ ;fi
+
+$(OUR_MODULES):
+	@set fnord $$MAKEFLAGS; amf=$$2; \
+	(cd src/mod && $(MAKE) $(AM_MAKEFLAGS) $@) \
+	   || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \
+	test -z "$$fail"
+
+# Special targets
+
+coffee me_a_sandwich me_a_sammich:
+	@echo "Who do you think I am?  Make it yourself!"

Modified: freeswitch/branches/cparker/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/Makefile.in	(original)
+++ freeswitch/branches/cparker/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -1,8 +1,8 @@
-# Makefile.in generated by automake 1.9.2 from Makefile.am.
+# Makefile.in generated by automake 1.9.5 from Makefile.am.
 # @configure_input@
 
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004  Free Software Foundation, Inc.
+# 2003, 2004, 2005  Free Software Foundation, Inc.
 # This Makefile.in 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.
@@ -108,11 +108,11 @@
 am__depfiles_maybe = depfiles
 COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) \
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
 	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
 	$(AM_CFLAGS) $(CFLAGS)
 CCLD = $(CC)
-LINK = $(LIBTOOL) --mode=link --tag=CC $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(AM_LDFLAGS) $(LDFLAGS) -o $@
 SOURCES = $(libfreeswitch_la_SOURCES) \
 	$(nodist_libfreeswitch_la_SOURCES) $(freeswitch_SOURCES)
@@ -540,109 +540,109 @@
 @am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
 
 libfreeswitch_la-switch_rtp.lo: src/switch_rtp.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_rtp.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_rtp.Tpo" -c -o libfreeswitch_la-switch_rtp.lo `test -f 'src/switch_rtp.c' || echo '$(srcdir)/'`src/switch_rtp.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_rtp.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_rtp.Tpo" -c -o libfreeswitch_la-switch_rtp.lo `test -f 'src/switch_rtp.c' || echo '$(srcdir)/'`src/switch_rtp.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_rtp.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_rtp.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_rtp.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_rtp.c' object='libfreeswitch_la-switch_rtp.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_rtp.lo `test -f 'src/switch_rtp.c' || echo '$(srcdir)/'`src/switch_rtp.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_rtp.lo `test -f 'src/switch_rtp.c' || echo '$(srcdir)/'`src/switch_rtp.c
 
 libfreeswitch_la-switch_buffer.lo: src/switch_buffer.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_buffer.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_buffer.Tpo" -c -o libfreeswitch_la-switch_buffer.lo `test -f 'src/switch_buffer.c' || echo '$(srcdir)/'`src/switch_buffer.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_buffer.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_buffer.Tpo" -c -o libfreeswitch_la-switch_buffer.lo `test -f 'src/switch_buffer.c' || echo '$(srcdir)/'`src/switch_buffer.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_buffer.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_buffer.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_buffer.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_buffer.c' object='libfreeswitch_la-switch_buffer.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_buffer.lo `test -f 'src/switch_buffer.c' || echo '$(srcdir)/'`src/switch_buffer.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_buffer.lo `test -f 'src/switch_buffer.c' || echo '$(srcdir)/'`src/switch_buffer.c
 
 libfreeswitch_la-switch_caller.lo: src/switch_caller.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_caller.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_caller.Tpo" -c -o libfreeswitch_la-switch_caller.lo `test -f 'src/switch_caller.c' || echo '$(srcdir)/'`src/switch_caller.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_caller.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_caller.Tpo" -c -o libfreeswitch_la-switch_caller.lo `test -f 'src/switch_caller.c' || echo '$(srcdir)/'`src/switch_caller.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_caller.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_caller.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_caller.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_caller.c' object='libfreeswitch_la-switch_caller.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_caller.lo `test -f 'src/switch_caller.c' || echo '$(srcdir)/'`src/switch_caller.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_caller.lo `test -f 'src/switch_caller.c' || echo '$(srcdir)/'`src/switch_caller.c
 
 libfreeswitch_la-switch_channel.lo: src/switch_channel.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_channel.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_channel.Tpo" -c -o libfreeswitch_la-switch_channel.lo `test -f 'src/switch_channel.c' || echo '$(srcdir)/'`src/switch_channel.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_channel.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_channel.Tpo" -c -o libfreeswitch_la-switch_channel.lo `test -f 'src/switch_channel.c' || echo '$(srcdir)/'`src/switch_channel.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_channel.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_channel.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_channel.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_channel.c' object='libfreeswitch_la-switch_channel.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_channel.lo `test -f 'src/switch_channel.c' || echo '$(srcdir)/'`src/switch_channel.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_channel.lo `test -f 'src/switch_channel.c' || echo '$(srcdir)/'`src/switch_channel.c
 
 libfreeswitch_la-switch_config.lo: src/switch_config.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_config.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_config.Tpo" -c -o libfreeswitch_la-switch_config.lo `test -f 'src/switch_config.c' || echo '$(srcdir)/'`src/switch_config.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_config.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_config.Tpo" -c -o libfreeswitch_la-switch_config.lo `test -f 'src/switch_config.c' || echo '$(srcdir)/'`src/switch_config.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_config.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_config.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_config.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_config.c' object='libfreeswitch_la-switch_config.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_config.lo `test -f 'src/switch_config.c' || echo '$(srcdir)/'`src/switch_config.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_config.lo `test -f 'src/switch_config.c' || echo '$(srcdir)/'`src/switch_config.c
 
 libfreeswitch_la-switch_console.lo: src/switch_console.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_console.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_console.Tpo" -c -o libfreeswitch_la-switch_console.lo `test -f 'src/switch_console.c' || echo '$(srcdir)/'`src/switch_console.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_console.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_console.Tpo" -c -o libfreeswitch_la-switch_console.lo `test -f 'src/switch_console.c' || echo '$(srcdir)/'`src/switch_console.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_console.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_console.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_console.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_console.c' object='libfreeswitch_la-switch_console.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_console.lo `test -f 'src/switch_console.c' || echo '$(srcdir)/'`src/switch_console.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_console.lo `test -f 'src/switch_console.c' || echo '$(srcdir)/'`src/switch_console.c
 
 libfreeswitch_la-switch_core.lo: src/switch_core.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_core.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_core.Tpo" -c -o libfreeswitch_la-switch_core.lo `test -f 'src/switch_core.c' || echo '$(srcdir)/'`src/switch_core.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_core.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_core.Tpo" -c -o libfreeswitch_la-switch_core.lo `test -f 'src/switch_core.c' || echo '$(srcdir)/'`src/switch_core.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_core.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_core.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_core.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_core.c' object='libfreeswitch_la-switch_core.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_core.lo `test -f 'src/switch_core.c' || echo '$(srcdir)/'`src/switch_core.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_core.lo `test -f 'src/switch_core.c' || echo '$(srcdir)/'`src/switch_core.c
 
 libfreeswitch_la-switch_loadable_module.lo: src/switch_loadable_module.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_loadable_module.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_loadable_module.Tpo" -c -o libfreeswitch_la-switch_loadable_module.lo `test -f 'src/switch_loadable_module.c' || echo '$(srcdir)/'`src/switch_loadable_module.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_loadable_module.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_loadable_module.Tpo" -c -o libfreeswitch_la-switch_loadable_module.lo `test -f 'src/switch_loadable_module.c' || echo '$(srcdir)/'`src/switch_loadable_module.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_loadable_module.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_loadable_module.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_loadable_module.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_loadable_module.c' object='libfreeswitch_la-switch_loadable_module.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_loadable_module.lo `test -f 'src/switch_loadable_module.c' || echo '$(srcdir)/'`src/switch_loadable_module.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_loadable_module.lo `test -f 'src/switch_loadable_module.c' || echo '$(srcdir)/'`src/switch_loadable_module.c
 
 libfreeswitch_la-switch_utils.lo: src/switch_utils.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_utils.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_utils.Tpo" -c -o libfreeswitch_la-switch_utils.lo `test -f 'src/switch_utils.c' || echo '$(srcdir)/'`src/switch_utils.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_utils.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_utils.Tpo" -c -o libfreeswitch_la-switch_utils.lo `test -f 'src/switch_utils.c' || echo '$(srcdir)/'`src/switch_utils.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_utils.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_utils.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_utils.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_utils.c' object='libfreeswitch_la-switch_utils.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_utils.lo `test -f 'src/switch_utils.c' || echo '$(srcdir)/'`src/switch_utils.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_utils.lo `test -f 'src/switch_utils.c' || echo '$(srcdir)/'`src/switch_utils.c
 
 libfreeswitch_la-switch_event.lo: src/switch_event.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_event.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_event.Tpo" -c -o libfreeswitch_la-switch_event.lo `test -f 'src/switch_event.c' || echo '$(srcdir)/'`src/switch_event.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_event.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_event.Tpo" -c -o libfreeswitch_la-switch_event.lo `test -f 'src/switch_event.c' || echo '$(srcdir)/'`src/switch_event.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_event.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_event.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_event.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_event.c' object='libfreeswitch_la-switch_event.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_event.lo `test -f 'src/switch_event.c' || echo '$(srcdir)/'`src/switch_event.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_event.lo `test -f 'src/switch_event.c' || echo '$(srcdir)/'`src/switch_event.c
 
 libfreeswitch_la-switch_resample.lo: src/switch_resample.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_resample.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_resample.Tpo" -c -o libfreeswitch_la-switch_resample.lo `test -f 'src/switch_resample.c' || echo '$(srcdir)/'`src/switch_resample.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_resample.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_resample.Tpo" -c -o libfreeswitch_la-switch_resample.lo `test -f 'src/switch_resample.c' || echo '$(srcdir)/'`src/switch_resample.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_resample.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_resample.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_resample.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_resample.c' object='libfreeswitch_la-switch_resample.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_resample.lo `test -f 'src/switch_resample.c' || echo '$(srcdir)/'`src/switch_resample.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_resample.lo `test -f 'src/switch_resample.c' || echo '$(srcdir)/'`src/switch_resample.c
 
 libfreeswitch_la-switch_ivr.lo: src/switch_ivr.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_ivr.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_ivr.Tpo" -c -o libfreeswitch_la-switch_ivr.lo `test -f 'src/switch_ivr.c' || echo '$(srcdir)/'`src/switch_ivr.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_ivr.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_ivr.Tpo" -c -o libfreeswitch_la-switch_ivr.lo `test -f 'src/switch_ivr.c' || echo '$(srcdir)/'`src/switch_ivr.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_ivr.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_ivr.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_ivr.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_ivr.c' object='libfreeswitch_la-switch_ivr.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_ivr.lo `test -f 'src/switch_ivr.c' || echo '$(srcdir)/'`src/switch_ivr.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_ivr.lo `test -f 'src/switch_ivr.c' || echo '$(srcdir)/'`src/switch_ivr.c
 
 libfreeswitch_la-switch_stun.lo: src/switch_stun.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_stun.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_stun.Tpo" -c -o libfreeswitch_la-switch_stun.lo `test -f 'src/switch_stun.c' || echo '$(srcdir)/'`src/switch_stun.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_stun.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_stun.Tpo" -c -o libfreeswitch_la-switch_stun.lo `test -f 'src/switch_stun.c' || echo '$(srcdir)/'`src/switch_stun.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_stun.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_stun.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_stun.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_stun.c' object='libfreeswitch_la-switch_stun.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_stun.lo `test -f 'src/switch_stun.c' || echo '$(srcdir)/'`src/switch_stun.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_stun.lo `test -f 'src/switch_stun.c' || echo '$(srcdir)/'`src/switch_stun.c
 
 libfreeswitch_la-switch_log.lo: src/switch_log.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_log.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_log.Tpo" -c -o libfreeswitch_la-switch_log.lo `test -f 'src/switch_log.c' || echo '$(srcdir)/'`src/switch_log.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_log.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_log.Tpo" -c -o libfreeswitch_la-switch_log.lo `test -f 'src/switch_log.c' || echo '$(srcdir)/'`src/switch_log.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_log.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_log.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_log.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_log.c' object='libfreeswitch_la-switch_log.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_log.lo `test -f 'src/switch_log.c' || echo '$(srcdir)/'`src/switch_log.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_log.lo `test -f 'src/switch_log.c' || echo '$(srcdir)/'`src/switch_log.c
 
 libfreeswitch_la-switch_xml.lo: src/switch_xml.c
- at am__fastdepCC_TRUE@	if $(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_xml.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_xml.Tpo" -c -o libfreeswitch_la-switch_xml.lo `test -f 'src/switch_xml.c' || echo '$(srcdir)/'`src/switch_xml.c; \
+ at am__fastdepCC_TRUE@	if $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -MT libfreeswitch_la-switch_xml.lo -MD -MP -MF "$(DEPDIR)/libfreeswitch_la-switch_xml.Tpo" -c -o libfreeswitch_la-switch_xml.lo `test -f 'src/switch_xml.c' || echo '$(srcdir)/'`src/switch_xml.c; \
 @am__fastdepCC_TRUE@	then mv -f "$(DEPDIR)/libfreeswitch_la-switch_xml.Tpo" "$(DEPDIR)/libfreeswitch_la-switch_xml.Plo"; else rm -f "$(DEPDIR)/libfreeswitch_la-switch_xml.Tpo"; exit 1; fi
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	source='src/switch_xml.c' object='libfreeswitch_la-switch_xml.lo' libtool=yes @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(LIBTOOL) --mode=compile --tag=CC $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_xml.lo `test -f 'src/switch_xml.c' || echo '$(srcdir)/'`src/switch_xml.c
+ at am__fastdepCC_FALSE@	$(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libfreeswitch_la_CFLAGS) $(CFLAGS) -c -o libfreeswitch_la-switch_xml.lo `test -f 'src/switch_xml.c' || echo '$(srcdir)/'`src/switch_xml.c
 
 freeswitch-switch.o: src/switch.c
 @am__fastdepCC_TRUE@	if $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(freeswitch_CFLAGS) $(CFLAGS) -MT freeswitch-switch.o -MD -MP -MF "$(DEPDIR)/freeswitch-switch.Tpo" -c -o freeswitch-switch.o `test -f 'src/switch.c' || echo '$(srcdir)/'`src/switch.c; \
@@ -692,7 +692,13 @@
 #     (which will cause the Makefiles to be regenerated when you run `make');
 # (2) otherwise, pass the desired values on the `make' command line.
 $(RECURSIVE_TARGETS):
-	@set fnord $$MAKEFLAGS; amf=$$2; \
+	@failcom='exit 1'; \
+	for f in x $$MAKEFLAGS; do \
+	  case $$f in \
+	    *=* | --[!k]*);; \
+	    *k*) failcom='fail=yes';; \
+	  esac; \
+	done; \
 	dot_seen=no; \
 	target=`echo $@ | sed s/-recursive//`; \
 	list='$(SUBDIRS)'; for subdir in $$list; do \
@@ -704,7 +710,7 @@
 	    local_target="$$target"; \
 	  fi; \
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	   || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \
+	  || eval $$failcom; \
 	done; \
 	if test "$$dot_seen" = "no"; then \
 	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
@@ -712,7 +718,13 @@
 
 mostlyclean-recursive clean-recursive distclean-recursive \
 maintainer-clean-recursive:
-	@set fnord $$MAKEFLAGS; amf=$$2; \
+	@failcom='exit 1'; \
+	for f in x $$MAKEFLAGS; do \
+	  case $$f in \
+	    *=* | --[!k]*);; \
+	    *k*) failcom='fail=yes';; \
+	  esac; \
+	done; \
 	dot_seen=no; \
 	case "$@" in \
 	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
@@ -733,7 +745,7 @@
 	    local_target="$$target"; \
 	  fi; \
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	   || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \
+	  || eval $$failcom; \
 	done && test -z "$$fail"
 tags-recursive:
 	list='$(SUBDIRS)'; for subdir in $$list; do \

Modified: freeswitch/branches/cparker/aclocal.m4
==============================================================================
--- freeswitch/branches/cparker/aclocal.m4	(original)
+++ freeswitch/branches/cparker/aclocal.m4	Tue Apr 24 10:14:28 2007
@@ -1,7 +1,7 @@
-# generated automatically by aclocal 1.9.2 -*- Autoconf -*-
+# generated automatically by aclocal 1.9.5 -*- Autoconf -*-
 
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
-# Free Software Foundation, Inc.
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+# 2005  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.
@@ -13,7 +13,7 @@
 
 # libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
 
-# serial 48 AC_PROG_LIBTOOL
+# serial 47 AC_PROG_LIBTOOL
 
 
 # AC_PROVIDE_IFELSE(MACRO-NAME, IF-PROVIDED, IF-NOT-PROVIDED)
@@ -123,7 +123,7 @@
 
 # Sed substitution that helps us do robust quoting.  It backslashifies
 # metacharacters that are still active within double-quoted strings.
-Xsed='sed -e 1s/^X//'
+Xsed='sed -e s/^X//'
 [sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g']
 
 # Same as above, but do not quote variable references.
@@ -143,7 +143,7 @@
 default_ofile=libtool
 can_build_shared=yes
 
-# All known linkers require a `.a' archive for static linking (except MSVC,
+# All known linkers require a `.a' archive for static linking (except M$VC,
 # which needs '.lib').
 libext=a
 ltmain="$ac_aux_dir/ltmain.sh"
@@ -163,7 +163,6 @@
 test -z "$AS" && AS=as
 test -z "$CC" && CC=cc
 test -z "$LTCC" && LTCC=$CC
-test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
 test -z "$DLLTOOL" && DLLTOOL=dlltool
 test -z "$LD" && LD=ld
 test -z "$LN_S" && LN_S="ln -s"
@@ -183,16 +182,16 @@
 if test -n "$RANLIB"; then
   case $host_os in
   openbsd*)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
+    old_postinstall_cmds="\$RANLIB -t \$oldlib~$old_postinstall_cmds"
     ;;
   *)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
+    old_postinstall_cmds="\$RANLIB \$oldlib~$old_postinstall_cmds"
     ;;
   esac
   old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
 fi
 
-_LT_CC_BASENAME([$compiler])
+cc_basename=`$echo X"$compiler" | $Xsed -e 's%^.*/%%'`
 
 # Only perform the check for file, if the check method requires it
 case $deplibs_check_method in
@@ -234,56 +233,11 @@
 # If no C compiler was specified, use CC.
 LTCC=${LTCC-"$CC"}
 
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
 # Allow CC to be a program name with arguments.
 compiler=$CC
 ])# _LT_AC_SYS_COMPILER
 
 
-# _LT_CC_BASENAME(CC)
-# -------------------
-# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
-AC_DEFUN([_LT_CC_BASENAME],
-[for cc_temp in $1""; do
-  case $cc_temp in
-    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
-    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
-])
-
-
-# _LT_COMPILER_BOILERPLATE
-# ------------------------
-# Check for compiler boilerplate output or warnings with
-# the simple compiler test code.
-AC_DEFUN([_LT_COMPILER_BOILERPLATE],
-[ac_outfile=conftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$rm conftest*
-])# _LT_COMPILER_BOILERPLATE
-
-
-# _LT_LINKER_BOILERPLATE
-# ----------------------
-# Check for linker boilerplate output or warnings with
-# the simple link test code.
-AC_DEFUN([_LT_LINKER_BOILERPLATE],
-[ac_outfile=conftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$rm conftest*
-])# _LT_LINKER_BOILERPLATE
-
-
 # _LT_AC_SYS_LIBPATH_AIX
 # ----------------------
 # Links a minimal program and checks the executable
@@ -363,8 +317,8 @@
 # find a string as large as possible, as long as the shell can cope with it
   for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do
     # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
-    if (echo_test_string=`eval $cmd`) 2>/dev/null &&
-       echo_test_string=`eval $cmd` &&
+    if (echo_test_string="`eval $cmd`") 2>/dev/null &&
+       echo_test_string="`eval $cmd`" &&
        (test "X$echo_test_string" = "X$echo_test_string") 2>/dev/null
     then
       break
@@ -533,7 +487,7 @@
   # Find out which ABI we are using.
   echo 'int i;' > conftest.$ac_ext
   if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
+    case "`/usr/bin/file conftest.o`" in
     *32-bit*)
       case $host in
         x86_64-*linux*)
@@ -584,22 +538,6 @@
     CFLAGS="$SAVE_CFLAGS"
   fi
   ;;
-sparc*-*solaris*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
-    *64-bit*)
-      case $lt_cv_prog_gnu_ld in
-      yes*) LD="${LD-ld} -m elf64_sparc" ;;
-      *)    LD="${LD-ld} -64" ;;
-      esac
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
 AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL],
 [*-*-cygwin* | *-*-mingw* | *-*-pw32*)
   AC_CHECK_TOOL(DLLTOOL, dlltool, false)
@@ -631,7 +569,7 @@
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    # The option is referenced via a variable to avoid confusing sed.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
    (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
@@ -641,10 +579,8 @@
    echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+     # So say no if there are warnings
+     if test ! -s conftest.err; then
        $2=yes
      fi
    fi
@@ -670,16 +606,11 @@
    LDFLAGS="$LDFLAGS $3"
    printf "$lt_simple_link_test_code" > conftest.$ac_ext
    if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
+     # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings
      if test -s conftest.err; then
        # Append any errors to the config.log.
        cat conftest.err 1>&AS_MESSAGE_LOG_FD
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         $2=yes
-       fi
      else
        $2=yes
      fi
@@ -745,42 +676,24 @@
     elif test -x /usr/sbin/sysctl; then
       lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
     else
-      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
+      lt_cv_sys_max_cmd_len=65536 # usable default for *BSD
     fi
     # And add a safety zone
     lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
     ;;
-
-  interix*)
-    # We know the value 262144 and hardcode it with a safety zone (like BSD)
-    lt_cv_sys_max_cmd_len=196608
-    ;;
-
   osf*)
     # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
     # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
     # nice to cause kernel panics so lets avoid the loop below.
     # First set a reasonable default.
     lt_cv_sys_max_cmd_len=16384
-    #
+    # 
     if test -x /sbin/sysconfig; then
       case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
         *1*) lt_cv_sys_max_cmd_len=-1 ;;
       esac
     fi
     ;;
-  sco3.2v5*)
-    lt_cv_sys_max_cmd_len=102400
-    ;;
-  sysv5* | sco5v6* | sysv4.2uw2*)
-    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
-    if test -n "$kargmax"; then
-      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ 	]]//'`
-    else
-      lt_cv_sys_max_cmd_len=32768
-    fi
-    ;;
   *)
     # If test is not a shell built-in, we'll probably end up computing a
     # maximum length that is only half of the actual maximum length, but
@@ -812,7 +725,7 @@
 
 
 # _LT_AC_CHECK_DLFCN
-# ------------------
+# --------------------
 AC_DEFUN([_LT_AC_CHECK_DLFCN],
 [AC_CHECK_HEADERS(dlfcn.h)dnl
 ])# _LT_AC_CHECK_DLFCN
@@ -820,7 +733,7 @@
 
 # _LT_AC_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
 #                           ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
-# ---------------------------------------------------------------------
+# ------------------------------------------------------------------
 AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF],
 [AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl
 if test "$cross_compiling" = yes; then :
@@ -886,19 +799,17 @@
       else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
       /* dlclose (self); */
     }
-  else
-    puts (dlerror ());
 
     exit (status);
 }]
 EOF
   if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
+    (./conftest; exit; ) 2>/dev/null
     lt_status=$?
     case x$lt_status in
       x$lt_dlno_uscore) $1 ;;
       x$lt_dlneed_uscore) $2 ;;
-      x$lt_dlunknown|x*) $3 ;;
+      x$lt_unknown|x*) $3 ;;
     esac
   else :
     # compilation failed
@@ -910,7 +821,7 @@
 
 
 # AC_LIBTOOL_DLOPEN_SELF
-# ----------------------
+# -------------------
 AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF],
 [AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl
 if test "x$enable_dlopen" != xyes; then
@@ -981,7 +892,7 @@
     test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
 
     save_LDFLAGS="$LDFLAGS"
-    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+    eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
 
     save_LIBS="$LIBS"
     LIBS="$lt_cv_dlopen_libs $LIBS"
@@ -994,7 +905,7 @@
     ])
 
     if test "x$lt_cv_dlopen_self" = xyes; then
-      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+      LDFLAGS="$LDFLAGS $link_static_flag"
       AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
     	  lt_cv_dlopen_self_static, [dnl
 	  _LT_AC_TRY_DLOPEN_SELF(
@@ -1042,7 +953,7 @@
    # Note that $ac_compile itself does not contain backslashes and begins
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
    (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
@@ -1054,13 +965,11 @@
    then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+     if test ! -s out/conftest.err; then
        _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
      fi
    fi
-   chmod u+w . 2>&AS_MESSAGE_LOG_FD
+   chmod u+w .
    $rm conftest*
    # SGI C++ compiler will create directory out/ii_files/ for
    # template instantiation
@@ -1320,8 +1229,7 @@
       dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
       dldir=$destdir/`dirname \$dlpath`~
       test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
+      $install_prog $dir/$dlname \$dldir/$dlname'
     postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
       dlpath=$dir/\$dldll~
        $rm \$dlpath'
@@ -1374,7 +1282,7 @@
   soname_spec='${libname}${release}${major}$shared_ext'
   shlibpath_overrides_runpath=yes
   shlibpath_var=DYLD_LIBRARY_PATH
-  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+  shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)'
   # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
   if test "$GCC" = yes; then
     sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
@@ -1412,14 +1320,7 @@
 freebsd* | dragonfly*)
   # DragonFly does not have aout.  When/if they implement a new
   # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[[123]]*) objformat=aout ;;
-    *) objformat=elf ;;
-    esac
-  fi
+  objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout`
   version_type=freebsd-$objformat
   case $version_type in
     freebsd-elf*)
@@ -1441,15 +1342,10 @@
     shlibpath_overrides_runpath=yes
     hardcode_into_libs=yes
     ;;
-  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
-  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
+  *) # from 3.2 on
     shlibpath_overrides_runpath=no
     hardcode_into_libs=yes
     ;;
-  freebsd*) # from 4.6 on
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
   esac
   ;;
 
@@ -1469,7 +1365,7 @@
   version_type=sunos
   need_lib_prefix=no
   need_version=no
-  case $host_cpu in
+  case "$host_cpu" in
   ia64*)
     shrext_cmds='.so'
     hardcode_into_libs=yes
@@ -1509,18 +1405,6 @@
   postinstall_cmds='chmod 555 $lib'
   ;;
 
-interix3*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
 irix5* | irix6* | nonstopux*)
   case $host_os in
     nonstopux*) version_type=nonstopux ;;
@@ -1580,7 +1464,7 @@
 
   # Append ld.so.conf contents to the search path
   if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,\t]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
     sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
   fi
 
@@ -1642,13 +1526,8 @@
 
 openbsd*)
   version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
   need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=yes ;;
-    *)                         need_version=no  ;;
-  esac
+  need_version=no
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
   finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
   shlibpath_var=LD_LIBRARY_PATH
@@ -1686,6 +1565,13 @@
   sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
   ;;
 
+sco3.2v5*)
+  version_type=osf
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
 solaris*)
   version_type=linux
   need_lib_prefix=no
@@ -1711,7 +1597,7 @@
   need_version=yes
   ;;
 
-sysv4 | sysv4.3*)
+sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
   version_type=linux
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
   soname_spec='${libname}${release}${shared_ext}$major'
@@ -1744,29 +1630,6 @@
   fi
   ;;
 
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-    shlibpath_overrides_runpath=no
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=yes
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
-
 uts4*)
   version_type=linux
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
@@ -1780,11 +1643,6 @@
 esac
 AC_MSG_RESULT([$dynamic_linker])
 test "$dynamic_linker" = no && can_build_shared=no
-
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
-fi
 ])# AC_LIBTOOL_SYS_DYNAMIC_LINKER
 
 
@@ -1809,9 +1667,6 @@
       AC_MSG_WARN([using `LTCC=$LTCC', extracted from `$ofile'])
     fi
   fi
-  if test -z "$LTCFLAGS"; then
-    eval "`$SHELL ${ofile} --config | grep '^LTCFLAGS='`"
-  fi
 
   # Extract list of available tagged configurations in $ofile.
   # Note that this assumes the entire list is on one line.
@@ -1902,7 +1757,7 @@
 
 # AC_LIBTOOL_WIN32_DLL
 # --------------------
-# declare package support for building win32 DLLs
+# declare package support for building win32 dll's
 AC_DEFUN([AC_LIBTOOL_WIN32_DLL],
 [AC_BEFORE([$0], [AC_LIBTOOL_SETUP])
 ])# AC_LIBTOOL_WIN32_DLL
@@ -1940,7 +1795,7 @@
 
 # AC_DISABLE_SHARED
 # -----------------
-# set the default shared flag to --disable-shared
+#- set the default shared flag to --disable-shared
 AC_DEFUN([AC_DISABLE_SHARED],
 [AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
 AC_ENABLE_SHARED(no)
@@ -2076,7 +1931,7 @@
       if test -n "$file_magic_test_file"; then
 	case $deplibs_check_method in
 	"file_magic "*)
-	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+	  file_magic_regex="`expr \"$deplibs_check_method\" : \"file_magic \(.*\)\"`"
 	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
 	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
 	    $EGREP "$file_magic_regex" > /dev/null; then
@@ -2186,7 +2041,7 @@
     if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
       lt_cv_path_LD="$ac_dir/$ac_prog"
       # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
+      # but apparently some GNU ld's only accept -v.
       # Break only if it was the GNU/non-GNU ld that we prefer.
       case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
       *GNU* | *'with BFD'*)
@@ -2218,7 +2073,7 @@
 AC_DEFUN([AC_PROG_LD_GNU],
 [AC_REQUIRE([AC_PROG_EGREP])dnl
 AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
-[# I'd rather use --version here, but apparently some GNU lds only accept -v.
+[# I'd rather use --version here, but apparently some GNU ld's only accept -v.
 case `$LD -v 2>&1 </dev/null` in
 *GNU* | *'with BFD'*)
   lt_cv_prog_gnu_ld=yes
@@ -2248,7 +2103,7 @@
 case $host_os in
   darwin*)
     if test "$GCC" = yes; then
-      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+      reload_cmds='$CC -nostdlib ${wl}-r -o $output$reload_objs'
     else
       reload_cmds='$LD$reload_flag -o $output$reload_objs'
     fi
@@ -2332,7 +2187,7 @@
 
 hpux10.20* | hpux11*)
   lt_cv_file_magic_cmd=/usr/bin/file
-  case $host_cpu in
+  case "$host_cpu" in
   ia64*)
     lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
     lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
@@ -2348,11 +2203,6 @@
   esac
   ;;
 
-interix3*)
-  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
-  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
-  ;;
-
 irix5* | irix6* | nonstopux*)
   case $LD in
   *-32|*"-32 ") libmagic=32-bit;;
@@ -2398,11 +2248,15 @@
   lt_cv_deplibs_check_method=pass_all
   ;;
 
+sco3.2v5*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
 solaris*)
   lt_cv_deplibs_check_method=pass_all
   ;;
 
-sysv4 | sysv4.3*)
+sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
   case $host_vendor in
   motorola)
     lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
@@ -2423,13 +2277,10 @@
   siemens)
     lt_cv_deplibs_check_method=pass_all
     ;;
-  pc)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
   esac
   ;;
 
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[[78]]* | unixware7* | sysv4*uw2*)
   lt_cv_deplibs_check_method=pass_all
   ;;
 esac
@@ -2449,43 +2300,36 @@
   # Let the user override the test.
   lt_cv_path_NM="$NM"
 else
-  lt_nm_to_check="${ac_tool_prefix}nm"
-  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then 
-    lt_nm_to_check="$lt_nm_to_check nm"
-  fi
-  for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS="$lt_save_ifs"
-      test -z "$ac_dir" && ac_dir=.
-      tmp_nm="$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
-	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
-	#   nm: unknown option "B" ignored
-	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
-	  lt_cv_path_NM="$tmp_nm -B"
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH /usr/ccs/bin /usr/ucb /bin; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    tmp_nm="$ac_dir/${ac_tool_prefix}nm"
+    if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+      # Check to see if the nm accepts a BSD-compat flag.
+      # Adding the `sed 1q' prevents false positives on HP-UX, which says:
+      #   nm: unknown option "B" ignored
+      # Tru64's nm complains that /dev/null is an invalid object file
+      case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+      */dev/null* | *'Invalid file or object type'*)
+	lt_cv_path_NM="$tmp_nm -B"
+	break
+        ;;
+      *)
+	case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+	*/dev/null*)
+	  lt_cv_path_NM="$tmp_nm -p"
 	  break
 	  ;;
 	*)
-	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
-	  */dev/null*)
-	    lt_cv_path_NM="$tmp_nm -p"
-	    break
-	    ;;
-	  *)
-	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
-	    continue # so that we can try to find one that supports BSD flags
-	    ;;
-	  esac
+	  lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+	  continue # so that we can try to find one that supports BSD flags
 	  ;;
 	esac
-      fi
-    done
-    IFS="$lt_save_ifs"
+      esac
+    fi
   done
+  IFS="$lt_save_ifs"
   test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm
 fi])
 NM="$lt_cv_path_NM"
@@ -2517,13 +2361,13 @@
 # -----------------------------------
 # sets LIBLTDL to the link flags for the libltdl convenience library and
 # LTDLINCL to the include flags for the libltdl header and adds
-# --enable-ltdl-convenience to the configure arguments.  Note that
-# AC_CONFIG_SUBDIRS is not called here.  If DIRECTORY is not provided,
-# it is assumed to be `libltdl'.  LIBLTDL will be prefixed with
-# '${top_builddir}/' and LTDLINCL will be prefixed with '${top_srcdir}/'
-# (note the single quotes!).  If your package is not flat and you're not
-# using automake, define top_builddir and top_srcdir appropriately in
-# the Makefiles.
+# --enable-ltdl-convenience to the configure arguments.  Note that LIBLTDL
+# and LTDLINCL are not AC_SUBSTed, nor is AC_CONFIG_SUBDIRS called.  If
+# DIRECTORY is not provided, it is assumed to be `libltdl'.  LIBLTDL will
+# be prefixed with '${top_builddir}/' and LTDLINCL will be prefixed with
+# '${top_srcdir}/' (note the single quotes!).  If your package is not
+# flat and you're not using automake, define top_builddir and
+# top_srcdir appropriately in the Makefiles.
 AC_DEFUN([AC_LIBLTDL_CONVENIENCE],
 [AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
   case $enable_ltdl_convenience in
@@ -2542,13 +2386,13 @@
 # -----------------------------------
 # sets LIBLTDL to the link flags for the libltdl installable library and
 # LTDLINCL to the include flags for the libltdl header and adds
-# --enable-ltdl-install to the configure arguments.  Note that
-# AC_CONFIG_SUBDIRS is not called here.  If DIRECTORY is not provided,
-# and an installed libltdl is not found, it is assumed to be `libltdl'.
-# LIBLTDL will be prefixed with '${top_builddir}/'# and LTDLINCL with
-# '${top_srcdir}/' (note the single quotes!).  If your package is not
-# flat and you're not using automake, define top_builddir and top_srcdir
-# appropriately in the Makefiles.
+# --enable-ltdl-install to the configure arguments.  Note that LIBLTDL
+# and LTDLINCL are not AC_SUBSTed, nor is AC_CONFIG_SUBDIRS called.  If
+# DIRECTORY is not provided and an installed libltdl is not found, it is
+# assumed to be `libltdl'.  LIBLTDL will be prefixed with '${top_builddir}/'
+# and LTDLINCL will be prefixed with '${top_srcdir}/' (note the single
+# quotes!).  If your package is not flat and you're not using automake,
+# define top_builddir and top_srcdir appropriately in the Makefiles.
 # In the future, this macro may have to be called after AC_PROG_LIBTOOL.
 AC_DEFUN([AC_LIBLTDL_INSTALLABLE],
 [AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
@@ -2591,7 +2435,7 @@
 ])# _LT_AC_LANG_CXX
 
 # _LT_AC_PROG_CXXCPP
-# ------------------
+# ---------------
 AC_DEFUN([_LT_AC_PROG_CXXCPP],
 [
 AC_REQUIRE([AC_PROG_CXX])
@@ -2640,7 +2484,7 @@
 
 
 # AC_LIBTOOL_RC
-# -------------
+# --------------
 # enable support for Windows resource files
 AC_DEFUN([AC_LIBTOOL_RC],
 [AC_REQUIRE([LT_AC_PROG_RC])
@@ -2673,9 +2517,36 @@
 
 _LT_AC_SYS_COMPILER
 
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
+#
+# Check for any special shared library compilation flags.
+#
+_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)=
+if test "$GCC" = no; then
+  case $host_os in
+  sco3.2v5*)
+    _LT_AC_TAGVAR(lt_prog_cc_shlib, $1)='-belf'
+    ;;
+  esac
+fi
+if test -n "$_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)"; then
+  AC_MSG_WARN([`$CC' requires `$_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)' to build shared libraries])
+  if echo "$old_CC $old_CFLAGS " | grep "[[ 	]]$_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)[[ 	]]" >/dev/null; then :
+  else
+    AC_MSG_WARN([add `$_LT_AC_TAGVAR(lt_prog_cc_shlib, $1)' to the CC or CFLAGS env variable and reconfigure])
+    _LT_AC_TAGVAR(lt_cv_prog_cc_can_build_shared, $1)=no
+  fi
+fi
+
+
+#
+# Check to make sure the static flag actually works.
+#
+AC_LIBTOOL_LINKER_OPTION([if $compiler static flag $_LT_AC_TAGVAR(lt_prog_compiler_static, $1) works],
+  _LT_AC_TAGVAR(lt_prog_compiler_static_works, $1),
+  $_LT_AC_TAGVAR(lt_prog_compiler_static, $1),
+  [],
+  [_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=])
+
 
 AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1)
 AC_LIBTOOL_PROG_COMPILER_PIC($1)
@@ -2685,9 +2556,9 @@
 AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
 AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
 AC_LIBTOOL_SYS_LIB_STRIP
-AC_LIBTOOL_DLOPEN_SELF
+AC_LIBTOOL_DLOPEN_SELF($1)
 
-# Report which library types will actually be built
+# Report which librarie types wil actually be built
 AC_MSG_CHECKING([if libtool supports shared libraries])
 AC_MSG_RESULT([$can_build_shared])
 
@@ -2696,7 +2567,7 @@
 
 # On AIX, shared libraries and static libraries use the same namespace, and
 # are all built from PIC.
-case $host_os in
+case "$host_os" in
 aix3*)
   test "$enable_shared" = yes && enable_static=no
   if test -n "$RANLIB"; then
@@ -2746,7 +2617,6 @@
 _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
 _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
 _LT_AC_TAGVAR(hardcode_minus_L, $1)=no
-_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
 _LT_AC_TAGVAR(hardcode_automatic, $1)=no
 _LT_AC_TAGVAR(module_cmds, $1)=
 _LT_AC_TAGVAR(module_expsym_cmds, $1)=
@@ -2764,7 +2634,7 @@
 _LT_AC_TAGVAR(compiler_lib_search_path, $1)=
 
 # Source file extension for C++ test sources.
-ac_ext=cpp
+ac_ext=cc
 
 # Object file extension for compiled C++ test sources.
 objext=o
@@ -2774,15 +2644,11 @@
 lt_simple_compile_test_code="int some_variable = 0;\n"
 
 # Code to be used in simple link tests
-lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }\n'
+lt_simple_link_test_code='int main(int, char *[]) { return(0); }\n'
 
 # ltmain only uses $CC for tagged configurations so make sure $CC is set.
 _LT_AC_SYS_COMPILER
 
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
 # Allow CC to be a program name with arguments.
 lt_save_CC=$CC
 lt_save_LD=$LD
@@ -2793,18 +2659,18 @@
 if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
   lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
 else
-  $as_unset lt_cv_prog_gnu_ld
+  unset lt_cv_prog_gnu_ld
 fi
 if test -n "${lt_cv_path_LDCXX+set}"; then
   lt_cv_path_LD=$lt_cv_path_LDCXX
 else
-  $as_unset lt_cv_path_LD
+  unset lt_cv_path_LD
 fi
 test -z "${LDCXX+set}" || LD=$LDCXX
 CC=${CXX-"c++"}
 compiler=$CC
 _LT_AC_TAGVAR(compiler, $1)=$CC
-_LT_CC_BASENAME([$compiler])
+cc_basename=`$echo X"$compiler" | $Xsed -e 's%^.*/%%'`
 
 # We don't want -fno-exception wen compiling C++ code, so set the
 # no_builtin_flag separately
@@ -2893,7 +2759,6 @@
 	    ;;
 	  esac
 	done
-	;;
       esac
 
       exp_sym_flag='-bexport'
@@ -2931,7 +2796,6 @@
 	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
 	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
 	fi
-	;;
       esac
       shared_flag='-shared'
       if test "$aix_use_runtimelinking" = yes; then
@@ -2963,12 +2827,12 @@
       _LT_AC_SYS_LIBPATH_AIX
       _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
 
-      _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+      _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag"
      else
       if test "$host_cpu" = ia64; then
 	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
 	_LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	_LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols"
       else
 	# Determine the default libpath from the value encoded in an empty executable.
 	_LT_AC_SYS_LIBPATH_AIX
@@ -2977,26 +2841,16 @@
 	# -berok will link without error, but may produce a broken library.
 	_LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
 	_LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	# -bexpall does not export symbols beginning with underscore (_)
+	_LT_AC_TAGVAR(always_export_symbols, $1)=yes
 	# Exported symbols can be pulled into shared objects from archives
-	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=' '
 	_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
-	# This is similar to how AIX traditionally builds its shared libraries.
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	# This is similar to how AIX traditionally builds it's shared libraries.
+	_LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
       fi
     fi
     ;;
-
-  beos*)
-    if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-      _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
-      # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
-      # support --undefined.  This deserves some investigation.  FIXME
-      _LT_AC_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-    else
-      _LT_AC_TAGVAR(ld_shlibs, $1)=no
-    fi
-    ;;
-
   chorus*)
     case $cc_basename in
       *)
@@ -3006,6 +2860,7 @@
     esac
     ;;
 
+
   cygwin* | mingw* | pw32*)
     # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
     # as there is no search path for DLLs.
@@ -3015,7 +2870,7 @@
     _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
 
     if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-      _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib'
       # If the export-symbols file already is a .def file (1st line
       # is EXPORTS), use it as is; otherwise, prepend...
       _LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
@@ -3024,13 +2879,13 @@
 	echo EXPORTS > $output_objdir/$soname.def;
 	cat $export_symbols >> $output_objdir/$soname.def;
       fi~
-      $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib'
     else
       _LT_AC_TAGVAR(ld_shlibs, $1)=no
     fi
   ;;
       darwin* | rhapsody*)
-        case $host_os in
+        case "$host_os" in
         rhapsody* | darwin1.[[012]])
          _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}suppress'
          ;;
@@ -3068,7 +2923,7 @@
           _LT_AC_TAGVAR(archive_cmds, $1)='$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
         fi
         _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-        # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+        # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
           if test "X$lt_int_apple_cc_single_mod" = Xyes ; then
             _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           else
@@ -3076,12 +2931,12 @@
           fi
             _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
       else
-      case $cc_basename in
+      case "$cc_basename" in
         xlc*)
          output_verbose_link_cmd='echo'
           _LT_AC_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
           _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
           _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           ;;
@@ -3094,11 +2949,11 @@
 
   dgux*)
     case $cc_basename in
-      ec++*)
+      ec++)
 	# FIXME: insert proper C++ library support
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
 	;;
-      ghcx*)
+      ghcx)
 	# Green Hills C++ Compiler
 	# FIXME: insert proper C++ library support
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
@@ -3133,11 +2988,11 @@
 				# location of the library.
 
     case $cc_basename in
-    CC*)
+    CC)
       # FIXME: insert proper C++ library support
       _LT_AC_TAGVAR(ld_shlibs, $1)=no
       ;;
-    aCC*)
+    aCC)
       _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
       # Commands to make compiler produce verbose output that lists
       # what "hidden" libraries, object files and flags are used when
@@ -3161,22 +3016,33 @@
     ;;
   hpux10*|hpux11*)
     if test $with_gnu_ld = no; then
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
-
-      case $host_cpu in
-      hppa*64*|ia64*)
+      case "$host_cpu" in
+      hppa*64*)
+	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
 	_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
+	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+        ;;
+      ia64*)
+	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
         ;;
       *)
+	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
 	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
         ;;
       esac
     fi
-    case $host_cpu in
-    hppa*64*|ia64*)
+    case "$host_cpu" in
+    hppa*64*)
+      _LT_AC_TAGVAR(hardcode_direct, $1)=no
+      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+    ia64*)
       _LT_AC_TAGVAR(hardcode_direct, $1)=no
       _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+					      # but as the default
+					      # location of the library.
       ;;
     *)
       _LT_AC_TAGVAR(hardcode_direct, $1)=yes
@@ -3187,17 +3053,14 @@
     esac
 
     case $cc_basename in
-      CC*)
+      CC)
 	# FIXME: insert proper C++ library support
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
 	;;
-      aCC*)
-	case $host_cpu in
-	hppa*64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+      aCC)
+	case "$host_cpu" in
+	hppa*64*|ia64*)
+	  _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname -o $lib $linker_flags $libobjs $deplibs'
 	  ;;
 	*)
 	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
@@ -3216,12 +3079,9 @@
       *)
 	if test "$GXX" = yes; then
 	  if test $with_gnu_ld = no; then
-	    case $host_cpu in
-	    hppa*64*)
-	      _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	      ;;
-	    ia64*)
-	      _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	    case "$host_cpu" in
+	    ia64*|hppa*64*)
+	      _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname -o $lib $linker_flags $libobjs $deplibs'
 	      ;;
 	    *)
 	      _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
@@ -3235,25 +3095,11 @@
 	;;
     esac
     ;;
-  interix3*)
-    _LT_AC_TAGVAR(hardcode_direct, $1)=no
-    _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-    _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-    # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-    # Instead, shared libraries are loaded at an image base (0x10000000 by
-    # default) and relocated if they conflict, which is a slow very memory
-    # consuming and fragmenting process.  To avoid this, we pick a random,
-    # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-    # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-    _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-    _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-    ;;
   irix5* | irix6*)
     case $cc_basename in
-      CC*)
+      CC)
 	# SGI C++
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib'
 
 	# Archives containing C++ object files must be created using
 	# "CC -ar", where "CC" is the IRIX C++ compiler.  This is
@@ -3264,7 +3110,7 @@
       *)
 	if test "$GXX" = yes; then
 	  if test "$with_gnu_ld" = no; then
-	    _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	    _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib'
 	  else
 	    _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib'
 	  fi
@@ -3277,7 +3123,7 @@
     ;;
   linux*)
     case $cc_basename in
-      KCC*)
+      KCC)
 	# Kuck and Associates, Inc. (KAI) C++ Compiler
 
 	# KCC will only create a shared library if the output file
@@ -3302,7 +3148,7 @@
 	# "CC -Bstatic", where "CC" is the KAI C++ compiler.
 	_LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
 	;;
-      icpc*)
+      icpc)
 	# Intel C++
 	with_gnu_ld=yes
 	# version 8.0 and above of icpc choke on multiply defined symbols
@@ -3327,16 +3173,15 @@
 	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
 	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
 	;;
-      pgCC*)
+      pgCC)
         # Portland Group C++ compiler
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
-  	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+  	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
 
 	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
 	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
         ;;
-      cxx*)
+      cxx)
 	# Compaq C++
 	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
 	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
@@ -3367,7 +3212,7 @@
     ;;
   mvs*)
     case $cc_basename in
-      cxx*)
+      cxx)
 	# FIXME: insert proper C++ library support
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
 	;;
@@ -3406,7 +3251,7 @@
     ;;
   osf3*)
     case $cc_basename in
-      KCC*)
+      KCC)
 	# Kuck and Associates, Inc. (KAI) C++ Compiler
 
 	# KCC will only create a shared library if the output file
@@ -3422,14 +3267,14 @@
 	_LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
 
 	;;
-      RCC*)
+      RCC)
 	# Rational C++ 2.4.1
 	# FIXME: insert proper C++ library support
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
 	;;
-      cxx*)
+      cxx)
 	_LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${objdir}/so_locations -o $lib'
 
 	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
 	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
@@ -3447,7 +3292,7 @@
       *)
 	if test "$GXX" = yes && test "$with_gnu_ld" = no; then
 	  _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib'
 
 	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
 	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
@@ -3466,7 +3311,7 @@
     ;;
   osf4* | osf5*)
     case $cc_basename in
-      KCC*)
+      KCC)
 	# Kuck and Associates, Inc. (KAI) C++ Compiler
 
 	# KCC will only create a shared library if the output file
@@ -3481,17 +3326,17 @@
 	# the KAI C++ compiler.
 	_LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs'
 	;;
-      RCC*)
+      RCC)
 	# Rational C++ 2.4.1
 	# FIXME: insert proper C++ library support
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
 	;;
-      cxx*)
+      cxx)
 	_LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib'
 	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
 	  echo "-hidden">> $lib.exp~
-	  $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp  `test -n "$verstring" && echo -set_version	$verstring` -update_registry ${output_objdir}/so_locations -o $lib~
+	  $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp  `test -n "$verstring" && echo -set_version	$verstring` -update_registry $objdir/so_locations -o $lib~
 	  $rm $lib.exp'
 
 	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
@@ -3510,7 +3355,7 @@
       *)
 	if test "$GXX" = yes && test "$with_gnu_ld" = no; then
 	  _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	 _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	 _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib'
 
 	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
 	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
@@ -3531,14 +3376,27 @@
     # FIXME: insert proper C++ library support
     _LT_AC_TAGVAR(ld_shlibs, $1)=no
     ;;
+  sco*)
+    _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+    case $cc_basename in
+      CC)
+	# FIXME: insert proper C++ library support
+	_LT_AC_TAGVAR(ld_shlibs, $1)=no
+	;;
+      *)
+	# FIXME: insert proper C++ library support
+	_LT_AC_TAGVAR(ld_shlibs, $1)=no
+	;;
+    esac
+    ;;
   sunos4*)
     case $cc_basename in
-      CC*)
+      CC)
 	# Sun C++ 4.x
 	# FIXME: insert proper C++ library support
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
 	;;
-      lcc*)
+      lcc)
 	# Lucid
 	# FIXME: insert proper C++ library support
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
@@ -3551,13 +3409,12 @@
     ;;
   solaris*)
     case $cc_basename in
-      CC*)
+      CC)
 	# Sun C++ 4.2, 5.x and Centerline C++
-        _LT_AC_TAGVAR(archive_cmds_need_lc,$1)=yes
 	_LT_AC_TAGVAR(no_undefined_flag, $1)=' -zdefs'
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -nolib -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-	$CC -G${allow_undefined_flag}  ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+	$CC -G${allow_undefined_flag} -nolib ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
 
 	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
 	_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
@@ -3566,18 +3423,22 @@
 	  *)
 	    # The C++ compiler is used as linker so we must use $wl
 	    # flag to pass the commands to the underlying system
-	    # linker. We must also pass each convience library through
-	    # to the system linker between allextract/defaultextract.
-	    # The C++ compiler will combine linker options so we
-	    # cannot just pass the convience library names through
-	    # without $wl.
+	    # linker.
 	    # Supported since Solaris 2.6 (maybe 2.5.1?)
-	    _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract'
+	    _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
 	    ;;
 	esac
 	_LT_AC_TAGVAR(link_all_deplibs, $1)=yes
 
-	output_verbose_link_cmd='echo'
+	# Commands to make compiler produce verbose output that lists
+	# what "hidden" libraries, object files and flags are used when
+	# linking a shared library.
+	#
+	# There doesn't appear to be a way to prevent this compiler from
+	# explicitly linking system object files so we need to strip them
+	# from the output so that they don't get included in the library
+	# dependencies.
+	output_verbose_link_cmd='templist=`$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep "\-[[LR]]"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
 
 	# Archives containing C++ object files must be created using
 	# "CC -xar", where "CC" is the Sun C++ compiler.  This is
@@ -3585,7 +3446,7 @@
 	# in the archive.
 	_LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
 	;;
-      gcx*)
+      gcx)
 	# Green Hills C++ Compiler
 	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
 
@@ -3623,63 +3484,12 @@
 	;;
     esac
     ;;
-  sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
-    _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-    _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
-    _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
-    runpath_var='LD_RUN_PATH'
-
-    case $cc_basename in
-      CC*)
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-      *)
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-    esac
-    ;;
-  sysv5* | sco3.2v5* | sco5v6*)
-    # Note: We can NOT use -z defs as we might desire, because we do not
-    # link with -lc, and that would cause any symbols used from libc to
-    # always be unresolved, which means just about no library would
-    # ever link correctly.  If we're not using GNU ld we use -z text
-    # though, which does catch some bad symbols but isn't as heavy-handed
-    # as -z defs.
-    # For security reasons, it is highly recommended that you always
-    # use absolute paths for naming shared libraries, and exclude the
-    # DT_RUNPATH tag from executables and libraries.  But doing so
-    # requires that you compile everything twice, which is a pain.
-    # So that behaviour is only enabled if SCOABSPATH is set to a
-    # non-empty value in the environment.  Most likely only useful for
-    # creating official distributions of packages.
-    # This is a hack until libtool officially supports absolute path
-    # names for shared libraries.
-    _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-    _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+  sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[[78]]* | unixware7*)
     _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
-    _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
-    _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
-    _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
-    _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
-    runpath_var='LD_RUN_PATH'
-
-    case $cc_basename in
-      CC*)
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-      *)
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-    esac
     ;;
   tandem*)
     case $cc_basename in
-      NCC*)
+      NCC)
 	# NonStop-UX NCC 3.20
 	# FIXME: insert proper C++ library support
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
@@ -3712,6 +3522,8 @@
 AC_LIBTOOL_PROG_LD_SHLIBS($1)
 AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
 AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+AC_LIBTOOL_SYS_LIB_STRIP
+AC_LIBTOOL_DLOPEN_SELF($1)
 
 AC_LIBTOOL_CONFIG($1)
 
@@ -3729,7 +3541,7 @@
 ])# AC_LIBTOOL_LANG_CXX_CONFIG
 
 # AC_LIBTOOL_POSTDEP_PREDEP([TAGNAME])
-# ------------------------------------
+# ------------------------
 # Figure out "hidden" library dependencies from verbose
 # compiler output when linking a shared library.
 # Parse the compiler output and extract the necessary
@@ -3783,7 +3595,7 @@
   # The `*' in the case matches for architectures that use `case' in
   # $output_verbose_cmd can trigger glob expansion during the loop
   # eval without this substitution.
-  output_verbose_link_cmd=`$echo "X$output_verbose_link_cmd" | $Xsed -e "$no_glob_subst"`
+  output_verbose_link_cmd="`$echo \"X$output_verbose_link_cmd\" | $Xsed -e \"$no_glob_subst\"`"
 
   for p in `eval $output_verbose_link_cmd`; do
     case $p in
@@ -3859,37 +3671,13 @@
 
 $rm -f confest.$objext
 
-# PORTME: override above test on systems where it is broken
-ifelse([$1],[CXX],
-[case $host_os in
-interix3*)
-  # Interix 3.5 installs completely hosed .la files for C++, so rather than
-  # hack all around it, let's just trust "g++" to DTRT.
-  _LT_AC_TAGVAR(predep_objects,$1)=
-  _LT_AC_TAGVAR(postdep_objects,$1)=
-  _LT_AC_TAGVAR(postdeps,$1)=
-  ;;
-
-solaris*)
-  case $cc_basename in
-  CC*)
-    # Adding this requires a known-good setup of shared libraries for
-    # Sun compiler versions before 5.6, else PIC objects from an old
-    # archive will be linked into the output, leading to subtle bugs.
-    _LT_AC_TAGVAR(postdeps,$1)='-lCstd -lCrun'
-    ;;
-  esac
-  ;;
-esac
-])
-
 case " $_LT_AC_TAGVAR(postdeps, $1) " in
 *" -lc "*) _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no ;;
 esac
 ])# AC_LIBTOOL_POSTDEP_PREDEP
 
 # AC_LIBTOOL_LANG_F77_CONFIG
-# --------------------------
+# ------------------------
 # Ensure that the configuration vars for the C compiler are
 # suitably defined.  Those variables are subsequently used by
 # AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
@@ -3933,16 +3721,12 @@
 # ltmain only uses $CC for tagged configurations so make sure $CC is set.
 _LT_AC_SYS_COMPILER
 
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
 # Allow CC to be a program name with arguments.
 lt_save_CC="$CC"
 CC=${F77-"f77"}
 compiler=$CC
 _LT_AC_TAGVAR(compiler, $1)=$CC
-_LT_CC_BASENAME([$compiler])
+cc_basename=`$echo X"$compiler" | $Xsed -e 's%^.*/%%'`
 
 AC_MSG_CHECKING([if libtool supports shared libraries])
 AC_MSG_RESULT([$can_build_shared])
@@ -3952,7 +3736,7 @@
 
 # On AIX, shared libraries and static libraries use the same namespace, and
 # are all built from PIC.
-case $host_os in
+case "$host_os" in
 aix3*)
   test "$enable_shared" = yes && enable_static=no
   if test -n "$RANLIB"; then
@@ -3961,9 +3745,7 @@
   fi
   ;;
 aix4* | aix5*)
-  if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-    test "$enable_shared" = yes && enable_static=no
-  fi
+  test "$enable_shared" = yes && enable_static=no
   ;;
 esac
 AC_MSG_RESULT([$enable_shared])
@@ -3973,6 +3755,8 @@
 test "$enable_shared" = yes || enable_static=yes
 AC_MSG_RESULT([$enable_static])
 
+test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
 _LT_AC_TAGVAR(GCC, $1)="$G77"
 _LT_AC_TAGVAR(LD, $1)="$LD"
 
@@ -3982,6 +3766,8 @@
 AC_LIBTOOL_PROG_LD_SHLIBS($1)
 AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
 AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+AC_LIBTOOL_SYS_LIB_STRIP
+
 
 AC_LIBTOOL_CONFIG($1)
 
@@ -4015,22 +3801,15 @@
 # ltmain only uses $CC for tagged configurations so make sure $CC is set.
 _LT_AC_SYS_COMPILER
 
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
 # Allow CC to be a program name with arguments.
 lt_save_CC="$CC"
 CC=${GCJ-"gcj"}
 compiler=$CC
 _LT_AC_TAGVAR(compiler, $1)=$CC
-_LT_CC_BASENAME([$compiler])
 
 # GCJ did not exist at the time GCC didn't implicitly link libc in.
 _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
 
-_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-
 AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1)
 AC_LIBTOOL_PROG_COMPILER_PIC($1)
 AC_LIBTOOL_PROG_CC_C_O($1)
@@ -4038,6 +3817,8 @@
 AC_LIBTOOL_PROG_LD_SHLIBS($1)
 AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
 AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+AC_LIBTOOL_SYS_LIB_STRIP
+AC_LIBTOOL_DLOPEN_SELF($1)
 
 AC_LIBTOOL_CONFIG($1)
 
@@ -4047,7 +3828,7 @@
 
 
 # AC_LIBTOOL_LANG_RC_CONFIG
-# -------------------------
+# --------------------------
 # Ensure that the configuration vars for the Windows resource compiler are
 # suitably defined.  Those variables are subsequently used by
 # AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
@@ -4071,16 +3852,11 @@
 # ltmain only uses $CC for tagged configurations so make sure $CC is set.
 _LT_AC_SYS_COMPILER
 
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
 # Allow CC to be a program name with arguments.
 lt_save_CC="$CC"
 CC=${RC-"windres"}
 compiler=$CC
 _LT_AC_TAGVAR(compiler, $1)=$CC
-_LT_CC_BASENAME([$compiler])
 _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
 
 AC_LIBTOOL_CONFIG($1)
@@ -4110,7 +3886,7 @@
   # Now quote all the things that may contain metacharacters while being
   # careful not to overquote the AC_SUBSTed values.  We take copies of the
   # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \
     SED SHELL STRIP \
     libname_spec library_names_spec soname_spec extract_expsyms_cmds \
     old_striplib striplib file_magic_cmd finish_cmds finish_eval \
@@ -4216,7 +3992,7 @@
 #
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 #
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
@@ -4227,7 +4003,7 @@
 SED=$lt_SED
 
 # Sed that helps us avoid accidentally triggering echo(1) options like -n.
-Xsed="$SED -e 1s/^X//"
+Xsed="$SED -e s/^X//"
 
 # The HP-UX ksh and POSIX shell print the target directory to stdout
 # if CDPATH is set.
@@ -4279,9 +4055,6 @@
 # A C compiler.
 LTCC=$lt_LTCC
 
-# LTCC compiler flags.
-LTCFLAGS=$lt_LTCFLAGS
-
 # A language-specific compiler.
 CC=$lt_[]_LT_AC_TAGVAR(compiler, $1)
 
@@ -4347,7 +4120,7 @@
 # Does compiler simultaneously support -c and -o options?
 compiler_c_o=$lt_[]_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)
 
-# Must we lock files when doing compilation?
+# Must we lock files when doing compilation ?
 need_locks=$lt_need_locks
 
 # Do we need the lib prefix for modules?
@@ -4655,18 +4428,9 @@
 osf*)
   symcode='[[BCDEGQRST]]'
   ;;
-solaris*)
+solaris* | sysv5*)
   symcode='[[BDRT]]'
   ;;
-sco3.2v5*)
-  symcode='[[DT]]'
-  ;;
-sysv4.2uw2*)
-  symcode='[[DT]]'
-  ;;
-sysv5* | sco5v6* | unixware* | OpenUNIX*)
-  symcode='[[ABDT]]'
-  ;;
 sysv4)
   symcode='[[DFNSTU]]'
   ;;
@@ -4849,10 +4613,6 @@
       # DJGPP does not support shared libraries at all
       _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
       ;;
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
     sysv4*MP*)
       if test -d /usr/nec; then
 	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
@@ -4861,7 +4621,7 @@
     hpux*)
       # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
       # not for PA HP-UX.
-      case $host_cpu in
+      case "$host_cpu" in
       hppa*64*|ia64*)
 	;;
       *)
@@ -4886,7 +4646,7 @@
 	;;
       chorus*)
 	case $cc_basename in
-	cxch68*)
+	cxch68)
 	  # Green Hills C++ Compiler
 	  # _LT_AC_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
 	  ;;
@@ -4895,7 +4655,7 @@
        darwin*)
          # PIC is the default on this platform
          # Common symbols not allowed in MH_DYLIB files
-         case $cc_basename in
+         case "$cc_basename" in
            xlc*)
            _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-qnocommon'
            _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
@@ -4904,10 +4664,10 @@
        ;;
       dgux*)
 	case $cc_basename in
-	  ec++*)
+	  ec++)
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
 	    ;;
-	  ghcx*)
+	  ghcx)
 	    # Green Hills C++ Compiler
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
 	    ;;
@@ -4920,17 +4680,17 @@
 	;;
       hpux9* | hpux10* | hpux11*)
 	case $cc_basename in
-	  CC*)
+	  CC)
 	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)="${ac_cv_prog_cc_wl}-a ${ac_cv_prog_cc_wl}archive"
 	    if test "$host_cpu" != ia64; then
 	      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
 	    fi
 	    ;;
-	  aCC*)
+	  aCC)
 	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-	    case $host_cpu in
+	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)="${ac_cv_prog_cc_wl}-a ${ac_cv_prog_cc_wl}archive"
+	    case "$host_cpu" in
 	    hppa*64*|ia64*)
 	      # +Z the default
 	      ;;
@@ -4943,13 +4703,9 @@
 	    ;;
 	esac
 	;;
-      interix*)
-	# This is c89, which is MS Visual C++ (no shared libs)
-	# Anyone wants to do a port?
-	;;
       irix5* | irix6* | nonstopux*)
 	case $cc_basename in
-	  CC*)
+	  CC)
 	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
 	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
 	    # CC pic flag -KPIC is the default.
@@ -4960,7 +4716,7 @@
 	;;
       linux*)
 	case $cc_basename in
-	  KCC*)
+	  KCC)
 	    # KAI C++ Compiler
 	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
@@ -4971,13 +4727,13 @@
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
 	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
 	    ;;
-	  pgCC*)
+	  pgCC)
 	    # Portland Group C++ compiler.
 	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
 	    ;;
-	  cxx*)
+	  cxx)
 	    # Compaq C++
 	    # Make sure the PIC flag is empty.  It appears that all Alpha
 	    # Linux and Compaq Tru64 Unix objects are PIC.
@@ -4994,7 +4750,7 @@
 	;;
       mvs*)
 	case $cc_basename in
-	  cxx*)
+	  cxx)
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
 	    ;;
 	  *)
@@ -5005,14 +4761,14 @@
 	;;
       osf3* | osf4* | osf5*)
 	case $cc_basename in
-	  KCC*)
+	  KCC)
 	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
 	    ;;
-	  RCC*)
+	  RCC)
 	    # Rational C++ 2.4.1
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
 	    ;;
-	  cxx*)
+	  cxx)
 	    # Digital/Compaq C++
 	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
 	    # Make sure the PIC flag is empty.  It appears that all Alpha
@@ -5026,15 +4782,24 @@
 	;;
       psos*)
 	;;
+      sco*)
+	case $cc_basename in
+	  CC)
+	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
       solaris*)
 	case $cc_basename in
-	  CC*)
+	  CC)
 	    # Sun C++ 4.2, 5.x and Centerline C++
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
 	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
 	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
 	    ;;
-	  gcx*)
+	  gcx)
 	    # Green Hills C++ Compiler
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
 	    ;;
@@ -5044,12 +4809,12 @@
 	;;
       sunos4*)
 	case $cc_basename in
-	  CC*)
+	  CC)
 	    # Sun C++ 4.x
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
 	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
 	    ;;
-	  lcc*)
+	  lcc)
 	    # Lucid
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
 	    ;;
@@ -5059,7 +4824,7 @@
 	;;
       tandem*)
 	case $cc_basename in
-	  NCC*)
+	  NCC)
 	    # NonStop-UX NCC 3.20
 	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
 	    ;;
@@ -5067,14 +4832,7 @@
 	    ;;
 	esac
 	;;
-      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-	case $cc_basename in
-	  CC*)
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	esac
+      unixware*)
 	;;
       vxworks*)
 	;;
@@ -5121,11 +4879,6 @@
       _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
       ;;
 
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
     msdosdjgpp*)
       # Just because we use GCC doesn't mean we suddenly get shared libraries
       # on systems that don't support them.
@@ -5142,7 +4895,7 @@
     hpux*)
       # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
       # not for PA HP-UX.
-      case $host_cpu in
+      case "$host_cpu" in
       hppa*64*|ia64*)
 	# +Z the default
 	;;
@@ -5171,7 +4924,7 @@
       darwin*)
         # PIC is the default on this platform
         # Common symbols not allowed in MH_DYLIB files
-       case $cc_basename in
+       case "$cc_basename" in
          xlc*)
          _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-qnocommon'
          _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
@@ -5189,7 +4942,7 @@
       _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
       # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
       # not for PA HP-UX.
-      case $host_cpu in
+      case "$host_cpu" in
       hppa*64*|ia64*)
 	# +Z the default
 	;;
@@ -5219,12 +4972,12 @@
 	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
 	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
         ;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
+      pgcc | pgf77 | pgf90)
         # Portland Group compilers (*not* the Pentium gcc compiler,
 	# which looks to be a dead project)
 	_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
 	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
         ;;
       ccc*)
         _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
@@ -5240,15 +4993,15 @@
       _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
       ;;
 
+    sco3.2v5*)
+      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-Kpic'
+      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-dn'
+      ;;
+
     solaris*)
+      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
       _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
       _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95*)
-	_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
-      *)
-	_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
-      esac
       ;;
 
     sunos4*)
@@ -5257,7 +5010,7 @@
       _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
       ;;
 
-    sysv4 | sysv4.2uw2* | sysv4.3*)
+    sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
       _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
       _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
       _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
@@ -5270,12 +5023,6 @@
       fi
       ;;
 
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
     unicos*)
       _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
       _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
@@ -5308,7 +5055,7 @@
     [_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
      _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
 fi
-case $host_os in
+case "$host_os" in
   # For platforms which do not support PIC, -DPIC is meaningless:
   *djgpp*)
     _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
@@ -5317,16 +5064,6 @@
     _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])"
     ;;
 esac
-
-#
-# Check to make sure the static flag actually works.
-#
-wl=$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_AC_TAGVAR(lt_prog_compiler_static, $1)\"
-AC_LIBTOOL_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
-  _LT_AC_TAGVAR(lt_prog_compiler_static_works, $1),
-  $lt_tmp_static_flag,
-  [],
-  [_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=])
 ])
 
 
@@ -5394,8 +5131,7 @@
   # rely on this symbol name, it's probably fine to never include it in
   # preloaded symbol tables.
   extract_expsyms_cmds=
-  # Just being paranoid about ensuring that cc_basename is set.
-  _LT_CC_BASENAME([$compiler])
+
   case $host_os in
   cygwin* | mingw* | pw32*)
     # FIXME: the MSVC++ port hasn't been tested in a loooong time
@@ -5405,10 +5141,6 @@
       with_gnu_ld=no
     fi
     ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (= MSVC++)
-    with_gnu_ld=yes
-    ;;
   openbsd*)
     with_gnu_ld=no
     ;;
@@ -5419,27 +5151,6 @@
     # If archive_cmds runs LD, not CC, wlarc should be empty
     wlarc='${wl}'
 
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=LD_RUN_PATH
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
-    _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
-	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-      else
-  	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
-    fi
-    supports_anon_versioning=no
-    case `$LD -v 2>/dev/null` in
-      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=yes ;;
-    esac
-
     # See if GNU ld supports shared libraries.
     case $host_os in
     aix3* | aix4* | aix5*)
@@ -5493,7 +5204,7 @@
       _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]] /s/.* \([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]] /s/.* //'\'' | sort | uniq > $export_symbols'
 
       if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-        _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+        _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib'
 	# If the export-symbols file already is a .def file (1st line
 	# is EXPORTS), use it as is; otherwise, prepend...
 	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
@@ -5502,53 +5213,7 @@
 	  echo EXPORTS > $output_objdir/$soname.def;
 	  cat $export_symbols >> $output_objdir/$soname.def;
 	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      else
-	_LT_AC_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    interix3*)
-      _LT_AC_TAGVAR(hardcode_direct, $1)=no
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-      # Instead, shared libraries are loaded at an image base (0x10000000 by
-      # default) and relocated if they conflict, which is a slow very memory
-      # consuming and fragmenting process.  To avoid this, we pick a random,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      ;;
-
-    linux*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	tmp_addflag=
-	case $cc_basename,$host_cpu in
-	pgcc*)				# Portland Group C compiler
-	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
-	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
-	  tmp_addflag=' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=' -nofor_main' ;;
-	esac
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-
-	if test $supports_anon_versioning = yes; then
-	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $output_objdir/$libname.ver~
-  cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-  $echo "local: *; };" >> $output_objdir/$libname.ver~
-	  $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-	fi
+	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000  ${wl}--out-implib,$lib'
       else
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
       fi
@@ -5564,7 +5229,7 @@
       fi
       ;;
 
-    solaris*)
+    solaris* | sysv5*)
       if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
 	_LT_AC_TAGVAR(ld_shlibs, $1)=no
 	cat <<EOF 1>&2
@@ -5585,33 +5250,6 @@
       fi
       ;;
 
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) 
-	_LT_AC_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
-	    _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
-	    _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib'
-	  else
-	    _LT_AC_TAGVAR(ld_shlibs, $1)=no
-	  fi
-	;;
-      esac
-      ;;
-
     sunos4*)
       _LT_AC_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
       wlarc=
@@ -5619,6 +5257,41 @@
       _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
       ;;
 
+  linux*)
+    if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+      tmp_addflag=
+      case $CC,$host_cpu in
+      pgf77* | pgf90* )			# Portland Group f77 and f90 compilers
+        tmp_addflag=' -fpic' ;;
+      ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
+        tmp_addflag=' -i_dynamic' ;;
+      efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
+        tmp_addflag=' -i_dynamic -nofor_main' ;;
+      ifc* | ifort*)			# Intel Fortran compiler
+      	tmp_addflag=' -nofor_main' ;;
+      esac
+      _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      supports_anon_versioning=no
+      case `$LD -v 2>/dev/null` in
+        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
+        *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+        *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+        *\ 2.11.*) ;; # other 2.11 versions
+        *) supports_anon_versioning=yes ;;
+      esac
+      if test $supports_anon_versioning = yes; then
+        _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $output_objdir/$libname.ver~
+cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+$echo "local: *; };" >> $output_objdir/$libname.ver~
+        $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+      else
+        _LT_AC_TAGVAR(archive_expsym_cmds, $1)=$_LT_AC_TAGVAR(archive_cmds, $1)
+      fi
+    else
+      _LT_AC_TAGVAR(ld_shlibs, $1)=no
+    fi
+    ;;
+
     *)
       if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
 	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
@@ -5629,11 +5302,16 @@
       ;;
     esac
 
-    if test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no; then
-      runpath_var=
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=
-      _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+    if test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = yes; then
+      runpath_var=LD_RUN_PATH
+      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+      # ancient GNU ld didn't support --whole-archive et. al.
+      if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
+ 	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+      else
+  	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+      fi
     fi
   else
     # PORTME fill in a description of your system's linker (not GNU ld)
@@ -5645,7 +5323,7 @@
       # Note: this linker hardcodes the directories in LIBPATH if there
       # are no directories specified by -L.
       _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+      if test "$GCC" = yes && test -z "$link_static_flag"; then
 	# Neither direct hardcoding nor static linking is supported with a
 	# broken collect2.
 	_LT_AC_TAGVAR(hardcode_direct, $1)=unsupported
@@ -5679,7 +5357,6 @@
   	    break
   	  fi
 	  done
-	  ;;
 	esac
 
 	exp_sym_flag='-bexport'
@@ -5717,7 +5394,6 @@
   	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
   	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
 	  fi
-	  ;;
 	esac
 	shared_flag='-shared'
 	if test "$aix_use_runtimelinking" = yes; then
@@ -5730,11 +5406,11 @@
   	# chokes on -Wl,-G. The following line is correct:
 	  shared_flag='-G'
 	else
-	  if test "$aix_use_runtimelinking" = yes; then
+  	if test "$aix_use_runtimelinking" = yes; then
 	    shared_flag='${wl}-G'
 	  else
 	    shared_flag='${wl}-bM:SRE'
-	  fi
+  	fi
 	fi
       fi
 
@@ -5748,12 +5424,12 @@
        # Determine the default libpath from the value encoded in an empty executable.
        _LT_AC_SYS_LIBPATH_AIX
        _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+	_LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag"
        else
 	if test "$host_cpu" = ia64; then
 	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
 	  _LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols"
 	else
 	 # Determine the default libpath from the value encoded in an empty executable.
 	 _LT_AC_SYS_LIBPATH_AIX
@@ -5762,11 +5438,13 @@
 	  # -berok will link without error, but may produce a broken library.
 	  _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
 	  _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	  # -bexpall does not export symbols beginning with underscore (_)
+	  _LT_AC_TAGVAR(always_export_symbols, $1)=yes
 	  # Exported symbols can be pulled into shared objects from archives
-	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=' '
 	  _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	  # This is similar to how AIX traditionally builds it's shared libraries.
+	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
 	fi
       fi
       ;;
@@ -5805,7 +5483,7 @@
       ;;
 
     darwin* | rhapsody*)
-      case $host_os in
+      case "$host_os" in
         rhapsody* | darwin1.[[012]])
          _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}suppress'
          ;;
@@ -5834,16 +5512,16 @@
     	output_verbose_link_cmd='echo'
         _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
       _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-      # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+      # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
       _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
       _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
     else
-      case $cc_basename in
+      case "$cc_basename" in
         xlc*)
          output_verbose_link_cmd='echo'
          _LT_AC_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
          _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
          _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           ;;
@@ -5907,62 +5585,47 @@
       _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
       ;;
 
-    hpux10*)
-      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" = no; then
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	_LT_AC_TAGVAR(hardcode_direct, $1)=yes
-	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	_LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
-      fi
-      ;;
-
-    hpux11*)
+    hpux10* | hpux11*)
       if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	case $host_cpu in
-	hppa*64*)
+	case "$host_cpu" in
+	hppa*64*|ia64*)
 	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
-	ia64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
 	*)
 	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	esac
       else
-	case $host_cpu in
-	hppa*64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	case "$host_cpu" in
+	hppa*64*|ia64*)
+	  _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname -o $lib $libobjs $deplibs $linker_flags'
 	  ;;
 	*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
 	  ;;
 	esac
       fi
       if test "$with_gnu_ld" = no; then
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
+	case "$host_cpu" in
+	hppa*64*)
+	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
 	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
+	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
 	  _LT_AC_TAGVAR(hardcode_direct, $1)=no
 	  _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
 	  ;;
+	ia64*)
+	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	  _LT_AC_TAGVAR(hardcode_direct, $1)=no
+	  _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+	  ;;
 	*)
+	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
 	  _LT_AC_TAGVAR(hardcode_direct, $1)=yes
 	  _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
 
@@ -6056,7 +5719,7 @@
 	_LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
 	_LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
 	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
-	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib~$rm $lib.exp'
 
 	# Both c and cxx compiler support -rpath directly
 	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
@@ -6064,15 +5727,21 @@
       _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
       ;;
 
+    sco3.2v5*)
+      _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+      runpath_var=LD_RUN_PATH
+      hardcode_runpath_var=yes
+      ;;
+
     solaris*)
       _LT_AC_TAGVAR(no_undefined_flag, $1)=' -z text'
       if test "$GCC" = yes; then
-	wlarc='${wl}'
 	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
 	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
 	  $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
       else
-	wlarc=''
 	_LT_AC_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
 	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
   	$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
@@ -6081,18 +5750,8 @@
       _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
       case $host_os in
       solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-      *)
- 	# The compiler driver will combine linker options so we
- 	# cannot just pass the convience library names through
- 	# without $wl, iff we do not link with $LD.
- 	# Luckily, gcc supports the same syntax we need for Sun Studio.
- 	# Supported since Solaris 2.6 (maybe 2.5.1?)
- 	case $wlarc in
- 	'')
- 	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;;
- 	*)
- 	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
- 	esac ;;
+      *) # Supported since Solaris 2.6 (maybe 2.5.1?)
+	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;;
       esac
       _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
       ;;
@@ -6149,45 +5808,36 @@
       fi
       ;;
 
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7*)
-      _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+    sysv4.2uw2*)
+      _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+      _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+      _LT_AC_TAGVAR(hardcode_minus_L, $1)=no
       _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
-      runpath_var='LD_RUN_PATH'
+      hardcode_runpath_var=yes
+      runpath_var=LD_RUN_PATH
+      ;;
 
+   sysv5OpenUNIX8* | sysv5UnixWare7* |  sysv5uw[[78]]* | unixware7*)
+      _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z ${wl}text'
       if test "$GCC" = yes; then
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
       else
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
       fi
+      runpath_var='LD_RUN_PATH'
+      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
       ;;
 
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
-      _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+    sysv5*)
+      _LT_AC_TAGVAR(no_undefined_flag, $1)=' -z text'
+      # $CC -shared without GNU ld will not create a library from C++
+      # object files and a static libstdc++, better avoid it by now
+      _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+  		$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
       _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
-      _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
       runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
       ;;
 
     uts4*)
@@ -6205,6 +5855,11 @@
 AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)])
 test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
 
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
 #
 # Do we need to explicitly link libc?
 #
@@ -6232,7 +5887,6 @@
         libobjs=conftest.$ac_objext
         deplibs=
         wl=$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)
-	pic_flag=$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)
         compiler_flags=-v
         linker_flags=-v
         verstring=
@@ -6388,23 +6042,11 @@
 AC_MSG_RESULT([$SED])
 ])
 
-#                                                        -*- Autoconf -*-
-# Copyright (C) 2002, 2003  Free Software Foundation, Inc.
-# Generated from amversion.in; do not edit by hand.
-
-# 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, 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
+# Copyright (C) 2002, 2003, 2005  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.
 
 # AM_AUTOMAKE_VERSION(VERSION)
 # ----------------------------
@@ -6417,26 +6059,15 @@
 # Call AM_AUTOMAKE_VERSION so it can be traced.
 # This function is AC_REQUIREd by AC_INIT_AUTOMAKE.
 AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION],
-	 [AM_AUTOMAKE_VERSION([1.9.2])])
-
-# AM_AUX_DIR_EXPAND
+	 [AM_AUTOMAKE_VERSION([1.9.5])])
 
-# Copyright (C) 2001, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
+# AM_AUX_DIR_EXPAND                                         -*- Autoconf -*-
 
-# 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.
+# Copyright (C) 2001, 2003, 2005  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.
 
 # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets
 # $ac_aux_dir to `$srcdir/foo'.  In other projects, it is set to
@@ -6483,26 +6114,16 @@
 am_aux_dir=`cd $ac_aux_dir && pwd`
 ])
 
-# AM_CONDITIONAL                                              -*- Autoconf -*-
-
-# Copyright (C) 1997, 2000, 2001, 2003, 2004 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, 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.
+# AM_CONDITIONAL                                            -*- Autoconf -*-
 
-# 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.
+# Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005
+# 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.
 
-# serial 6
+# serial 7
 
 # AM_CONDITIONAL(NAME, SHELL-CONDITION)
 # -------------------------------------
@@ -6526,26 +6147,15 @@
 Usually this means the macro was only invoked conditionally.]])
 fi])])
 
-# serial 7						-*- Autoconf -*-
 
-# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004
+# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005
 # 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 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, 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.
-
+# serial 8
 
 # There are a few dirty hacks below to avoid letting `AC_PROG_CC' be
 # written in clear, in which case automake, when reading aclocal.m4,
@@ -6554,7 +6164,6 @@
 # CC etc. in the Makefile, will ask for an AC_PROG_CC use...
 
 
-
 # _AM_DEPENDENCIES(NAME)
 # ----------------------
 # See how the compiler implements dependency checking.
@@ -6694,27 +6303,16 @@
 AC_SUBST([AMDEPBACKSLASH])
 ])
 
-# Generate code to set up dependency tracking.   -*- Autoconf -*-
-
-# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004
-#   Free Software Foundation, Inc.
+# Generate code to set up dependency tracking.              -*- Autoconf -*-
 
-# 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, 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.
+# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005
+# 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.
 
-#serial 2
+#serial 3
 
 # _AM_OUTPUT_DEPENDENCY_COMMANDS
 # ------------------------------
@@ -6773,30 +6371,19 @@
      [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"])
 ])
 
-# Do all the work for Automake.                            -*- Autoconf -*-
+# Do all the work for Automake.                             -*- Autoconf -*-
 
-# This macro actually does too much some checks are only needed if
-# your package does certain things.  But this isn't really a big deal.
-
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
 # 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 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, 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.
+# serial 12
 
-# serial 11
+# This macro actually does too much.  Some checks are only needed if
+# your package does certain things.  But this isn't really a big deal.
 
 # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE])
 # AM_INIT_AUTOMAKE([OPTIONS])
@@ -6898,51 +6485,27 @@
 done
 echo "timestamp for $1" >`AS_DIRNAME([$1])`/stamp-h[]$_am_stamp_count])
 
+# Copyright (C) 2001, 2003, 2005  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.
+
 # AM_PROG_INSTALL_SH
 # ------------------
 # Define $install_sh.
-
-# Copyright (C) 2001, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, 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.
-
 AC_DEFUN([AM_PROG_INSTALL_SH],
 [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
 install_sh=${install_sh-"$am_aux_dir/install-sh"}
 AC_SUBST(install_sh)])
 
-#                                                          -*- Autoconf -*-
-# Copyright (C) 2003  Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, 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.
+# Copyright (C) 2003, 2005  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.
 
-# serial 1
+# serial 2
 
 # Check whether the underlying file-system supports filenames
 # with a leading dot.  For instance MS-DOS doesn't.
@@ -6957,26 +6520,15 @@
 rmdir .tst 2>/dev/null
 AC_SUBST([am__leading_dot])])
 
-# Check to see how 'make' treats includes.	-*- Autoconf -*-
-
-# Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
+# Check to see how 'make' treats includes.	            -*- Autoconf -*-
 
-# 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.
+# Copyright (C) 2001, 2002, 2003, 2005  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.
 
-# serial 2
+# serial 3
 
 # AM_MAKE_INCLUDE()
 # -----------------
@@ -7020,27 +6572,16 @@
 rm -f confinc confmf
 ])
 
-#  -*- Autoconf -*-
-
-
-# Copyright (C) 1997, 1999, 2000, 2001, 2003 Free Software Foundation, Inc.
+# Fake the existence of programs that GNU maintainers use.  -*- Autoconf -*-
 
-# 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, 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.
+# Copyright (C) 1997, 1999, 2000, 2001, 2003, 2005
+# 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.
 
-# serial 3
+# serial 4
 
 # AM_MISSING_PROG(NAME, PROGRAM)
 # ------------------------------
@@ -7066,27 +6607,16 @@
 fi
 ])
 
+# Copyright (C) 2003, 2004, 2005  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.
+
 # AM_PROG_MKDIR_P
 # ---------------
 # Check whether `mkdir -p' is supported, fallback to mkinstalldirs otherwise.
-
-# Copyright (C) 2003, 2004 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, 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.
-
+#
 # Automake 1.8 used `mkdir -m 0755 -p --' to ensure that directories
 # created by `make install' are always world readable, even if the
 # installer happens to have an overly restrictive umask (e.g. 077).
@@ -7140,26 +6670,15 @@
 fi
 AC_SUBST([mkdir_p])])
 
-# Helper functions for option handling.                    -*- Autoconf -*-
-
-# Copyright (C) 2001, 2002, 2003  Free Software Foundation, Inc.
+# Helper functions for option handling.                     -*- Autoconf -*-
 
-# 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, 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.
+# Copyright (C) 2001, 2002, 2003, 2005  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.
 
-# serial 2
+# serial 3
 
 # _AM_MANGLE_OPTION(NAME)
 # -----------------------
@@ -7184,28 +6703,16 @@
 AC_DEFUN([_AM_IF_OPTION],
 [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])])
 
-#
-# Check to make sure that the build environment is sane.
-#
-
-# Copyright (C) 1996, 1997, 2000, 2001, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, 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.
+# Check to make sure that the build environment is sane.    -*- Autoconf -*-
 
-# 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.
+# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005
+# 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.
 
-# serial 3
+# serial 4
 
 # AM_SANITY_CHECK
 # ---------------
@@ -7248,25 +6755,14 @@
 fi
 AC_MSG_RESULT(yes)])
 
-# AM_PROG_INSTALL_STRIP
-
-# Copyright (C) 2001, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, 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.
+# Copyright (C) 2001, 2003, 2005  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.
 
+# AM_PROG_INSTALL_STRIP
+# ---------------------
 # One issue with vendor `install' (even GNU) is that you can't
 # specify the program used to strip binaries.  This is especially
 # annoying in cross-compiling environments, where the build's strip
@@ -7289,25 +6785,13 @@
 
 # Check how to create a tarball.                            -*- Autoconf -*-
 
-# Copyright (C) 2004  Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, 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.
-
-# serial 1
+# Copyright (C) 2004, 2005  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.
 
+# serial 2
 
 # _AM_PROG_TAR(FORMAT)
 # --------------------

Modified: freeswitch/branches/cparker/build/buildlib.sh
==============================================================================
--- freeswitch/branches/cparker/build/buildlib.sh	(original)
+++ freeswitch/branches/cparker/build/buildlib.sh	Tue Apr 24 10:14:28 2007
@@ -9,10 +9,6 @@
     exit 0
 fi
 
-if [ -f $root/build/freeswitch.env ] ; then
-    . $root/build/freeswitch.env
-fi
-
 if [ -z "$MAKE" ] ; then
     make=`which gmake 2>/dev/null`
     if [ -z "$MAKE" ] ; then
@@ -81,7 +77,7 @@
     MAKE=$MAKE ../$uncompressed.build.sh $@
 else
     $MAKE clean 2>&1
-    CFLAGS="$MOD_CFLAGS" ; export CFLAGS; sh ./configure $@
+    CFLAGS="$MOD_CFLAGS" sh ./configure $@
 
     if [ $? = 0 ] ; then
 	$MAKE

Modified: freeswitch/branches/cparker/conf/default_context.xml
==============================================================================
--- freeswitch/branches/cparker/conf/default_context.xml	(original)
+++ freeswitch/branches/cparker/conf/default_context.xml	Tue Apr 24 10:14:28 2007
@@ -98,7 +98,7 @@
   <extension name="To PRI">
     <condition field="rdnis" expression="8881231234"/>
     <condition field="destination_number" expression="(.*)">
-      <action application="bridge" data="wanpipe/a/a/$1"/>
+      <action application="bridge" data="wanpipe/pri/a/a/$1"/>
     </condition>
   </extension>
 
@@ -110,4 +110,23 @@
     </condition>
   </extension>
 
+  <!--This extension will start a conference and invite several people upon entering -->
+  <extension name="0911">
+    <condition field="destination_number" expression="0911">
+      
+      <!--These params effect the outcalls made once you join-->
+      <action application="set" data="conference_auto_outcall_caller_id_name=pissed off boss"/>
+      <action application="set" data="conference_auto_outcall_caller_id_number=0911"/>
+      <action application="set" data="conference_auto_outcall_timeout=60"/>
+      <action application="set" data="conference_auto_outcall_flags=none"/>
+      <action application="set" data="conference_auto_outcall_announce=say:You have been called into an emergency conference"/>
+
+      <!--Add as many of these as you need, These are the people you are going to call-->
+      <action application="conference_set_auto_outcall" data="sofia/gateway/mygateway/12121231234"/>
+      <action application="conference_set_auto_outcall" data="sofia/$${domain}/1234 at somewhere.com"/>
+      
+      <action application="conference" data="cool at default"/>
+    </condition>
+  </extension>
+
 </context>

Modified: freeswitch/branches/cparker/conf/dingaling.conf.xml
==============================================================================
--- freeswitch/branches/cparker/conf/dingaling.conf.xml	(original)
+++ freeswitch/branches/cparker/conf/dingaling.conf.xml	Tue Apr 24 10:14:28 2007
@@ -15,7 +15,6 @@
     <param name="message" value="Jingle all the way"/>
     <param name="rtp-ip" value="auto"/>
     <param name="auto-login" value="true"/>
-    <param name="auto-reply" value="Press *Call* to call FreeSWITCH and be sure to come to ClueCon! http://www.cluecon.com"/>
     <!-- SASL "plain" or "md5" -->
     <param name="sasl" value="plain"/>
     <!-- if the server where the jabber is hosted is not the same as the one in the jid -->
@@ -33,6 +32,7 @@
     <!-- <param name="vad" value="in"/> -->
     <!-- <param name="vad" value="out"/> -->
     <param name="vad" value="both"/>
+    <!--<param name="avatar" value="/path/to/tiny.jpg"/>-->
   </x-profile>
 
   <!-- Component (Server to Server Login) -->
@@ -48,6 +48,10 @@
     <!-- "_auto_" means the extension will be automaticly set to the called jid -->
     <param name="exten" value="_auto_"/>
     <!--<param name="vad" value="both"/>-->
+    <!--<param name="avatar" value="/path/to/tiny.jpg"/>-->
+    <!--If you have ODBC support and a working dsn you can use it instead of SQLite-->
+    <!--<param name="odbc-dsn" value="dsn:user:pass"/>-->
+
   </x-profile>
 
 </configuration>

Modified: freeswitch/branches/cparker/conf/freeswitch.xml
==============================================================================
--- freeswitch/branches/cparker/conf/freeswitch.xml	(original)
+++ freeswitch/branches/cparker/conf/freeswitch.xml	Tue Apr 24 10:14:28 2007
@@ -40,6 +40,7 @@
     <!--#include "conference.conf.xml"-->
     <!--#include "enum.conf.xml"-->
     <!--#include "ivr.conf.xml"-->
+    <!--#include "mod_cdr.conf.xml"-->
   </section>
   
   <section name="dialplan" description="Regex/XML Dialplan">

Modified: freeswitch/branches/cparker/conf/freeswitch_combined.xml
==============================================================================
--- freeswitch/branches/cparker/conf/freeswitch_combined.xml	(original)
+++ freeswitch/branches/cparker/conf/freeswitch_combined.xml	Tue Apr 24 10:14:28 2007
@@ -7,6 +7,9 @@
       <settings>
 	<!--Most channels to allow at once -->
 	<param name="max-sessions" value="1000"/>
+	<!--RTP port range -->
+	<!--<param name="rtp-start-port" value="16384"/>-->
+	<!--<param name="rtp-end-port" value="32768"/>-->
       </settings>
       <!--Any variables defined here will be available in every channel, in the dialplan etc -->
       <variables>
@@ -524,7 +527,32 @@
 	  <entry action="menu-top" digits="*"/>
 	</menu>
       </menus>
-    </configuration> 
+    </configuration>
+    <configuration name="mod_cdr.conf" description="CDR Configuration">
+      <pddcdr>
+        <param name="path" value="/work/temp/pddcdr"/>
+        <!-- <param name="chanvars" value="username,accountcode"/> -->
+        <!-- <param name="chanvars_fixed" value="foo"/> -->
+      </pddcdr>
+      <csvcdr>
+        <param name="path" value="/work/temp/csvcdr"/>
+        <param name="size_limit" value="25"/>
+        <!-- <param name="chanvars_fixed" value="username"/> -->
+        <!-- <param name="chanvars_supp" value="*"/> -->
+        <!-- <param name="repeat_fixed_in_supp" value="0"/> -->
+      </csvcdr>
+      <mysqlcdr>
+        <param name="hostname" value="10.0.0.1"/>
+        <param name="username" value="test"/>
+        <param name="password" value="test"/>
+        <param name="dbname" value="testing"/>
+        <!-- This following line logs username as a varchar, and The_Kow as a tiny -->
+        <!-- <param name="chanvars_fixed" value="username=s,The_Kow=t"/> -->
+        <!-- If you do not want to log any and all chanvars to the chanvar table, comment the next 2 lines out -->
+        <param name="chanvars_supp" value="*"/>
+        <param name="chanvars_supp_repeat_fixed" value="0"/>
+      </mysqlcdr>
+    </configuration>
 
   </section>
   

Modified: freeswitch/branches/cparker/conf/modules.conf.xml
==============================================================================
--- freeswitch/branches/cparker/conf/modules.conf.xml	(original)
+++ freeswitch/branches/cparker/conf/modules.conf.xml	Tue Apr 24 10:14:28 2007
@@ -54,6 +54,8 @@
     <!-- File Format Interfaces -->
     <load module="mod_sndfile"/>
     <load module="mod_native_file"/>
+    <!--For icecast/mp3 streams/files-->
+    <!--<load module="mod_shout"/>-->
 
     <!-- Timers -->
     <load module="mod_softtimer"/>

Modified: freeswitch/branches/cparker/conf/sofia.conf.xml
==============================================================================
--- freeswitch/branches/cparker/conf/sofia.conf.xml	(original)
+++ freeswitch/branches/cparker/conf/sofia.conf.xml	Tue Apr 24 10:14:28 2007
@@ -1,18 +1,27 @@
 <configuration name="sofia.conf" description="sofia Endpoint">
   <profiles>
     <profile name="$${domain}">
-      <registrations>
-	<!-- <registration name="asterlink">
-	     <param name="register-scheme" value="Digest"/>
-	     <param name="register-realm" value=""/>
-	     <param name="register-username" value="1001"/>
-	     <param name="register-password" value="nhy65tgb"/>
-	     <param name="register-from" value="sip:1001 at 208.64.200.40"/>
-	     <param name="register-to" value="sip:1001 at conference.freeswitch.org"/>
-	     <param name="register-proxy" value="sip:conference.freeswitch.org:5060"/>
-	     <param name="register-frequency" value="20"/>
-	     </registration> -->
-      </registrations>
+      <!-- Outbound Registrations -->
+      <gateways>
+	<!--<gateway name="asterlink.com">-->
+	  <!--/// account username *required* ///-->
+	  <!--<param name="username" value="cluecon"/>-->
+	  <!--/// auth realm: *optional* same as gateway name, if blank ///-->
+	  <!--<param name="realm" value="asterlink.com"/>-->
+	  <!--/// account password *required* ///-->
+	  <!--<param name="password" value="2007"/>--> 
+	  <!--/// replace the INVITE from user with the auth username ///-->
+	  <!--<param name="force-fromuser" value="false"/>-->
+	  <!--/// extension for inbound calls: *optional* same as username, if blank ///-->
+	  <!--<param name="extension" value="cluecon"/>-->
+	  <!--/// proxy host: *optional* same as realm, if blank ///-->
+	  <!--<param name="proxy" value="asterlink.com"/>-->
+	  <!--/// expire in seconds: *optional* 3600, if blank ///-->
+	  <!--<param name="expire-seconds" value="60"/>-->
+	  <!--/// do not register ///-->
+	  <!--<param name="register" value="false"/>-->
+	<!--</gateway>-->
+      </gateways>
       <settings>
 	<param name="debug" value="1"/>
 	<param name="rfc2833-pt" value="101"/>
@@ -26,6 +35,12 @@
 	<param name="rtp-ip" value="auto"/>
 	<param name="sip-ip" value="auto"/>
 
+	<!--If you don't want to pass through timestampes from 1 RTP call to another (on a per call basis with rtp_rewrite_timestamps chanvar)-->
+	<!--<param name="rtp-rewrite-timestampes" value="true"/>-->
+
+	<!--If you have ODBC support and a working dsn you can use it instead of SQLite-->
+	<!--<param name="odbc-dsn" value="dsn:user:pass"/>-->
+
 	<!--Uncomment to set all inbound calls to no media mode-->
 	<!--<param name="inbound-no-media" value="true"/>-->
 
@@ -48,6 +63,7 @@
 	<!-- optional ; -->
 	<!-- <param name="ext-rtp-ip" value="stun:stun.server.com"/>-->
 	<!-- <param name="ext-rtp-ip" value="100.101.102.103"/> -->
+	<!-- <param name="ext-sip-ip" value="100.101.102.103"/> -->
 	<!-- VAD choose one (out is a good choice); -->
 	<!-- <param name="vad" value="in"/> -->
 	<!-- <param name="vad" value="out"/> -->

Modified: freeswitch/branches/cparker/conf/switch.conf.xml
==============================================================================
--- freeswitch/branches/cparker/conf/switch.conf.xml	(original)
+++ freeswitch/branches/cparker/conf/switch.conf.xml	Tue Apr 24 10:14:28 2007
@@ -2,6 +2,9 @@
   <settings>
     <!--Most channels to allow at once -->
     <param name="max-sessions" value="1000"/>
+    <!--RTP port range -->
+    <!--<param name="rtp-start-port" value="16384"/>-->
+    <!--<param name="rtp-end-port" value="32768"/>-->
   </settings>
   <!--Any variables defined here will be available in every channel, in the dialplan etc -->
   <variables>

Modified: freeswitch/branches/cparker/conf/wanpipe.conf.xml
==============================================================================
--- freeswitch/branches/cparker/conf/wanpipe.conf.xml	(original)
+++ freeswitch/branches/cparker/conf/wanpipe.conf.xml	Tue Apr 24 10:14:28 2007
@@ -7,25 +7,37 @@
     <param name="dtmf-off" value="100"/>
     <param name="supress-dtmf-tone" value="yes"/>
   </settings>
-  <!-- may be any single digit or a range of digits separated by a '-' e.g "1-4" -->
-  <span id="1">
-    <param name="node" value="cpe"/>
-    <param name="switch" value="ni2"/>
-    <!--<param name="switch" value="dms100"/>-->
-    <!-- <param name="switch" value="lucent5e"/> -->
-    <!-- <param name="switch" value="att4ess"/> -->
-    <!-- <param name="switch" value="euroisdn"/> -->
-    <!-- <param name="switch" value="gr303eoc"/> -->
-    <!-- <param name="switch" value="gr303tmc"/> -->
-    <param name="dp" value="national"/>
-    <!-- <param name="dp" value="international"/> -->
-    <!-- <param name="dp" value="local"/> -->
-    <!-- <param name="dp" value="private"/> -->
-    <!-- <param name="dp" value="unknown"/> -->
-    <param name="l1" value="ulaw"/>
-    <!-- <param name="l1" value="alaw"/> -->
-    <param name="bchan" value="1-23"/>
-    <param name="dchan" value="24"/>
-    <param name="dialplan" value="XML"/>
-  </span>
+  <ss7boost_handles>
+<!--
+    <handle>
+      <param name="local-ip" value="127.0.0.65"/>
+      <param name="local-port" value="53000"/>
+      <param name="remote-ip" value="127.0.0.66"/>
+      <param name="remote-port" value="53000"/>
+    </handle>
+-->
+  </ss7boost_handles>
+  <pri_spans>
+    <!-- may be any single digit or a range of digits separated by a '-' e.g "1-4" -->
+    <span id="1">
+      <param name="node" value="cpe"/>
+      <param name="switch" value="ni2"/>
+      <!--<param name="switch" value="dms100"/>-->
+      <!-- <param name="switch" value="lucent5e"/> -->
+      <!-- <param name="switch" value="att4ess"/> -->
+      <!-- <param name="switch" value="euroisdn"/> -->
+      <!-- <param name="switch" value="gr303eoc"/> -->
+      <!-- <param name="switch" value="gr303tmc"/> -->
+      <param name="dp" value="national"/>
+      <!-- <param name="dp" value="international"/> -->
+      <!-- <param name="dp" value="local"/> -->
+      <!-- <param name="dp" value="private"/> -->
+      <!-- <param name="dp" value="unknown"/> -->
+      <param name="l1" value="ulaw"/>
+      <!-- <param name="l1" value="alaw"/> -->
+      <param name="bchan" value="1-23"/>
+      <param name="dchan" value="24"/>
+      <param name="dialplan" value="XML"/>
+    </span>
+  </pri_spans>
 </configuration>

Modified: freeswitch/branches/cparker/configure
==============================================================================
--- freeswitch/branches/cparker/configure	(original)
+++ freeswitch/branches/cparker/configure	Tue Apr 24 10:14:28 2007
@@ -287,8 +287,8 @@
 # find a string as large as possible, as long as the shell can cope with it
   for cmd in 'sed 50q "$0"' 'sed 20q "$0"' 'sed 10q "$0"' 'sed 2q "$0"' 'echo test'; do
     # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
-    if (echo_test_string=`eval $cmd`) 2>/dev/null &&
-       echo_test_string=`eval $cmd` &&
+    if (echo_test_string="`eval $cmd`") 2>/dev/null &&
+       echo_test_string="`eval $cmd`" &&
        (test "X$echo_test_string" = "X$echo_test_string") 2>/dev/null
     then
       break
@@ -3478,7 +3478,7 @@
     if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
       lt_cv_path_LD="$ac_dir/$ac_prog"
       # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
+      # but apparently some GNU ld's only accept -v.
       # Break only if it was the GNU/non-GNU ld that we prefer.
       case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
       *GNU* | *'with BFD'*)
@@ -3512,7 +3512,7 @@
 if test "${lt_cv_prog_gnu_ld+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  # I'd rather use --version here, but apparently some GNU lds only accept -v.
+  # I'd rather use --version here, but apparently some GNU ld's only accept -v.
 case `$LD -v 2>&1 </dev/null` in
 *GNU* | *'with BFD'*)
   lt_cv_prog_gnu_ld=yes
@@ -3545,7 +3545,7 @@
 case $host_os in
   darwin*)
     if test "$GCC" = yes; then
-      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+      reload_cmds='$CC -nostdlib ${wl}-r -o $output$reload_objs'
     else
       reload_cmds='$LD$reload_flag -o $output$reload_objs'
     fi
@@ -3561,43 +3561,36 @@
   # Let the user override the test.
   lt_cv_path_NM="$NM"
 else
-  lt_nm_to_check="${ac_tool_prefix}nm"
-  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
-    lt_nm_to_check="$lt_nm_to_check nm"
-  fi
-  for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS="$lt_save_ifs"
-      test -z "$ac_dir" && ac_dir=.
-      tmp_nm="$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
-	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
-	#   nm: unknown option "B" ignored
-	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
-	  lt_cv_path_NM="$tmp_nm -B"
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH /usr/ccs/bin /usr/ucb /bin; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    tmp_nm="$ac_dir/${ac_tool_prefix}nm"
+    if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+      # Check to see if the nm accepts a BSD-compat flag.
+      # Adding the `sed 1q' prevents false positives on HP-UX, which says:
+      #   nm: unknown option "B" ignored
+      # Tru64's nm complains that /dev/null is an invalid object file
+      case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+      */dev/null* | *'Invalid file or object type'*)
+	lt_cv_path_NM="$tmp_nm -B"
+	break
+        ;;
+      *)
+	case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+	*/dev/null*)
+	  lt_cv_path_NM="$tmp_nm -p"
 	  break
 	  ;;
 	*)
-	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
-	  */dev/null*)
-	    lt_cv_path_NM="$tmp_nm -p"
-	    break
-	    ;;
-	  *)
-	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
-	    continue # so that we can try to find one that supports BSD flags
-	    ;;
-	  esac
+	  lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+	  continue # so that we can try to find one that supports BSD flags
 	  ;;
 	esac
-      fi
-    done
-    IFS="$lt_save_ifs"
+      esac
+    fi
   done
+  IFS="$lt_save_ifs"
   test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm
 fi
 fi
@@ -3689,7 +3682,7 @@
 
 hpux10.20* | hpux11*)
   lt_cv_file_magic_cmd=/usr/bin/file
-  case $host_cpu in
+  case "$host_cpu" in
   ia64*)
     lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64'
     lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
@@ -3705,11 +3698,6 @@
   esac
   ;;
 
-interix3*)
-  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
-  lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$'
-  ;;
-
 irix5* | irix6* | nonstopux*)
   case $LD in
   *-32|*"-32 ") libmagic=32-bit;;
@@ -3755,11 +3743,15 @@
   lt_cv_deplibs_check_method=pass_all
   ;;
 
+sco3.2v5*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
 solaris*)
   lt_cv_deplibs_check_method=pass_all
   ;;
 
-sysv4 | sysv4.3*)
+sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
   case $host_vendor in
   motorola)
     lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]'
@@ -3780,13 +3772,10 @@
   siemens)
     lt_cv_deplibs_check_method=pass_all
     ;;
-  pc)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
   esac
   ;;
 
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[78]* | unixware7* | sysv4*uw2*)
   lt_cv_deplibs_check_method=pass_all
   ;;
 esac
@@ -3804,9 +3793,6 @@
 # If no C compiler was specified, use CC.
 LTCC=${LTCC-"$CC"}
 
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
 # Allow CC to be a program name with arguments.
 compiler=$CC
 
@@ -3842,7 +3828,7 @@
   ;;
 *-*-irix6*)
   # Find out which ABI we are using.
-  echo '#line 3845 "configure"' > conftest.$ac_ext
+  echo '#line 3831 "configure"' > conftest.$ac_ext
   if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
   (eval $ac_compile) 2>&5
   ac_status=$?
@@ -3885,7 +3871,7 @@
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; then
-    case `/usr/bin/file conftest.o` in
+    case "`/usr/bin/file conftest.o`" in
     *32-bit*)
       case $host in
         x86_64-*linux*)
@@ -3998,26 +3984,6 @@
     CFLAGS="$SAVE_CFLAGS"
   fi
   ;;
-sparc*-*solaris*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; then
-    case `/usr/bin/file conftest.o` in
-    *64-bit*)
-      case $lt_cv_prog_gnu_ld in
-      yes*) LD="${LD-ld} -m elf64_sparc" ;;
-      *)    LD="${LD-ld} -64" ;;
-      esac
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
 
 esac
 
@@ -5441,7 +5407,7 @@
 
 
 # Provide some information about the compiler.
-echo "$as_me:5444:" \
+echo "$as_me:5410:" \
      "checking for Fortran 77 compiler version" >&5
 ac_compiler=`set X $ac_compile; echo $2`
 { (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
@@ -5638,18 +5604,11 @@
     elif test -x /usr/sbin/sysctl; then
       lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
     else
-      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
+      lt_cv_sys_max_cmd_len=65536 # usable default for *BSD
     fi
     # And add a safety zone
     lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    ;;
-
-  interix*)
-    # We know the value 262144 and hardcode it with a safety zone (like BSD)
-    lt_cv_sys_max_cmd_len=196608
     ;;
-
   osf*)
     # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
     # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
@@ -5663,17 +5622,6 @@
       esac
     fi
     ;;
-  sco3.2v5*)
-    lt_cv_sys_max_cmd_len=102400
-    ;;
-  sysv5* | sco5v6* | sysv4.2uw2*)
-    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
-    if test -n "$kargmax"; then
-      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ 	]//'`
-    else
-      lt_cv_sys_max_cmd_len=32768
-    fi
-    ;;
   *)
     # If test is not a shell built-in, we'll probably end up computing a
     # maximum length that is only half of the actual maximum length, but
@@ -5759,18 +5707,9 @@
 osf*)
   symcode='[BCDEGQRST]'
   ;;
-solaris*)
+solaris* | sysv5*)
   symcode='[BDRT]'
   ;;
-sco3.2v5*)
-  symcode='[DT]'
-  ;;
-sysv4.2uw2*)
-  symcode='[DT]'
-  ;;
-sysv5* | sco5v6* | unixware* | OpenUNIX*)
-  symcode='[ABDT]'
-  ;;
 sysv4)
   symcode='[DFNSTU]'
   ;;
@@ -5959,7 +5898,7 @@
 
 # Sed substitution that helps us do robust quoting.  It backslashifies
 # metacharacters that are still active within double-quoted strings.
-Xsed='sed -e 1s/^X//'
+Xsed='sed -e s/^X//'
 sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g'
 
 # Same as above, but do not quote variable references.
@@ -5979,7 +5918,7 @@
 default_ofile=libtool
 can_build_shared=yes
 
-# All known linkers require a `.a' archive for static linking (except MSVC,
+# All known linkers require a `.a' archive for static linking (except M$VC,
 # which needs '.lib').
 libext=a
 ltmain="$ac_aux_dir/ltmain.sh"
@@ -6236,7 +6175,6 @@
 test -z "$AS" && AS=as
 test -z "$CC" && CC=cc
 test -z "$LTCC" && LTCC=$CC
-test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
 test -z "$DLLTOOL" && DLLTOOL=dlltool
 test -z "$LD" && LD=ld
 test -z "$LN_S" && LN_S="ln -s"
@@ -6256,25 +6194,16 @@
 if test -n "$RANLIB"; then
   case $host_os in
   openbsd*)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
+    old_postinstall_cmds="\$RANLIB -t \$oldlib~$old_postinstall_cmds"
     ;;
   *)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
+    old_postinstall_cmds="\$RANLIB \$oldlib~$old_postinstall_cmds"
     ;;
   esac
   old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
 fi
 
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
-
+cc_basename=`$echo X"$compiler" | $Xsed -e 's%^.*/%%'`
 
 # Only perform the check for file, if the check method requires it
 case $deplibs_check_method in
@@ -6301,7 +6230,7 @@
       if test -n "$file_magic_test_file"; then
 	case $deplibs_check_method in
 	"file_magic "*)
-	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+	  file_magic_regex="`expr \"$deplibs_check_method\" : \"file_magic \(.*\)\"`"
 	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
 	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
 	    $EGREP "$file_magic_regex" > /dev/null; then
@@ -6363,7 +6292,7 @@
       if test -n "$file_magic_test_file"; then
 	case $deplibs_check_method in
 	"file_magic "*)
-	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+	  file_magic_regex="`expr \"$deplibs_check_method\" : \"file_magic \(.*\)\"`"
 	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
 	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
 	    $EGREP "$file_magic_regex" > /dev/null; then
@@ -6458,25 +6387,68 @@
 # If no C compiler was specified, use CC.
 LTCC=${LTCC-"$CC"}
 
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
 # Allow CC to be a program name with arguments.
 compiler=$CC
 
 
-# save warnings/boilerplate of simple test code
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$rm conftest*
-
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$rm conftest*
+#
+# Check for any special shared library compilation flags.
+#
+lt_prog_cc_shlib=
+if test "$GCC" = no; then
+  case $host_os in
+  sco3.2v5*)
+    lt_prog_cc_shlib='-belf'
+    ;;
+  esac
+fi
+if test -n "$lt_prog_cc_shlib"; then
+  { echo "$as_me:$LINENO: WARNING: \`$CC' requires \`$lt_prog_cc_shlib' to build shared libraries" >&5
+echo "$as_me: WARNING: \`$CC' requires \`$lt_prog_cc_shlib' to build shared libraries" >&2;}
+  if echo "$old_CC $old_CFLAGS " | grep "[ 	]$lt_prog_cc_shlib[ 	]" >/dev/null; then :
+  else
+    { echo "$as_me:$LINENO: WARNING: add \`$lt_prog_cc_shlib' to the CC or CFLAGS env variable and reconfigure" >&5
+echo "$as_me: WARNING: add \`$lt_prog_cc_shlib' to the CC or CFLAGS env variable and reconfigure" >&2;}
+    lt_cv_prog_cc_can_build_shared=no
+  fi
+fi
+
+
+#
+# Check to make sure the static flag actually works.
+#
+echo "$as_me:$LINENO: checking if $compiler static flag $lt_prog_compiler_static works" >&5
+echo $ECHO_N "checking if $compiler static flag $lt_prog_compiler_static works... $ECHO_C" >&6
+if test "${lt_prog_compiler_static_works+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  lt_prog_compiler_static_works=no
+   save_LDFLAGS="$LDFLAGS"
+   LDFLAGS="$LDFLAGS $lt_prog_compiler_static"
+   printf "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&5
+     else
+       lt_prog_compiler_static_works=yes
+     fi
+   fi
+   $rm conftest*
+   LDFLAGS="$save_LDFLAGS"
+
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works" >&5
+echo "${ECHO_T}$lt_prog_compiler_static_works" >&6
+
+if test x"$lt_prog_compiler_static_works" = xyes; then
+    :
+else
+    lt_prog_compiler_static=
+fi
+
 
 
 
@@ -6501,20 +6473,18 @@
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    # The option is referenced via a variable to avoid confusing sed.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:6507: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:6479: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:6511: \$? = $ac_status" >&5
+   echo "$as_me:6483: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+     # So say no if there are warnings
+     if test ! -s conftest.err; then
        lt_cv_prog_compiler_rtti_exceptions=yes
      fi
    fi
@@ -6575,11 +6545,6 @@
       lt_prog_compiler_pic='-fno-common'
       ;;
 
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
     msdosdjgpp*)
       # Just because we use GCC doesn't mean we suddenly get shared libraries
       # on systems that don't support them.
@@ -6596,7 +6561,7 @@
     hpux*)
       # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
       # not for PA HP-UX.
-      case $host_cpu in
+      case "$host_cpu" in
       hppa*64*|ia64*)
 	# +Z the default
 	;;
@@ -6625,7 +6590,7 @@
       darwin*)
         # PIC is the default on this platform
         # Common symbols not allowed in MH_DYLIB files
-       case $cc_basename in
+       case "$cc_basename" in
          xlc*)
          lt_prog_compiler_pic='-qnocommon'
          lt_prog_compiler_wl='-Wl,'
@@ -6643,7 +6608,7 @@
       lt_prog_compiler_wl='-Wl,'
       # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
       # not for PA HP-UX.
-      case $host_cpu in
+      case "$host_cpu" in
       hppa*64*|ia64*)
 	# +Z the default
 	;;
@@ -6673,12 +6638,12 @@
 	lt_prog_compiler_pic='-KPIC'
 	lt_prog_compiler_static='-static'
         ;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
+      pgcc | pgf77 | pgf90)
         # Portland Group compilers (*not* the Pentium gcc compiler,
 	# which looks to be a dead project)
 	lt_prog_compiler_wl='-Wl,'
 	lt_prog_compiler_pic='-fpic'
-	lt_prog_compiler_static='-Bstatic'
+	lt_prog_compiler_static='-static'
         ;;
       ccc*)
         lt_prog_compiler_wl='-Wl,'
@@ -6694,15 +6659,15 @@
       lt_prog_compiler_static='-non_shared'
       ;;
 
+    sco3.2v5*)
+      lt_prog_compiler_pic='-Kpic'
+      lt_prog_compiler_static='-dn'
+      ;;
+
     solaris*)
+      lt_prog_compiler_wl='-Wl,'
       lt_prog_compiler_pic='-KPIC'
       lt_prog_compiler_static='-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95*)
-	lt_prog_compiler_wl='-Qoption ld ';;
-      *)
-	lt_prog_compiler_wl='-Wl,';;
-      esac
       ;;
 
     sunos4*)
@@ -6711,7 +6676,7 @@
       lt_prog_compiler_static='-Bstatic'
       ;;
 
-    sysv4 | sysv4.2uw2* | sysv4.3*)
+    sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
       lt_prog_compiler_wl='-Wl,'
       lt_prog_compiler_pic='-KPIC'
       lt_prog_compiler_static='-Bstatic'
@@ -6724,12 +6689,6 @@
       fi
       ;;
 
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      lt_prog_compiler_wl='-Wl,'
-      lt_prog_compiler_pic='-KPIC'
-      lt_prog_compiler_static='-Bstatic'
-      ;;
-
     unicos*)
       lt_prog_compiler_wl='-Wl,'
       lt_prog_compiler_can_build_shared=no
@@ -6769,20 +6728,18 @@
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    # The option is referenced via a variable to avoid confusing sed.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:6775: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:6734: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:6779: \$? = $ac_status" >&5
+   echo "$as_me:6738: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+     # So say no if there are warnings
+     if test ! -s conftest.err; then
        lt_prog_compiler_pic_works=yes
      fi
    fi
@@ -6803,7 +6760,7 @@
 fi
 
 fi
-case $host_os in
+case "$host_os" in
   # For platforms which do not support PIC, -DPIC is meaningless:
   *djgpp*)
     lt_prog_compiler_pic=
@@ -6813,48 +6770,6 @@
     ;;
 esac
 
-#
-# Check to make sure the static flag actually works.
-#
-wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\"
-echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
-if test "${lt_prog_compiler_static_works+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_static_works=no
-   save_LDFLAGS="$LDFLAGS"
-   LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
-   printf "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&5
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_prog_compiler_static_works=yes
-       fi
-     else
-       lt_prog_compiler_static_works=yes
-     fi
-   fi
-   $rm conftest*
-   LDFLAGS="$save_LDFLAGS"
-
-fi
-echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works" >&6
-
-if test x"$lt_prog_compiler_static_works" = xyes; then
-    :
-else
-    lt_prog_compiler_static=
-fi
-
-
 echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
 echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
 if test "${lt_cv_prog_compiler_c_o+set}" = set; then
@@ -6873,25 +6788,23 @@
    # Note that $ac_compile itself does not contain backslashes and begins
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:6879: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:6794: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>out/conftest.err)
    ac_status=$?
    cat out/conftest.err >&5
-   echo "$as_me:6883: \$? = $ac_status" >&5
+   echo "$as_me:6798: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s out/conftest2.$ac_objext
    then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+     if test ! -s out/conftest.err; then
        lt_cv_prog_compiler_c_o=yes
      fi
    fi
-   chmod u+w . 2>&5
+   chmod u+w .
    $rm conftest*
    # SGI C++ compiler will create directory out/ii_files/ for
    # template instantiation
@@ -6967,16 +6880,6 @@
   # rely on this symbol name, it's probably fine to never include it in
   # preloaded symbol tables.
   extract_expsyms_cmds=
-  # Just being paranoid about ensuring that cc_basename is set.
-  for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
 
   case $host_os in
   cygwin* | mingw* | pw32*)
@@ -6987,10 +6890,6 @@
       with_gnu_ld=no
     fi
     ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (= MSVC++)
-    with_gnu_ld=yes
-    ;;
   openbsd*)
     with_gnu_ld=no
     ;;
@@ -7001,27 +6900,6 @@
     # If archive_cmds runs LD, not CC, wlarc should be empty
     wlarc='${wl}'
 
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=LD_RUN_PATH
-    hardcode_libdir_flag_spec='${wl}--rpath ${wl}$libdir'
-    export_dynamic_flag_spec='${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
-	whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-      else
-  	whole_archive_flag_spec=
-    fi
-    supports_anon_versioning=no
-    case `$LD -v 2>/dev/null` in
-      *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=yes ;;
-    esac
-
     # See if GNU ld supports shared libraries.
     case $host_os in
     aix3* | aix4* | aix5*)
@@ -7075,7 +6953,7 @@
       export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
 
       if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-        archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+        archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib'
 	# If the export-symbols file already is a .def file (1st line
 	# is EXPORTS), use it as is; otherwise, prepend...
 	archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
@@ -7084,53 +6962,7 @@
 	  echo EXPORTS > $output_objdir/$soname.def;
 	  cat $export_symbols >> $output_objdir/$soname.def;
 	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      else
-	ld_shlibs=no
-      fi
-      ;;
-
-    interix3*)
-      hardcode_direct=no
-      hardcode_shlibpath_var=no
-      hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
-      export_dynamic_flag_spec='${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-      # Instead, shared libraries are loaded at an image base (0x10000000 by
-      # default) and relocated if they conflict, which is a slow very memory
-      # consuming and fragmenting process.  To avoid this, we pick a random,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      ;;
-
-    linux*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	tmp_addflag=
-	case $cc_basename,$host_cpu in
-	pgcc*)				# Portland Group C compiler
-	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
-	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
-	  tmp_addflag=' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=' -nofor_main' ;;
-	esac
-	archive_cmds='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-
-	if test $supports_anon_versioning = yes; then
-	  archive_expsym_cmds='$echo "{ global:" > $output_objdir/$libname.ver~
-  cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-  $echo "local: *; };" >> $output_objdir/$libname.ver~
-	  $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-	fi
+	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000  ${wl}--out-implib,$lib'
       else
 	ld_shlibs=no
       fi
@@ -7146,7 +6978,7 @@
       fi
       ;;
 
-    solaris*)
+    solaris* | sysv5*)
       if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
 	ld_shlibs=no
 	cat <<EOF 1>&2
@@ -7167,33 +6999,6 @@
       fi
       ;;
 
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
-	ld_shlibs=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	    hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
-	    archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
-	    archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib'
-	  else
-	    ld_shlibs=no
-	  fi
-	;;
-      esac
-      ;;
-
     sunos4*)
       archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
       wlarc=
@@ -7201,6 +7006,41 @@
       hardcode_shlibpath_var=no
       ;;
 
+  linux*)
+    if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+      tmp_addflag=
+      case $CC,$host_cpu in
+      pgf77* | pgf90* )			# Portland Group f77 and f90 compilers
+        tmp_addflag=' -fpic' ;;
+      ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
+        tmp_addflag=' -i_dynamic' ;;
+      efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
+        tmp_addflag=' -i_dynamic -nofor_main' ;;
+      ifc* | ifort*)			# Intel Fortran compiler
+      	tmp_addflag=' -nofor_main' ;;
+      esac
+      archive_cmds='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      supports_anon_versioning=no
+      case `$LD -v 2>/dev/null` in
+        *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
+        *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+        *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+        *\ 2.11.*) ;; # other 2.11 versions
+        *) supports_anon_versioning=yes ;;
+      esac
+      if test $supports_anon_versioning = yes; then
+        archive_expsym_cmds='$echo "{ global:" > $output_objdir/$libname.ver~
+cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+$echo "local: *; };" >> $output_objdir/$libname.ver~
+        $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+      else
+        archive_expsym_cmds=$archive_cmds
+      fi
+    else
+      ld_shlibs=no
+    fi
+    ;;
+
     *)
       if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
 	archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
@@ -7211,11 +7051,16 @@
       ;;
     esac
 
-    if test "$ld_shlibs" = no; then
-      runpath_var=
-      hardcode_libdir_flag_spec=
-      export_dynamic_flag_spec=
-      whole_archive_flag_spec=
+    if test "$ld_shlibs" = yes; then
+      runpath_var=LD_RUN_PATH
+      hardcode_libdir_flag_spec='${wl}--rpath ${wl}$libdir'
+      export_dynamic_flag_spec='${wl}--export-dynamic'
+      # ancient GNU ld didn't support --whole-archive et. al.
+      if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
+ 	whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+      else
+  	whole_archive_flag_spec=
+      fi
     fi
   else
     # PORTME fill in a description of your system's linker (not GNU ld)
@@ -7227,7 +7072,7 @@
       # Note: this linker hardcodes the directories in LIBPATH if there
       # are no directories specified by -L.
       hardcode_minus_L=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+      if test "$GCC" = yes && test -z "$link_static_flag"; then
 	# Neither direct hardcoding nor static linking is supported with a
 	# broken collect2.
 	hardcode_direct=unsupported
@@ -7261,7 +7106,6 @@
   	    break
   	  fi
 	  done
-	  ;;
 	esac
 
 	exp_sym_flag='-bexport'
@@ -7299,7 +7143,6 @@
   	  hardcode_libdir_flag_spec='-L$libdir'
   	  hardcode_libdir_separator=
 	  fi
-	  ;;
 	esac
 	shared_flag='-shared'
 	if test "$aix_use_runtimelinking" = yes; then
@@ -7312,11 +7155,11 @@
   	# chokes on -Wl,-G. The following line is correct:
 	  shared_flag='-G'
 	else
-	  if test "$aix_use_runtimelinking" = yes; then
+  	if test "$aix_use_runtimelinking" = yes; then
 	    shared_flag='${wl}-G'
 	  else
 	    shared_flag='${wl}-bM:SRE'
-	  fi
+  	fi
 	fi
       fi
 
@@ -7381,12 +7224,12 @@
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
        hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
-	archive_expsym_cmds="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+	archive_expsym_cmds="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag"
        else
 	if test "$host_cpu" = ia64; then
 	  hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib'
 	  allow_undefined_flag="-z nodefs"
-	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols"
 	else
 	 # Determine the default libpath from the value encoded in an empty executable.
 	 cat >conftest.$ac_ext <<_ACEOF
@@ -7446,11 +7289,13 @@
 	  # -berok will link without error, but may produce a broken library.
 	  no_undefined_flag=' ${wl}-bernotok'
 	  allow_undefined_flag=' ${wl}-berok'
+	  # -bexpall does not export symbols beginning with underscore (_)
+	  always_export_symbols=yes
 	  # Exported symbols can be pulled into shared objects from archives
-	  whole_archive_flag_spec='$convenience'
+	  whole_archive_flag_spec=' '
 	  archive_cmds_need_lc=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	  # This is similar to how AIX traditionally builds it's shared libraries.
+	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
 	fi
       fi
       ;;
@@ -7489,7 +7334,7 @@
       ;;
 
     darwin* | rhapsody*)
-      case $host_os in
+      case "$host_os" in
         rhapsody* | darwin1.[012])
          allow_undefined_flag='${wl}-undefined ${wl}suppress'
          ;;
@@ -7518,16 +7363,16 @@
     	output_verbose_link_cmd='echo'
         archive_cmds='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
       module_cmds='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-      # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+      # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
       archive_expsym_cmds='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
       module_expsym_cmds='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
     else
-      case $cc_basename in
+      case "$cc_basename" in
         xlc*)
          output_verbose_link_cmd='echo'
          archive_cmds='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
          module_cmds='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
          archive_expsym_cmds='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           module_expsym_cmds='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           ;;
@@ -7591,62 +7436,47 @@
       export_dynamic_flag_spec='${wl}-E'
       ;;
 
-    hpux10*)
-      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator=:
-
-	hardcode_direct=yes
-	export_dynamic_flag_spec='${wl}-E'
-
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	hardcode_minus_L=yes
-      fi
-      ;;
-
-    hpux11*)
+    hpux10* | hpux11*)
       if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	case $host_cpu in
-	hppa*64*)
+	case "$host_cpu" in
+	hppa*64*|ia64*)
 	  archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
-	ia64*)
-	  archive_cmds='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
 	*)
 	  archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	esac
       else
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	case "$host_cpu" in
+	hppa*64*|ia64*)
+	  archive_cmds='$LD -b +h $soname -o $lib $libobjs $deplibs $linker_flags'
 	  ;;
 	*)
-	  archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
 	  ;;
 	esac
       fi
       if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator=:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
+	case "$host_cpu" in
+	hppa*64*)
+	  hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
 	  hardcode_libdir_flag_spec_ld='+b $libdir'
+	  hardcode_libdir_separator=:
+	  hardcode_direct=no
+	  hardcode_shlibpath_var=no
+	  ;;
+	ia64*)
+	  hardcode_libdir_flag_spec='-L$libdir'
 	  hardcode_direct=no
 	  hardcode_shlibpath_var=no
+
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  hardcode_minus_L=yes
 	  ;;
 	*)
+	  hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+	  hardcode_libdir_separator=:
 	  hardcode_direct=yes
 	  export_dynamic_flag_spec='${wl}-E'
 
@@ -7740,7 +7570,7 @@
 	allow_undefined_flag=' -expect_unresolved \*'
 	archive_cmds='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
 	archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
-	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib~$rm $lib.exp'
 
 	# Both c and cxx compiler support -rpath directly
 	hardcode_libdir_flag_spec='-rpath $libdir'
@@ -7748,15 +7578,21 @@
       hardcode_libdir_separator=:
       ;;
 
+    sco3.2v5*)
+      archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_shlibpath_var=no
+      export_dynamic_flag_spec='${wl}-Bexport'
+      runpath_var=LD_RUN_PATH
+      hardcode_runpath_var=yes
+      ;;
+
     solaris*)
       no_undefined_flag=' -z text'
       if test "$GCC" = yes; then
-	wlarc='${wl}'
 	archive_cmds='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
 	archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
 	  $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
       else
-	wlarc=''
 	archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
 	archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
   	$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
@@ -7765,18 +7601,8 @@
       hardcode_shlibpath_var=no
       case $host_os in
       solaris2.[0-5] | solaris2.[0-5].*) ;;
-      *)
- 	# The compiler driver will combine linker options so we
- 	# cannot just pass the convience library names through
- 	# without $wl, iff we do not link with $LD.
- 	# Luckily, gcc supports the same syntax we need for Sun Studio.
- 	# Supported since Solaris 2.6 (maybe 2.5.1?)
- 	case $wlarc in
- 	'')
- 	  whole_archive_flag_spec='-z allextract$convenience -z defaultextract' ;;
- 	*)
- 	  whole_archive_flag_spec='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
- 	esac ;;
+      *) # Supported since Solaris 2.6 (maybe 2.5.1?)
+	whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;;
       esac
       link_all_deplibs=yes
       ;;
@@ -7833,45 +7659,36 @@
       fi
       ;;
 
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*)
-      no_undefined_flag='${wl}-z,text'
-      archive_cmds_need_lc=no
+    sysv4.2uw2*)
+      archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_direct=yes
+      hardcode_minus_L=no
       hardcode_shlibpath_var=no
-      runpath_var='LD_RUN_PATH'
+      hardcode_runpath_var=yes
+      runpath_var=LD_RUN_PATH
+      ;;
 
+   sysv5OpenUNIX8* | sysv5UnixWare7* |  sysv5uw[78]* | unixware7*)
+      no_undefined_flag='${wl}-z ${wl}text'
       if test "$GCC" = yes; then
-	archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_cmds='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
       else
-	archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_cmds='$CC -G ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
       fi
+      runpath_var='LD_RUN_PATH'
+      hardcode_shlibpath_var=no
       ;;
 
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      no_undefined_flag='${wl}-z,text'
-      allow_undefined_flag='${wl}-z,nodefs'
-      archive_cmds_need_lc=no
+    sysv5*)
+      no_undefined_flag=' -z text'
+      # $CC -shared without GNU ld will not create a library from C++
+      # object files and a static libstdc++, better avoid it by now
+      archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+  		$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+      hardcode_libdir_flag_spec=
       hardcode_shlibpath_var=no
-      hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
-      hardcode_libdir_separator=':'
-      link_all_deplibs=yes
-      export_dynamic_flag_spec='${wl}-Bexport'
       runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	archive_cmds='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
       ;;
 
     uts4*)
@@ -7890,6 +7707,11 @@
 echo "${ECHO_T}$ld_shlibs" >&6
 test "$ld_shlibs" = no && can_build_shared=no
 
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
 #
 # Do we need to explicitly link libc?
 #
@@ -7922,7 +7744,6 @@
         libobjs=conftest.$ac_objext
         deplibs=
         wl=$lt_prog_compiler_wl
-	pic_flag=$lt_prog_compiler_pic
         compiler_flags=-v
         linker_flags=-v
         verstring=
@@ -8083,8 +7904,7 @@
       dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
       dldir=$destdir/`dirname \$dlpath`~
       test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
+      $install_prog $dir/$dlname \$dldir/$dlname'
     postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
       dlpath=$dir/\$dldll~
        $rm \$dlpath'
@@ -8137,7 +7957,7 @@
   soname_spec='${libname}${release}${major}$shared_ext'
   shlibpath_overrides_runpath=yes
   shlibpath_var=DYLD_LIBRARY_PATH
-  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+  shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)'
   # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
   if test "$GCC" = yes; then
     sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
@@ -8175,14 +7995,7 @@
 freebsd* | dragonfly*)
   # DragonFly does not have aout.  When/if they implement a new
   # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[123]*) objformat=aout ;;
-    *) objformat=elf ;;
-    esac
-  fi
+  objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout`
   version_type=freebsd-$objformat
   case $version_type in
     freebsd-elf*)
@@ -8204,15 +8017,10 @@
     shlibpath_overrides_runpath=yes
     hardcode_into_libs=yes
     ;;
-  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
-  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+  *) # from 3.2 on
     shlibpath_overrides_runpath=no
     hardcode_into_libs=yes
     ;;
-  freebsd*) # from 4.6 on
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
   esac
   ;;
 
@@ -8232,7 +8040,7 @@
   version_type=sunos
   need_lib_prefix=no
   need_version=no
-  case $host_cpu in
+  case "$host_cpu" in
   ia64*)
     shrext_cmds='.so'
     hardcode_into_libs=yes
@@ -8272,18 +8080,6 @@
   postinstall_cmds='chmod 555 $lib'
   ;;
 
-interix3*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
 irix5* | irix6* | nonstopux*)
   case $host_os in
     nonstopux*) version_type=nonstopux ;;
@@ -8343,7 +8139,7 @@
 
   # Append ld.so.conf contents to the search path
   if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,\t]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
     sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
   fi
 
@@ -8405,13 +8201,8 @@
 
 openbsd*)
   version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
   need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=yes ;;
-    *)                         need_version=no  ;;
-  esac
+  need_version=no
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
   finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
   shlibpath_var=LD_LIBRARY_PATH
@@ -8449,6 +8240,13 @@
   sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
   ;;
 
+sco3.2v5*)
+  version_type=osf
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
 solaris*)
   version_type=linux
   need_lib_prefix=no
@@ -8474,7 +8272,7 @@
   need_version=yes
   ;;
 
-sysv4 | sysv4.3*)
+sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
   version_type=linux
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
   soname_spec='${libname}${release}${shared_ext}$major'
@@ -8507,29 +8305,6 @@
   fi
   ;;
 
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-    shlibpath_overrides_runpath=no
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=yes
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
-
 uts4*)
   version_type=linux
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
@@ -8545,11 +8320,6 @@
 echo "${ECHO_T}$dynamic_linker" >&6
 test "$dynamic_linker" = no && can_build_shared=no
 
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
-fi
-
 echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
 echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
 hardcode_action=
@@ -9205,7 +8975,7 @@
     test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
 
     save_LDFLAGS="$LDFLAGS"
-    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+    eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
 
     save_LIBS="$LIBS"
     LIBS="$lt_cv_dlopen_libs $LIBS"
@@ -9221,7 +8991,7 @@
   lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
   lt_status=$lt_dlunknown
   cat > conftest.$ac_ext <<EOF
-#line 9224 "configure"
+#line 8994 "configure"
 #include "confdefs.h"
 
 #if HAVE_DLFCN_H
@@ -9278,8 +9048,6 @@
       else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
       /* dlclose (self); */
     }
-  else
-    puts (dlerror ());
 
     exit (status);
 }
@@ -9289,12 +9057,12 @@
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&5 2>/dev/null
+    (./conftest; exit; ) 2>/dev/null
     lt_status=$?
     case x$lt_status in
       x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;;
       x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;;
-      x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;;
+      x$lt_unknown|x*) lt_cv_dlopen_self=no ;;
     esac
   else :
     # compilation failed
@@ -9309,7 +9077,7 @@
 echo "${ECHO_T}$lt_cv_dlopen_self" >&6
 
     if test "x$lt_cv_dlopen_self" = xyes; then
-      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+      LDFLAGS="$LDFLAGS $link_static_flag"
       echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5
 echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6
 if test "${lt_cv_dlopen_self_static+set}" = set; then
@@ -9321,7 +9089,7 @@
   lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
   lt_status=$lt_dlunknown
   cat > conftest.$ac_ext <<EOF
-#line 9324 "configure"
+#line 9092 "configure"
 #include "confdefs.h"
 
 #if HAVE_DLFCN_H
@@ -9378,8 +9146,6 @@
       else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
       /* dlclose (self); */
     }
-  else
-    puts (dlerror ());
 
     exit (status);
 }
@@ -9389,12 +9155,12 @@
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&5 2>/dev/null
+    (./conftest; exit; ) 2>/dev/null
     lt_status=$?
     case x$lt_status in
       x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;;
       x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;;
-      x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;;
+      x$lt_unknown|x*) lt_cv_dlopen_self_static=no ;;
     esac
   else :
     # compilation failed
@@ -9427,7 +9193,7 @@
 fi
 
 
-# Report which library types will actually be built
+# Report which librarie types wil actually be built
 echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
 echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6
 echo "$as_me:$LINENO: result: $can_build_shared" >&5
@@ -9439,7 +9205,7 @@
 
 # On AIX, shared libraries and static libraries use the same namespace, and
 # are all built from PIC.
-case $host_os in
+case "$host_os" in
 aix3*)
   test "$enable_shared" = yes && enable_static=no
   if test -n "$RANLIB"; then
@@ -9477,7 +9243,7 @@
   # Now quote all the things that may contain metacharacters while being
   # careful not to overquote the AC_SUBSTed values.  We take copies of the
   # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \
     SED SHELL STRIP \
     libname_spec library_names_spec soname_spec extract_expsyms_cmds \
     old_striplib striplib file_magic_cmd finish_cmds finish_eval \
@@ -9581,7 +9347,7 @@
 #
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 #
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
@@ -9592,7 +9358,7 @@
 SED=$lt_SED
 
 # Sed that helps us avoid accidentally triggering echo(1) options like -n.
-Xsed="$SED -e 1s/^X//"
+Xsed="$SED -e s/^X//"
 
 # The HP-UX ksh and POSIX shell print the target directory to stdout
 # if CDPATH is set.
@@ -9643,9 +9409,6 @@
 # A C compiler.
 LTCC=$lt_LTCC
 
-# LTCC compiler flags.
-LTCFLAGS=$lt_LTCFLAGS
-
 # A language-specific compiler.
 CC=$lt_compiler
 
@@ -9711,7 +9474,7 @@
 # Does compiler simultaneously support -c and -o options?
 compiler_c_o=$lt_lt_cv_prog_compiler_c_o
 
-# Must we lock files when doing compilation?
+# Must we lock files when doing compilation ?
 need_locks=$lt_need_locks
 
 # Do we need the lib prefix for modules?
@@ -9976,9 +9739,6 @@
 echo "$as_me: WARNING: using \`LTCC=$LTCC', extracted from \`$ofile'" >&2;}
     fi
   fi
-  if test -z "$LTCFLAGS"; then
-    eval "`$SHELL ${ofile} --config | grep '^LTCFLAGS='`"
-  fi
 
   # Extract list of available tagged configurations in $ofile.
   # Note that this assumes the entire list is on one line.
@@ -10031,7 +9791,6 @@
 hardcode_libdir_flag_spec_ld_CXX=
 hardcode_libdir_separator_CXX=
 hardcode_minus_L_CXX=no
-hardcode_shlibpath_var_CXX=unsupported
 hardcode_automatic_CXX=no
 module_cmds_CXX=
 module_expsym_cmds_CXX=
@@ -10049,7 +9808,7 @@
 compiler_lib_search_path_CXX=
 
 # Source file extension for C++ test sources.
-ac_ext=cpp
+ac_ext=cc
 
 # Object file extension for compiled C++ test sources.
 objext=o
@@ -10059,34 +9818,17 @@
 lt_simple_compile_test_code="int some_variable = 0;\n"
 
 # Code to be used in simple link tests
-lt_simple_link_test_code='int main(int, char *[]) { return(0); }\n'
+lt_simple_link_test_code='int main(int, char *) { return(0); }\n'
 
 # ltmain only uses $CC for tagged configurations so make sure $CC is set.
 
 # If no C compiler was specified, use CC.
 LTCC=${LTCC-"$CC"}
 
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
 # Allow CC to be a program name with arguments.
 compiler=$CC
 
 
-# save warnings/boilerplate of simple test code
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$rm conftest*
-
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$rm conftest*
-
-
 # Allow CC to be a program name with arguments.
 lt_save_CC=$CC
 lt_save_LD=$LD
@@ -10097,27 +9839,18 @@
 if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
   lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
 else
-  $as_unset lt_cv_prog_gnu_ld
+  unset lt_cv_prog_gnu_ld
 fi
 if test -n "${lt_cv_path_LDCXX+set}"; then
   lt_cv_path_LD=$lt_cv_path_LDCXX
 else
-  $as_unset lt_cv_path_LD
+  unset lt_cv_path_LD
 fi
 test -z "${LDCXX+set}" || LD=$LDCXX
 CC=${CXX-"c++"}
 compiler=$CC
 compiler_CXX=$CC
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
-
+cc_basename=`$echo X"$compiler" | $Xsed -e 's%^.*/%%'`
 
 # We don't want -fno-exception wen compiling C++ code, so set the
 # no_builtin_flag separately
@@ -10188,7 +9921,7 @@
     if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
       lt_cv_path_LD="$ac_dir/$ac_prog"
       # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
+      # but apparently some GNU ld's only accept -v.
       # Break only if it was the GNU/non-GNU ld that we prefer.
       case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
       *GNU* | *'with BFD'*)
@@ -10222,7 +9955,7 @@
 if test "${lt_cv_prog_gnu_ld+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  # I'd rather use --version here, but apparently some GNU lds only accept -v.
+  # I'd rather use --version here, but apparently some GNU ld's only accept -v.
 case `$LD -v 2>&1 </dev/null` in
 *GNU* | *'with BFD'*)
   lt_cv_prog_gnu_ld=yes
@@ -10313,7 +10046,6 @@
 	    ;;
 	  esac
 	done
-	;;
       esac
 
       exp_sym_flag='-bexport'
@@ -10351,7 +10083,6 @@
 	  hardcode_libdir_flag_spec_CXX='-L$libdir'
 	  hardcode_libdir_separator_CXX=
 	fi
-	;;
       esac
       shared_flag='-shared'
       if test "$aix_use_runtimelinking" = yes; then
@@ -10434,12 +10165,12 @@
 
       hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath"
 
-      archive_expsym_cmds_CXX="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+      archive_expsym_cmds_CXX="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag"
      else
       if test "$host_cpu" = ia64; then
 	hardcode_libdir_flag_spec_CXX='${wl}-R $libdir:/usr/lib:/lib'
 	allow_undefined_flag_CXX="-z nodefs"
-	archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols"
       else
 	# Determine the default libpath from the value encoded in an empty executable.
 	cat >conftest.$ac_ext <<_ACEOF
@@ -10499,26 +10230,16 @@
 	# -berok will link without error, but may produce a broken library.
 	no_undefined_flag_CXX=' ${wl}-bernotok'
 	allow_undefined_flag_CXX=' ${wl}-berok'
+	# -bexpall does not export symbols beginning with underscore (_)
+	always_export_symbols_CXX=yes
 	# Exported symbols can be pulled into shared objects from archives
-	whole_archive_flag_spec_CXX='$convenience'
+	whole_archive_flag_spec_CXX=' '
 	archive_cmds_need_lc_CXX=yes
-	# This is similar to how AIX traditionally builds its shared libraries.
-	archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	# This is similar to how AIX traditionally builds it's shared libraries.
+	archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
       fi
     fi
     ;;
-
-  beos*)
-    if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-      allow_undefined_flag_CXX=unsupported
-      # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
-      # support --undefined.  This deserves some investigation.  FIXME
-      archive_cmds_CXX='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-    else
-      ld_shlibs_CXX=no
-    fi
-    ;;
-
   chorus*)
     case $cc_basename in
       *)
@@ -10528,6 +10249,7 @@
     esac
     ;;
 
+
   cygwin* | mingw* | pw32*)
     # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningless,
     # as there is no search path for DLLs.
@@ -10537,7 +10259,7 @@
     enable_shared_with_static_runtimes_CXX=yes
 
     if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-      archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib'
       # If the export-symbols file already is a .def file (1st line
       # is EXPORTS), use it as is; otherwise, prepend...
       archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
@@ -10546,13 +10268,13 @@
 	echo EXPORTS > $output_objdir/$soname.def;
 	cat $export_symbols >> $output_objdir/$soname.def;
       fi~
-      $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib'
     else
       ld_shlibs_CXX=no
     fi
   ;;
       darwin* | rhapsody*)
-        case $host_os in
+        case "$host_os" in
         rhapsody* | darwin1.[012])
          allow_undefined_flag_CXX='${wl}-undefined ${wl}suppress'
          ;;
@@ -10590,7 +10312,7 @@
           archive_cmds_CXX='$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
         fi
         module_cmds_CXX='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-        # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+        # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
           if test "X$lt_int_apple_cc_single_mod" = Xyes ; then
             archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           else
@@ -10598,12 +10320,12 @@
           fi
             module_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
       else
-      case $cc_basename in
+      case "$cc_basename" in
         xlc*)
          output_verbose_link_cmd='echo'
           archive_cmds_CXX='$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
           module_cmds_CXX='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
           archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           module_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           ;;
@@ -10616,11 +10338,11 @@
 
   dgux*)
     case $cc_basename in
-      ec++*)
+      ec++)
 	# FIXME: insert proper C++ library support
 	ld_shlibs_CXX=no
 	;;
-      ghcx*)
+      ghcx)
 	# Green Hills C++ Compiler
 	# FIXME: insert proper C++ library support
 	ld_shlibs_CXX=no
@@ -10655,11 +10377,11 @@
 				# location of the library.
 
     case $cc_basename in
-    CC*)
+    CC)
       # FIXME: insert proper C++ library support
       ld_shlibs_CXX=no
       ;;
-    aCC*)
+    aCC)
       archive_cmds_CXX='$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
       # Commands to make compiler produce verbose output that lists
       # what "hidden" libraries, object files and flags are used when
@@ -10683,22 +10405,33 @@
     ;;
   hpux10*|hpux11*)
     if test $with_gnu_ld = no; then
-      hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir'
-      hardcode_libdir_separator_CXX=:
-
-      case $host_cpu in
-      hppa*64*|ia64*)
+      case "$host_cpu" in
+      hppa*64*)
+	hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir'
 	hardcode_libdir_flag_spec_ld_CXX='+b $libdir'
+	hardcode_libdir_separator_CXX=:
+        ;;
+      ia64*)
+	hardcode_libdir_flag_spec_CXX='-L$libdir'
         ;;
       *)
+	hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir'
+	hardcode_libdir_separator_CXX=:
 	export_dynamic_flag_spec_CXX='${wl}-E'
         ;;
       esac
     fi
-    case $host_cpu in
-    hppa*64*|ia64*)
+    case "$host_cpu" in
+    hppa*64*)
+      hardcode_direct_CXX=no
+      hardcode_shlibpath_var_CXX=no
+      ;;
+    ia64*)
       hardcode_direct_CXX=no
       hardcode_shlibpath_var_CXX=no
+      hardcode_minus_L_CXX=yes # Not in the search PATH,
+					      # but as the default
+					      # location of the library.
       ;;
     *)
       hardcode_direct_CXX=yes
@@ -10709,17 +10442,14 @@
     esac
 
     case $cc_basename in
-      CC*)
+      CC)
 	# FIXME: insert proper C++ library support
 	ld_shlibs_CXX=no
 	;;
-      aCC*)
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+      aCC)
+	case "$host_cpu" in
+	hppa*64*|ia64*)
+	  archive_cmds_CXX='$LD -b +h $soname -o $lib $linker_flags $libobjs $deplibs'
 	  ;;
 	*)
 	  archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
@@ -10738,12 +10468,9 @@
       *)
 	if test "$GXX" = yes; then
 	  if test $with_gnu_ld = no; then
-	    case $host_cpu in
-	    hppa*64*)
-	      archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	      ;;
-	    ia64*)
-	      archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	    case "$host_cpu" in
+	    ia64*|hppa*64*)
+	      archive_cmds_CXX='$LD -b +h $soname -o $lib $linker_flags $libobjs $deplibs'
 	      ;;
 	    *)
 	      archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
@@ -10757,25 +10484,11 @@
 	;;
     esac
     ;;
-  interix3*)
-    hardcode_direct_CXX=no
-    hardcode_shlibpath_var_CXX=no
-    hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
-    export_dynamic_flag_spec_CXX='${wl}-E'
-    # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-    # Instead, shared libraries are loaded at an image base (0x10000000 by
-    # default) and relocated if they conflict, which is a slow very memory
-    # consuming and fragmenting process.  To avoid this, we pick a random,
-    # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-    # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-    archive_cmds_CXX='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-    archive_expsym_cmds_CXX='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-    ;;
   irix5* | irix6*)
     case $cc_basename in
-      CC*)
+      CC)
 	# SGI C++
-	archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+	archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib'
 
 	# Archives containing C++ object files must be created using
 	# "CC -ar", where "CC" is the IRIX C++ compiler.  This is
@@ -10786,7 +10499,7 @@
       *)
 	if test "$GXX" = yes; then
 	  if test "$with_gnu_ld" = no; then
-	    archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	    archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib'
 	  else
 	    archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib'
 	  fi
@@ -10799,7 +10512,7 @@
     ;;
   linux*)
     case $cc_basename in
-      KCC*)
+      KCC)
 	# Kuck and Associates, Inc. (KAI) C++ Compiler
 
 	# KCC will only create a shared library if the output file
@@ -10824,7 +10537,7 @@
 	# "CC -Bstatic", where "CC" is the KAI C++ compiler.
 	old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs'
 	;;
-      icpc*)
+      icpc)
 	# Intel C++
 	with_gnu_ld=yes
 	# version 8.0 and above of icpc choke on multiply defined symbols
@@ -10849,16 +10562,15 @@
 	export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
 	whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
 	;;
-      pgCC*)
+      pgCC)
         # Portland Group C++ compiler
-	archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
-  	archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+  	archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
 
 	hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir'
 	export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
-	whole_archive_flag_spec_CXX='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
         ;;
-      cxx*)
+      cxx)
 	# Compaq C++
 	archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
 	archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
@@ -10889,7 +10601,7 @@
     ;;
   mvs*)
     case $cc_basename in
-      cxx*)
+      cxx)
 	# FIXME: insert proper C++ library support
 	ld_shlibs_CXX=no
 	;;
@@ -10928,7 +10640,7 @@
     ;;
   osf3*)
     case $cc_basename in
-      KCC*)
+      KCC)
 	# Kuck and Associates, Inc. (KAI) C++ Compiler
 
 	# KCC will only create a shared library if the output file
@@ -10944,14 +10656,14 @@
 	old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs'
 
 	;;
-      RCC*)
+      RCC)
 	# Rational C++ 2.4.1
 	# FIXME: insert proper C++ library support
 	ld_shlibs_CXX=no
 	;;
-      cxx*)
+      cxx)
 	allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+	archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${objdir}/so_locations -o $lib'
 
 	hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
 	hardcode_libdir_separator_CXX=:
@@ -10969,7 +10681,7 @@
       *)
 	if test "$GXX" = yes && test "$with_gnu_ld" = no; then
 	  allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*'
-	  archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	  archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib'
 
 	  hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
 	  hardcode_libdir_separator_CXX=:
@@ -10988,7 +10700,7 @@
     ;;
   osf4* | osf5*)
     case $cc_basename in
-      KCC*)
+      KCC)
 	# Kuck and Associates, Inc. (KAI) C++ Compiler
 
 	# KCC will only create a shared library if the output file
@@ -11003,17 +10715,17 @@
 	# the KAI C++ compiler.
 	old_archive_cmds_CXX='$CC -o $oldlib $oldobjs'
 	;;
-      RCC*)
+      RCC)
 	# Rational C++ 2.4.1
 	# FIXME: insert proper C++ library support
 	ld_shlibs_CXX=no
 	;;
-      cxx*)
+      cxx)
 	allow_undefined_flag_CXX=' -expect_unresolved \*'
-	archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+	archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib'
 	archive_expsym_cmds_CXX='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
 	  echo "-hidden">> $lib.exp~
-	  $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp  `test -n "$verstring" && echo -set_version	$verstring` -update_registry ${output_objdir}/so_locations -o $lib~
+	  $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp  `test -n "$verstring" && echo -set_version	$verstring` -update_registry $objdir/so_locations -o $lib~
 	  $rm $lib.exp'
 
 	hardcode_libdir_flag_spec_CXX='-rpath $libdir'
@@ -11032,7 +10744,7 @@
       *)
 	if test "$GXX" = yes && test "$with_gnu_ld" = no; then
 	  allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*'
-	 archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	 archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${objdir}/so_locations -o $lib'
 
 	  hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
 	  hardcode_libdir_separator_CXX=:
@@ -11053,14 +10765,27 @@
     # FIXME: insert proper C++ library support
     ld_shlibs_CXX=no
     ;;
+  sco*)
+    archive_cmds_need_lc_CXX=no
+    case $cc_basename in
+      CC)
+	# FIXME: insert proper C++ library support
+	ld_shlibs_CXX=no
+	;;
+      *)
+	# FIXME: insert proper C++ library support
+	ld_shlibs_CXX=no
+	;;
+    esac
+    ;;
   sunos4*)
     case $cc_basename in
-      CC*)
+      CC)
 	# Sun C++ 4.x
 	# FIXME: insert proper C++ library support
 	ld_shlibs_CXX=no
 	;;
-      lcc*)
+      lcc)
 	# Lucid
 	# FIXME: insert proper C++ library support
 	ld_shlibs_CXX=no
@@ -11073,13 +10798,12 @@
     ;;
   solaris*)
     case $cc_basename in
-      CC*)
+      CC)
 	# Sun C++ 4.2, 5.x and Centerline C++
-        archive_cmds_need_lc_CXX=yes
 	no_undefined_flag_CXX=' -zdefs'
-	archive_cmds_CXX='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	archive_cmds_CXX='$CC -G${allow_undefined_flag} -nolib -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-	$CC -G${allow_undefined_flag}  ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+	$CC -G${allow_undefined_flag} -nolib ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
 
 	hardcode_libdir_flag_spec_CXX='-R$libdir'
 	hardcode_shlibpath_var_CXX=no
@@ -11088,18 +10812,22 @@
 	  *)
 	    # The C++ compiler is used as linker so we must use $wl
 	    # flag to pass the commands to the underlying system
-	    # linker. We must also pass each convience library through
-	    # to the system linker between allextract/defaultextract.
-	    # The C++ compiler will combine linker options so we
-	    # cannot just pass the convience library names through
-	    # without $wl.
+	    # linker.
 	    # Supported since Solaris 2.6 (maybe 2.5.1?)
-	    whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract'
+	    whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
 	    ;;
 	esac
 	link_all_deplibs_CXX=yes
 
-	output_verbose_link_cmd='echo'
+	# Commands to make compiler produce verbose output that lists
+	# what "hidden" libraries, object files and flags are used when
+	# linking a shared library.
+	#
+	# There doesn't appear to be a way to prevent this compiler from
+	# explicitly linking system object files so we need to strip them
+	# from the output so that they don't get included in the library
+	# dependencies.
+	output_verbose_link_cmd='templist=`$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep "\-[LR]"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
 
 	# Archives containing C++ object files must be created using
 	# "CC -xar", where "CC" is the Sun C++ compiler.  This is
@@ -11107,7 +10835,7 @@
 	# in the archive.
 	old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs'
 	;;
-      gcx*)
+      gcx)
 	# Green Hills C++ Compiler
 	archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
 
@@ -11145,63 +10873,12 @@
 	;;
     esac
     ;;
-  sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*)
-    no_undefined_flag_CXX='${wl}-z,text'
-    archive_cmds_need_lc_CXX=no
-    hardcode_shlibpath_var_CXX=no
-    runpath_var='LD_RUN_PATH'
-
-    case $cc_basename in
-      CC*)
-	archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-      *)
-	archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-    esac
-    ;;
-  sysv5* | sco3.2v5* | sco5v6*)
-    # Note: We can NOT use -z defs as we might desire, because we do not
-    # link with -lc, and that would cause any symbols used from libc to
-    # always be unresolved, which means just about no library would
-    # ever link correctly.  If we're not using GNU ld we use -z text
-    # though, which does catch some bad symbols but isn't as heavy-handed
-    # as -z defs.
-    # For security reasons, it is highly recommended that you always
-    # use absolute paths for naming shared libraries, and exclude the
-    # DT_RUNPATH tag from executables and libraries.  But doing so
-    # requires that you compile everything twice, which is a pain.
-    # So that behaviour is only enabled if SCOABSPATH is set to a
-    # non-empty value in the environment.  Most likely only useful for
-    # creating official distributions of packages.
-    # This is a hack until libtool officially supports absolute path
-    # names for shared libraries.
-    no_undefined_flag_CXX='${wl}-z,text'
-    allow_undefined_flag_CXX='${wl}-z,nodefs'
+  sysv5OpenUNIX8* | sysv5UnixWare7* | sysv5uw[78]* | unixware7*)
     archive_cmds_need_lc_CXX=no
-    hardcode_shlibpath_var_CXX=no
-    hardcode_libdir_flag_spec_CXX='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
-    hardcode_libdir_separator_CXX=':'
-    link_all_deplibs_CXX=yes
-    export_dynamic_flag_spec_CXX='${wl}-Bexport'
-    runpath_var='LD_RUN_PATH'
-
-    case $cc_basename in
-      CC*)
-	archive_cmds_CXX='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-      *)
-	archive_cmds_CXX='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-    esac
     ;;
   tandem*)
     case $cc_basename in
-      NCC*)
+      NCC)
 	# NonStop-UX NCC 3.20
 	# FIXME: insert proper C++ library support
 	ld_shlibs_CXX=no
@@ -11254,7 +10931,7 @@
   # The `*' in the case matches for architectures that use `case' in
   # $output_verbose_cmd can trigger glob expansion during the loop
   # eval without this substitution.
-  output_verbose_link_cmd=`$echo "X$output_verbose_link_cmd" | $Xsed -e "$no_glob_subst"`
+  output_verbose_link_cmd="`$echo \"X$output_verbose_link_cmd\" | $Xsed -e \"$no_glob_subst\"`"
 
   for p in `eval $output_verbose_link_cmd`; do
     case $p in
@@ -11330,29 +11007,6 @@
 
 $rm -f confest.$objext
 
-# PORTME: override above test on systems where it is broken
-case $host_os in
-interix3*)
-  # Interix 3.5 installs completely hosed .la files for C++, so rather than
-  # hack all around it, let's just trust "g++" to DTRT.
-  predep_objects_CXX=
-  postdep_objects_CXX=
-  postdeps_CXX=
-  ;;
-
-solaris*)
-  case $cc_basename in
-  CC*)
-    # Adding this requires a known-good setup of shared libraries for
-    # Sun compiler versions before 5.6, else PIC objects from an old
-    # archive will be linked into the output, leading to subtle bugs.
-    postdeps_CXX='-lCstd -lCrun'
-    ;;
-  esac
-  ;;
-esac
-
-
 case " $postdeps_CXX " in
 *" -lc "*) archive_cmds_need_lc_CXX=no ;;
 esac
@@ -11400,10 +11054,6 @@
       # DJGPP does not support shared libraries at all
       lt_prog_compiler_pic_CXX=
       ;;
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
     sysv4*MP*)
       if test -d /usr/nec; then
 	lt_prog_compiler_pic_CXX=-Kconform_pic
@@ -11412,7 +11062,7 @@
     hpux*)
       # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
       # not for PA HP-UX.
-      case $host_cpu in
+      case "$host_cpu" in
       hppa*64*|ia64*)
 	;;
       *)
@@ -11437,7 +11087,7 @@
 	;;
       chorus*)
 	case $cc_basename in
-	cxch68*)
+	cxch68)
 	  # Green Hills C++ Compiler
 	  # _LT_AC_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
 	  ;;
@@ -11446,7 +11096,7 @@
        darwin*)
          # PIC is the default on this platform
          # Common symbols not allowed in MH_DYLIB files
-         case $cc_basename in
+         case "$cc_basename" in
            xlc*)
            lt_prog_compiler_pic_CXX='-qnocommon'
            lt_prog_compiler_wl_CXX='-Wl,'
@@ -11455,10 +11105,10 @@
        ;;
       dgux*)
 	case $cc_basename in
-	  ec++*)
+	  ec++)
 	    lt_prog_compiler_pic_CXX='-KPIC'
 	    ;;
-	  ghcx*)
+	  ghcx)
 	    # Green Hills C++ Compiler
 	    lt_prog_compiler_pic_CXX='-pic'
 	    ;;
@@ -11471,17 +11121,17 @@
 	;;
       hpux9* | hpux10* | hpux11*)
 	case $cc_basename in
-	  CC*)
+	  CC)
 	    lt_prog_compiler_wl_CXX='-Wl,'
-	    lt_prog_compiler_static_CXX='${wl}-a ${wl}archive'
+	    lt_prog_compiler_static_CXX="${ac_cv_prog_cc_wl}-a ${ac_cv_prog_cc_wl}archive"
 	    if test "$host_cpu" != ia64; then
 	      lt_prog_compiler_pic_CXX='+Z'
 	    fi
 	    ;;
-	  aCC*)
+	  aCC)
 	    lt_prog_compiler_wl_CXX='-Wl,'
-	    lt_prog_compiler_static_CXX='${wl}-a ${wl}archive'
-	    case $host_cpu in
+	    lt_prog_compiler_static_CXX="${ac_cv_prog_cc_wl}-a ${ac_cv_prog_cc_wl}archive"
+	    case "$host_cpu" in
 	    hppa*64*|ia64*)
 	      # +Z the default
 	      ;;
@@ -11494,13 +11144,9 @@
 	    ;;
 	esac
 	;;
-      interix*)
-	# This is c89, which is MS Visual C++ (no shared libs)
-	# Anyone wants to do a port?
-	;;
       irix5* | irix6* | nonstopux*)
 	case $cc_basename in
-	  CC*)
+	  CC)
 	    lt_prog_compiler_wl_CXX='-Wl,'
 	    lt_prog_compiler_static_CXX='-non_shared'
 	    # CC pic flag -KPIC is the default.
@@ -11511,7 +11157,7 @@
 	;;
       linux*)
 	case $cc_basename in
-	  KCC*)
+	  KCC)
 	    # KAI C++ Compiler
 	    lt_prog_compiler_wl_CXX='--backend -Wl,'
 	    lt_prog_compiler_pic_CXX='-fPIC'
@@ -11522,13 +11168,13 @@
 	    lt_prog_compiler_pic_CXX='-KPIC'
 	    lt_prog_compiler_static_CXX='-static'
 	    ;;
-	  pgCC*)
+	  pgCC)
 	    # Portland Group C++ compiler.
 	    lt_prog_compiler_wl_CXX='-Wl,'
 	    lt_prog_compiler_pic_CXX='-fpic'
-	    lt_prog_compiler_static_CXX='-Bstatic'
+	    lt_prog_compiler_static_CXX='-static'
 	    ;;
-	  cxx*)
+	  cxx)
 	    # Compaq C++
 	    # Make sure the PIC flag is empty.  It appears that all Alpha
 	    # Linux and Compaq Tru64 Unix objects are PIC.
@@ -11545,7 +11191,7 @@
 	;;
       mvs*)
 	case $cc_basename in
-	  cxx*)
+	  cxx)
 	    lt_prog_compiler_pic_CXX='-W c,exportall'
 	    ;;
 	  *)
@@ -11556,14 +11202,14 @@
 	;;
       osf3* | osf4* | osf5*)
 	case $cc_basename in
-	  KCC*)
+	  KCC)
 	    lt_prog_compiler_wl_CXX='--backend -Wl,'
 	    ;;
-	  RCC*)
+	  RCC)
 	    # Rational C++ 2.4.1
 	    lt_prog_compiler_pic_CXX='-pic'
 	    ;;
-	  cxx*)
+	  cxx)
 	    # Digital/Compaq C++
 	    lt_prog_compiler_wl_CXX='-Wl,'
 	    # Make sure the PIC flag is empty.  It appears that all Alpha
@@ -11577,15 +11223,24 @@
 	;;
       psos*)
 	;;
+      sco*)
+	case $cc_basename in
+	  CC)
+	    lt_prog_compiler_pic_CXX='-fPIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
       solaris*)
 	case $cc_basename in
-	  CC*)
+	  CC)
 	    # Sun C++ 4.2, 5.x and Centerline C++
 	    lt_prog_compiler_pic_CXX='-KPIC'
 	    lt_prog_compiler_static_CXX='-Bstatic'
 	    lt_prog_compiler_wl_CXX='-Qoption ld '
 	    ;;
-	  gcx*)
+	  gcx)
 	    # Green Hills C++ Compiler
 	    lt_prog_compiler_pic_CXX='-PIC'
 	    ;;
@@ -11595,12 +11250,12 @@
 	;;
       sunos4*)
 	case $cc_basename in
-	  CC*)
+	  CC)
 	    # Sun C++ 4.x
 	    lt_prog_compiler_pic_CXX='-pic'
 	    lt_prog_compiler_static_CXX='-Bstatic'
 	    ;;
-	  lcc*)
+	  lcc)
 	    # Lucid
 	    lt_prog_compiler_pic_CXX='-pic'
 	    ;;
@@ -11610,7 +11265,7 @@
 	;;
       tandem*)
 	case $cc_basename in
-	  NCC*)
+	  NCC)
 	    # NonStop-UX NCC 3.20
 	    lt_prog_compiler_pic_CXX='-KPIC'
 	    ;;
@@ -11618,14 +11273,7 @@
 	    ;;
 	esac
 	;;
-      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-	case $cc_basename in
-	  CC*)
-	    lt_prog_compiler_wl_CXX='-Wl,'
-	    lt_prog_compiler_pic_CXX='-KPIC'
-	    lt_prog_compiler_static_CXX='-Bstatic'
-	    ;;
-	esac
+      unixware*)
 	;;
       vxworks*)
 	;;
@@ -11658,20 +11306,18 @@
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    # The option is referenced via a variable to avoid confusing sed.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:11664: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:11312: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:11668: \$? = $ac_status" >&5
+   echo "$as_me:11316: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+     # So say no if there are warnings
+     if test ! -s conftest.err; then
        lt_prog_compiler_pic_works_CXX=yes
      fi
    fi
@@ -11692,7 +11338,7 @@
 fi
 
 fi
-case $host_os in
+case "$host_os" in
   # For platforms which do not support PIC, -DPIC is meaningless:
   *djgpp*)
     lt_prog_compiler_pic_CXX=
@@ -11702,48 +11348,6 @@
     ;;
 esac
 
-#
-# Check to make sure the static flag actually works.
-#
-wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\"
-echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
-if test "${lt_prog_compiler_static_works_CXX+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_static_works_CXX=no
-   save_LDFLAGS="$LDFLAGS"
-   LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
-   printf "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&5
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_prog_compiler_static_works_CXX=yes
-       fi
-     else
-       lt_prog_compiler_static_works_CXX=yes
-     fi
-   fi
-   $rm conftest*
-   LDFLAGS="$save_LDFLAGS"
-
-fi
-echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_CXX" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works_CXX" >&6
-
-if test x"$lt_prog_compiler_static_works_CXX" = xyes; then
-    :
-else
-    lt_prog_compiler_static_CXX=
-fi
-
-
 echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
 echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
 if test "${lt_cv_prog_compiler_c_o_CXX+set}" = set; then
@@ -11762,25 +11366,23 @@
    # Note that $ac_compile itself does not contain backslashes and begins
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:11768: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:11372: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>out/conftest.err)
    ac_status=$?
    cat out/conftest.err >&5
-   echo "$as_me:11772: \$? = $ac_status" >&5
+   echo "$as_me:11376: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s out/conftest2.$ac_objext
    then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+     if test ! -s out/conftest.err; then
        lt_cv_prog_compiler_c_o_CXX=yes
      fi
    fi
-   chmod u+w . 2>&5
+   chmod u+w .
    $rm conftest*
    # SGI C++ compiler will create directory out/ii_files/ for
    # template instantiation
@@ -11846,6 +11448,11 @@
 echo "${ECHO_T}$ld_shlibs_CXX" >&6
 test "$ld_shlibs_CXX" = no && can_build_shared=no
 
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
 #
 # Do we need to explicitly link libc?
 #
@@ -11878,7 +11485,6 @@
         libobjs=conftest.$ac_objext
         deplibs=
         wl=$lt_prog_compiler_wl_CXX
-	pic_flag=$lt_prog_compiler_pic_CXX
         compiler_flags=-v
         linker_flags=-v
         verstring=
@@ -12039,8 +11645,7 @@
       dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
       dldir=$destdir/`dirname \$dlpath`~
       test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
+      $install_prog $dir/$dlname \$dldir/$dlname'
     postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
       dlpath=$dir/\$dldll~
        $rm \$dlpath'
@@ -12093,7 +11698,7 @@
   soname_spec='${libname}${release}${major}$shared_ext'
   shlibpath_overrides_runpath=yes
   shlibpath_var=DYLD_LIBRARY_PATH
-  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+  shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)'
   # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
   if test "$GCC" = yes; then
     sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
@@ -12131,14 +11736,7 @@
 freebsd* | dragonfly*)
   # DragonFly does not have aout.  When/if they implement a new
   # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[123]*) objformat=aout ;;
-    *) objformat=elf ;;
-    esac
-  fi
+  objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout`
   version_type=freebsd-$objformat
   case $version_type in
     freebsd-elf*)
@@ -12160,15 +11758,10 @@
     shlibpath_overrides_runpath=yes
     hardcode_into_libs=yes
     ;;
-  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
-  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+  *) # from 3.2 on
     shlibpath_overrides_runpath=no
     hardcode_into_libs=yes
     ;;
-  freebsd*) # from 4.6 on
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
   esac
   ;;
 
@@ -12188,7 +11781,7 @@
   version_type=sunos
   need_lib_prefix=no
   need_version=no
-  case $host_cpu in
+  case "$host_cpu" in
   ia64*)
     shrext_cmds='.so'
     hardcode_into_libs=yes
@@ -12228,18 +11821,6 @@
   postinstall_cmds='chmod 555 $lib'
   ;;
 
-interix3*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
 irix5* | irix6* | nonstopux*)
   case $host_os in
     nonstopux*) version_type=nonstopux ;;
@@ -12299,7 +11880,7 @@
 
   # Append ld.so.conf contents to the search path
   if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,\t]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
     sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
   fi
 
@@ -12361,13 +11942,8 @@
 
 openbsd*)
   version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
   need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=yes ;;
-    *)                         need_version=no  ;;
-  esac
+  need_version=no
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
   finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
   shlibpath_var=LD_LIBRARY_PATH
@@ -12405,6 +11981,13 @@
   sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
   ;;
 
+sco3.2v5*)
+  version_type=osf
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
 solaris*)
   version_type=linux
   need_lib_prefix=no
@@ -12430,7 +12013,7 @@
   need_version=yes
   ;;
 
-sysv4 | sysv4.3*)
+sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
   version_type=linux
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
   soname_spec='${libname}${release}${shared_ext}$major'
@@ -12463,29 +12046,6 @@
   fi
   ;;
 
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-    shlibpath_overrides_runpath=no
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=yes
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
-
 uts4*)
   version_type=linux
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
@@ -12501,11 +12061,6 @@
 echo "${ECHO_T}$dynamic_linker" >&6
 test "$dynamic_linker" = no && can_build_shared=no
 
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
-fi
-
 echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
 echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
 hardcode_action_CXX=
@@ -12543,2910 +12098,3543 @@
   enable_fast_install=needless
 fi
 
-
-# The else clause should only fire when bootstrapping the
-# libtool distribution, otherwise you forgot to ship ltmain.sh
-# with your package, and you will get complaints that there are
-# no rules to generate ltmain.sh.
-if test -f "$ltmain"; then
-  # See if we are running on zsh, and set the options which allow our commands through
-  # without removal of \ escapes.
-  if test -n "${ZSH_VERSION+set}" ; then
-    setopt NO_GLOB_SUBST
-  fi
-  # Now quote all the things that may contain metacharacters while being
-  # careful not to overquote the AC_SUBSTed values.  We take copies of the
-  # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
-    SED SHELL STRIP \
-    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
-    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
-    deplibs_check_method reload_flag reload_cmds need_locks \
-    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
-    lt_cv_sys_global_symbol_to_c_name_address \
-    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
-    old_postinstall_cmds old_postuninstall_cmds \
-    compiler_CXX \
-    CC_CXX \
-    LD_CXX \
-    lt_prog_compiler_wl_CXX \
-    lt_prog_compiler_pic_CXX \
-    lt_prog_compiler_static_CXX \
-    lt_prog_compiler_no_builtin_flag_CXX \
-    export_dynamic_flag_spec_CXX \
-    thread_safe_flag_spec_CXX \
-    whole_archive_flag_spec_CXX \
-    enable_shared_with_static_runtimes_CXX \
-    old_archive_cmds_CXX \
-    old_archive_from_new_cmds_CXX \
-    predep_objects_CXX \
-    postdep_objects_CXX \
-    predeps_CXX \
-    postdeps_CXX \
-    compiler_lib_search_path_CXX \
-    archive_cmds_CXX \
-    archive_expsym_cmds_CXX \
-    postinstall_cmds_CXX \
-    postuninstall_cmds_CXX \
-    old_archive_from_expsyms_cmds_CXX \
-    allow_undefined_flag_CXX \
-    no_undefined_flag_CXX \
-    export_symbols_cmds_CXX \
-    hardcode_libdir_flag_spec_CXX \
-    hardcode_libdir_flag_spec_ld_CXX \
-    hardcode_libdir_separator_CXX \
-    hardcode_automatic_CXX \
-    module_cmds_CXX \
-    module_expsym_cmds_CXX \
-    lt_cv_prog_compiler_c_o_CXX \
-    exclude_expsyms_CXX \
-    include_expsyms_CXX; do
-
-    case $var in
-    old_archive_cmds_CXX | \
-    old_archive_from_new_cmds_CXX | \
-    archive_cmds_CXX | \
-    archive_expsym_cmds_CXX | \
-    module_cmds_CXX | \
-    module_expsym_cmds_CXX | \
-    old_archive_from_expsyms_cmds_CXX | \
-    export_symbols_cmds_CXX | \
-    extract_expsyms_cmds | reload_cmds | finish_cmds | \
-    postinstall_cmds | postuninstall_cmds | \
-    old_postinstall_cmds | old_postuninstall_cmds | \
-    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
-      # Double-quote double-evaled strings.
-      eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
-      ;;
-    *)
-      eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
-      ;;
-    esac
-  done
-
-  case $lt_echo in
-  *'\$0 --fallback-echo"')
-    lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'`
+striplib=
+old_striplib=
+echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5
+echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6
+if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+   darwin*)
+       if test -n "$STRIP" ; then
+         striplib="$STRIP -x"
+         echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+       else
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+       ;;
+   *)
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
     ;;
   esac
+fi
 
-cfgfile="$ofile"
+if test "x$enable_dlopen" != xyes; then
+  enable_dlopen=unknown
+  enable_dlopen_self=unknown
+  enable_dlopen_self_static=unknown
+else
+  lt_cv_dlopen=no
+  lt_cv_dlopen_libs=
 
-  cat <<__EOF__ >> "$cfgfile"
-# ### BEGIN LIBTOOL TAG CONFIG: $tagname
+  case $host_os in
+  beos*)
+    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ;;
 
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+  mingw* | pw32*)
+    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen_libs=
+   ;;
 
-# Shell to use when invoking shell scripts.
-SHELL=$lt_SHELL
+  cygwin*)
+    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen_libs=
+   ;;
 
-# Whether or not to build shared libraries.
-build_libtool_libs=$enable_shared
+  darwin*)
+  # if libdl is installed we need to link against it
+    echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
+echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6
+if test "${ac_cv_lib_dl_dlopen+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
 
-# Whether or not to build static libraries.
-build_old_libs=$enable_static
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dlopen ();
+int
+main ()
+{
+dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_dl_dlopen=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=$archive_cmds_need_lc_CXX
+ac_cv_lib_dl_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6
+if test $ac_cv_lib_dl_dlopen = yes; then
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
 
-# Whether or not to disallow shared libs when runtime libs are static
-allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX
+    lt_cv_dlopen="dyld"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
 
-# Whether or not to optimize for fast installation.
-fast_install=$enable_fast_install
+fi
 
-# The host system.
-host_alias=$host_alias
-host=$host
-host_os=$host_os
+   ;;
 
-# The build system.
-build_alias=$build_alias
-build=$build
-build_os=$build_os
+  *)
+    echo "$as_me:$LINENO: checking for shl_load" >&5
+echo $ECHO_N "checking for shl_load... $ECHO_C" >&6
+if test "${ac_cv_func_shl_load+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+/* Define shl_load to an innocuous variant, in case <limits.h> declares shl_load.
+   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
+#define shl_load innocuous_shl_load
 
-# An echo program that does not interpret backslashes.
-echo=$lt_echo
+/* System header to define __stub macros and hopefully few prototypes,
+    which can conflict with char shl_load (); below.
+    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+    <limits.h> exists even on freestanding compilers.  */
 
-# The archiver.
-AR=$lt_AR
-AR_FLAGS=$lt_AR_FLAGS
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
 
-# A C compiler.
-LTCC=$lt_LTCC
+#undef shl_load
 
-# LTCC compiler flags.
-LTCFLAGS=$lt_LTCFLAGS
-
-# A language-specific compiler.
-CC=$lt_compiler_CXX
-
-# Is the compiler the GNU C compiler?
-with_gcc=$GCC_CXX
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char shl_load ();
+/* 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_shl_load) || defined (__stub___shl_load)
+choke me
+#else
+char (*f) () = shl_load;
+#endif
+#ifdef __cplusplus
+}
+#endif
 
-# An ERE matcher.
-EGREP=$lt_EGREP
+int
+main ()
+{
+return f != shl_load;
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_func_shl_load=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-# The linker used to build libraries.
-LD=$lt_LD_CXX
+ac_cv_func_shl_load=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5
+echo "${ECHO_T}$ac_cv_func_shl_load" >&6
+if test $ac_cv_func_shl_load = yes; then
+  lt_cv_dlopen="shl_load"
+else
+  echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5
+echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6
+if test "${ac_cv_lib_dld_shl_load+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
 
-# Whether we need hard or soft links.
-LN_S=$lt_LN_S
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char shl_load ();
+int
+main ()
+{
+shl_load ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_dld_shl_load=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-# A BSD-compatible nm program.
-NM=$lt_NM
+ac_cv_lib_dld_shl_load=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6
+if test $ac_cv_lib_dld_shl_load = yes; then
+  lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld"
+else
+  echo "$as_me:$LINENO: checking for dlopen" >&5
+echo $ECHO_N "checking for dlopen... $ECHO_C" >&6
+if test "${ac_cv_func_dlopen+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+/* Define dlopen to an innocuous variant, in case <limits.h> declares dlopen.
+   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
+#define dlopen innocuous_dlopen
 
-# A symbol stripping program
-STRIP=$lt_STRIP
+/* System header to define __stub macros and hopefully few prototypes,
+    which can conflict with char dlopen (); below.
+    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+    <limits.h> exists even on freestanding compilers.  */
 
-# Used to examine libraries when file_magic_cmd begins "file"
-MAGIC_CMD=$MAGIC_CMD
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
 
-# Used on cygwin: DLL creation program.
-DLLTOOL="$DLLTOOL"
+#undef dlopen
 
-# Used on cygwin: object dumper.
-OBJDUMP="$OBJDUMP"
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dlopen ();
+/* 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_dlopen) || defined (__stub___dlopen)
+choke me
+#else
+char (*f) () = dlopen;
+#endif
+#ifdef __cplusplus
+}
+#endif
 
-# Used on cygwin: assembler.
-AS="$AS"
+int
+main ()
+{
+return f != dlopen;
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_func_dlopen=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-# The name of the directory that contains temporary libtool files.
-objdir=$objdir
+ac_cv_func_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5
+echo "${ECHO_T}$ac_cv_func_dlopen" >&6
+if test $ac_cv_func_dlopen = yes; then
+  lt_cv_dlopen="dlopen"
+else
+  echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
+echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6
+if test "${ac_cv_lib_dl_dlopen+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
 
-# How to create reloadable object files.
-reload_flag=$lt_reload_flag
-reload_cmds=$lt_reload_cmds
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dlopen ();
+int
+main ()
+{
+dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_dl_dlopen=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-# How to pass a linker flag through the compiler.
-wl=$lt_lt_prog_compiler_wl_CXX
+ac_cv_lib_dl_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6
+if test $ac_cv_lib_dl_dlopen = yes; then
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
+  echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5
+echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6
+if test "${ac_cv_lib_svld_dlopen+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lsvld  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
 
-# Object file suffix (normally "o").
-objext="$ac_objext"
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dlopen ();
+int
+main ()
+{
+dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_svld_dlopen=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-# Old archive suffix (normally "a").
-libext="$libext"
+ac_cv_lib_svld_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6
+if test $ac_cv_lib_svld_dlopen = yes; then
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
+else
+  echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5
+echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6
+if test "${ac_cv_lib_dld_dld_link+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
 
-# Shared library suffix (normally ".so").
-shrext_cmds='$shrext_cmds'
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dld_link ();
+int
+main ()
+{
+dld_link ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_dld_dld_link=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-# Executable file suffix (normally "").
-exeext="$exeext"
+ac_cv_lib_dld_dld_link=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6
+if test $ac_cv_lib_dld_dld_link = yes; then
+  lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld"
+fi
 
-# Additional compiler flags for building library objects.
-pic_flag=$lt_lt_prog_compiler_pic_CXX
-pic_mode=$pic_mode
 
-# What is the maximum length of a command?
-max_cmd_len=$lt_cv_sys_max_cmd_len
+fi
 
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX
 
-# Must we lock files when doing compilation?
-need_locks=$lt_need_locks
+fi
 
-# Do we need the lib prefix for modules?
-need_lib_prefix=$need_lib_prefix
 
-# Do we need a version for libraries?
-need_version=$need_version
+fi
 
-# Whether dlopen is supported.
-dlopen_support=$enable_dlopen
 
-# Whether dlopen of programs is supported.
-dlopen_self=$enable_dlopen_self
+fi
 
-# Whether dlopen of statically linked programs is supported.
-dlopen_self_static=$enable_dlopen_self_static
 
-# Compiler flag to prevent dynamic linking.
-link_static_flag=$lt_lt_prog_compiler_static_CXX
+fi
 
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX
+    ;;
+  esac
 
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX
+  if test "x$lt_cv_dlopen" != xno; then
+    enable_dlopen=yes
+  else
+    enable_dlopen=no
+  fi
 
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX
+  case $lt_cv_dlopen in
+  dlopen)
+    save_CPPFLAGS="$CPPFLAGS"
+    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
 
-# Compiler flag to generate thread-safe objects.
-thread_safe_flag_spec=$lt_thread_safe_flag_spec_CXX
+    save_LDFLAGS="$LDFLAGS"
+    eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
 
-# Library versioning type.
-version_type=$version_type
+    save_LIBS="$LIBS"
+    LIBS="$lt_cv_dlopen_libs $LIBS"
 
-# Format of library name prefix.
-libname_spec=$lt_libname_spec
+    echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5
+echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6
+if test "${lt_cv_dlopen_self+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  	  if test "$cross_compiling" = yes; then :
+  lt_cv_dlopen_self=cross
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<EOF
+#line 12735 "configure"
+#include "confdefs.h"
 
-# List of archive names.  First name is the real one, the rest are links.
-# The last name is the one that the linker finds with -lNAME.
-library_names_spec=$lt_library_names_spec
-
-# The coded name of the library, if different from the real name.
-soname_spec=$lt_soname_spec
-
-# Commands used to build and install an old-style archive.
-RANLIB=$lt_RANLIB
-old_archive_cmds=$lt_old_archive_cmds_CXX
-old_postinstall_cmds=$lt_old_postinstall_cmds
-old_postuninstall_cmds=$lt_old_postuninstall_cmds
-
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX
-
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX
-
-# Commands used to build and install a shared archive.
-archive_cmds=$lt_archive_cmds_CXX
-archive_expsym_cmds=$lt_archive_expsym_cmds_CXX
-postinstall_cmds=$lt_postinstall_cmds
-postuninstall_cmds=$lt_postuninstall_cmds
-
-# Commands used to build a loadable module (assumed same as above if empty)
-module_cmds=$lt_module_cmds_CXX
-module_expsym_cmds=$lt_module_expsym_cmds_CXX
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
 
-# Commands to strip libraries.
-old_striplib=$lt_old_striplib
-striplib=$lt_striplib
+#include <stdio.h>
 
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predep_objects=$lt_predep_objects_CXX
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
 
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdep_objects=$lt_postdep_objects_CXX
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
 
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predeps=$lt_predeps_CXX
+#ifdef __cplusplus
+extern "C" void exit (int);
+#endif
 
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdeps=$lt_postdeps_CXX
+void fnord() { int i=42;}
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
 
-# The library search path used internally by the compiler when linking
-# a shared library.
-compiler_lib_search_path=$lt_compiler_lib_search_path_CXX
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+      /* dlclose (self); */
+    }
 
-# Method to check whether dependent libraries are shared objects.
-deplibs_check_method=$lt_deplibs_check_method
+    exit (status);
+}
+EOF
+  if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;;
+      x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;;
+      x$lt_unknown|x*) lt_cv_dlopen_self=no ;;
+    esac
+  else :
+    # compilation failed
+    lt_cv_dlopen_self=no
+  fi
+fi
+rm -fr conftest*
 
-# Command to use when deplibs_check_method == file_magic.
-file_magic_cmd=$lt_file_magic_cmd
 
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=$lt_allow_undefined_flag_CXX
+fi
+echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5
+echo "${ECHO_T}$lt_cv_dlopen_self" >&6
 
-# Flag that forces no undefined symbols.
-no_undefined_flag=$lt_no_undefined_flag_CXX
+    if test "x$lt_cv_dlopen_self" = xyes; then
+      LDFLAGS="$LDFLAGS $link_static_flag"
+      echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5
+echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6
+if test "${lt_cv_dlopen_self_static+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  	  if test "$cross_compiling" = yes; then :
+  lt_cv_dlopen_self_static=cross
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<EOF
+#line 12833 "configure"
+#include "confdefs.h"
 
-# Commands used to finish a libtool library installation in a directory.
-finish_cmds=$lt_finish_cmds
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
 
-# Same as above, but a single script fragment to be evaled but not shown.
-finish_eval=$lt_finish_eval
+#include <stdio.h>
 
-# Take the output of nm and produce a listing of raw symbols and C names.
-global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
 
-# Transform the output of nm in a proper C declaration
-global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
 
-# Transform the output of nm in a C name address pair
-global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
+#ifdef __cplusplus
+extern "C" void exit (int);
+#endif
 
-# This is the shared library runtime path variable.
-runpath_var=$runpath_var
+void fnord() { int i=42;}
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
 
-# This is the shared library path variable.
-shlibpath_var=$shlibpath_var
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+      /* dlclose (self); */
+    }
 
-# Is shlibpath searched before the hard-coded library search path?
-shlibpath_overrides_runpath=$shlibpath_overrides_runpath
+    exit (status);
+}
+EOF
+  if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;;
+      x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;;
+      x$lt_unknown|x*) lt_cv_dlopen_self_static=no ;;
+    esac
+  else :
+    # compilation failed
+    lt_cv_dlopen_self_static=no
+  fi
+fi
+rm -fr conftest*
 
-# How to hardcode a shared library path into an executable.
-hardcode_action=$hardcode_action_CXX
 
-# Whether we should hardcode library paths into libraries.
-hardcode_into_libs=$hardcode_into_libs
+fi
+echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5
+echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6
+    fi
 
-# Flag to hardcode \$libdir into a binary during linking.
-# This must work even if \$libdir does not exist.
-hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX
+    CPPFLAGS="$save_CPPFLAGS"
+    LDFLAGS="$save_LDFLAGS"
+    LIBS="$save_LIBS"
+    ;;
+  esac
 
-# If ld is used when linking, flag to hardcode \$libdir into
-# a binary during linking. This must work even if \$libdir does
-# not exist.
-hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_CXX
+  case $lt_cv_dlopen_self in
+  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+  *) enable_dlopen_self=unknown ;;
+  esac
 
-# Whether we need a single -rpath flag with a separated argument.
-hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX
+  case $lt_cv_dlopen_self_static in
+  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+  *) enable_dlopen_self_static=unknown ;;
+  esac
+fi
 
-# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the
-# resulting binary.
-hardcode_direct=$hardcode_direct_CXX
 
-# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
-# resulting binary.
-hardcode_minus_L=$hardcode_minus_L_CXX
+# The else clause should only fire when bootstrapping the
+# libtool distribution, otherwise you forgot to ship ltmain.sh
+# with your package, and you will get complaints that there are
+# no rules to generate ltmain.sh.
+if test -f "$ltmain"; then
+  # See if we are running on zsh, and set the options which allow our commands through
+  # without removal of \ escapes.
+  if test -n "${ZSH_VERSION+set}" ; then
+    setopt NO_GLOB_SUBST
+  fi
+  # Now quote all the things that may contain metacharacters while being
+  # careful not to overquote the AC_SUBSTed values.  We take copies of the
+  # variables and quote the copies for generation of the libtool script.
+  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \
+    SED SHELL STRIP \
+    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
+    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
+    deplibs_check_method reload_flag reload_cmds need_locks \
+    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
+    lt_cv_sys_global_symbol_to_c_name_address \
+    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
+    old_postinstall_cmds old_postuninstall_cmds \
+    compiler_CXX \
+    CC_CXX \
+    LD_CXX \
+    lt_prog_compiler_wl_CXX \
+    lt_prog_compiler_pic_CXX \
+    lt_prog_compiler_static_CXX \
+    lt_prog_compiler_no_builtin_flag_CXX \
+    export_dynamic_flag_spec_CXX \
+    thread_safe_flag_spec_CXX \
+    whole_archive_flag_spec_CXX \
+    enable_shared_with_static_runtimes_CXX \
+    old_archive_cmds_CXX \
+    old_archive_from_new_cmds_CXX \
+    predep_objects_CXX \
+    postdep_objects_CXX \
+    predeps_CXX \
+    postdeps_CXX \
+    compiler_lib_search_path_CXX \
+    archive_cmds_CXX \
+    archive_expsym_cmds_CXX \
+    postinstall_cmds_CXX \
+    postuninstall_cmds_CXX \
+    old_archive_from_expsyms_cmds_CXX \
+    allow_undefined_flag_CXX \
+    no_undefined_flag_CXX \
+    export_symbols_cmds_CXX \
+    hardcode_libdir_flag_spec_CXX \
+    hardcode_libdir_flag_spec_ld_CXX \
+    hardcode_libdir_separator_CXX \
+    hardcode_automatic_CXX \
+    module_cmds_CXX \
+    module_expsym_cmds_CXX \
+    lt_cv_prog_compiler_c_o_CXX \
+    exclude_expsyms_CXX \
+    include_expsyms_CXX; do
 
-# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
-# the resulting binary.
-hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX
+    case $var in
+    old_archive_cmds_CXX | \
+    old_archive_from_new_cmds_CXX | \
+    archive_cmds_CXX | \
+    archive_expsym_cmds_CXX | \
+    module_cmds_CXX | \
+    module_expsym_cmds_CXX | \
+    old_archive_from_expsyms_cmds_CXX | \
+    export_symbols_cmds_CXX | \
+    extract_expsyms_cmds | reload_cmds | finish_cmds | \
+    postinstall_cmds | postuninstall_cmds | \
+    old_postinstall_cmds | old_postuninstall_cmds | \
+    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
+      # Double-quote double-evaled strings.
+      eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+      ;;
+    *)
+      eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+      ;;
+    esac
+  done
 
-# Set to yes if building a shared library automatically hardcodes DIR into the library
-# and all subsequent libraries and executables linked against it.
-hardcode_automatic=$hardcode_automatic_CXX
+  case $lt_echo in
+  *'\$0 --fallback-echo"')
+    lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'`
+    ;;
+  esac
 
-# Variables whose values should be saved in libtool wrapper scripts and
-# restored at relink time.
-variables_saved_for_relink="$variables_saved_for_relink"
+cfgfile="$ofile"
 
-# Whether libtool must link a program against all its dependency libraries.
-link_all_deplibs=$link_all_deplibs_CXX
+  cat <<__EOF__ >> "$cfgfile"
+# ### BEGIN LIBTOOL TAG CONFIG: $tagname
 
-# Compile-time system search path for libraries
-sys_lib_search_path_spec=$lt_sys_lib_search_path_spec
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
 
-# Run-time system search path for libraries
-sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
 
-# Fix the shell variable \$srcfile for the compiler.
-fix_srcfile_path="$fix_srcfile_path_CXX"
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
 
-# Set to yes if exported symbols are required.
-always_export_symbols=$always_export_symbols_CXX
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
 
-# The commands to list exported symbols.
-export_symbols_cmds=$lt_export_symbols_cmds_CXX
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$archive_cmds_need_lc_CXX
 
-# The commands to extract the exported symbol list from a shared archive.
-extract_expsyms_cmds=$lt_extract_expsyms_cmds
+# Whether or not to disallow shared libs when runtime libs are static
+allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX
 
-# Symbols that should not be listed in the preloaded symbols.
-exclude_expsyms=$lt_exclude_expsyms_CXX
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
 
-# Symbols that must always be exported.
-include_expsyms=$lt_include_expsyms_CXX
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
 
-# ### END LIBTOOL TAG CONFIG: $tagname
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
 
-__EOF__
+# An echo program that does not interpret backslashes.
+echo=$lt_echo
 
+# The archiver.
+AR=$lt_AR
+AR_FLAGS=$lt_AR_FLAGS
 
-else
-  # If there is no Makefile yet, we rely on a make rule to execute
-  # `config.status --recheck' to rerun these tests and create the
-  # libtool script then.
-  ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'`
-  if test -f "$ltmain_in"; then
-    test -f Makefile && make "$ltmain"
-  fi
-fi
+# A C compiler.
+LTCC=$lt_LTCC
 
+# A language-specific compiler.
+CC=$lt_compiler_CXX
 
-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
+# Is the compiler the GNU C compiler?
+with_gcc=$GCC_CXX
 
-CC=$lt_save_CC
-LDCXX=$LD
-LD=$lt_save_LD
-GCC=$lt_save_GCC
-with_gnu_ldcxx=$with_gnu_ld
-with_gnu_ld=$lt_save_with_gnu_ld
-lt_cv_path_LDCXX=$lt_cv_path_LD
-lt_cv_path_LD=$lt_save_path_LD
-lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
-lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+# An ERE matcher.
+EGREP=$lt_EGREP
 
-	else
-	  tagname=""
-	fi
-	;;
+# The linker used to build libraries.
+LD=$lt_LD_CXX
 
-      F77)
-	if test -n "$F77" && test "X$F77" != "Xno"; then
+# Whether we need hard or soft links.
+LN_S=$lt_LN_S
 
-ac_ext=f
-ac_compile='$F77 -c $FFLAGS conftest.$ac_ext >&5'
-ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_f77_compiler_gnu
+# A BSD-compatible nm program.
+NM=$lt_NM
 
+# A symbol stripping program
+STRIP=$lt_STRIP
 
-archive_cmds_need_lc_F77=no
-allow_undefined_flag_F77=
-always_export_symbols_F77=no
-archive_expsym_cmds_F77=
-export_dynamic_flag_spec_F77=
-hardcode_direct_F77=no
-hardcode_libdir_flag_spec_F77=
-hardcode_libdir_flag_spec_ld_F77=
-hardcode_libdir_separator_F77=
-hardcode_minus_L_F77=no
-hardcode_automatic_F77=no
-module_cmds_F77=
-module_expsym_cmds_F77=
-link_all_deplibs_F77=unknown
-old_archive_cmds_F77=$old_archive_cmds
-no_undefined_flag_F77=
-whole_archive_flag_spec_F77=
-enable_shared_with_static_runtimes_F77=no
+# Used to examine libraries when file_magic_cmd begins "file"
+MAGIC_CMD=$MAGIC_CMD
 
-# Source file extension for f77 test sources.
-ac_ext=f
+# Used on cygwin: DLL creation program.
+DLLTOOL="$DLLTOOL"
 
-# Object file extension for compiled f77 test sources.
-objext=o
-objext_F77=$objext
+# Used on cygwin: object dumper.
+OBJDUMP="$OBJDUMP"
 
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="      subroutine t\n      return\n      end\n"
+# Used on cygwin: assembler.
+AS="$AS"
 
-# Code to be used in simple link tests
-lt_simple_link_test_code="      program t\n      end\n"
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
 
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
 
-# If no C compiler was specified, use CC.
-LTCC=${LTCC-"$CC"}
+# How to pass a linker flag through the compiler.
+wl=$lt_lt_prog_compiler_wl_CXX
 
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+# Object file suffix (normally "o").
+objext="$ac_objext"
 
-# Allow CC to be a program name with arguments.
-compiler=$CC
+# Old archive suffix (normally "a").
+libext="$libext"
 
+# Shared library suffix (normally ".so").
+shrext_cmds='$shrext_cmds'
 
-# save warnings/boilerplate of simple test code
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$rm conftest*
-
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$rm conftest*
+# Executable file suffix (normally "").
+exeext="$exeext"
 
+# Additional compiler flags for building library objects.
+pic_flag=$lt_lt_prog_compiler_pic_CXX
+pic_mode=$pic_mode
 
-# Allow CC to be a program name with arguments.
-lt_save_CC="$CC"
-CC=${F77-"f77"}
-compiler=$CC
-compiler_F77=$CC
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+# What is the maximum length of a command?
+max_cmd_len=$lt_cv_sys_max_cmd_len
 
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX
 
-echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
-echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6
-echo "$as_me:$LINENO: result: $can_build_shared" >&5
-echo "${ECHO_T}$can_build_shared" >&6
+# Must we lock files when doing compilation ?
+need_locks=$lt_need_locks
 
-echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
-echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6
-test "$can_build_shared" = "no" && enable_shared=no
+# Do we need the lib prefix for modules?
+need_lib_prefix=$need_lib_prefix
 
-# On AIX, shared libraries and static libraries use the same namespace, and
-# are all built from PIC.
-case $host_os in
-aix3*)
-  test "$enable_shared" = yes && enable_static=no
-  if test -n "$RANLIB"; then
-    archive_cmds="$archive_cmds~\$RANLIB \$lib"
-    postinstall_cmds='$RANLIB $lib'
-  fi
-  ;;
-aix4* | aix5*)
-  if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-    test "$enable_shared" = yes && enable_static=no
-  fi
-  ;;
-esac
-echo "$as_me:$LINENO: result: $enable_shared" >&5
-echo "${ECHO_T}$enable_shared" >&6
+# Do we need a version for libraries?
+need_version=$need_version
 
-echo "$as_me:$LINENO: checking whether to build static libraries" >&5
-echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6
-# Make sure either enable_shared or enable_static is yes.
-test "$enable_shared" = yes || enable_static=yes
-echo "$as_me:$LINENO: result: $enable_static" >&5
-echo "${ECHO_T}$enable_static" >&6
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
 
-GCC_F77="$G77"
-LD_F77="$LD"
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
 
-lt_prog_compiler_wl_F77=
-lt_prog_compiler_pic_F77=
-lt_prog_compiler_static_F77=
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
 
-echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
-echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_lt_prog_compiler_static_CXX
 
-  if test "$GCC" = yes; then
-    lt_prog_compiler_wl_F77='-Wl,'
-    lt_prog_compiler_static_F77='-static'
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX
 
-    case $host_os in
-      aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	lt_prog_compiler_static_F77='-Bstatic'
-      fi
-      ;;
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX
 
-    amigaos*)
-      # FIXME: we need at least 68020 code to build shared libraries, but
-      # adding the `-m68020' flag to GCC prevents building anything better,
-      # like `-m68040'.
-      lt_prog_compiler_pic_F77='-m68020 -resident32 -malways-restore-a4'
-      ;;
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX
 
-    beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
+# Compiler flag to generate thread-safe objects.
+thread_safe_flag_spec=$lt_thread_safe_flag_spec_CXX
 
-    mingw* | pw32* | os2*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      lt_prog_compiler_pic_F77='-DDLL_EXPORT'
-      ;;
+# Library versioning type.
+version_type=$version_type
 
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      lt_prog_compiler_pic_F77='-fno-common'
-      ;;
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
 
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
+# List of archive names.  First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec=$lt_library_names_spec
 
-    msdosdjgpp*)
-      # Just because we use GCC doesn't mean we suddenly get shared libraries
-      # on systems that don't support them.
-      lt_prog_compiler_can_build_shared_F77=no
-      enable_shared=no
-      ;;
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
 
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	lt_prog_compiler_pic_F77=-Kconform_pic
-      fi
-      ;;
+# Commands used to build and install an old-style archive.
+RANLIB=$lt_RANLIB
+old_archive_cmds=$lt_old_archive_cmds_CXX
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
 
-    hpux*)
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	lt_prog_compiler_pic_F77='-fPIC'
-	;;
-      esac
-      ;;
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX
 
-    *)
-      lt_prog_compiler_pic_F77='-fPIC'
-      ;;
-    esac
-  else
-    # PORTME Check for flag to pass linker flags through the system compiler.
-    case $host_os in
-    aix*)
-      lt_prog_compiler_wl_F77='-Wl,'
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	lt_prog_compiler_static_F77='-Bstatic'
-      else
-	lt_prog_compiler_static_F77='-bnso -bI:/lib/syscalls.exp'
-      fi
-      ;;
-      darwin*)
-        # PIC is the default on this platform
-        # Common symbols not allowed in MH_DYLIB files
-       case $cc_basename in
-         xlc*)
-         lt_prog_compiler_pic_F77='-qnocommon'
-         lt_prog_compiler_wl_F77='-Wl,'
-         ;;
-       esac
-       ;;
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX
 
-    mingw* | pw32* | os2*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      lt_prog_compiler_pic_F77='-DDLL_EXPORT'
-      ;;
+# Commands used to build and install a shared archive.
+archive_cmds=$lt_archive_cmds_CXX
+archive_expsym_cmds=$lt_archive_expsym_cmds_CXX
+postinstall_cmds=$lt_postinstall_cmds
+postuninstall_cmds=$lt_postuninstall_cmds
 
-    hpux9* | hpux10* | hpux11*)
-      lt_prog_compiler_wl_F77='-Wl,'
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	lt_prog_compiler_pic_F77='+Z'
-	;;
-      esac
-      # Is there a better lt_prog_compiler_static that works with the bundled CC?
-      lt_prog_compiler_static_F77='${wl}-a ${wl}archive'
-      ;;
+# Commands used to build a loadable module (assumed same as above if empty)
+module_cmds=$lt_module_cmds_CXX
+module_expsym_cmds=$lt_module_expsym_cmds_CXX
 
-    irix5* | irix6* | nonstopux*)
-      lt_prog_compiler_wl_F77='-Wl,'
-      # PIC (with -KPIC) is the default.
-      lt_prog_compiler_static_F77='-non_shared'
-      ;;
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
 
-    newsos6)
-      lt_prog_compiler_pic_F77='-KPIC'
-      lt_prog_compiler_static_F77='-Bstatic'
-      ;;
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predep_objects=$lt_predep_objects_CXX
 
-    linux*)
-      case $cc_basename in
-      icc* | ecc*)
-	lt_prog_compiler_wl_F77='-Wl,'
-	lt_prog_compiler_pic_F77='-KPIC'
-	lt_prog_compiler_static_F77='-static'
-        ;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
-        # Portland Group compilers (*not* the Pentium gcc compiler,
-	# which looks to be a dead project)
-	lt_prog_compiler_wl_F77='-Wl,'
-	lt_prog_compiler_pic_F77='-fpic'
-	lt_prog_compiler_static_F77='-Bstatic'
-        ;;
-      ccc*)
-        lt_prog_compiler_wl_F77='-Wl,'
-        # All Alpha code is PIC.
-        lt_prog_compiler_static_F77='-non_shared'
-        ;;
-      esac
-      ;;
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdep_objects=$lt_postdep_objects_CXX
 
-    osf3* | osf4* | osf5*)
-      lt_prog_compiler_wl_F77='-Wl,'
-      # All OSF/1 code is PIC.
-      lt_prog_compiler_static_F77='-non_shared'
-      ;;
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predeps=$lt_predeps_CXX
 
-    solaris*)
-      lt_prog_compiler_pic_F77='-KPIC'
-      lt_prog_compiler_static_F77='-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95*)
-	lt_prog_compiler_wl_F77='-Qoption ld ';;
-      *)
-	lt_prog_compiler_wl_F77='-Wl,';;
-      esac
-      ;;
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdeps=$lt_postdeps_CXX
 
-    sunos4*)
-      lt_prog_compiler_wl_F77='-Qoption ld '
-      lt_prog_compiler_pic_F77='-PIC'
-      lt_prog_compiler_static_F77='-Bstatic'
-      ;;
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=$lt_compiler_lib_search_path_CXX
 
-    sysv4 | sysv4.2uw2* | sysv4.3*)
-      lt_prog_compiler_wl_F77='-Wl,'
-      lt_prog_compiler_pic_F77='-KPIC'
-      lt_prog_compiler_static_F77='-Bstatic'
-      ;;
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
 
-    sysv4*MP*)
-      if test -d /usr/nec ;then
-	lt_prog_compiler_pic_F77='-Kconform_pic'
-	lt_prog_compiler_static_F77='-Bstatic'
-      fi
-      ;;
+# Command to use when deplibs_check_method == file_magic.
+file_magic_cmd=$lt_file_magic_cmd
 
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      lt_prog_compiler_wl_F77='-Wl,'
-      lt_prog_compiler_pic_F77='-KPIC'
-      lt_prog_compiler_static_F77='-Bstatic'
-      ;;
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_allow_undefined_flag_CXX
 
-    unicos*)
-      lt_prog_compiler_wl_F77='-Wl,'
-      lt_prog_compiler_can_build_shared_F77=no
-      ;;
+# Flag that forces no undefined symbols.
+no_undefined_flag=$lt_no_undefined_flag_CXX
 
-    uts4*)
-      lt_prog_compiler_pic_F77='-pic'
-      lt_prog_compiler_static_F77='-Bstatic'
-      ;;
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
 
-    *)
-      lt_prog_compiler_can_build_shared_F77=no
-      ;;
-    esac
-  fi
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval=$lt_finish_eval
 
-echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_F77" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_F77" >&6
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
 
-#
-# Check to make sure the PIC flag actually works.
-#
-if test -n "$lt_prog_compiler_pic_F77"; then
+# Transform the output of nm in a proper C declaration
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
 
-echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works" >&5
-echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works... $ECHO_C" >&6
-if test "${lt_prog_compiler_pic_works_F77+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_pic_works_F77=no
-  ac_outfile=conftest.$ac_objext
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag="$lt_prog_compiler_pic_F77"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:13338: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=$?
-   cat conftest.err >&5
-   echo "$as_me:13342: \$? = $ac_status" >&5
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
-       lt_prog_compiler_pic_works_F77=yes
-     fi
-   fi
-   $rm conftest*
+# Transform the output of nm in a C name address pair
+global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
 
-fi
-echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_F77" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_works_F77" >&6
+# This is the shared library runtime path variable.
+runpath_var=$runpath_var
 
-if test x"$lt_prog_compiler_pic_works_F77" = xyes; then
-    case $lt_prog_compiler_pic_F77 in
-     "" | " "*) ;;
-     *) lt_prog_compiler_pic_F77=" $lt_prog_compiler_pic_F77" ;;
-     esac
-else
-    lt_prog_compiler_pic_F77=
-     lt_prog_compiler_can_build_shared_F77=no
-fi
+# This is the shared library path variable.
+shlibpath_var=$shlibpath_var
 
-fi
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    lt_prog_compiler_pic_F77=
-    ;;
-  *)
-    lt_prog_compiler_pic_F77="$lt_prog_compiler_pic_F77"
-    ;;
-esac
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=$shlibpath_overrides_runpath
 
-#
-# Check to make sure the static flag actually works.
-#
-wl=$lt_prog_compiler_wl_F77 eval lt_tmp_static_flag=\"$lt_prog_compiler_static_F77\"
-echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
-if test "${lt_prog_compiler_static_works_F77+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_static_works_F77=no
-   save_LDFLAGS="$LDFLAGS"
-   LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
-   printf "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&5
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_prog_compiler_static_works_F77=yes
-       fi
-     else
-       lt_prog_compiler_static_works_F77=yes
-     fi
-   fi
-   $rm conftest*
-   LDFLAGS="$save_LDFLAGS"
+# How to hardcode a shared library path into an executable.
+hardcode_action=$hardcode_action_CXX
 
-fi
-echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_F77" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works_F77" >&6
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=$hardcode_into_libs
 
-if test x"$lt_prog_compiler_static_works_F77" = xyes; then
-    :
-else
-    lt_prog_compiler_static_F77=
-fi
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX
 
+# If ld is used when linking, flag to hardcode \$libdir into
+# a binary during linking. This must work even if \$libdir does
+# not exist.
+hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_CXX
 
-echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
-echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
-if test "${lt_cv_prog_compiler_c_o_F77+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_cv_prog_compiler_c_o_F77=no
-   $rm -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX
 
-   lt_compiler_flag="-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:13442: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>out/conftest.err)
-   ac_status=$?
-   cat out/conftest.err >&5
-   echo "$as_me:13446: \$? = $ac_status" >&5
-   if (exit $ac_status) && test -s out/conftest2.$ac_objext
-   then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
-       lt_cv_prog_compiler_c_o_F77=yes
-     fi
-   fi
-   chmod u+w . 2>&5
-   $rm conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
-   $rm out/* && rmdir out
-   cd ..
-   rmdir conftest
-   $rm conftest*
+# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct=$hardcode_direct_CXX
 
-fi
-echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_F77" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_c_o_F77" >&6
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L=$hardcode_minus_L_CXX
+
+# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
+# the resulting binary.
+hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX
+
+# Set to yes if building a shared library automatically hardcodes DIR into the library
+# and all subsequent libraries and executables linked against it.
+hardcode_automatic=$hardcode_automatic_CXX
+
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at relink time.
+variables_saved_for_relink="$variables_saved_for_relink"
+
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$link_all_deplibs_CXX
+
+# Compile-time system search path for libraries
+sys_lib_search_path_spec=$lt_sys_lib_search_path_spec
+
+# Run-time system search path for libraries
+sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+
+# Fix the shell variable \$srcfile for the compiler.
+fix_srcfile_path="$fix_srcfile_path_CXX"
+
+# Set to yes if exported symbols are required.
+always_export_symbols=$always_export_symbols_CXX
+
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_export_symbols_cmds_CXX
+
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=$lt_extract_expsyms_cmds
+
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_exclude_expsyms_CXX
+
+# Symbols that must always be exported.
+include_expsyms=$lt_include_expsyms_CXX
+
+# ### END LIBTOOL TAG CONFIG: $tagname
+
+__EOF__
 
 
-hard_links="nottested"
-if test "$lt_cv_prog_compiler_c_o_F77" = no && test "$need_locks" != no; then
-  # do not overwrite the value of need_locks provided by the user
-  echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
-echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
-  hard_links=yes
-  $rm conftest*
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  touch conftest.a
-  ln conftest.a conftest.b 2>&5 || hard_links=no
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  echo "$as_me:$LINENO: result: $hard_links" >&5
-echo "${ECHO_T}$hard_links" >&6
-  if test "$hard_links" = no; then
-    { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
-echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
-    need_locks=warn
-  fi
 else
-  need_locks=no
+  # If there is no Makefile yet, we rely on a make rule to execute
+  # `config.status --recheck' to rerun these tests and create the
+  # libtool script then.
+  ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'`
+  if test -f "$ltmain_in"; then
+    test -f Makefile && make "$ltmain"
+  fi
 fi
 
-echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
 
-  runpath_var=
-  allow_undefined_flag_F77=
-  enable_shared_with_static_runtimes_F77=no
-  archive_cmds_F77=
-  archive_expsym_cmds_F77=
-  old_archive_From_new_cmds_F77=
-  old_archive_from_expsyms_cmds_F77=
-  export_dynamic_flag_spec_F77=
-  whole_archive_flag_spec_F77=
-  thread_safe_flag_spec_F77=
-  hardcode_libdir_flag_spec_F77=
-  hardcode_libdir_flag_spec_ld_F77=
-  hardcode_libdir_separator_F77=
-  hardcode_direct_F77=no
-  hardcode_minus_L_F77=no
-  hardcode_shlibpath_var_F77=unsupported
-  link_all_deplibs_F77=unknown
-  hardcode_automatic_F77=no
-  module_cmds_F77=
-  module_expsym_cmds_F77=
-  always_export_symbols_F77=no
-  export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  # include_expsyms should be a list of space-separated symbols to be *always*
-  # included in the symbol list
-  include_expsyms_F77=
-  # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
-  # as well as any symbol that contains `d'.
-  exclude_expsyms_F77="_GLOBAL_OFFSET_TABLE_"
-  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
-  # platforms (ab)use it in PIC code, but their linkers get confused if
-  # the symbol is explicitly referenced.  Since portable code cannot
-  # rely on this symbol name, it's probably fine to never include it in
-  # preloaded symbol tables.
-  extract_expsyms_cmds=
-  # Just being paranoid about ensuring that cc_basename is set.
-  for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+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
 
-  case $host_os in
-  cygwin* | mingw* | pw32*)
-    # FIXME: the MSVC++ port hasn't been tested in a loooong time
-    # When not using gcc, we currently assume that we are using
-    # Microsoft Visual C++.
-    if test "$GCC" != yes; then
-      with_gnu_ld=no
-    fi
-    ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (= MSVC++)
-    with_gnu_ld=yes
-    ;;
-  openbsd*)
-    with_gnu_ld=no
-    ;;
-  esac
+CC=$lt_save_CC
+LDCXX=$LD
+LD=$lt_save_LD
+GCC=$lt_save_GCC
+with_gnu_ldcxx=$with_gnu_ld
+with_gnu_ld=$lt_save_with_gnu_ld
+lt_cv_path_LDCXX=$lt_cv_path_LD
+lt_cv_path_LD=$lt_save_path_LD
+lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
 
-  ld_shlibs_F77=yes
-  if test "$with_gnu_ld" = yes; then
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc='${wl}'
+	else
+	  tagname=""
+	fi
+	;;
 
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=LD_RUN_PATH
-    hardcode_libdir_flag_spec_F77='${wl}--rpath ${wl}$libdir'
-    export_dynamic_flag_spec_F77='${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
-	whole_archive_flag_spec_F77="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-      else
-  	whole_archive_flag_spec_F77=
-    fi
-    supports_anon_versioning=no
-    case `$LD -v 2>/dev/null` in
-      *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=yes ;;
-    esac
+      F77)
+	if test -n "$F77" && test "X$F77" != "Xno"; then
 
-    # See if GNU ld supports shared libraries.
-    case $host_os in
-    aix3* | aix4* | aix5*)
-      # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" != ia64; then
-	ld_shlibs_F77=no
-	cat <<EOF 1>&2
+ac_ext=f
+ac_compile='$F77 -c $FFLAGS conftest.$ac_ext >&5'
+ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_f77_compiler_gnu
 
-*** Warning: the GNU linker, at least up to release 2.9.1, is reported
-*** to be unable to reliably create shared libraries on AIX.
-*** Therefore, libtool is disabling shared libraries support.  If you
-*** really care for shared libraries, you may want to modify your PATH
-*** so that a non-GNU linker is found, and then restart.
 
-EOF
-      fi
-      ;;
+archive_cmds_need_lc_F77=no
+allow_undefined_flag_F77=
+always_export_symbols_F77=no
+archive_expsym_cmds_F77=
+export_dynamic_flag_spec_F77=
+hardcode_direct_F77=no
+hardcode_libdir_flag_spec_F77=
+hardcode_libdir_flag_spec_ld_F77=
+hardcode_libdir_separator_F77=
+hardcode_minus_L_F77=no
+hardcode_automatic_F77=no
+module_cmds_F77=
+module_expsym_cmds_F77=
+link_all_deplibs_F77=unknown
+old_archive_cmds_F77=$old_archive_cmds
+no_undefined_flag_F77=
+whole_archive_flag_spec_F77=
+enable_shared_with_static_runtimes_F77=no
 
-    amigaos*)
-      archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-      hardcode_libdir_flag_spec_F77='-L$libdir'
-      hardcode_minus_L_F77=yes
+# Source file extension for f77 test sources.
+ac_ext=f
 
-      # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
-      # that the semantics of dynamic libraries on AmigaOS, at least up
-      # to version 4, is to share data among multiple programs linked
-      # with the same dynamic library.  Since this doesn't match the
-      # behavior of shared libraries on other platforms, we can't use
-      # them.
-      ld_shlibs_F77=no
-      ;;
+# Object file extension for compiled f77 test sources.
+objext=o
+objext_F77=$objext
 
-    beos*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	allow_undefined_flag_F77=unsupported
-	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
-	# support --undefined.  This deserves some investigation.  FIXME
-	archive_cmds_F77='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-      else
-	ld_shlibs_F77=no
-      fi
-      ;;
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="      subroutine t\n      return\n      end\n"
 
-    cygwin* | mingw* | pw32*)
-      # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, F77) is actually meaningless,
-      # as there is no search path for DLLs.
-      hardcode_libdir_flag_spec_F77='-L$libdir'
-      allow_undefined_flag_F77=unsupported
-      always_export_symbols_F77=no
-      enable_shared_with_static_runtimes_F77=yes
-      export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
+# Code to be used in simple link tests
+lt_simple_link_test_code="      program t\n      end\n"
 
-      if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-        archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	# If the export-symbols file already is a .def file (1st line
-	# is EXPORTS), use it as is; otherwise, prepend...
-	archive_expsym_cmds_F77='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	  cp $export_symbols $output_objdir/$soname.def;
-	else
-	  echo EXPORTS > $output_objdir/$soname.def;
-	  cat $export_symbols >> $output_objdir/$soname.def;
-	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      else
-	ld_shlibs_F77=no
-      fi
-      ;;
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
 
-    interix3*)
-      hardcode_direct_F77=no
-      hardcode_shlibpath_var_F77=no
-      hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir'
-      export_dynamic_flag_spec_F77='${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-      # Instead, shared libraries are loaded at an image base (0x10000000 by
-      # default) and relocated if they conflict, which is a slow very memory
-      # consuming and fragmenting process.  To avoid this, we pick a random,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      archive_cmds_F77='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      archive_expsym_cmds_F77='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      ;;
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
 
-    linux*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	tmp_addflag=
-	case $cc_basename,$host_cpu in
-	pgcc*)				# Portland Group C compiler
-	  whole_archive_flag_spec_F77='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
-	  whole_archive_flag_spec_F77='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
-	  tmp_addflag=' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=' -nofor_main' ;;
-	esac
-	archive_cmds_F77='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+# Allow CC to be a program name with arguments.
+compiler=$CC
 
-	if test $supports_anon_versioning = yes; then
-	  archive_expsym_cmds_F77='$echo "{ global:" > $output_objdir/$libname.ver~
-  cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-  $echo "local: *; };" >> $output_objdir/$libname.ver~
-	  $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-	fi
-      else
-	ld_shlibs_F77=no
-      fi
-      ;;
 
-    netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-	archive_cmds_F77='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
-	wlarc=
-      else
-	archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      fi
-      ;;
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${F77-"f77"}
+compiler=$CC
+compiler_F77=$CC
+cc_basename=`$echo X"$compiler" | $Xsed -e 's%^.*/%%'`
 
-    solaris*)
-      if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
-	ld_shlibs_F77=no
-	cat <<EOF 1>&2
+echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
+echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6
+echo "$as_me:$LINENO: result: $can_build_shared" >&5
+echo "${ECHO_T}$can_build_shared" >&6
 
-*** Warning: The releases 2.8.* of the GNU linker cannot reliably
-*** create shared libraries on Solaris systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.9.1 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
+echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
+echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6
+test "$can_build_shared" = "no" && enable_shared=no
 
-EOF
-      elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      else
-	ld_shlibs_F77=no
-      fi
-      ;;
+# On AIX, shared libraries and static libraries use the same namespace, and
+# are all built from PIC.
+case "$host_os" in
+aix3*)
+  test "$enable_shared" = yes && enable_static=no
+  if test -n "$RANLIB"; then
+    archive_cmds="$archive_cmds~\$RANLIB \$lib"
+    postinstall_cmds='$RANLIB $lib'
+  fi
+  ;;
+aix4* | aix5*)
+  test "$enable_shared" = yes && enable_static=no
+  ;;
+esac
+echo "$as_me:$LINENO: result: $enable_shared" >&5
+echo "${ECHO_T}$enable_shared" >&6
 
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
-	ld_shlibs_F77=no
-	cat <<_LT_EOF 1>&2
+echo "$as_me:$LINENO: checking whether to build static libraries" >&5
+echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6
+# Make sure either enable_shared or enable_static is yes.
+test "$enable_shared" = yes || enable_static=yes
+echo "$as_me:$LINENO: result: $enable_static" >&5
+echo "${ECHO_T}$enable_static" >&6
 
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
+test "$ld_shlibs_F77" = no && can_build_shared=no
 
-_LT_EOF
-	;;
-	*)
-	  if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	    hardcode_libdir_flag_spec_F77='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
-	    archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
-	    archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib'
-	  else
-	    ld_shlibs_F77=no
-	  fi
-	;;
-      esac
-      ;;
+GCC_F77="$G77"
+LD_F77="$LD"
 
-    sunos4*)
-      archive_cmds_F77='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      wlarc=
-      hardcode_direct_F77=yes
-      hardcode_shlibpath_var_F77=no
-      ;;
+lt_prog_compiler_wl_F77=
+lt_prog_compiler_pic_F77=
+lt_prog_compiler_static_F77=
 
-    *)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      else
-	ld_shlibs_F77=no
-      fi
-      ;;
-    esac
+echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
+echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
+
+  if test "$GCC" = yes; then
+    lt_prog_compiler_wl_F77='-Wl,'
+    lt_prog_compiler_static_F77='-static'
 
-    if test "$ld_shlibs_F77" = no; then
-      runpath_var=
-      hardcode_libdir_flag_spec_F77=
-      export_dynamic_flag_spec_F77=
-      whole_archive_flag_spec_F77=
-    fi
-  else
-    # PORTME fill in a description of your system's linker (not GNU ld)
     case $host_os in
-    aix3*)
-      allow_undefined_flag_F77=unsupported
-      always_export_symbols_F77=yes
-      archive_expsym_cmds_F77='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
-      # Note: this linker hardcodes the directories in LIBPATH if there
-      # are no directories specified by -L.
-      hardcode_minus_L_F77=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
-	# Neither direct hardcoding nor static linking is supported with a
-	# broken collect2.
-	hardcode_direct_F77=unsupported
+      aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	lt_prog_compiler_static_F77='-Bstatic'
       fi
       ;;
 
-    aix4* | aix5*)
-      if test "$host_cpu" = ia64; then
-	# On IA64, the linker does run time linking by default, so we don't
-	# have to do anything special.
-	aix_use_runtimelinking=no
-	exp_sym_flag='-Bexport'
-	no_entry_flag=""
-      else
-	# If we're using GNU nm, then we don't want the "-C" option.
-	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
-	  export_symbols_cmds_F77='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
-	else
-	  export_symbols_cmds_F77='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
-	fi
-	aix_use_runtimelinking=no
+    amigaos*)
+      # FIXME: we need at least 68020 code to build shared libraries, but
+      # adding the `-m68020' flag to GCC prevents building anything better,
+      # like `-m68040'.
+      lt_prog_compiler_pic_F77='-m68020 -resident32 -malways-restore-a4'
+      ;;
 
-	# Test if we are trying to use run time linking or normal
-	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
-	case $host_os in aix4.[23]|aix4.[23].*|aix5*)
-	  for ld_flag in $LDFLAGS; do
-  	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
-  	    aix_use_runtimelinking=yes
-  	    break
-  	  fi
-	  done
-	  ;;
-	esac
+    beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
 
-	exp_sym_flag='-bexport'
-	no_entry_flag='-bnoentry'
-      fi
+    mingw* | pw32* | os2*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      lt_prog_compiler_pic_F77='-DDLL_EXPORT'
+      ;;
 
-      # When large executables or shared objects are built, AIX ld can
-      # have problems creating the table of contents.  If linking a library
-      # or program results in "error TOC overflow" add -mminimal-toc to
-      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      lt_prog_compiler_pic_F77='-fno-common'
+      ;;
 
-      archive_cmds_F77=''
-      hardcode_direct_F77=yes
-      hardcode_libdir_separator_F77=':'
-      link_all_deplibs_F77=yes
+    msdosdjgpp*)
+      # Just because we use GCC doesn't mean we suddenly get shared libraries
+      # on systems that don't support them.
+      lt_prog_compiler_can_build_shared_F77=no
+      enable_shared=no
+      ;;
 
-      if test "$GCC" = yes; then
-	case $host_os in aix4.[012]|aix4.[012].*)
-	# We only want to do this on AIX 4.2 and lower, the check
-	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
-	  if test -f "$collect2name" && \
-  	   strings "$collect2name" | grep resolve_lib_name >/dev/null
-	  then
-  	  # We have reworked collect2
-  	  hardcode_direct_F77=yes
-	  else
-  	  # We have old collect2
-  	  hardcode_direct_F77=unsupported
-  	  # It fails to find uninstalled libraries when the uninstalled
-  	  # path is not listed in the libpath.  Setting hardcode_minus_L
-  	  # to unsupported forces relinking
-  	  hardcode_minus_L_F77=yes
-  	  hardcode_libdir_flag_spec_F77='-L$libdir'
-  	  hardcode_libdir_separator_F77=
-	  fi
-	  ;;
-	esac
-	shared_flag='-shared'
-	if test "$aix_use_runtimelinking" = yes; then
-	  shared_flag="$shared_flag "'${wl}-G'
-	fi
-      else
-	# not using gcc
-	if test "$host_cpu" = ia64; then
-  	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-  	# chokes on -Wl,-G. The following line is correct:
-	  shared_flag='-G'
-	else
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag='${wl}-G'
-	  else
-	    shared_flag='${wl}-bM:SRE'
-	  fi
-	fi
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	lt_prog_compiler_pic_F77=-Kconform_pic
       fi
+      ;;
 
-      # It seems that -bexpall does not export symbols beginning with
-      # underscore (_), so it is better to generate a list of symbols to export.
-      always_export_symbols_F77=yes
-      if test "$aix_use_runtimelinking" = yes; then
-	# Warning - without using the other runtime loading flags (-brtl),
-	# -berok will link without error, but may produce a broken library.
-	allow_undefined_flag_F77='-berok'
-       # Determine the default libpath from the value encoded in an empty executable.
-       cat >conftest.$ac_ext <<_ACEOF
-      program main
+    hpux*)
+      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+      # not for PA HP-UX.
+      case "$host_cpu" in
+      hppa*64*|ia64*)
+	# +Z the default
+	;;
+      *)
+	lt_prog_compiler_pic_F77='-fPIC'
+	;;
+      esac
+      ;;
 
-      end
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_f77_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+    *)
+      lt_prog_compiler_pic_F77='-fPIC'
+      ;;
+    esac
+  else
+    # PORTME Check for flag to pass linker flags through the system compiler.
+    case $host_os in
+    aix*)
+      lt_prog_compiler_wl_F77='-Wl,'
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	lt_prog_compiler_static_F77='-Bstatic'
+      else
+	lt_prog_compiler_static_F77='-bnso -bI:/lib/syscalls.exp'
+      fi
+      ;;
+      darwin*)
+        # PIC is the default on this platform
+        # Common symbols not allowed in MH_DYLIB files
+       case "$cc_basename" in
+         xlc*)
+         lt_prog_compiler_pic_F77='-qnocommon'
+         lt_prog_compiler_wl_F77='-Wl,'
+         ;;
+       esac
+       ;;
 
-aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+    mingw* | pw32* | os2*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      lt_prog_compiler_pic_F77='-DDLL_EXPORT'
+      ;;
 
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+    hpux9* | hpux10* | hpux11*)
+      lt_prog_compiler_wl_F77='-Wl,'
+      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+      # not for PA HP-UX.
+      case "$host_cpu" in
+      hppa*64*|ia64*)
+	# +Z the default
+	;;
+      *)
+	lt_prog_compiler_pic_F77='+Z'
+	;;
+      esac
+      # Is there a better lt_prog_compiler_static that works with the bundled CC?
+      lt_prog_compiler_static_F77='${wl}-a ${wl}archive'
+      ;;
 
-       hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath"
-	archive_expsym_cmds_F77="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
-       else
-	if test "$host_cpu" = ia64; then
-	  hardcode_libdir_flag_spec_F77='${wl}-R $libdir:/usr/lib:/lib'
-	  allow_undefined_flag_F77="-z nodefs"
-	  archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-	else
-	 # Determine the default libpath from the value encoded in an empty executable.
-	 cat >conftest.$ac_ext <<_ACEOF
-      program main
-
-      end
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_f77_werror_flag"
-			 || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-	 { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-
-aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
-
-	 hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath"
-	  # Warning - without using the other run time loading flags,
-	  # -berok will link without error, but may produce a broken library.
-	  no_undefined_flag_F77=' ${wl}-bernotok'
-	  allow_undefined_flag_F77=' ${wl}-berok'
-	  # Exported symbols can be pulled into shared objects from archives
-	  whole_archive_flag_spec_F77='$convenience'
-	  archive_cmds_need_lc_F77=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
-	fi
-      fi
-      ;;
-
-    amigaos*)
-      archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-      hardcode_libdir_flag_spec_F77='-L$libdir'
-      hardcode_minus_L_F77=yes
-      # see comment about different semantics on the GNU ld section
-      ld_shlibs_F77=no
-      ;;
-
-    bsdi[45]*)
-      export_dynamic_flag_spec_F77=-rdynamic
+    irix5* | irix6* | nonstopux*)
+      lt_prog_compiler_wl_F77='-Wl,'
+      # PIC (with -KPIC) is the default.
+      lt_prog_compiler_static_F77='-non_shared'
       ;;
 
-    cygwin* | mingw* | pw32*)
-      # When not using gcc, we currently assume that we are using
-      # Microsoft Visual C++.
-      # hardcode_libdir_flag_spec is actually meaningless, as there is
-      # no search path for DLLs.
-      hardcode_libdir_flag_spec_F77=' '
-      allow_undefined_flag_F77=unsupported
-      # Tell ltmain to make .lib files, not .a files.
-      libext=lib
-      # Tell ltmain to make .dll files, not .so files.
-      shrext_cmds=".dll"
-      # FIXME: Setting linknames here is a bad hack.
-      archive_cmds_F77='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames='
-      # The linker will automatically build a .lib file if we build a DLL.
-      old_archive_From_new_cmds_F77='true'
-      # FIXME: Should let the user specify the lib program.
-      old_archive_cmds_F77='lib /OUT:$oldlib$oldobjs$old_deplibs'
-      fix_srcfile_path_F77='`cygpath -w "$srcfile"`'
-      enable_shared_with_static_runtimes_F77=yes
+    newsos6)
+      lt_prog_compiler_pic_F77='-KPIC'
+      lt_prog_compiler_static_F77='-Bstatic'
       ;;
 
-    darwin* | rhapsody*)
-      case $host_os in
-        rhapsody* | darwin1.[012])
-         allow_undefined_flag_F77='${wl}-undefined ${wl}suppress'
-         ;;
-       *) # Darwin 1.3 on
-         if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
-           allow_undefined_flag_F77='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
-         else
-           case ${MACOSX_DEPLOYMENT_TARGET} in
-             10.[012])
-               allow_undefined_flag_F77='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
-               ;;
-             10.*)
-               allow_undefined_flag_F77='${wl}-undefined ${wl}dynamic_lookup'
-               ;;
-           esac
-         fi
-         ;;
-      esac
-      archive_cmds_need_lc_F77=no
-      hardcode_direct_F77=no
-      hardcode_automatic_F77=yes
-      hardcode_shlibpath_var_F77=unsupported
-      whole_archive_flag_spec_F77=''
-      link_all_deplibs_F77=yes
-    if test "$GCC" = yes ; then
-    	output_verbose_link_cmd='echo'
-        archive_cmds_F77='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
-      module_cmds_F77='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-      # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
-      archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-      module_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-    else
+    linux*)
       case $cc_basename in
-        xlc*)
-         output_verbose_link_cmd='echo'
-         archive_cmds_F77='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
-         module_cmds_F77='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
-         archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          module_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          ;;
-       *)
-         ld_shlibs_F77=no
-          ;;
+      icc* | ecc*)
+	lt_prog_compiler_wl_F77='-Wl,'
+	lt_prog_compiler_pic_F77='-KPIC'
+	lt_prog_compiler_static_F77='-static'
+        ;;
+      pgcc | pgf77 | pgf90)
+        # Portland Group compilers (*not* the Pentium gcc compiler,
+	# which looks to be a dead project)
+	lt_prog_compiler_wl_F77='-Wl,'
+	lt_prog_compiler_pic_F77='-fpic'
+	lt_prog_compiler_static_F77='-static'
+        ;;
+      ccc*)
+        lt_prog_compiler_wl_F77='-Wl,'
+        # All Alpha code is PIC.
+        lt_prog_compiler_static_F77='-non_shared'
+        ;;
       esac
-    fi
       ;;
 
-    dgux*)
-      archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_libdir_flag_spec_F77='-L$libdir'
-      hardcode_shlibpath_var_F77=no
+    osf3* | osf4* | osf5*)
+      lt_prog_compiler_wl_F77='-Wl,'
+      # All OSF/1 code is PIC.
+      lt_prog_compiler_static_F77='-non_shared'
       ;;
 
-    freebsd1*)
-      ld_shlibs_F77=no
+    sco3.2v5*)
+      lt_prog_compiler_pic_F77='-Kpic'
+      lt_prog_compiler_static_F77='-dn'
       ;;
 
-    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
-    # support.  Future versions do this automatically, but an explicit c++rt0.o
-    # does not break anything, and helps significantly (at the cost of a little
-    # extra space).
-    freebsd2.2*)
-      archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
-      hardcode_libdir_flag_spec_F77='-R$libdir'
-      hardcode_direct_F77=yes
-      hardcode_shlibpath_var_F77=no
+    solaris*)
+      lt_prog_compiler_wl_F77='-Wl,'
+      lt_prog_compiler_pic_F77='-KPIC'
+      lt_prog_compiler_static_F77='-Bstatic'
       ;;
 
-    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2*)
-      archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_direct_F77=yes
-      hardcode_minus_L_F77=yes
-      hardcode_shlibpath_var_F77=no
+    sunos4*)
+      lt_prog_compiler_wl_F77='-Qoption ld '
+      lt_prog_compiler_pic_F77='-PIC'
+      lt_prog_compiler_static_F77='-Bstatic'
       ;;
 
-    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
-    freebsd* | kfreebsd*-gnu | dragonfly*)
-      archive_cmds_F77='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
-      hardcode_libdir_flag_spec_F77='-R$libdir'
-      hardcode_direct_F77=yes
-      hardcode_shlibpath_var_F77=no
+    sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+      lt_prog_compiler_wl_F77='-Wl,'
+      lt_prog_compiler_pic_F77='-KPIC'
+      lt_prog_compiler_static_F77='-Bstatic'
       ;;
 
-    hpux9*)
-      if test "$GCC" = yes; then
-	archive_cmds_F77='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-      else
-	archive_cmds_F77='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+    sysv4*MP*)
+      if test -d /usr/nec ;then
+	lt_prog_compiler_pic_F77='-Kconform_pic'
+	lt_prog_compiler_static_F77='-Bstatic'
       fi
-      hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir'
-      hardcode_libdir_separator_F77=:
-      hardcode_direct_F77=yes
-
-      # hardcode_minus_L: Not really in the search PATH,
-      # but as the default location of the library.
-      hardcode_minus_L_F77=yes
-      export_dynamic_flag_spec_F77='${wl}-E'
       ;;
 
-    hpux10*)
-      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	archive_cmds_F77='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds_F77='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator_F77=:
+    unicos*)
+      lt_prog_compiler_wl_F77='-Wl,'
+      lt_prog_compiler_can_build_shared_F77=no
+      ;;
 
-	hardcode_direct_F77=yes
-	export_dynamic_flag_spec_F77='${wl}-E'
+    uts4*)
+      lt_prog_compiler_pic_F77='-pic'
+      lt_prog_compiler_static_F77='-Bstatic'
+      ;;
 
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	hardcode_minus_L_F77=yes
-      fi
+    *)
+      lt_prog_compiler_can_build_shared_F77=no
       ;;
+    esac
+  fi
 
-    hpux11*)
-      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds_F77='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds_F77='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  archive_cmds_F77='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      else
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds_F77='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds_F77='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  archive_cmds_F77='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      fi
-      if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator_F77=:
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_F77" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_F77" >&6
 
-	case $host_cpu in
-	hppa*64*|ia64*)
-	  hardcode_libdir_flag_spec_ld_F77='+b $libdir'
-	  hardcode_direct_F77=no
-	  hardcode_shlibpath_var_F77=no
-	  ;;
-	*)
-	  hardcode_direct_F77=yes
-	  export_dynamic_flag_spec_F77='${wl}-E'
-
-	  # hardcode_minus_L: Not really in the search PATH,
-	  # but as the default location of the library.
-	  hardcode_minus_L_F77=yes
-	  ;;
-	esac
-      fi
-      ;;
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$lt_prog_compiler_pic_F77"; then
 
-    irix5* | irix6* | nonstopux*)
-      if test "$GCC" = yes; then
-	archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-      else
-	archive_cmds_F77='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
-	hardcode_libdir_flag_spec_ld_F77='-rpath $libdir'
-      fi
-      hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator_F77=:
-      link_all_deplibs_F77=yes
-      ;;
+echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works" >&5
+echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works... $ECHO_C" >&6
+if test "${lt_prog_compiler_pic_works_F77+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  lt_prog_compiler_pic_works_F77=no
+  ac_outfile=conftest.$ac_objext
+   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+   lt_compiler_flag="$lt_prog_compiler_pic_F77"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   # The option is referenced via a variable to avoid confusing sed.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:13688: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>conftest.err)
+   ac_status=$?
+   cat conftest.err >&5
+   echo "$as_me:13692: \$? = $ac_status" >&5
+   if (exit $ac_status) && test -s "$ac_outfile"; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test ! -s conftest.err; then
+       lt_prog_compiler_pic_works_F77=yes
+     fi
+   fi
+   $rm conftest*
 
-    netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-	archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
-      else
-	archive_cmds_F77='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
-      fi
-      hardcode_libdir_flag_spec_F77='-R$libdir'
-      hardcode_direct_F77=yes
-      hardcode_shlibpath_var_F77=no
-      ;;
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_F77" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_works_F77" >&6
 
-    newsos6)
-      archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_direct_F77=yes
-      hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator_F77=:
-      hardcode_shlibpath_var_F77=no
-      ;;
+if test x"$lt_prog_compiler_pic_works_F77" = xyes; then
+    case $lt_prog_compiler_pic_F77 in
+     "" | " "*) ;;
+     *) lt_prog_compiler_pic_F77=" $lt_prog_compiler_pic_F77" ;;
+     esac
+else
+    lt_prog_compiler_pic_F77=
+     lt_prog_compiler_can_build_shared_F77=no
+fi
 
-    openbsd*)
-      hardcode_direct_F77=yes
-      hardcode_shlibpath_var_F77=no
-      if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-	archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir'
-	export_dynamic_flag_spec_F77='${wl}-E'
-      else
-       case $host_os in
-	 openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
-	   archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-	   hardcode_libdir_flag_spec_F77='-R$libdir'
-	   ;;
-	 *)
-	   archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	   hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir'
-	   ;;
-       esac
-      fi
-      ;;
+fi
+case "$host_os" in
+  # For platforms which do not support PIC, -DPIC is meaningless:
+  *djgpp*)
+    lt_prog_compiler_pic_F77=
+    ;;
+  *)
+    lt_prog_compiler_pic_F77="$lt_prog_compiler_pic_F77"
+    ;;
+esac
 
-    os2*)
-      hardcode_libdir_flag_spec_F77='-L$libdir'
-      hardcode_minus_L_F77=yes
-      allow_undefined_flag_F77=unsupported
-      archive_cmds_F77='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
-      old_archive_From_new_cmds_F77='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
-      ;;
+echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
+echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
+if test "${lt_cv_prog_compiler_c_o_F77+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  lt_cv_prog_compiler_c_o_F77=no
+   $rm -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
 
-    osf3*)
-      if test "$GCC" = yes; then
-	allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-      else
-	allow_undefined_flag_F77=' -expect_unresolved \*'
-	archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
-      fi
-      hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator_F77=:
-      ;;
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:13748: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&5
+   echo "$as_me:13752: \$? = $ac_status" >&5
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test ! -s out/conftest.err; then
+       lt_cv_prog_compiler_c_o_F77=yes
+     fi
+   fi
+   chmod u+w .
+   $rm conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
+   $rm out/* && rmdir out
+   cd ..
+   rmdir conftest
+   $rm conftest*
 
-    osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      if test "$GCC" = yes; then
-	allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
-      else
-	allow_undefined_flag_F77=' -expect_unresolved \*'
-	archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
-	archive_expsym_cmds_F77='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
-	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+fi
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_F77" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_c_o_F77" >&6
 
-	# Both c and cxx compiler support -rpath directly
-	hardcode_libdir_flag_spec_F77='-rpath $libdir'
-      fi
-      hardcode_libdir_separator_F77=:
-      ;;
 
-    solaris*)
-      no_undefined_flag_F77=' -z text'
-      if test "$GCC" = yes; then
-	wlarc='${wl}'
-	archive_cmds_F77='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-	  $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
-      else
-	wlarc=''
-	archive_cmds_F77='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-  	$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
-      fi
-      hardcode_libdir_flag_spec_F77='-R$libdir'
-      hardcode_shlibpath_var_F77=no
-      case $host_os in
-      solaris2.[0-5] | solaris2.[0-5].*) ;;
-      *)
- 	# The compiler driver will combine linker options so we
- 	# cannot just pass the convience library names through
- 	# without $wl, iff we do not link with $LD.
- 	# Luckily, gcc supports the same syntax we need for Sun Studio.
- 	# Supported since Solaris 2.6 (maybe 2.5.1?)
- 	case $wlarc in
- 	'')
- 	  whole_archive_flag_spec_F77='-z allextract$convenience -z defaultextract' ;;
- 	*)
- 	  whole_archive_flag_spec_F77='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
- 	esac ;;
-      esac
-      link_all_deplibs_F77=yes
-      ;;
+hard_links="nottested"
+if test "$lt_cv_prog_compiler_c_o_F77" = no && test "$need_locks" != no; then
+  # do not overwrite the value of need_locks provided by the user
+  echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
+echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
+  hard_links=yes
+  $rm conftest*
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  touch conftest.a
+  ln conftest.a conftest.b 2>&5 || hard_links=no
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  echo "$as_me:$LINENO: result: $hard_links" >&5
+echo "${ECHO_T}$hard_links" >&6
+  if test "$hard_links" = no; then
+    { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
+echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
+    need_locks=warn
+  fi
+else
+  need_locks=no
+fi
 
-    sunos4*)
-      if test "x$host_vendor" = xsequent; then
-	# Use $CC to link under sequent, because it throws in some extra .o
-	# files that make .init and .fini sections work.
-	archive_cmds_F77='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds_F77='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      hardcode_libdir_flag_spec_F77='-L$libdir'
-      hardcode_direct_F77=yes
-      hardcode_minus_L_F77=yes
-      hardcode_shlibpath_var_F77=no
-      ;;
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
 
-    sysv4)
-      case $host_vendor in
-	sni)
-	  archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  hardcode_direct_F77=yes # is this really true???
-	;;
-	siemens)
-	  ## LD is ld it makes a PLAMLIB
-	  ## CC just makes a GrossModule.
-	  archive_cmds_F77='$LD -G -o $lib $libobjs $deplibs $linker_flags'
-	  reload_cmds_F77='$CC -r -o $output$reload_objs'
-	  hardcode_direct_F77=no
-        ;;
-	motorola)
-	  archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  hardcode_direct_F77=no #Motorola manual says yes, but my tests say they lie
-	;;
-      esac
-      runpath_var='LD_RUN_PATH'
-      hardcode_shlibpath_var_F77=no
-      ;;
+  runpath_var=
+  allow_undefined_flag_F77=
+  enable_shared_with_static_runtimes_F77=no
+  archive_cmds_F77=
+  archive_expsym_cmds_F77=
+  old_archive_From_new_cmds_F77=
+  old_archive_from_expsyms_cmds_F77=
+  export_dynamic_flag_spec_F77=
+  whole_archive_flag_spec_F77=
+  thread_safe_flag_spec_F77=
+  hardcode_libdir_flag_spec_F77=
+  hardcode_libdir_flag_spec_ld_F77=
+  hardcode_libdir_separator_F77=
+  hardcode_direct_F77=no
+  hardcode_minus_L_F77=no
+  hardcode_shlibpath_var_F77=unsupported
+  link_all_deplibs_F77=unknown
+  hardcode_automatic_F77=no
+  module_cmds_F77=
+  module_expsym_cmds_F77=
+  always_export_symbols_F77=no
+  export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  # include_expsyms should be a list of space-separated symbols to be *always*
+  # included in the symbol list
+  include_expsyms_F77=
+  # exclude_expsyms can be an extended regexp of symbols to exclude
+  # it will be wrapped by ` (' and `)$', so one must not match beginning or
+  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+  # as well as any symbol that contains `d'.
+  exclude_expsyms_F77="_GLOBAL_OFFSET_TABLE_"
+  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+  # platforms (ab)use it in PIC code, but their linkers get confused if
+  # the symbol is explicitly referenced.  Since portable code cannot
+  # rely on this symbol name, it's probably fine to never include it in
+  # preloaded symbol tables.
+  extract_expsyms_cmds=
 
-    sysv4.3*)
-      archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_shlibpath_var_F77=no
-      export_dynamic_flag_spec_F77='-Bexport'
-      ;;
+  case $host_os in
+  cygwin* | mingw* | pw32*)
+    # FIXME: the MSVC++ port hasn't been tested in a loooong time
+    # When not using gcc, we currently assume that we are using
+    # Microsoft Visual C++.
+    if test "$GCC" != yes; then
+      with_gnu_ld=no
+    fi
+    ;;
+  openbsd*)
+    with_gnu_ld=no
+    ;;
+  esac
 
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	hardcode_shlibpath_var_F77=no
-	runpath_var=LD_RUN_PATH
-	hardcode_runpath_var=yes
-	ld_shlibs_F77=yes
+  ld_shlibs_F77=yes
+  if test "$with_gnu_ld" = yes; then
+    # If archive_cmds runs LD, not CC, wlarc should be empty
+    wlarc='${wl}'
+
+    # See if GNU ld supports shared libraries.
+    case $host_os in
+    aix3* | aix4* | aix5*)
+      # On AIX/PPC, the GNU linker is very broken
+      if test "$host_cpu" != ia64; then
+	ld_shlibs_F77=no
+	cat <<EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support.  If you
+*** really care for shared libraries, you may want to modify your PATH
+*** so that a non-GNU linker is found, and then restart.
+
+EOF
       fi
       ;;
 
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*)
-      no_undefined_flag_F77='${wl}-z,text'
-      archive_cmds_need_lc_F77=no
-      hardcode_shlibpath_var_F77=no
-      runpath_var='LD_RUN_PATH'
+    amigaos*)
+      archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+      hardcode_libdir_flag_spec_F77='-L$libdir'
+      hardcode_minus_L_F77=yes
 
-      if test "$GCC" = yes; then
-	archive_cmds_F77='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_F77='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
+      # that the semantics of dynamic libraries on AmigaOS, at least up
+      # to version 4, is to share data among multiple programs linked
+      # with the same dynamic library.  Since this doesn't match the
+      # behavior of shared libraries on other platforms, we can't use
+      # them.
+      ld_shlibs_F77=no
+      ;;
+
+    beos*)
+      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+	allow_undefined_flag_F77=unsupported
+	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+	# support --undefined.  This deserves some investigation.  FIXME
+	archive_cmds_F77='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
       else
-	archive_cmds_F77='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_F77='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	ld_shlibs_F77=no
       fi
       ;;
 
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      no_undefined_flag_F77='${wl}-z,text'
-      allow_undefined_flag_F77='${wl}-z,nodefs'
-      archive_cmds_need_lc_F77=no
-      hardcode_shlibpath_var_F77=no
-      hardcode_libdir_flag_spec_F77='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
-      hardcode_libdir_separator_F77=':'
-      link_all_deplibs_F77=yes
-      export_dynamic_flag_spec_F77='${wl}-Bexport'
-      runpath_var='LD_RUN_PATH'
+    cygwin* | mingw* | pw32*)
+      # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, F77) is actually meaningless,
+      # as there is no search path for DLLs.
+      hardcode_libdir_flag_spec_F77='-L$libdir'
+      allow_undefined_flag_F77=unsupported
+      always_export_symbols_F77=no
+      enable_shared_with_static_runtimes_F77=yes
+      export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
 
-      if test "$GCC" = yes; then
-	archive_cmds_F77='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_F77='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+      if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+        archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib'
+	# If the export-symbols file already is a .def file (1st line
+	# is EXPORTS), use it as is; otherwise, prepend...
+	archive_expsym_cmds_F77='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	  cp $export_symbols $output_objdir/$soname.def;
+	else
+	  echo EXPORTS > $output_objdir/$soname.def;
+	  cat $export_symbols >> $output_objdir/$soname.def;
+	fi~
+	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000  ${wl}--out-implib,$lib'
       else
-	archive_cmds_F77='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_F77='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	ld_shlibs_F77=no
       fi
       ;;
 
-    uts4*)
-      archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_libdir_flag_spec_F77='-L$libdir'
-      hardcode_shlibpath_var_F77=no
+    netbsd*)
+      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+	archive_cmds_F77='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+	wlarc=
+      else
+	archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      fi
       ;;
 
-    *)
-      ld_shlibs_F77=no
-      ;;
-    esac
-  fi
+    solaris* | sysv5*)
+      if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
+	ld_shlibs_F77=no
+	cat <<EOF 1>&2
 
-echo "$as_me:$LINENO: result: $ld_shlibs_F77" >&5
-echo "${ECHO_T}$ld_shlibs_F77" >&6
-test "$ld_shlibs_F77" = no && can_build_shared=no
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
 
-#
-# Do we need to explicitly link libc?
-#
-case "x$archive_cmds_need_lc_F77" in
-x|xyes)
-  # Assume -lc should be added
-  archive_cmds_need_lc_F77=yes
+EOF
+      elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+	archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	ld_shlibs_F77=no
+      fi
+      ;;
 
-  if test "$enable_shared" = yes && test "$GCC" = yes; then
-    case $archive_cmds_F77 in
-    *'~'*)
-      # FIXME: we may have to deal with multi-command sequences.
+    sunos4*)
+      archive_cmds_F77='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      wlarc=
+      hardcode_direct_F77=yes
+      hardcode_shlibpath_var_F77=no
       ;;
-    '$CC '*)
-      # Test whether the compiler implicitly links with -lc since on some
-      # systems, -lgcc has to come before -lc. If gcc already passes -lc
-      # to ld, don't add -lc before -lgcc.
-      echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
-echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
-      $rm conftest*
-      printf "$lt_simple_compile_test_code" > conftest.$ac_ext
 
-      if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } 2>conftest.err; then
-        soname=conftest
-        lib=conftest
-        libobjs=conftest.$ac_objext
-        deplibs=
-        wl=$lt_prog_compiler_wl_F77
-	pic_flag=$lt_prog_compiler_pic_F77
-        compiler_flags=-v
-        linker_flags=-v
-        verstring=
-        output_objdir=.
-        libname=conftest
-        lt_save_allow_undefined_flag=$allow_undefined_flag_F77
-        allow_undefined_flag_F77=
-        if { (eval echo "$as_me:$LINENO: \"$archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5
-  (eval $archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }
-        then
-	  archive_cmds_need_lc_F77=no
-        else
-	  archive_cmds_need_lc_F77=yes
-        fi
-        allow_undefined_flag_F77=$lt_save_allow_undefined_flag
+  linux*)
+    if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+      tmp_addflag=
+      case $CC,$host_cpu in
+      pgf77* | pgf90* )			# Portland Group f77 and f90 compilers
+        tmp_addflag=' -fpic' ;;
+      ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
+        tmp_addflag=' -i_dynamic' ;;
+      efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
+        tmp_addflag=' -i_dynamic -nofor_main' ;;
+      ifc* | ifort*)			# Intel Fortran compiler
+      	tmp_addflag=' -nofor_main' ;;
+      esac
+      archive_cmds_F77='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      supports_anon_versioning=no
+      case `$LD -v 2>/dev/null` in
+        *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
+        *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+        *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+        *\ 2.11.*) ;; # other 2.11 versions
+        *) supports_anon_versioning=yes ;;
+      esac
+      if test $supports_anon_versioning = yes; then
+        archive_expsym_cmds_F77='$echo "{ global:" > $output_objdir/$libname.ver~
+cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+$echo "local: *; };" >> $output_objdir/$libname.ver~
+        $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
       else
-        cat conftest.err 1>&5
+        archive_expsym_cmds_F77=$archive_cmds_F77
+      fi
+    else
+      ld_shlibs_F77=no
+    fi
+    ;;
+
+    *)
+      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+	archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	ld_shlibs_F77=no
       fi
-      $rm conftest*
-      echo "$as_me:$LINENO: result: $archive_cmds_need_lc_F77" >&5
-echo "${ECHO_T}$archive_cmds_need_lc_F77" >&6
       ;;
     esac
-  fi
-  ;;
-esac
 
-echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
-echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
-library_names_spec=
-libname_spec='lib$name'
-soname_spec=
-shrext_cmds=".so"
-postinstall_cmds=
-postuninstall_cmds=
-finish_cmds=
-finish_eval=
-shlibpath_var=
-shlibpath_overrides_runpath=unknown
-version_type=none
-dynamic_linker="$host_os ld.so"
-sys_lib_dlsearch_path_spec="/lib /usr/lib"
-if test "$GCC" = yes; then
-  sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
-  if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
-    # if the path contains ";" then we assume it to be the separator
-    # otherwise default to the standard path separator (i.e. ":") - it is
-    # assumed that no part of a normal pathname contains ";" but that should
-    # okay in the real world where ";" in dirpaths is itself problematic.
-    sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
-  else
-    sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
-  fi
-else
-  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
-fi
-need_lib_prefix=unknown
-hardcode_into_libs=no
-
-# when you set need_version to no, make sure it does not cause -set_version
-# flags to be left without arguments
-need_version=unknown
-
-case $host_os in
-aix3*)
-  version_type=linux
-  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
-  shlibpath_var=LIBPATH
-
-  # AIX 3 has no versioning support, so we append a major version to the name.
-  soname_spec='${libname}${release}${shared_ext}$major'
-  ;;
-
-aix4* | aix5*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  hardcode_into_libs=yes
-  if test "$host_cpu" = ia64; then
-    # AIX 5 supports IA64
-    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
-    shlibpath_var=LD_LIBRARY_PATH
+    if test "$ld_shlibs_F77" = yes; then
+      runpath_var=LD_RUN_PATH
+      hardcode_libdir_flag_spec_F77='${wl}--rpath ${wl}$libdir'
+      export_dynamic_flag_spec_F77='${wl}--export-dynamic'
+      # ancient GNU ld didn't support --whole-archive et. al.
+      if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
+ 	whole_archive_flag_spec_F77="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+      else
+  	whole_archive_flag_spec_F77=
+      fi
+    fi
   else
-    # With GCC up to 2.95.x, collect2 would create an import file
-    # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
-    # development snapshots of GCC prior to 3.0.
+    # PORTME fill in a description of your system's linker (not GNU ld)
     case $host_os in
-      aix4 | aix4.[01] | aix4.[01].*)
-      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
-	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
-	:
-      else
-	can_build_shared=no
+    aix3*)
+      allow_undefined_flag_F77=unsupported
+      always_export_symbols_F77=yes
+      archive_expsym_cmds_F77='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+      # Note: this linker hardcodes the directories in LIBPATH if there
+      # are no directories specified by -L.
+      hardcode_minus_L_F77=yes
+      if test "$GCC" = yes && test -z "$link_static_flag"; then
+	# Neither direct hardcoding nor static linking is supported with a
+	# broken collect2.
+	hardcode_direct_F77=unsupported
       fi
       ;;
-    esac
-    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
-    # soname into executable. Probably we can add versioning support to
-    # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" = yes; then
-      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
-      # instead of lib<name>.a to let people know that these are not
-      # typical AIX shared libraries.
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
-      # We preserve .a as extension for shared libraries through AIX4.2
-      # and later when we are not doing run time linking.
-      library_names_spec='${libname}${release}.a $libname.a'
-      soname_spec='${libname}${release}${shared_ext}$major'
-    fi
-    shlibpath_var=LIBPATH
-  fi
-  ;;
 
-amigaos*)
-  library_names_spec='$libname.ixlibrary $libname.a'
-  # Create ${libname}_ixlibrary.a entries in /sys/libs.
-  finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
-  ;;
+    aix4* | aix5*)
+      if test "$host_cpu" = ia64; then
+	# On IA64, the linker does run time linking by default, so we don't
+	# have to do anything special.
+	aix_use_runtimelinking=no
+	exp_sym_flag='-Bexport'
+	no_entry_flag=""
+      else
+	# If we're using GNU nm, then we don't want the "-C" option.
+	# -C means demangle to AIX nm, but means don't demangle with GNU nm
+	if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
+	  export_symbols_cmds_F77='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+	else
+	  export_symbols_cmds_F77='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+	fi
+	aix_use_runtimelinking=no
 
-beos*)
-  library_names_spec='${libname}${shared_ext}'
-  dynamic_linker="$host_os ld.so"
-  shlibpath_var=LIBRARY_PATH
-  ;;
+	# Test if we are trying to use run time linking or normal
+	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
+	# need to do runtime linking.
+	case $host_os in aix4.[23]|aix4.[23].*|aix5*)
+	  for ld_flag in $LDFLAGS; do
+  	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+  	    aix_use_runtimelinking=yes
+  	    break
+  	  fi
+	  done
+	esac
 
-bsdi[45]*)
-  version_type=linux
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
-  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
-  # the default ld.so.conf also contains /usr/contrib/lib and
-  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
-  # libtool to hard-code these into programs
-  ;;
+	exp_sym_flag='-bexport'
+	no_entry_flag='-bnoentry'
+      fi
 
-cygwin* | mingw* | pw32*)
-  version_type=windows
-  shrext_cmds=".dll"
-  need_version=no
-  need_lib_prefix=no
+      # When large executables or shared objects are built, AIX ld can
+      # have problems creating the table of contents.  If linking a library
+      # or program results in "error TOC overflow" add -mminimal-toc to
+      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
 
-  case $GCC,$host_os in
-  yes,cygwin* | yes,mingw* | yes,pw32*)
-    library_names_spec='$libname.dll.a'
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
-      dldir=$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
-    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
-      dlpath=$dir/\$dldll~
-       $rm \$dlpath'
-    shlibpath_overrides_runpath=yes
+      archive_cmds_F77=''
+      hardcode_direct_F77=yes
+      hardcode_libdir_separator_F77=':'
+      link_all_deplibs_F77=yes
 
-    case $host_os in
-    cygwin*)
-      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
-      ;;
-    mingw*)
-      # MinGW DLLs use traditional 'lib' prefix
-      soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
-      if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then
-        # It is most probably a Windows format PATH printed by
-        # mingw gcc, but we are running on Cygwin. Gcc prints its search
-        # path with ; separators, and with drive letters. We can handle the
-        # drive letters (cygwin fileutils understands them), so leave them,
-        # especially as we might pass files found there to a mingw objdump,
-        # which wouldn't understand a cygwinified path. Ahh.
-        sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      if test "$GCC" = yes; then
+	case $host_os in aix4.[012]|aix4.[012].*)
+	# We only want to do this on AIX 4.2 and lower, the check
+	# below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" && \
+  	   strings "$collect2name" | grep resolve_lib_name >/dev/null
+	  then
+  	  # We have reworked collect2
+  	  hardcode_direct_F77=yes
+	  else
+  	  # We have old collect2
+  	  hardcode_direct_F77=unsupported
+  	  # It fails to find uninstalled libraries when the uninstalled
+  	  # path is not listed in the libpath.  Setting hardcode_minus_L
+  	  # to unsupported forces relinking
+  	  hardcode_minus_L_F77=yes
+  	  hardcode_libdir_flag_spec_F77='-L$libdir'
+  	  hardcode_libdir_separator_F77=
+	  fi
+	esac
+	shared_flag='-shared'
+	if test "$aix_use_runtimelinking" = yes; then
+	  shared_flag="$shared_flag "'${wl}-G'
+	fi
       else
-        sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
+	# not using gcc
+	if test "$host_cpu" = ia64; then
+  	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+  	# chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+	else
+  	if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag='${wl}-G'
+	  else
+	    shared_flag='${wl}-bM:SRE'
+  	fi
+	fi
       fi
-      ;;
-    pw32*)
-      # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    esac
-    ;;
 
-  *)
-    library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
-    ;;
-  esac
-  dynamic_linker='Win32 ld.exe'
-  # FIXME: first we should search . and the directory the executable is in
-  shlibpath_var=PATH
-  ;;
+      # It seems that -bexpall does not export symbols beginning with
+      # underscore (_), so it is better to generate a list of symbols to export.
+      always_export_symbols_F77=yes
+      if test "$aix_use_runtimelinking" = yes; then
+	# Warning - without using the other runtime loading flags (-brtl),
+	# -berok will link without error, but may produce a broken library.
+	allow_undefined_flag_F77='-berok'
+       # Determine the default libpath from the value encoded in an empty executable.
+       cat >conftest.$ac_ext <<_ACEOF
+      program main
 
-darwin* | rhapsody*)
-  dynamic_linker="$host_os dyld"
-  version_type=darwin
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext'
-  soname_spec='${libname}${release}${major}$shared_ext'
-  shlibpath_overrides_runpath=yes
-  shlibpath_var=DYLD_LIBRARY_PATH
-  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
-  # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
-  if test "$GCC" = yes; then
-    sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
-  else
-    sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib'
-  fi
-  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
-  ;;
+      end
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_f77_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
 
-dgux*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
+}'`; fi
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-freebsd1*)
-  dynamic_linker=no
-  ;;
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
-kfreebsd*-gnu)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='GNU ld.so'
-  ;;
+       hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath"
+	archive_expsym_cmds_F77="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+       else
+	if test "$host_cpu" = ia64; then
+	  hardcode_libdir_flag_spec_F77='${wl}-R $libdir:/usr/lib:/lib'
+	  allow_undefined_flag_F77="-z nodefs"
+	  archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols"
+	else
+	 # Determine the default libpath from the value encoded in an empty executable.
+	 cat >conftest.$ac_ext <<_ACEOF
+      program main
 
-freebsd* | dragonfly*)
-  # DragonFly does not have aout.  When/if they implement a new
-  # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[123]*) objformat=aout ;;
-    *) objformat=elf ;;
-    esac
-  fi
-  version_type=freebsd-$objformat
-  case $version_type in
-    freebsd-elf*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-      need_version=no
-      need_lib_prefix=no
-      ;;
-    freebsd-*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
-      need_version=yes
+      end
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_f77_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
+}'`; fi
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+
+	 hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath"
+	  # Warning - without using the other run time loading flags,
+	  # -berok will link without error, but may produce a broken library.
+	  no_undefined_flag_F77=' ${wl}-bernotok'
+	  allow_undefined_flag_F77=' ${wl}-berok'
+	  # -bexpall does not export symbols beginning with underscore (_)
+	  always_export_symbols_F77=yes
+	  # Exported symbols can be pulled into shared objects from archives
+	  whole_archive_flag_spec_F77=' '
+	  archive_cmds_need_lc_F77=yes
+	  # This is similar to how AIX traditionally builds it's shared libraries.
+	  archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	fi
+      fi
       ;;
-  esac
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_os in
-  freebsd2*)
-    shlibpath_overrides_runpath=yes
-    ;;
-  freebsd3.[01]* | freebsdelf3.[01]*)
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
-  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
-    shlibpath_overrides_runpath=no
-    hardcode_into_libs=yes
-    ;;
-  freebsd*) # from 4.6 on
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  esac
-  ;;
 
-gnu*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  hardcode_into_libs=yes
-  ;;
+    amigaos*)
+      archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+      hardcode_libdir_flag_spec_F77='-L$libdir'
+      hardcode_minus_L_F77=yes
+      # see comment about different semantics on the GNU ld section
+      ld_shlibs_F77=no
+      ;;
 
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuses to
-  # link against other versions.
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  case $host_cpu in
-  ia64*)
-    shrext_cmds='.so'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.so"
-    shlibpath_var=LD_LIBRARY_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" = X32; then
-      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
-    else
-      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-   hppa*64*)
-     shrext_cmds='.sl'
-     hardcode_into_libs=yes
-     dynamic_linker="$host_os dld.sl"
-     shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
-     shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-     library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-     soname_spec='${libname}${release}${shared_ext}$major'
-     sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-     sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-     ;;
-   *)
-    shrext_cmds='.sl'
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=SHLIB_PATH
-    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555.
-  postinstall_cmds='chmod 555 $lib'
-  ;;
+    bsdi[45]*)
+      export_dynamic_flag_spec_F77=-rdynamic
+      ;;
 
-interix3*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
+    cygwin* | mingw* | pw32*)
+      # When not using gcc, we currently assume that we are using
+      # Microsoft Visual C++.
+      # hardcode_libdir_flag_spec is actually meaningless, as there is
+      # no search path for DLLs.
+      hardcode_libdir_flag_spec_F77=' '
+      allow_undefined_flag_F77=unsupported
+      # Tell ltmain to make .lib files, not .a files.
+      libext=lib
+      # Tell ltmain to make .dll files, not .so files.
+      shrext_cmds=".dll"
+      # FIXME: Setting linknames here is a bad hack.
+      archive_cmds_F77='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames='
+      # The linker will automatically build a .lib file if we build a DLL.
+      old_archive_From_new_cmds_F77='true'
+      # FIXME: Should let the user specify the lib program.
+      old_archive_cmds_F77='lib /OUT:$oldlib$oldobjs$old_deplibs'
+      fix_srcfile_path_F77='`cygpath -w "$srcfile"`'
+      enable_shared_with_static_runtimes_F77=yes
+      ;;
 
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=nonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" = yes; then
-		version_type=linux
-	else
-		version_type=irix
-	fi ;;
-  esac
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff= shlibsuff=
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff= shlibsuff= libmagic=32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=32 shlibsuff=N32 libmagic=N32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=64 shlibsuff=64 libmagic=64-bit;;
-    *) libsuff= shlibsuff= libmagic=never-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=no
-  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
-  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=yes
-  ;;
+    darwin* | rhapsody*)
+      case "$host_os" in
+        rhapsody* | darwin1.[012])
+         allow_undefined_flag_F77='${wl}-undefined ${wl}suppress'
+         ;;
+       *) # Darwin 1.3 on
+         if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
+           allow_undefined_flag_F77='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+         else
+           case ${MACOSX_DEPLOYMENT_TARGET} in
+             10.[012])
+               allow_undefined_flag_F77='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+               ;;
+             10.*)
+               allow_undefined_flag_F77='${wl}-undefined ${wl}dynamic_lookup'
+               ;;
+           esac
+         fi
+         ;;
+      esac
+      archive_cmds_need_lc_F77=no
+      hardcode_direct_F77=no
+      hardcode_automatic_F77=yes
+      hardcode_shlibpath_var_F77=unsupported
+      whole_archive_flag_spec_F77=''
+      link_all_deplibs_F77=yes
+    if test "$GCC" = yes ; then
+    	output_verbose_link_cmd='echo'
+        archive_cmds_F77='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+      module_cmds_F77='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+      # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
+      archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+      module_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+    else
+      case "$cc_basename" in
+        xlc*)
+         output_verbose_link_cmd='echo'
+         archive_cmds_F77='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
+         module_cmds_F77='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
+         archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+          module_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+          ;;
+       *)
+         ld_shlibs_F77=no
+          ;;
+      esac
+    fi
+      ;;
 
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=no
-  ;;
+    dgux*)
+      archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_libdir_flag_spec_F77='-L$libdir'
+      hardcode_shlibpath_var_F77=no
+      ;;
 
-# This must be Linux ELF.
-linux*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=yes
+    freebsd1*)
+      ld_shlibs_F77=no
+      ;;
 
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
-    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
-  fi
+    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+    # support.  Future versions do this automatically, but an explicit c++rt0.o
+    # does not break anything, and helps significantly (at the cost of a little
+    # extra space).
+    freebsd2.2*)
+      archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+      hardcode_libdir_flag_spec_F77='-R$libdir'
+      hardcode_direct_F77=yes
+      hardcode_shlibpath_var_F77=no
+      ;;
 
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker='GNU/Linux ld.so'
-  ;;
+    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+    freebsd2*)
+      archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_direct_F77=yes
+      hardcode_minus_L_F77=yes
+      hardcode_shlibpath_var_F77=no
+      ;;
 
-knetbsd*-gnu)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='GNU ld.so'
-  ;;
+    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+    freebsd* | kfreebsd*-gnu | dragonfly*)
+      archive_cmds_F77='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
+      hardcode_libdir_flag_spec_F77='-R$libdir'
+      hardcode_direct_F77=yes
+      hardcode_shlibpath_var_F77=no
+      ;;
 
-netbsd*)
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker='NetBSD (a.out) ld.so'
-  else
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    dynamic_linker='NetBSD ld.elf_so'
-  fi
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  ;;
+    hpux9*)
+      if test "$GCC" = yes; then
+	archive_cmds_F77='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      else
+	archive_cmds_F77='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      fi
+      hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir'
+      hardcode_libdir_separator_F77=:
+      hardcode_direct_F77=yes
 
-newsos6)
-  version_type=linux
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  ;;
+      # hardcode_minus_L: Not really in the search PATH,
+      # but as the default location of the library.
+      hardcode_minus_L_F77=yes
+      export_dynamic_flag_spec_F77='${wl}-E'
+      ;;
 
-nto-qnx*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  ;;
+    hpux10* | hpux11*)
+      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+	case "$host_cpu" in
+	hppa*64*|ia64*)
+	  archive_cmds_F77='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  archive_cmds_F77='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	esac
+      else
+	case "$host_cpu" in
+	hppa*64*|ia64*)
+	  archive_cmds_F77='$LD -b +h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  ;;
+	*)
+	  archive_cmds_F77='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+	  ;;
+	esac
+      fi
+      if test "$with_gnu_ld" = no; then
+	case "$host_cpu" in
+	hppa*64*)
+	  hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir'
+	  hardcode_libdir_flag_spec_ld_F77='+b $libdir'
+	  hardcode_libdir_separator_F77=:
+	  hardcode_direct_F77=no
+	  hardcode_shlibpath_var_F77=no
+	  ;;
+	ia64*)
+	  hardcode_libdir_flag_spec_F77='-L$libdir'
+	  hardcode_direct_F77=no
+	  hardcode_shlibpath_var_F77=no
 
-openbsd*)
-  version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
-  need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=yes ;;
-    *)                         need_version=no  ;;
-  esac
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[89] | openbsd2.[89].*)
-	shlibpath_overrides_runpath=no
-	;;
-      *)
-	shlibpath_overrides_runpath=yes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=yes
-  fi
-  ;;
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  hardcode_minus_L_F77=yes
+	  ;;
+	*)
+	  hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir'
+	  hardcode_libdir_separator_F77=:
+	  hardcode_direct_F77=yes
+	  export_dynamic_flag_spec_F77='${wl}-E'
 
-os2*)
-  libname_spec='$name'
-  shrext_cmds=".dll"
-  need_lib_prefix=no
-  library_names_spec='$libname${shared_ext} $libname.a'
-  dynamic_linker='OS/2 ld.exe'
-  shlibpath_var=LIBPATH
-  ;;
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  hardcode_minus_L_F77=yes
+	  ;;
+	esac
+      fi
+      ;;
 
-osf3* | osf4* | osf5*)
-  version_type=osf
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
-  ;;
+    irix5* | irix6* | nonstopux*)
+      if test "$GCC" = yes; then
+	archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      else
+	archive_cmds_F77='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+	hardcode_libdir_flag_spec_ld_F77='-rpath $libdir'
+      fi
+      hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_separator_F77=:
+      link_all_deplibs_F77=yes
+      ;;
 
-solaris*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  # ldd complains unless libraries are executable
-  postinstall_cmds='chmod +x $lib'
-  ;;
+    netbsd*)
+      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+	archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
+      else
+	archive_cmds_F77='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
+      fi
+      hardcode_libdir_flag_spec_F77='-R$libdir'
+      hardcode_direct_F77=yes
+      hardcode_shlibpath_var_F77=no
+      ;;
 
-sunos4*)
-  version_type=sunos
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  if test "$with_gnu_ld" = yes; then
-    need_lib_prefix=no
-  fi
-  need_version=yes
-  ;;
+    newsos6)
+      archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_direct_F77=yes
+      hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_separator_F77=:
+      hardcode_shlibpath_var_F77=no
+      ;;
 
-sysv4 | sysv4.3*)
-  version_type=linux
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=no
-      need_lib_prefix=no
-      export_dynamic_flag_spec='${wl}-Blargedynsym'
-      runpath_var=LD_RUN_PATH
+    openbsd*)
+      hardcode_direct_F77=yes
+      hardcode_shlibpath_var_F77=no
+      if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+	hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir'
+	export_dynamic_flag_spec_F77='${wl}-E'
+      else
+       case $host_os in
+	 openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
+	   archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+	   hardcode_libdir_flag_spec_F77='-R$libdir'
+	   ;;
+	 *)
+	   archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	   hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir'
+	   ;;
+       esac
+      fi
       ;;
-    siemens)
-      need_lib_prefix=no
+
+    os2*)
+      hardcode_libdir_flag_spec_F77='-L$libdir'
+      hardcode_minus_L_F77=yes
+      allow_undefined_flag_F77=unsupported
+      archive_cmds_F77='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+      old_archive_From_new_cmds_F77='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
       ;;
-    motorola)
-      need_lib_prefix=no
-      need_version=no
-      shlibpath_overrides_runpath=no
-      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+
+    osf3*)
+      if test "$GCC" = yes; then
+	allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*'
+	archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      else
+	allow_undefined_flag_F77=' -expect_unresolved \*'
+	archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+      fi
+      hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_separator_F77=:
       ;;
-  esac
-  ;;
 
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=linux
-    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
-    soname_spec='$libname${shared_ext}.$major'
-    shlibpath_var=LD_LIBRARY_PATH
-  fi
-  ;;
+    osf4* | osf5*)	# as osf3* with the addition of -msym flag
+      if test "$GCC" = yes; then
+	allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*'
+	archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
+      else
+	allow_undefined_flag_F77=' -expect_unresolved \*'
+	archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+	archive_expsym_cmds_F77='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
+	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib~$rm $lib.exp'
 
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-    shlibpath_overrides_runpath=no
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=yes
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
+	# Both c and cxx compiler support -rpath directly
+	hardcode_libdir_flag_spec_F77='-rpath $libdir'
+      fi
+      hardcode_libdir_separator_F77=:
+      ;;
 
-uts4*)
-  version_type=linux
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
+    sco3.2v5*)
+      archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_shlibpath_var_F77=no
+      export_dynamic_flag_spec_F77='${wl}-Bexport'
+      runpath_var=LD_RUN_PATH
+      hardcode_runpath_var=yes
+      ;;
 
-*)
-  dynamic_linker=no
-  ;;
-esac
-echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6
-test "$dynamic_linker" = no && can_build_shared=no
+    solaris*)
+      no_undefined_flag_F77=' -z text'
+      if test "$GCC" = yes; then
+	archive_cmds_F77='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+	  $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
+      else
+	archive_cmds_F77='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+  	$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+      fi
+      hardcode_libdir_flag_spec_F77='-R$libdir'
+      hardcode_shlibpath_var_F77=no
+      case $host_os in
+      solaris2.[0-5] | solaris2.[0-5].*) ;;
+      *) # Supported since Solaris 2.6 (maybe 2.5.1?)
+	whole_archive_flag_spec_F77='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;;
+      esac
+      link_all_deplibs_F77=yes
+      ;;
 
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
-fi
+    sunos4*)
+      if test "x$host_vendor" = xsequent; then
+	# Use $CC to link under sequent, because it throws in some extra .o
+	# files that make .init and .fini sections work.
+	archive_cmds_F77='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	archive_cmds_F77='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      hardcode_libdir_flag_spec_F77='-L$libdir'
+      hardcode_direct_F77=yes
+      hardcode_minus_L_F77=yes
+      hardcode_shlibpath_var_F77=no
+      ;;
 
-echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
-hardcode_action_F77=
-if test -n "$hardcode_libdir_flag_spec_F77" || \
-   test -n "$runpath_var_F77" || \
-   test "X$hardcode_automatic_F77" = "Xyes" ; then
+    sysv4)
+      case $host_vendor in
+	sni)
+	  archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  hardcode_direct_F77=yes # is this really true???
+	;;
+	siemens)
+	  ## LD is ld it makes a PLAMLIB
+	  ## CC just makes a GrossModule.
+	  archive_cmds_F77='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+	  reload_cmds_F77='$CC -r -o $output$reload_objs'
+	  hardcode_direct_F77=no
+        ;;
+	motorola)
+	  archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  hardcode_direct_F77=no #Motorola manual says yes, but my tests say they lie
+	;;
+      esac
+      runpath_var='LD_RUN_PATH'
+      hardcode_shlibpath_var_F77=no
+      ;;
 
-  # We can hardcode non-existant directories.
-  if test "$hardcode_direct_F77" != no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, F77)" != no &&
-     test "$hardcode_minus_L_F77" != no; then
-    # Linking always hardcodes the temporary library directory.
-    hardcode_action_F77=relink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    hardcode_action_F77=immediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  hardcode_action_F77=unsupported
-fi
-echo "$as_me:$LINENO: result: $hardcode_action_F77" >&5
-echo "${ECHO_T}$hardcode_action_F77" >&6
+    sysv4.3*)
+      archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_shlibpath_var_F77=no
+      export_dynamic_flag_spec_F77='-Bexport'
+      ;;
 
-if test "$hardcode_action_F77" = relink; then
-  # Fast installation is not supported
-  enable_fast_install=no
-elif test "$shlibpath_overrides_runpath" = yes ||
-     test "$enable_shared" = no; then
-  # Fast installation is not necessary
-  enable_fast_install=needless
-fi
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	hardcode_shlibpath_var_F77=no
+	runpath_var=LD_RUN_PATH
+	hardcode_runpath_var=yes
+	ld_shlibs_F77=yes
+      fi
+      ;;
 
+    sysv4.2uw2*)
+      archive_cmds_F77='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_direct_F77=yes
+      hardcode_minus_L_F77=no
+      hardcode_shlibpath_var_F77=no
+      hardcode_runpath_var=yes
+      runpath_var=LD_RUN_PATH
+      ;;
 
-# The else clause should only fire when bootstrapping the
-# libtool distribution, otherwise you forgot to ship ltmain.sh
-# with your package, and you will get complaints that there are
-# no rules to generate ltmain.sh.
-if test -f "$ltmain"; then
-  # See if we are running on zsh, and set the options which allow our commands through
-  # without removal of \ escapes.
-  if test -n "${ZSH_VERSION+set}" ; then
-    setopt NO_GLOB_SUBST
-  fi
-  # Now quote all the things that may contain metacharacters while being
-  # careful not to overquote the AC_SUBSTed values.  We take copies of the
-  # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
-    SED SHELL STRIP \
-    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
-    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
-    deplibs_check_method reload_flag reload_cmds need_locks \
-    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
-    lt_cv_sys_global_symbol_to_c_name_address \
-    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
-    old_postinstall_cmds old_postuninstall_cmds \
-    compiler_F77 \
-    CC_F77 \
-    LD_F77 \
-    lt_prog_compiler_wl_F77 \
-    lt_prog_compiler_pic_F77 \
-    lt_prog_compiler_static_F77 \
-    lt_prog_compiler_no_builtin_flag_F77 \
-    export_dynamic_flag_spec_F77 \
-    thread_safe_flag_spec_F77 \
-    whole_archive_flag_spec_F77 \
-    enable_shared_with_static_runtimes_F77 \
-    old_archive_cmds_F77 \
-    old_archive_from_new_cmds_F77 \
-    predep_objects_F77 \
-    postdep_objects_F77 \
-    predeps_F77 \
-    postdeps_F77 \
-    compiler_lib_search_path_F77 \
-    archive_cmds_F77 \
-    archive_expsym_cmds_F77 \
-    postinstall_cmds_F77 \
-    postuninstall_cmds_F77 \
-    old_archive_from_expsyms_cmds_F77 \
-    allow_undefined_flag_F77 \
-    no_undefined_flag_F77 \
-    export_symbols_cmds_F77 \
-    hardcode_libdir_flag_spec_F77 \
-    hardcode_libdir_flag_spec_ld_F77 \
-    hardcode_libdir_separator_F77 \
-    hardcode_automatic_F77 \
-    module_cmds_F77 \
-    module_expsym_cmds_F77 \
-    lt_cv_prog_compiler_c_o_F77 \
-    exclude_expsyms_F77 \
-    include_expsyms_F77; do
+   sysv5OpenUNIX8* | sysv5UnixWare7* |  sysv5uw[78]* | unixware7*)
+      no_undefined_flag_F77='${wl}-z ${wl}text'
+      if test "$GCC" = yes; then
+	archive_cmds_F77='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	archive_cmds_F77='$CC -G ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      runpath_var='LD_RUN_PATH'
+      hardcode_shlibpath_var_F77=no
+      ;;
 
-    case $var in
-    old_archive_cmds_F77 | \
-    old_archive_from_new_cmds_F77 | \
-    archive_cmds_F77 | \
-    archive_expsym_cmds_F77 | \
-    module_cmds_F77 | \
-    module_expsym_cmds_F77 | \
-    old_archive_from_expsyms_cmds_F77 | \
-    export_symbols_cmds_F77 | \
-    extract_expsyms_cmds | reload_cmds | finish_cmds | \
-    postinstall_cmds | postuninstall_cmds | \
-    old_postinstall_cmds | old_postuninstall_cmds | \
-    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
-      # Double-quote double-evaled strings.
-      eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+    sysv5*)
+      no_undefined_flag_F77=' -z text'
+      # $CC -shared without GNU ld will not create a library from C++
+      # object files and a static libstdc++, better avoid it by now
+      archive_cmds_F77='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+  		$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+      hardcode_libdir_flag_spec_F77=
+      hardcode_shlibpath_var_F77=no
+      runpath_var='LD_RUN_PATH'
+      ;;
+
+    uts4*)
+      archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_libdir_flag_spec_F77='-L$libdir'
+      hardcode_shlibpath_var_F77=no
       ;;
+
     *)
-      eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+      ld_shlibs_F77=no
       ;;
     esac
-  done
-
-  case $lt_echo in
-  *'\$0 --fallback-echo"')
-    lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'`
-    ;;
-  esac
+  fi
 
-cfgfile="$ofile"
+echo "$as_me:$LINENO: result: $ld_shlibs_F77" >&5
+echo "${ECHO_T}$ld_shlibs_F77" >&6
+test "$ld_shlibs_F77" = no && can_build_shared=no
 
-  cat <<__EOF__ >> "$cfgfile"
-# ### BEGIN LIBTOOL TAG CONFIG: $tagname
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
 
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+#
+# Do we need to explicitly link libc?
+#
+case "x$archive_cmds_need_lc_F77" in
+x|xyes)
+  # Assume -lc should be added
+  archive_cmds_need_lc_F77=yes
 
-# Shell to use when invoking shell scripts.
-SHELL=$lt_SHELL
+  if test "$enable_shared" = yes && test "$GCC" = yes; then
+    case $archive_cmds_F77 in
+    *'~'*)
+      # FIXME: we may have to deal with multi-command sequences.
+      ;;
+    '$CC '*)
+      # Test whether the compiler implicitly links with -lc since on some
+      # systems, -lgcc has to come before -lc. If gcc already passes -lc
+      # to ld, don't add -lc before -lgcc.
+      echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
+echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
+      $rm conftest*
+      printf "$lt_simple_compile_test_code" > conftest.$ac_ext
 
-# Whether or not to build shared libraries.
-build_libtool_libs=$enable_shared
+      if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } 2>conftest.err; then
+        soname=conftest
+        lib=conftest
+        libobjs=conftest.$ac_objext
+        deplibs=
+        wl=$lt_prog_compiler_wl_F77
+        compiler_flags=-v
+        linker_flags=-v
+        verstring=
+        output_objdir=.
+        libname=conftest
+        lt_save_allow_undefined_flag=$allow_undefined_flag_F77
+        allow_undefined_flag_F77=
+        if { (eval echo "$as_me:$LINENO: \"$archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5
+  (eval $archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+        then
+	  archive_cmds_need_lc_F77=no
+        else
+	  archive_cmds_need_lc_F77=yes
+        fi
+        allow_undefined_flag_F77=$lt_save_allow_undefined_flag
+      else
+        cat conftest.err 1>&5
+      fi
+      $rm conftest*
+      echo "$as_me:$LINENO: result: $archive_cmds_need_lc_F77" >&5
+echo "${ECHO_T}$archive_cmds_need_lc_F77" >&6
+      ;;
+    esac
+  fi
+  ;;
+esac
 
-# Whether or not to build static libraries.
-build_old_libs=$enable_static
+echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+if test "$GCC" = yes; then
+  sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+  if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
+    # if the path contains ";" then we assume it to be the separator
+    # otherwise default to the standard path separator (i.e. ":") - it is
+    # assumed that no part of a normal pathname contains ";" but that should
+    # okay in the real world where ";" in dirpaths is itself problematic.
+    sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+  else
+    sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
+  fi
+else
+  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi
+need_lib_prefix=unknown
+hardcode_into_libs=no
 
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=$archive_cmds_need_lc_F77
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
 
-# Whether or not to disallow shared libs when runtime libs are static
-allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_F77
+case $host_os in
+aix3*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  shlibpath_var=LIBPATH
 
-# Whether or not to optimize for fast installation.
-fast_install=$enable_fast_install
+  # AIX 3 has no versioning support, so we append a major version to the name.
+  soname_spec='${libname}${release}${shared_ext}$major'
+  ;;
 
-# The host system.
-host_alias=$host_alias
-host=$host
-host_os=$host_os
-
-# The build system.
-build_alias=$build_alias
-build=$build
-build_os=$build_os
-
-# An echo program that does not interpret backslashes.
-echo=$lt_echo
-
-# The archiver.
-AR=$lt_AR
-AR_FLAGS=$lt_AR_FLAGS
-
-# A C compiler.
-LTCC=$lt_LTCC
-
-# LTCC compiler flags.
-LTCFLAGS=$lt_LTCFLAGS
-
-# A language-specific compiler.
-CC=$lt_compiler_F77
-
-# Is the compiler the GNU C compiler?
-with_gcc=$GCC_F77
-
-# An ERE matcher.
-EGREP=$lt_EGREP
-
-# The linker used to build libraries.
-LD=$lt_LD_F77
+aix4* | aix5*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  hardcode_into_libs=yes
+  if test "$host_cpu" = ia64; then
+    # AIX 5 supports IA64
+    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    shlibpath_var=LD_LIBRARY_PATH
+  else
+    # With GCC up to 2.95.x, collect2 would create an import file
+    # for dependence libraries.  The import file would start with
+    # the line `#! .'.  This would cause the generated library to
+    # depend on `.', always an invalid library.  This was fixed in
+    # development snapshots of GCC prior to 3.0.
+    case $host_os in
+      aix4 | aix4.[01] | aix4.[01].*)
+      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+	   echo ' yes '
+	   echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
+	:
+      else
+	can_build_shared=no
+      fi
+      ;;
+    esac
+    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # soname into executable. Probably we can add versioning support to
+    # collect2, so additional links can be useful in future.
+    if test "$aix_use_runtimelinking" = yes; then
+      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+      # instead of lib<name>.a to let people know that these are not
+      # typical AIX shared libraries.
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    else
+      # We preserve .a as extension for shared libraries through AIX4.2
+      # and later when we are not doing run time linking.
+      library_names_spec='${libname}${release}.a $libname.a'
+      soname_spec='${libname}${release}${shared_ext}$major'
+    fi
+    shlibpath_var=LIBPATH
+  fi
+  ;;
 
-# Whether we need hard or soft links.
-LN_S=$lt_LN_S
+amigaos*)
+  library_names_spec='$libname.ixlibrary $libname.a'
+  # Create ${libname}_ixlibrary.a entries in /sys/libs.
+  finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+  ;;
 
-# A BSD-compatible nm program.
-NM=$lt_NM
+beos*)
+  library_names_spec='${libname}${shared_ext}'
+  dynamic_linker="$host_os ld.so"
+  shlibpath_var=LIBRARY_PATH
+  ;;
 
-# A symbol stripping program
-STRIP=$lt_STRIP
+bsdi[45]*)
+  version_type=linux
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+  # the default ld.so.conf also contains /usr/contrib/lib and
+  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+  # libtool to hard-code these into programs
+  ;;
 
-# Used to examine libraries when file_magic_cmd begins "file"
-MAGIC_CMD=$MAGIC_CMD
+cygwin* | mingw* | pw32*)
+  version_type=windows
+  shrext_cmds=".dll"
+  need_version=no
+  need_lib_prefix=no
 
-# Used on cygwin: DLL creation program.
-DLLTOOL="$DLLTOOL"
+  case $GCC,$host_os in
+  yes,cygwin* | yes,mingw* | yes,pw32*)
+    library_names_spec='$libname.dll.a'
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $rm \$dlpath'
+    shlibpath_overrides_runpath=yes
 
-# Used on cygwin: object dumper.
-OBJDUMP="$OBJDUMP"
+    case $host_os in
+    cygwin*)
+      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+      ;;
+    mingw*)
+      # MinGW DLLs use traditional 'lib' prefix
+      soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+      if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then
+        # It is most probably a Windows format PATH printed by
+        # mingw gcc, but we are running on Cygwin. Gcc prints its search
+        # path with ; separators, and with drive letters. We can handle the
+        # drive letters (cygwin fileutils understands them), so leave them,
+        # especially as we might pass files found there to a mingw objdump,
+        # which wouldn't understand a cygwinified path. Ahh.
+        sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      ;;
+    pw32*)
+      # pw32 DLLs use 'pw' prefix rather than 'lib'
+      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    esac
+    ;;
 
-# Used on cygwin: assembler.
-AS="$AS"
+  *)
+    library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    ;;
+  esac
+  dynamic_linker='Win32 ld.exe'
+  # FIXME: first we should search . and the directory the executable is in
+  shlibpath_var=PATH
+  ;;
 
-# The name of the directory that contains temporary libtool files.
-objdir=$objdir
+darwin* | rhapsody*)
+  dynamic_linker="$host_os dyld"
+  version_type=darwin
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+  soname_spec='${libname}${release}${major}$shared_ext'
+  shlibpath_overrides_runpath=yes
+  shlibpath_var=DYLD_LIBRARY_PATH
+  shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)'
+  # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
+  if test "$GCC" = yes; then
+    sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
+  else
+    sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib'
+  fi
+  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+  ;;
 
-# How to create reloadable object files.
-reload_flag=$lt_reload_flag
-reload_cmds=$lt_reload_cmds
+dgux*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
 
-# How to pass a linker flag through the compiler.
-wl=$lt_lt_prog_compiler_wl_F77
+freebsd1*)
+  dynamic_linker=no
+  ;;
 
-# Object file suffix (normally "o").
-objext="$ac_objext"
+kfreebsd*-gnu)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='GNU ld.so'
+  ;;
 
-# Old archive suffix (normally "a").
-libext="$libext"
+freebsd* | dragonfly*)
+  # DragonFly does not have aout.  When/if they implement a new
+  # versioning mechanism, adjust this.
+  objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout`
+  version_type=freebsd-$objformat
+  case $version_type in
+    freebsd-elf*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      need_version=no
+      need_lib_prefix=no
+      ;;
+    freebsd-*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      need_version=yes
+      ;;
+  esac
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_os in
+  freebsd2*)
+    shlibpath_overrides_runpath=yes
+    ;;
+  freebsd3.[01]* | freebsdelf3.[01]*)
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  *) # from 3.2 on
+    shlibpath_overrides_runpath=no
+    hardcode_into_libs=yes
+    ;;
+  esac
+  ;;
 
-# Shared library suffix (normally ".so").
-shrext_cmds='$shrext_cmds'
+gnu*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  hardcode_into_libs=yes
+  ;;
 
-# Executable file suffix (normally "").
-exeext="$exeext"
-
-# Additional compiler flags for building library objects.
-pic_flag=$lt_lt_prog_compiler_pic_F77
-pic_mode=$pic_mode
+hpux9* | hpux10* | hpux11*)
+  # Give a soname corresponding to the major version so that dld.sl refuses to
+  # link against other versions.
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  case "$host_cpu" in
+  ia64*)
+    shrext_cmds='.so'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.so"
+    shlibpath_var=LD_LIBRARY_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    if test "X$HPUX_IA64_MODE" = X32; then
+      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+    else
+      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+    fi
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+   hppa*64*)
+     shrext_cmds='.sl'
+     hardcode_into_libs=yes
+     dynamic_linker="$host_os dld.sl"
+     shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+     shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+     library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+     soname_spec='${libname}${release}${shared_ext}$major'
+     sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+     sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+     ;;
+   *)
+    shrext_cmds='.sl'
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=SHLIB_PATH
+    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    ;;
+  esac
+  # HP-UX runs *really* slowly unless shared libraries are mode 555.
+  postinstall_cmds='chmod 555 $lib'
+  ;;
 
-# What is the maximum length of a command?
-max_cmd_len=$lt_cv_sys_max_cmd_len
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+	if test "$lt_cv_prog_gnu_ld" = yes; then
+		version_type=linux
+	else
+		version_type=irix
+	fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
 
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=$lt_lt_cv_prog_compiler_c_o_F77
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
 
-# Must we lock files when doing compilation?
-need_locks=$lt_need_locks
+# This must be Linux ELF.
+linux*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
 
-# Do we need the lib prefix for modules?
-need_lib_prefix=$need_lib_prefix
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,\t]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+  fi
 
-# Do we need a version for libraries?
-need_version=$need_version
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
 
-# Whether dlopen is supported.
-dlopen_support=$enable_dlopen
+knetbsd*-gnu)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='GNU ld.so'
+  ;;
 
-# Whether dlopen of programs is supported.
-dlopen_self=$enable_dlopen_self
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
 
-# Whether dlopen of statically linked programs is supported.
-dlopen_self_static=$enable_dlopen_self_static
+newsos6)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
 
-# Compiler flag to prevent dynamic linking.
-link_static_flag=$lt_lt_prog_compiler_static_F77
+nto-qnx*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
 
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_F77
+openbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[89] | openbsd2.[89].*)
+	shlibpath_overrides_runpath=no
+	;;
+      *)
+	shlibpath_overrides_runpath=yes
+	;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
 
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_F77
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
 
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=$lt_whole_archive_flag_spec_F77
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
 
-# Compiler flag to generate thread-safe objects.
-thread_safe_flag_spec=$lt_thread_safe_flag_spec_F77
+sco3.2v5*)
+  version_type=osf
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
 
-# Library versioning type.
-version_type=$version_type
+solaris*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
 
-# Format of library name prefix.
-libname_spec=$lt_libname_spec
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
 
-# List of archive names.  First name is the real one, the rest are links.
-# The last name is the one that the linker finds with -lNAME.
-library_names_spec=$lt_library_names_spec
+sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      export_dynamic_flag_spec='${wl}-Blargedynsym'
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
 
-# The coded name of the library, if different from the real name.
-soname_spec=$lt_soname_spec
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
 
-# Commands used to build and install an old-style archive.
-RANLIB=$lt_RANLIB
-old_archive_cmds=$lt_old_archive_cmds_F77
-old_postinstall_cmds=$lt_old_postinstall_cmds
-old_postuninstall_cmds=$lt_old_postuninstall_cmds
+uts4*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
 
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_F77
+*)
+  dynamic_linker=no
+  ;;
+esac
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
+test "$dynamic_linker" = no && can_build_shared=no
 
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_F77
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
+hardcode_action_F77=
+if test -n "$hardcode_libdir_flag_spec_F77" || \
+   test -n "$runpath_var_F77" || \
+   test "X$hardcode_automatic_F77" = "Xyes" ; then
 
-# Commands used to build and install a shared archive.
-archive_cmds=$lt_archive_cmds_F77
-archive_expsym_cmds=$lt_archive_expsym_cmds_F77
-postinstall_cmds=$lt_postinstall_cmds
-postuninstall_cmds=$lt_postuninstall_cmds
+  # We can hardcode non-existant directories.
+  if test "$hardcode_direct_F77" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, F77)" != no &&
+     test "$hardcode_minus_L_F77" != no; then
+    # Linking always hardcodes the temporary library directory.
+    hardcode_action_F77=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    hardcode_action_F77=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  hardcode_action_F77=unsupported
+fi
+echo "$as_me:$LINENO: result: $hardcode_action_F77" >&5
+echo "${ECHO_T}$hardcode_action_F77" >&6
 
-# Commands used to build a loadable module (assumed same as above if empty)
-module_cmds=$lt_module_cmds_F77
-module_expsym_cmds=$lt_module_expsym_cmds_F77
+if test "$hardcode_action_F77" = relink; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
 
-# Commands to strip libraries.
-old_striplib=$lt_old_striplib
-striplib=$lt_striplib
+striplib=
+old_striplib=
+echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5
+echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6
+if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+   darwin*)
+       if test -n "$STRIP" ; then
+         striplib="$STRIP -x"
+         echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+       else
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+       ;;
+   *)
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+    ;;
+  esac
+fi
 
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predep_objects=$lt_predep_objects_F77
 
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdep_objects=$lt_postdep_objects_F77
 
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predeps=$lt_predeps_F77
+# The else clause should only fire when bootstrapping the
+# libtool distribution, otherwise you forgot to ship ltmain.sh
+# with your package, and you will get complaints that there are
+# no rules to generate ltmain.sh.
+if test -f "$ltmain"; then
+  # See if we are running on zsh, and set the options which allow our commands through
+  # without removal of \ escapes.
+  if test -n "${ZSH_VERSION+set}" ; then
+    setopt NO_GLOB_SUBST
+  fi
+  # Now quote all the things that may contain metacharacters while being
+  # careful not to overquote the AC_SUBSTed values.  We take copies of the
+  # variables and quote the copies for generation of the libtool script.
+  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \
+    SED SHELL STRIP \
+    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
+    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
+    deplibs_check_method reload_flag reload_cmds need_locks \
+    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
+    lt_cv_sys_global_symbol_to_c_name_address \
+    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
+    old_postinstall_cmds old_postuninstall_cmds \
+    compiler_F77 \
+    CC_F77 \
+    LD_F77 \
+    lt_prog_compiler_wl_F77 \
+    lt_prog_compiler_pic_F77 \
+    lt_prog_compiler_static_F77 \
+    lt_prog_compiler_no_builtin_flag_F77 \
+    export_dynamic_flag_spec_F77 \
+    thread_safe_flag_spec_F77 \
+    whole_archive_flag_spec_F77 \
+    enable_shared_with_static_runtimes_F77 \
+    old_archive_cmds_F77 \
+    old_archive_from_new_cmds_F77 \
+    predep_objects_F77 \
+    postdep_objects_F77 \
+    predeps_F77 \
+    postdeps_F77 \
+    compiler_lib_search_path_F77 \
+    archive_cmds_F77 \
+    archive_expsym_cmds_F77 \
+    postinstall_cmds_F77 \
+    postuninstall_cmds_F77 \
+    old_archive_from_expsyms_cmds_F77 \
+    allow_undefined_flag_F77 \
+    no_undefined_flag_F77 \
+    export_symbols_cmds_F77 \
+    hardcode_libdir_flag_spec_F77 \
+    hardcode_libdir_flag_spec_ld_F77 \
+    hardcode_libdir_separator_F77 \
+    hardcode_automatic_F77 \
+    module_cmds_F77 \
+    module_expsym_cmds_F77 \
+    lt_cv_prog_compiler_c_o_F77 \
+    exclude_expsyms_F77 \
+    include_expsyms_F77; do
 
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdeps=$lt_postdeps_F77
+    case $var in
+    old_archive_cmds_F77 | \
+    old_archive_from_new_cmds_F77 | \
+    archive_cmds_F77 | \
+    archive_expsym_cmds_F77 | \
+    module_cmds_F77 | \
+    module_expsym_cmds_F77 | \
+    old_archive_from_expsyms_cmds_F77 | \
+    export_symbols_cmds_F77 | \
+    extract_expsyms_cmds | reload_cmds | finish_cmds | \
+    postinstall_cmds | postuninstall_cmds | \
+    old_postinstall_cmds | old_postuninstall_cmds | \
+    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
+      # Double-quote double-evaled strings.
+      eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+      ;;
+    *)
+      eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+      ;;
+    esac
+  done
 
-# The library search path used internally by the compiler when linking
-# a shared library.
-compiler_lib_search_path=$lt_compiler_lib_search_path_F77
+  case $lt_echo in
+  *'\$0 --fallback-echo"')
+    lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'`
+    ;;
+  esac
 
-# Method to check whether dependent libraries are shared objects.
-deplibs_check_method=$lt_deplibs_check_method
+cfgfile="$ofile"
 
-# Command to use when deplibs_check_method == file_magic.
-file_magic_cmd=$lt_file_magic_cmd
+  cat <<__EOF__ >> "$cfgfile"
+# ### BEGIN LIBTOOL TAG CONFIG: $tagname
 
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=$lt_allow_undefined_flag_F77
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
 
-# Flag that forces no undefined symbols.
-no_undefined_flag=$lt_no_undefined_flag_F77
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
 
-# Commands used to finish a libtool library installation in a directory.
-finish_cmds=$lt_finish_cmds
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
 
-# Same as above, but a single script fragment to be evaled but not shown.
-finish_eval=$lt_finish_eval
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
 
-# Take the output of nm and produce a listing of raw symbols and C names.
-global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$archive_cmds_need_lc_F77
 
-# Transform the output of nm in a proper C declaration
-global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+# Whether or not to disallow shared libs when runtime libs are static
+allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_F77
 
-# Transform the output of nm in a C name address pair
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
+
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
+
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
+
+# An echo program that does not interpret backslashes.
+echo=$lt_echo
+
+# The archiver.
+AR=$lt_AR
+AR_FLAGS=$lt_AR_FLAGS
+
+# A C compiler.
+LTCC=$lt_LTCC
+
+# A language-specific compiler.
+CC=$lt_compiler_F77
+
+# Is the compiler the GNU C compiler?
+with_gcc=$GCC_F77
+
+# An ERE matcher.
+EGREP=$lt_EGREP
+
+# The linker used to build libraries.
+LD=$lt_LD_F77
+
+# Whether we need hard or soft links.
+LN_S=$lt_LN_S
+
+# A BSD-compatible nm program.
+NM=$lt_NM
+
+# A symbol stripping program
+STRIP=$lt_STRIP
+
+# Used to examine libraries when file_magic_cmd begins "file"
+MAGIC_CMD=$MAGIC_CMD
+
+# Used on cygwin: DLL creation program.
+DLLTOOL="$DLLTOOL"
+
+# Used on cygwin: object dumper.
+OBJDUMP="$OBJDUMP"
+
+# Used on cygwin: assembler.
+AS="$AS"
+
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
+
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
+
+# How to pass a linker flag through the compiler.
+wl=$lt_lt_prog_compiler_wl_F77
+
+# Object file suffix (normally "o").
+objext="$ac_objext"
+
+# Old archive suffix (normally "a").
+libext="$libext"
+
+# Shared library suffix (normally ".so").
+shrext_cmds='$shrext_cmds'
+
+# Executable file suffix (normally "").
+exeext="$exeext"
+
+# Additional compiler flags for building library objects.
+pic_flag=$lt_lt_prog_compiler_pic_F77
+pic_mode=$pic_mode
+
+# What is the maximum length of a command?
+max_cmd_len=$lt_cv_sys_max_cmd_len
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_lt_cv_prog_compiler_c_o_F77
+
+# Must we lock files when doing compilation ?
+need_locks=$lt_need_locks
+
+# Do we need the lib prefix for modules?
+need_lib_prefix=$need_lib_prefix
+
+# Do we need a version for libraries?
+need_version=$need_version
+
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
+
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
+
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_lt_prog_compiler_static_F77
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_F77
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_F77
+
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_whole_archive_flag_spec_F77
+
+# Compiler flag to generate thread-safe objects.
+thread_safe_flag_spec=$lt_thread_safe_flag_spec_F77
+
+# Library versioning type.
+version_type=$version_type
+
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
+
+# List of archive names.  First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec=$lt_library_names_spec
+
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
+
+# Commands used to build and install an old-style archive.
+RANLIB=$lt_RANLIB
+old_archive_cmds=$lt_old_archive_cmds_F77
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_F77
+
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_F77
+
+# Commands used to build and install a shared archive.
+archive_cmds=$lt_archive_cmds_F77
+archive_expsym_cmds=$lt_archive_expsym_cmds_F77
+postinstall_cmds=$lt_postinstall_cmds
+postuninstall_cmds=$lt_postuninstall_cmds
+
+# Commands used to build a loadable module (assumed same as above if empty)
+module_cmds=$lt_module_cmds_F77
+module_expsym_cmds=$lt_module_expsym_cmds_F77
+
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predep_objects=$lt_predep_objects_F77
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdep_objects=$lt_postdep_objects_F77
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predeps=$lt_predeps_F77
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdeps=$lt_postdeps_F77
+
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=$lt_compiler_lib_search_path_F77
+
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
+
+# Command to use when deplibs_check_method == file_magic.
+file_magic_cmd=$lt_file_magic_cmd
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_allow_undefined_flag_F77
+
+# Flag that forces no undefined symbols.
+no_undefined_flag=$lt_no_undefined_flag_F77
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
+
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval=$lt_finish_eval
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+
+# Transform the output of nm in a proper C declaration
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+
+# Transform the output of nm in a C name address pair
 global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
 
 # This is the shared library runtime path variable.
@@ -15575,48 +15763,19 @@
 # If no C compiler was specified, use CC.
 LTCC=${LTCC-"$CC"}
 
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
 # Allow CC to be a program name with arguments.
 compiler=$CC
 
 
-# save warnings/boilerplate of simple test code
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$rm conftest*
-
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$rm conftest*
-
-
 # Allow CC to be a program name with arguments.
 lt_save_CC="$CC"
 CC=${GCJ-"gcj"}
 compiler=$CC
 compiler_GCJ=$CC
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
-
 
 # GCJ did not exist at the time GCC didn't implicitly link libc in.
 archive_cmds_need_lc_GCJ=no
 
-old_archive_cmds_GCJ=$old_archive_cmds
-
 
 lt_prog_compiler_no_builtin_flag_GCJ=
 
@@ -15639,20 +15798,18 @@
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    # The option is referenced via a variable to avoid confusing sed.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:15645: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:15804: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:15649: \$? = $ac_status" >&5
+   echo "$as_me:15808: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+     # So say no if there are warnings
+     if test ! -s conftest.err; then
        lt_cv_prog_compiler_rtti_exceptions=yes
      fi
    fi
@@ -15713,11 +15870,6 @@
       lt_prog_compiler_pic_GCJ='-fno-common'
       ;;
 
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
     msdosdjgpp*)
       # Just because we use GCC doesn't mean we suddenly get shared libraries
       # on systems that don't support them.
@@ -15734,7 +15886,7 @@
     hpux*)
       # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
       # not for PA HP-UX.
-      case $host_cpu in
+      case "$host_cpu" in
       hppa*64*|ia64*)
 	# +Z the default
 	;;
@@ -15763,7 +15915,7 @@
       darwin*)
         # PIC is the default on this platform
         # Common symbols not allowed in MH_DYLIB files
-       case $cc_basename in
+       case "$cc_basename" in
          xlc*)
          lt_prog_compiler_pic_GCJ='-qnocommon'
          lt_prog_compiler_wl_GCJ='-Wl,'
@@ -15781,7 +15933,7 @@
       lt_prog_compiler_wl_GCJ='-Wl,'
       # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
       # not for PA HP-UX.
-      case $host_cpu in
+      case "$host_cpu" in
       hppa*64*|ia64*)
 	# +Z the default
 	;;
@@ -15811,12 +15963,12 @@
 	lt_prog_compiler_pic_GCJ='-KPIC'
 	lt_prog_compiler_static_GCJ='-static'
         ;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
+      pgcc | pgf77 | pgf90)
         # Portland Group compilers (*not* the Pentium gcc compiler,
 	# which looks to be a dead project)
 	lt_prog_compiler_wl_GCJ='-Wl,'
 	lt_prog_compiler_pic_GCJ='-fpic'
-	lt_prog_compiler_static_GCJ='-Bstatic'
+	lt_prog_compiler_static_GCJ='-static'
         ;;
       ccc*)
         lt_prog_compiler_wl_GCJ='-Wl,'
@@ -15832,15 +15984,15 @@
       lt_prog_compiler_static_GCJ='-non_shared'
       ;;
 
+    sco3.2v5*)
+      lt_prog_compiler_pic_GCJ='-Kpic'
+      lt_prog_compiler_static_GCJ='-dn'
+      ;;
+
     solaris*)
+      lt_prog_compiler_wl_GCJ='-Wl,'
       lt_prog_compiler_pic_GCJ='-KPIC'
       lt_prog_compiler_static_GCJ='-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95*)
-	lt_prog_compiler_wl_GCJ='-Qoption ld ';;
-      *)
-	lt_prog_compiler_wl_GCJ='-Wl,';;
-      esac
       ;;
 
     sunos4*)
@@ -15849,7 +16001,7 @@
       lt_prog_compiler_static_GCJ='-Bstatic'
       ;;
 
-    sysv4 | sysv4.2uw2* | sysv4.3*)
+    sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
       lt_prog_compiler_wl_GCJ='-Wl,'
       lt_prog_compiler_pic_GCJ='-KPIC'
       lt_prog_compiler_static_GCJ='-Bstatic'
@@ -15862,12 +16014,6 @@
       fi
       ;;
 
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      lt_prog_compiler_wl_GCJ='-Wl,'
-      lt_prog_compiler_pic_GCJ='-KPIC'
-      lt_prog_compiler_static_GCJ='-Bstatic'
-      ;;
-
     unicos*)
       lt_prog_compiler_wl_GCJ='-Wl,'
       lt_prog_compiler_can_build_shared_GCJ=no
@@ -15907,20 +16053,18 @@
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    # The option is referenced via a variable to avoid confusing sed.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:15913: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:16059: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:15917: \$? = $ac_status" >&5
+   echo "$as_me:16063: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+     # So say no if there are warnings
+     if test ! -s conftest.err; then
        lt_prog_compiler_pic_works_GCJ=yes
      fi
    fi
@@ -15941,7 +16085,7 @@
 fi
 
 fi
-case $host_os in
+case "$host_os" in
   # For platforms which do not support PIC, -DPIC is meaningless:
   *djgpp*)
     lt_prog_compiler_pic_GCJ=
@@ -15951,48 +16095,6 @@
     ;;
 esac
 
-#
-# Check to make sure the static flag actually works.
-#
-wl=$lt_prog_compiler_wl_GCJ eval lt_tmp_static_flag=\"$lt_prog_compiler_static_GCJ\"
-echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
-if test "${lt_prog_compiler_static_works_GCJ+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_static_works_GCJ=no
-   save_LDFLAGS="$LDFLAGS"
-   LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
-   printf "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&5
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_prog_compiler_static_works_GCJ=yes
-       fi
-     else
-       lt_prog_compiler_static_works_GCJ=yes
-     fi
-   fi
-   $rm conftest*
-   LDFLAGS="$save_LDFLAGS"
-
-fi
-echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_GCJ" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works_GCJ" >&6
-
-if test x"$lt_prog_compiler_static_works_GCJ" = xyes; then
-    :
-else
-    lt_prog_compiler_static_GCJ=
-fi
-
-
 echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
 echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
 if test "${lt_cv_prog_compiler_c_o_GCJ+set}" = set; then
@@ -16011,25 +16113,23 @@
    # Note that $ac_compile itself does not contain backslashes and begins
    # with a dollar sign (not a hyphen), so the echo should work correctly.
    lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's:.*FLAGS}? :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:16017: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:16119: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>out/conftest.err)
    ac_status=$?
    cat out/conftest.err >&5
-   echo "$as_me:16021: \$? = $ac_status" >&5
+   echo "$as_me:16123: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s out/conftest2.$ac_objext
    then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+     if test ! -s out/conftest.err; then
        lt_cv_prog_compiler_c_o_GCJ=yes
      fi
    fi
-   chmod u+w . 2>&5
+   chmod u+w .
    $rm conftest*
    # SGI C++ compiler will create directory out/ii_files/ for
    # template instantiation
@@ -16105,16 +16205,6 @@
   # rely on this symbol name, it's probably fine to never include it in
   # preloaded symbol tables.
   extract_expsyms_cmds=
-  # Just being paranoid about ensuring that cc_basename is set.
-  for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
 
   case $host_os in
   cygwin* | mingw* | pw32*)
@@ -16125,10 +16215,6 @@
       with_gnu_ld=no
     fi
     ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (= MSVC++)
-    with_gnu_ld=yes
-    ;;
   openbsd*)
     with_gnu_ld=no
     ;;
@@ -16139,27 +16225,6 @@
     # If archive_cmds runs LD, not CC, wlarc should be empty
     wlarc='${wl}'
 
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=LD_RUN_PATH
-    hardcode_libdir_flag_spec_GCJ='${wl}--rpath ${wl}$libdir'
-    export_dynamic_flag_spec_GCJ='${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
-	whole_archive_flag_spec_GCJ="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-      else
-  	whole_archive_flag_spec_GCJ=
-    fi
-    supports_anon_versioning=no
-    case `$LD -v 2>/dev/null` in
-      *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=yes ;;
-    esac
-
     # See if GNU ld supports shared libraries.
     case $host_os in
     aix3* | aix4* | aix5*)
@@ -16213,7 +16278,7 @@
       export_symbols_cmds_GCJ='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
 
       if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-        archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+        archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000 ${wl}--out-implib,$lib'
 	# If the export-symbols file already is a .def file (1st line
 	# is EXPORTS), use it as is; otherwise, prepend...
 	archive_expsym_cmds_GCJ='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
@@ -16222,53 +16287,7 @@
 	  echo EXPORTS > $output_objdir/$soname.def;
 	  cat $export_symbols >> $output_objdir/$soname.def;
 	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      else
-	ld_shlibs_GCJ=no
-      fi
-      ;;
-
-    interix3*)
-      hardcode_direct_GCJ=no
-      hardcode_shlibpath_var_GCJ=no
-      hardcode_libdir_flag_spec_GCJ='${wl}-rpath,$libdir'
-      export_dynamic_flag_spec_GCJ='${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-      # Instead, shared libraries are loaded at an image base (0x10000000 by
-      # default) and relocated if they conflict, which is a slow very memory
-      # consuming and fragmenting process.  To avoid this, we pick a random,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      archive_cmds_GCJ='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      archive_expsym_cmds_GCJ='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      ;;
-
-    linux*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	tmp_addflag=
-	case $cc_basename,$host_cpu in
-	pgcc*)				# Portland Group C compiler
-	  whole_archive_flag_spec_GCJ='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
-	  whole_archive_flag_spec_GCJ='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
-	  tmp_addflag=' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=' -nofor_main' ;;
-	esac
-	archive_cmds_GCJ='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-
-	if test $supports_anon_versioning = yes; then
-	  archive_expsym_cmds_GCJ='$echo "{ global:" > $output_objdir/$libname.ver~
-  cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-  $echo "local: *; };" >> $output_objdir/$libname.ver~
-	  $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-	fi
+	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--image-base=0x10000000  ${wl}--out-implib,$lib'
       else
 	ld_shlibs_GCJ=no
       fi
@@ -16284,7 +16303,7 @@
       fi
       ;;
 
-    solaris*)
+    solaris* | sysv5*)
       if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
 	ld_shlibs_GCJ=no
 	cat <<EOF 1>&2
@@ -16305,33 +16324,6 @@
       fi
       ;;
 
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
-	ld_shlibs_GCJ=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	    hardcode_libdir_flag_spec_GCJ='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
-	    archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
-	    archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib'
-	  else
-	    ld_shlibs_GCJ=no
-	  fi
-	;;
-      esac
-      ;;
-
     sunos4*)
       archive_cmds_GCJ='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
       wlarc=
@@ -16339,6 +16331,41 @@
       hardcode_shlibpath_var_GCJ=no
       ;;
 
+  linux*)
+    if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+      tmp_addflag=
+      case $CC,$host_cpu in
+      pgf77* | pgf90* )			# Portland Group f77 and f90 compilers
+        tmp_addflag=' -fpic' ;;
+      ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
+        tmp_addflag=' -i_dynamic' ;;
+      efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
+        tmp_addflag=' -i_dynamic -nofor_main' ;;
+      ifc* | ifort*)			# Intel Fortran compiler
+      	tmp_addflag=' -nofor_main' ;;
+      esac
+      archive_cmds_GCJ='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      supports_anon_versioning=no
+      case `$LD -v 2>/dev/null` in
+        *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
+        *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+        *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+        *\ 2.11.*) ;; # other 2.11 versions
+        *) supports_anon_versioning=yes ;;
+      esac
+      if test $supports_anon_versioning = yes; then
+        archive_expsym_cmds_GCJ='$echo "{ global:" > $output_objdir/$libname.ver~
+cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+$echo "local: *; };" >> $output_objdir/$libname.ver~
+        $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+      else
+        archive_expsym_cmds_GCJ=$archive_cmds_GCJ
+      fi
+    else
+      ld_shlibs_GCJ=no
+    fi
+    ;;
+
     *)
       if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
 	archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
@@ -16349,11 +16376,16 @@
       ;;
     esac
 
-    if test "$ld_shlibs_GCJ" = no; then
-      runpath_var=
-      hardcode_libdir_flag_spec_GCJ=
-      export_dynamic_flag_spec_GCJ=
-      whole_archive_flag_spec_GCJ=
+    if test "$ld_shlibs_GCJ" = yes; then
+      runpath_var=LD_RUN_PATH
+      hardcode_libdir_flag_spec_GCJ='${wl}--rpath ${wl}$libdir'
+      export_dynamic_flag_spec_GCJ='${wl}--export-dynamic'
+      # ancient GNU ld didn't support --whole-archive et. al.
+      if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
+ 	whole_archive_flag_spec_GCJ="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+      else
+  	whole_archive_flag_spec_GCJ=
+      fi
     fi
   else
     # PORTME fill in a description of your system's linker (not GNU ld)
@@ -16365,7 +16397,7 @@
       # Note: this linker hardcodes the directories in LIBPATH if there
       # are no directories specified by -L.
       hardcode_minus_L_GCJ=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+      if test "$GCC" = yes && test -z "$link_static_flag"; then
 	# Neither direct hardcoding nor static linking is supported with a
 	# broken collect2.
 	hardcode_direct_GCJ=unsupported
@@ -16399,7 +16431,6 @@
   	    break
   	  fi
 	  done
-	  ;;
 	esac
 
 	exp_sym_flag='-bexport'
@@ -16437,7 +16468,6 @@
   	  hardcode_libdir_flag_spec_GCJ='-L$libdir'
   	  hardcode_libdir_separator_GCJ=
 	  fi
-	  ;;
 	esac
 	shared_flag='-shared'
 	if test "$aix_use_runtimelinking" = yes; then
@@ -16450,11 +16480,11 @@
   	# chokes on -Wl,-G. The following line is correct:
 	  shared_flag='-G'
 	else
-	  if test "$aix_use_runtimelinking" = yes; then
+  	if test "$aix_use_runtimelinking" = yes; then
 	    shared_flag='${wl}-G'
 	  else
 	    shared_flag='${wl}-bM:SRE'
-	  fi
+  	fi
 	fi
       fi
 
@@ -16519,12 +16549,12 @@
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
        hardcode_libdir_flag_spec_GCJ='${wl}-blibpath:$libdir:'"$aix_libpath"
-	archive_expsym_cmds_GCJ="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+	archive_expsym_cmds_GCJ="\$CC"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols $shared_flag"
        else
 	if test "$host_cpu" = ia64; then
 	  hardcode_libdir_flag_spec_GCJ='${wl}-R $libdir:/usr/lib:/lib'
 	  allow_undefined_flag_GCJ="-z nodefs"
-	  archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	  archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$no_entry_flag \${wl}$exp_sym_flag:\$export_symbols"
 	else
 	 # Determine the default libpath from the value encoded in an empty executable.
 	 cat >conftest.$ac_ext <<_ACEOF
@@ -16584,11 +16614,13 @@
 	  # -berok will link without error, but may produce a broken library.
 	  no_undefined_flag_GCJ=' ${wl}-bernotok'
 	  allow_undefined_flag_GCJ=' ${wl}-berok'
+	  # -bexpall does not export symbols beginning with underscore (_)
+	  always_export_symbols_GCJ=yes
 	  # Exported symbols can be pulled into shared objects from archives
-	  whole_archive_flag_spec_GCJ='$convenience'
+	  whole_archive_flag_spec_GCJ=' '
 	  archive_cmds_need_lc_GCJ=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	  # This is similar to how AIX traditionally builds it's shared libraries.
+	  archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs $compiler_flags ${wl}-bE:$export_symbols ${wl}-bnoentry${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
 	fi
       fi
       ;;
@@ -16627,7 +16659,7 @@
       ;;
 
     darwin* | rhapsody*)
-      case $host_os in
+      case "$host_os" in
         rhapsody* | darwin1.[012])
          allow_undefined_flag_GCJ='${wl}-undefined ${wl}suppress'
          ;;
@@ -16656,16 +16688,16 @@
     	output_verbose_link_cmd='echo'
         archive_cmds_GCJ='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
       module_cmds_GCJ='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-      # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+      # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
       archive_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
       module_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
     else
-      case $cc_basename in
+      case "$cc_basename" in
         xlc*)
          output_verbose_link_cmd='echo'
          archive_cmds_GCJ='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
          module_cmds_GCJ='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+          # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin ld's
          archive_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           module_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
           ;;
@@ -16729,62 +16761,47 @@
       export_dynamic_flag_spec_GCJ='${wl}-E'
       ;;
 
-    hpux10*)
-      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	archive_cmds_GCJ='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds_GCJ='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator_GCJ=:
-
-	hardcode_direct_GCJ=yes
-	export_dynamic_flag_spec_GCJ='${wl}-E'
-
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	hardcode_minus_L_GCJ=yes
-      fi
-      ;;
-
-    hpux11*)
+    hpux10* | hpux11*)
       if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	case $host_cpu in
-	hppa*64*)
+	case "$host_cpu" in
+	hppa*64*|ia64*)
 	  archive_cmds_GCJ='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
-	ia64*)
-	  archive_cmds_GCJ='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
 	*)
 	  archive_cmds_GCJ='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	esac
       else
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds_GCJ='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds_GCJ='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	case "$host_cpu" in
+	hppa*64*|ia64*)
+	  archive_cmds_GCJ='$LD -b +h $soname -o $lib $libobjs $deplibs $linker_flags'
 	  ;;
 	*)
-	  archive_cmds_GCJ='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_cmds_GCJ='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
 	  ;;
 	esac
       fi
       if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator_GCJ=:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
+	case "$host_cpu" in
+	hppa*64*)
+	  hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir'
 	  hardcode_libdir_flag_spec_ld_GCJ='+b $libdir'
+	  hardcode_libdir_separator_GCJ=:
+	  hardcode_direct_GCJ=no
+	  hardcode_shlibpath_var_GCJ=no
+	  ;;
+	ia64*)
+	  hardcode_libdir_flag_spec_GCJ='-L$libdir'
 	  hardcode_direct_GCJ=no
 	  hardcode_shlibpath_var_GCJ=no
+
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  hardcode_minus_L_GCJ=yes
 	  ;;
 	*)
+	  hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir'
+	  hardcode_libdir_separator_GCJ=:
 	  hardcode_direct_GCJ=yes
 	  export_dynamic_flag_spec_GCJ='${wl}-E'
 
@@ -16878,7 +16895,7 @@
 	allow_undefined_flag_GCJ=' -expect_unresolved \*'
 	archive_cmds_GCJ='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
 	archive_expsym_cmds_GCJ='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
-	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${objdir}/so_locations -o $lib~$rm $lib.exp'
 
 	# Both c and cxx compiler support -rpath directly
 	hardcode_libdir_flag_spec_GCJ='-rpath $libdir'
@@ -16886,15 +16903,21 @@
       hardcode_libdir_separator_GCJ=:
       ;;
 
+    sco3.2v5*)
+      archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_shlibpath_var_GCJ=no
+      export_dynamic_flag_spec_GCJ='${wl}-Bexport'
+      runpath_var=LD_RUN_PATH
+      hardcode_runpath_var=yes
+      ;;
+
     solaris*)
       no_undefined_flag_GCJ=' -z text'
       if test "$GCC" = yes; then
-	wlarc='${wl}'
 	archive_cmds_GCJ='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
 	archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
 	  $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
       else
-	wlarc=''
 	archive_cmds_GCJ='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
 	archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
   	$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
@@ -16903,18 +16926,8 @@
       hardcode_shlibpath_var_GCJ=no
       case $host_os in
       solaris2.[0-5] | solaris2.[0-5].*) ;;
-      *)
- 	# The compiler driver will combine linker options so we
- 	# cannot just pass the convience library names through
- 	# without $wl, iff we do not link with $LD.
- 	# Luckily, gcc supports the same syntax we need for Sun Studio.
- 	# Supported since Solaris 2.6 (maybe 2.5.1?)
- 	case $wlarc in
- 	'')
- 	  whole_archive_flag_spec_GCJ='-z allextract$convenience -z defaultextract' ;;
- 	*)
- 	  whole_archive_flag_spec_GCJ='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
- 	esac ;;
+      *) # Supported since Solaris 2.6 (maybe 2.5.1?)
+	whole_archive_flag_spec_GCJ='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;;
       esac
       link_all_deplibs_GCJ=yes
       ;;
@@ -16971,45 +16984,36 @@
       fi
       ;;
 
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*)
-      no_undefined_flag_GCJ='${wl}-z,text'
-      archive_cmds_need_lc_GCJ=no
+    sysv4.2uw2*)
+      archive_cmds_GCJ='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+      hardcode_direct_GCJ=yes
+      hardcode_minus_L_GCJ=no
       hardcode_shlibpath_var_GCJ=no
-      runpath_var='LD_RUN_PATH'
+      hardcode_runpath_var=yes
+      runpath_var=LD_RUN_PATH
+      ;;
 
+   sysv5OpenUNIX8* | sysv5UnixWare7* |  sysv5uw[78]* | unixware7*)
+      no_undefined_flag_GCJ='${wl}-z ${wl}text'
       if test "$GCC" = yes; then
-	archive_cmds_GCJ='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_GCJ='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_cmds_GCJ='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
       else
-	archive_cmds_GCJ='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_GCJ='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_cmds_GCJ='$CC -G ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
       fi
+      runpath_var='LD_RUN_PATH'
+      hardcode_shlibpath_var_GCJ=no
       ;;
 
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      no_undefined_flag_GCJ='${wl}-z,text'
-      allow_undefined_flag_GCJ='${wl}-z,nodefs'
-      archive_cmds_need_lc_GCJ=no
+    sysv5*)
+      no_undefined_flag_GCJ=' -z text'
+      # $CC -shared without GNU ld will not create a library from C++
+      # object files and a static libstdc++, better avoid it by now
+      archive_cmds_GCJ='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+  		$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+      hardcode_libdir_flag_spec_GCJ=
       hardcode_shlibpath_var_GCJ=no
-      hardcode_libdir_flag_spec_GCJ='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
-      hardcode_libdir_separator_GCJ=':'
-      link_all_deplibs_GCJ=yes
-      export_dynamic_flag_spec_GCJ='${wl}-Bexport'
       runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	archive_cmds_GCJ='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_GCJ='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds_GCJ='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_GCJ='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
       ;;
 
     uts4*)
@@ -17028,6 +17032,11 @@
 echo "${ECHO_T}$ld_shlibs_GCJ" >&6
 test "$ld_shlibs_GCJ" = no && can_build_shared=no
 
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
 #
 # Do we need to explicitly link libc?
 #
@@ -17060,7 +17069,6 @@
         libobjs=conftest.$ac_objext
         deplibs=
         wl=$lt_prog_compiler_wl_GCJ
-	pic_flag=$lt_prog_compiler_pic_GCJ
         compiler_flags=-v
         linker_flags=-v
         verstring=
@@ -17221,8 +17229,7 @@
       dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
       dldir=$destdir/`dirname \$dlpath`~
       test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
+      $install_prog $dir/$dlname \$dldir/$dlname'
     postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
       dlpath=$dir/\$dldll~
        $rm \$dlpath'
@@ -17275,7 +17282,7 @@
   soname_spec='${libname}${release}${major}$shared_ext'
   shlibpath_overrides_runpath=yes
   shlibpath_var=DYLD_LIBRARY_PATH
-  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+  shrext_cmds='$(test .$module = .yes && echo .so || echo .dylib)'
   # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
   if test "$GCC" = yes; then
     sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
@@ -17313,14 +17320,7 @@
 freebsd* | dragonfly*)
   # DragonFly does not have aout.  When/if they implement a new
   # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[123]*) objformat=aout ;;
-    *) objformat=elf ;;
-    esac
-  fi
+  objformat=`test -x /usr/bin/objformat && /usr/bin/objformat || echo aout`
   version_type=freebsd-$objformat
   case $version_type in
     freebsd-elf*)
@@ -17342,15 +17342,10 @@
     shlibpath_overrides_runpath=yes
     hardcode_into_libs=yes
     ;;
-  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
-  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+  *) # from 3.2 on
     shlibpath_overrides_runpath=no
     hardcode_into_libs=yes
     ;;
-  freebsd*) # from 4.6 on
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
   esac
   ;;
 
@@ -17370,7 +17365,7 @@
   version_type=sunos
   need_lib_prefix=no
   need_version=no
-  case $host_cpu in
+  case "$host_cpu" in
   ia64*)
     shrext_cmds='.so'
     hardcode_into_libs=yes
@@ -17410,319 +17405,1116 @@
   postinstall_cmds='chmod 555 $lib'
   ;;
 
-interix3*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+	if test "$lt_cv_prog_gnu_ld" = yes; then
+		version_type=linux
+	else
+		version_type=irix
+	fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
+
+# This must be Linux ELF.
+linux*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,\t]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+  fi
+
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
+
+knetbsd*-gnu)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='GNU ld.so'
+  ;;
+
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
+
+newsos6)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
+
+nto-qnx*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
+
+openbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[89] | openbsd2.[89].*)
+	shlibpath_overrides_runpath=no
+	;;
+      *)
+	shlibpath_overrides_runpath=yes
+	;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
+
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
+
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
+
+sco3.2v5*)
+  version_type=osf
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+solaris*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
+
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
+
+sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      export_dynamic_flag_spec='${wl}-Blargedynsym'
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
+
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
+
+uts4*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+*)
+  dynamic_linker=no
+  ;;
+esac
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
+test "$dynamic_linker" = no && can_build_shared=no
+
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
+hardcode_action_GCJ=
+if test -n "$hardcode_libdir_flag_spec_GCJ" || \
+   test -n "$runpath_var_GCJ" || \
+   test "X$hardcode_automatic_GCJ" = "Xyes" ; then
+
+  # We can hardcode non-existant directories.
+  if test "$hardcode_direct_GCJ" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, GCJ)" != no &&
+     test "$hardcode_minus_L_GCJ" != no; then
+    # Linking always hardcodes the temporary library directory.
+    hardcode_action_GCJ=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    hardcode_action_GCJ=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  hardcode_action_GCJ=unsupported
+fi
+echo "$as_me:$LINENO: result: $hardcode_action_GCJ" >&5
+echo "${ECHO_T}$hardcode_action_GCJ" >&6
+
+if test "$hardcode_action_GCJ" = relink; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
+
+striplib=
+old_striplib=
+echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5
+echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6
+if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+   darwin*)
+       if test -n "$STRIP" ; then
+         striplib="$STRIP -x"
+         echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+       else
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+       ;;
+   *)
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+    ;;
+  esac
+fi
+
+if test "x$enable_dlopen" != xyes; then
+  enable_dlopen=unknown
+  enable_dlopen_self=unknown
+  enable_dlopen_self_static=unknown
+else
+  lt_cv_dlopen=no
+  lt_cv_dlopen_libs=
+
+  case $host_os in
+  beos*)
+    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ;;
+
+  mingw* | pw32*)
+    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen_libs=
+   ;;
+
+  cygwin*)
+    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen_libs=
+   ;;
+
+  darwin*)
+  # if libdl is installed we need to link against it
+    echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
+echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6
+if test "${ac_cv_lib_dl_dlopen+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dlopen ();
+int
+main ()
+{
+dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_dl_dlopen=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dl_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6
+if test $ac_cv_lib_dl_dlopen = yes; then
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
+
+    lt_cv_dlopen="dyld"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+
+fi
+
+   ;;
+
+  *)
+    echo "$as_me:$LINENO: checking for shl_load" >&5
+echo $ECHO_N "checking for shl_load... $ECHO_C" >&6
+if test "${ac_cv_func_shl_load+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+/* Define shl_load to an innocuous variant, in case <limits.h> declares shl_load.
+   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
+#define shl_load innocuous_shl_load
+
+/* System header to define __stub macros and hopefully few prototypes,
+    which can conflict with char shl_load (); 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 shl_load
+
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char shl_load ();
+/* 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_shl_load) || defined (__stub___shl_load)
+choke me
+#else
+char (*f) () = shl_load;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != shl_load;
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_func_shl_load=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_func_shl_load=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5
+echo "${ECHO_T}$ac_cv_func_shl_load" >&6
+if test $ac_cv_func_shl_load = yes; then
+  lt_cv_dlopen="shl_load"
+else
+  echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5
+echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6
+if test "${ac_cv_lib_dld_shl_load+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char shl_load ();
+int
+main ()
+{
+shl_load ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_dld_shl_load=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dld_shl_load=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6
+if test $ac_cv_lib_dld_shl_load = yes; then
+  lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld"
+else
+  echo "$as_me:$LINENO: checking for dlopen" >&5
+echo $ECHO_N "checking for dlopen... $ECHO_C" >&6
+if test "${ac_cv_func_dlopen+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+/* Define dlopen to an innocuous variant, in case <limits.h> declares dlopen.
+   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
+#define dlopen innocuous_dlopen
+
+/* System header to define __stub macros and hopefully few prototypes,
+    which can conflict with char dlopen (); 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 dlopen
+
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dlopen ();
+/* 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_dlopen) || defined (__stub___dlopen)
+choke me
+#else
+char (*f) () = dlopen;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != dlopen;
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_func_dlopen=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_func_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5
+echo "${ECHO_T}$ac_cv_func_dlopen" >&6
+if test $ac_cv_func_dlopen = yes; then
+  lt_cv_dlopen="dlopen"
+else
+  echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
+echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6
+if test "${ac_cv_lib_dl_dlopen+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dlopen ();
+int
+main ()
+{
+dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_dl_dlopen=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dl_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6
+if test $ac_cv_lib_dl_dlopen = yes; then
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
+  echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5
+echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6
+if test "${ac_cv_lib_svld_dlopen+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lsvld  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dlopen ();
+int
+main ()
+{
+dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_svld_dlopen=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_svld_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6
+if test $ac_cv_lib_svld_dlopen = yes; then
+  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
+else
+  echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5
+echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6
+if test "${ac_cv_lib_dld_dld_link+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+/* Override any gcc2 internal prototype to avoid an error.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
+char dld_link ();
+int
+main ()
+{
+dld_link ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_dld_dld_link=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dld_dld_link=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6
+if test $ac_cv_lib_dld_dld_link = yes; then
+  lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld"
+fi
 
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=nonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" = yes; then
-		version_type=linux
-	else
-		version_type=irix
-	fi ;;
-  esac
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff= shlibsuff=
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff= shlibsuff= libmagic=32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=32 shlibsuff=N32 libmagic=N32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=64 shlibsuff=64 libmagic=64-bit;;
-    *) libsuff= shlibsuff= libmagic=never-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=no
-  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
-  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=yes
-  ;;
 
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=no
-  ;;
+fi
 
-# This must be Linux ELF.
-linux*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=yes
 
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
-    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
-  fi
+fi
 
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker='GNU/Linux ld.so'
-  ;;
 
-knetbsd*-gnu)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='GNU ld.so'
-  ;;
+fi
 
-netbsd*)
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker='NetBSD (a.out) ld.so'
-  else
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    dynamic_linker='NetBSD ld.elf_so'
-  fi
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  ;;
 
-newsos6)
-  version_type=linux
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  ;;
+fi
 
-nto-qnx*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  ;;
 
-openbsd*)
-  version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
-  need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=yes ;;
-    *)                         need_version=no  ;;
+fi
+
+    ;;
   esac
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[89] | openbsd2.[89].*)
-	shlibpath_overrides_runpath=no
-	;;
-      *)
-	shlibpath_overrides_runpath=yes
-	;;
-      esac
+
+  if test "x$lt_cv_dlopen" != xno; then
+    enable_dlopen=yes
   else
-    shlibpath_overrides_runpath=yes
+    enable_dlopen=no
+  fi
+
+  case $lt_cv_dlopen in
+  dlopen)
+    save_CPPFLAGS="$CPPFLAGS"
+    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+    save_LDFLAGS="$LDFLAGS"
+    eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+    save_LIBS="$LIBS"
+    LIBS="$lt_cv_dlopen_libs $LIBS"
+
+    echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5
+echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6
+if test "${lt_cv_dlopen_self+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  	  if test "$cross_compiling" = yes; then :
+  lt_cv_dlopen_self=cross
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<EOF
+#line 18319 "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
+
+#ifdef __cplusplus
+extern "C" void exit (int);
+#endif
+
+void fnord() { int i=42;}
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
+
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+      /* dlclose (self); */
+    }
+
+    exit (status);
+}
+EOF
+  if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;;
+      x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;;
+      x$lt_unknown|x*) lt_cv_dlopen_self=no ;;
+    esac
+  else :
+    # compilation failed
+    lt_cv_dlopen_self=no
   fi
-  ;;
+fi
+rm -fr conftest*
 
-os2*)
-  libname_spec='$name'
-  shrext_cmds=".dll"
-  need_lib_prefix=no
-  library_names_spec='$libname${shared_ext} $libname.a'
-  dynamic_linker='OS/2 ld.exe'
-  shlibpath_var=LIBPATH
-  ;;
 
-osf3* | osf4* | osf5*)
-  version_type=osf
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
-  ;;
+fi
+echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5
+echo "${ECHO_T}$lt_cv_dlopen_self" >&6
 
-solaris*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  # ldd complains unless libraries are executable
-  postinstall_cmds='chmod +x $lib'
-  ;;
+    if test "x$lt_cv_dlopen_self" = xyes; then
+      LDFLAGS="$LDFLAGS $link_static_flag"
+      echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5
+echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6
+if test "${lt_cv_dlopen_self_static+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  	  if test "$cross_compiling" = yes; then :
+  lt_cv_dlopen_self_static=cross
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<EOF
+#line 18417 "configure"
+#include "confdefs.h"
 
-sunos4*)
-  version_type=sunos
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  if test "$with_gnu_ld" = yes; then
-    need_lib_prefix=no
-  fi
-  need_version=yes
-  ;;
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
 
-sysv4 | sysv4.3*)
-  version_type=linux
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=no
-      need_lib_prefix=no
-      export_dynamic_flag_spec='${wl}-Blargedynsym'
-      runpath_var=LD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=no
-      ;;
-    motorola)
-      need_lib_prefix=no
-      need_version=no
-      shlibpath_overrides_runpath=no
-      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
+#include <stdio.h>
 
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=linux
-    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
-    soname_spec='$libname${shared_ext}.$major'
-    shlibpath_var=LD_LIBRARY_PATH
-  fi
-  ;;
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
 
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-    shlibpath_overrides_runpath=no
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=yes
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
 
-uts4*)
-  version_type=linux
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
+#ifdef __cplusplus
+extern "C" void exit (int);
+#endif
 
-*)
-  dynamic_linker=no
-  ;;
-esac
-echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6
-test "$dynamic_linker" = no && can_build_shared=no
+void fnord() { int i=42;}
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
 
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+      /* dlclose (self); */
+    }
+
+    exit (status);
+}
+EOF
+  if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;;
+      x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;;
+      x$lt_unknown|x*) lt_cv_dlopen_self_static=no ;;
+    esac
+  else :
+    # compilation failed
+    lt_cv_dlopen_self_static=no
+  fi
 fi
+rm -fr conftest*
 
-echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
-hardcode_action_GCJ=
-if test -n "$hardcode_libdir_flag_spec_GCJ" || \
-   test -n "$runpath_var_GCJ" || \
-   test "X$hardcode_automatic_GCJ" = "Xyes" ; then
 
-  # We can hardcode non-existant directories.
-  if test "$hardcode_direct_GCJ" != no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, GCJ)" != no &&
-     test "$hardcode_minus_L_GCJ" != no; then
-    # Linking always hardcodes the temporary library directory.
-    hardcode_action_GCJ=relink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    hardcode_action_GCJ=immediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  hardcode_action_GCJ=unsupported
 fi
-echo "$as_me:$LINENO: result: $hardcode_action_GCJ" >&5
-echo "${ECHO_T}$hardcode_action_GCJ" >&6
+echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5
+echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6
+    fi
 
-if test "$hardcode_action_GCJ" = relink; then
-  # Fast installation is not supported
-  enable_fast_install=no
-elif test "$shlibpath_overrides_runpath" = yes ||
-     test "$enable_shared" = no; then
-  # Fast installation is not necessary
-  enable_fast_install=needless
+    CPPFLAGS="$save_CPPFLAGS"
+    LDFLAGS="$save_LDFLAGS"
+    LIBS="$save_LIBS"
+    ;;
+  esac
+
+  case $lt_cv_dlopen_self in
+  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+  *) enable_dlopen_self=unknown ;;
+  esac
+
+  case $lt_cv_dlopen_self_static in
+  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+  *) enable_dlopen_self_static=unknown ;;
+  esac
 fi
 
 
@@ -17739,7 +18531,7 @@
   # Now quote all the things that may contain metacharacters while being
   # careful not to overquote the AC_SUBSTed values.  We take copies of the
   # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \
     SED SHELL STRIP \
     libname_spec library_names_spec soname_spec extract_expsyms_cmds \
     old_striplib striplib file_magic_cmd finish_cmds finish_eval \
@@ -17857,9 +18649,6 @@
 # A C compiler.
 LTCC=$lt_LTCC
 
-# LTCC compiler flags.
-LTCFLAGS=$lt_LTCFLAGS
-
 # A language-specific compiler.
 CC=$lt_compiler_GCJ
 
@@ -17925,7 +18714,7 @@
 # Does compiler simultaneously support -c and -o options?
 compiler_c_o=$lt_lt_cv_prog_compiler_c_o_GCJ
 
-# Must we lock files when doing compilation?
+# Must we lock files when doing compilation ?
 need_locks=$lt_need_locks
 
 # Do we need the lib prefix for modules?
@@ -18169,42 +18958,15 @@
 # If no C compiler was specified, use CC.
 LTCC=${LTCC-"$CC"}
 
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
 # Allow CC to be a program name with arguments.
 compiler=$CC
 
 
-# save warnings/boilerplate of simple test code
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$rm conftest*
-
-ac_outfile=conftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$rm conftest*
-
-
 # Allow CC to be a program name with arguments.
 lt_save_CC="$CC"
 CC=${RC-"windres"}
 compiler=$CC
 compiler_RC=$CC
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
-
 lt_cv_prog_compiler_c_o_RC=yes
 
 # The else clause should only fire when bootstrapping the
@@ -18220,7 +18982,7 @@
   # Now quote all the things that may contain metacharacters while being
   # careful not to overquote the AC_SUBSTed values.  We take copies of the
   # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC NM \
     SED SHELL STRIP \
     libname_spec library_names_spec soname_spec extract_expsyms_cmds \
     old_striplib striplib file_magic_cmd finish_cmds finish_eval \
@@ -18338,9 +19100,6 @@
 # A C compiler.
 LTCC=$lt_LTCC
 
-# LTCC compiler flags.
-LTCFLAGS=$lt_LTCFLAGS
-
 # A language-specific compiler.
 CC=$lt_compiler_RC
 
@@ -18406,7 +19165,7 @@
 # Does compiler simultaneously support -c and -o options?
 compiler_c_o=$lt_lt_cv_prog_compiler_c_o_RC
 
-# Must we lock files when doing compilation?
+# Must we lock files when doing compilation ?
 need_locks=$lt_need_locks
 
 # Do we need the lib prefix for modules?

Modified: freeswitch/branches/cparker/configure.in
==============================================================================
--- freeswitch/branches/cparker/configure.in	(original)
+++ freeswitch/branches/cparker/configure.in	Tue Apr 24 10:14:28 2007
@@ -6,9 +6,24 @@
 AC_CONFIG_AUX_DIR(build/config)
 AM_INIT_AUTOMAKE(libfreeswitch,0.1)
 AC_CONFIG_SRCDIR([src/switch.c])
-AC_CONFIG_HEADER([src/include/switch_am_config.h])
+AC_CONFIG_HEADER([src/include/switch_private.h])
 
 AC_PREFIX_DEFAULT(/usr/local/freeswitch)
+# AC_PREFIX_DEFAULT does not get expanded until too late so we need to do this to use prefix in this script
+if test "x$prefix" = "xNONE" ; then
+    prefix='/usr/local/freeswitch'
+fi
+
+AC_CANONICAL_HOST
+
+# Absolute source/build directory
+switch_srcdir=`(cd $srcdir && pwd)`
+switch_builddir=`pwd`
+AC_SUBST(switch_srcdir)
+AC_SUBST(switch_builddir)
+
+moddir=$prefix/mod
+AC_SUBST(moddir)
 
 #Set default language
 AC_LANG_C
@@ -17,6 +32,11 @@
 AC_PROG_AWK
 AC_PROG_MAKE_SET
 AC_PROG_INSTALL
+
+#override some default libtool behavior and invoke AC_PROG_LIBTOOL (see http://lists.gnu.org/archive/html/libtool/2007-03/msg00000.html)
+m4_defun([_LT_AC_LANG_F77_CONFIG], [:])
+m4_defun([_LT_AC_LANG_GCJ_CONFIG], [:])
+m4_defun([_LT_AC_LANG_RC_CONFIG], [:])
 AC_PROG_LIBTOOL
 
 #Check for compiler vendor
@@ -42,76 +62,92 @@
 
 AM_CONDITIONAL([WANT_DEBUG],[test "${enable_debug}" = "yes"])
 
+# Optional Features
+
+AC_ARG_ENABLE(resample,
+[AC_HELP_STRING([--enable-resample],[build with embedded resamper])],[enable_resample="$enable_resample"],[enable_resample="yes"])
+
+# We should add checking for out of tree libresample here
+RESAMPLE_LIB=
+RESAMPLE_CFLAGS=
+if test "${enable_resample}" = "yes"; then
+       RESAMPLE_LIB="libs/libresample/libresample.la"
+       RESAMPLE_CFLAGS="-I${switch_srcdir}/libs/libresample/include"
+else
+        AC_DEFINE([DISABLE_RESAMPLE],[],[Disable the embedded resampler])
+fi
+
+AC_SUBST(RESAMPLE_LIB)
+AC_SUBST(RESAMPLE_CFLAGS)
+
+AM_CONDITIONAL([USE_INTREE_RESAMPLE],[test "${enable_resample}" = "yes"])
+
+# set defaults for use on all platforms
+SWITCH_AM_CFLAGS="-I${switch_srcdir}/src/include -I${switch_srcdir}/libs/libteletone/src"
+SWITCH_AM_CXXFLAGS="-I${switch_srcdir}/src/include -I${switch_srcdir}/libs/libteletone/src"
+SWITCH_AM_LDFLAGS="-lm -L/usr/local/lib"
+
+#set SOLINK variable based on compiler and host
+if test "x${ax_cv_c_compiler_vendor}"  =  "xsun" ; then
+    SOLINK="-Bdynamic -dy -G"
+elif test "x${ax_cv_c_compiler_vendor}" = "xgnu" ; then
+    case "$host" in
+        *darwin*)
+            SOLINK="-dynamic -bundle -force-flat-namespace"
+        ;;
+        *)
+            SOLINK="-shared -Xlinker -x"
+        ;;
+    esac
+else
+    AC_ERROR([Please update configure.in with SOLINK values for your compiler])
+fi
+
+# set DYNAMIC_LIB_EXTEN
+# we should really be using libtool so we don't need to do this
+case "$host" in
+    *darwin*)
+        DYNAMIC_LIB_EXTEN="dylib"
+    ;;
+    *cygwin* | *mingw*)
+        DYNAMIC_LIB_EXTEN="dll"
+    ;;
+    *)
+        DYNAMIC_LIB_EXTEN="so"
+    ;;
+esac
+
+# tweak compiler specific flags
+if test "x${ax_cv_c_compiler_vendor}"  =  "xsun" ; then
+    APR_ADDTO(SWITCH_AM_CFLAGS, -KPIC)
+    APR_ADDTO(SWITCH_AM_CFLAGS, -DPIC)
+    APR_ADDTO(SWITCH_AM_CXXFLAGS, -KPIC)
+    APR_ADDTO(SWITCH_AM_CXXFLAGS, -DPIC)
+    APR_ADDTO(SWITCH_AM_LDFLAGS, -R${prefix}/lib)
+elif test "x${ax_cv_c_compiler_vendor}" = "xgnu" ; then
+    APR_ADDTO(SWITCH_AM_CFLAGS, -fPIC)
+    APR_ADDTO(SWITCH_AM_CXXFLAGS, -fPIC)
+    APR_ADDTO(SWITCH_AM_CFLAGS, -Werror)
+fi
 
+# tweak platform specific flags
 case "$host" in
-                *-solaris2*)
-                        if test "x${ax_cv_c_compiler_vendor}"  =  "xsun" ; then                                SOLINK="-Bdynamic -dy -G"
-                                new_AM_CFLAGS="-DPATH_MAX=2048 -KPIC -DPIC"
-                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
-                                IN_LINE=""
-                        elif test "x${ax_cv_c_compiler_vendor}" = "xgnu" ; then                                SOLINK="-Bdynamic -dy -G"
-                                new_AM_CFLAGS="-DPATH_MAX=2048 -fPIC"
-                                new_AM_LDFLAGS=""
-                                IN_LINE=inline
-                        fi
-                        DYNAMIC_LIB_EXTEN="so"
-                ;;
-                *-darwin*)
-                        if test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
-                                SOLINK="-dynamic -bundle -force-flat-namespace"
-                                new_AM_CFLAGS="-DMACOSX"
-                                new_AM_LDFLAGS=""
-                        fi
-                        DYNAMIC_LIB_EXTEN="dylib"
-                        IN_LINE=inline
-                ;;
-                x86_64-*-linux-gnu)
-                        if test "x${ax_cv_c_compiler_vendor}" = "xsun" ; then
-                                SOLINK="-Bdynamic -dy -G"
-                                new_AM_CFLAGS="-KPIC -DPIC"
-                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
-                        elif test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
-                                SOLINK="-shared -Xlinker -x"
-                                new_AM_CFLAGS="-fPIC"
-                                new_AM_LDFLAGS=""
-                        fi
-                        DYNAMIC_LIB_EXTEN="so"
-                        IN_LINE=inline
-                ;;
-                i*6-*-linux-gnu)
-                        if test "x${ax_cv_c_compiler_vendor}" = "xsun" ; then
-                                SOLINK="-Bdynamic -dy -G"
-                                new_AM_CFLAGS="-KPIC -DPIC"
-                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
-                        elif test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
-                                SOLINK="-shared -Xlinker -x"
-                                new_AM_CFLAGS="-fpic"
-                                new_AM_LDFLAGS=""
-                        fi
-                        IN_LINE=inline
-                        DYNAMIC_LIB_EXTEN="so"
-                ;;
-	        *)
-                        if test "x${ax_cv_c_compiler_vendor}" = "xsun" ; then
-                                SOLINK="-Bdynamic -dy -G"
-                                new_AM_CFLAGS="-KPIC -DPIC"
-                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
-                        elif test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
-                                SOLINK="-shared -Xlinker -x"
-                                new_AM_CFLAGS="-fPIC"
-                                new_AM_LDFLAGS=""
-                        fi
-                        DYNAMIC_LIB_EXTEN="so"
-                        IN_LINE=inline
-			;;
+    *darwin*)
+        APR_ADDTO(SWITCH_AM_CFLAGS, -DMACOSX)
+        APR_REMOVEFROM(SWITCH_AM_CFLAGS, -fPIC)
+    ;;
+    *-solaris2*)
+        APR_ADDTO(SWITCH_AM_CFLAGS, -DPATH_MAX=2048)
+    ;;
 esac
-AC_SUBST(new_AM_CFLAGS)
-AC_SUBST(new_AM_LDFLAGS)
+
+APR_REMOVEFROM(SWITCH_AM_CXXFLAGS, -std=c99)
+
+AC_SUBST(SWITCH_AM_CFLAGS)
+AC_SUBST(SWITCH_AM_CXXFLAGS)
+AC_SUBST(SWITCH_AM_LDFLAGS)
 AC_SUBST(SOLINK)
 AC_SUBST(DYNAMIC_LIB_EXTEN)
-AC_DEFINE_UNQUOTED([inline],[$IN_LINE],[sunpro is bad at inline])
-AC_DEFINE_UNQUOTED([__inline__],[$IN_LINE],[sunpro is bad at inline])
-
 
 # Checks for header files.
 AC_HEADER_DIRENT
@@ -134,15 +170,215 @@
 
 AC_C_BIGENDIAN(AC_DEFINE([SWITCH_BYTE_ORDER],__BIG_ENDIAN,[Big Endian]),AC_DEFINE([SWITCH_BYTE_ORDER],__LITTLE_ENDIAN,[Little Endian]))
 
+# Checks for integer size
+AC_CHECK_SIZEOF(char, 1)
+AC_CHECK_SIZEOF(int, 4)
+AC_CHECK_SIZEOF(long, 4)
+AC_CHECK_SIZEOF(short, 2)
+AC_CHECK_SIZEOF(long long, 8)
+AC_TYPE_SIZE_T
+AC_CHECK_TYPE(ssize_t, int)
+
+# Checks for pointer size
+AC_CHECK_SIZEOF(void*, 4)
+
+if test "x$ac_cv_sizeof_voidp" != "x"; then
+    voidp_size=$ac_cv_sizeof_voidp
+else
+    AC_ERROR([Cannot determine size of void*])
+fi
+
+if test "$ac_cv_sizeof_short" = "2"; then
+    short_value=short
+fi
+if test "$ac_cv_sizeof_int" = "4"; then
+    int_value=int
+fi
+
+if test "$ac_cv_sizeof_int" = "8"; then
+    int64_t_fmt='#define SWITCH_INT64_T_FMT "d"'
+    uint64_t_fmt='#define SWITCH_UINT64_T_FMT "u"'
+    int64_value="int"
+    long_value=int
+elif test "$ac_cv_sizeof_long" = "8"; then
+    int64_t_fmt='#define SWITCH_INT64_T_FMT "ld"'
+    uint64_t_fmt='#define SWITCH_UINT64_T_FMT "lu"'
+    int64_value="long"
+    long_value=long
+elif test "$ac_cv_sizeof_long_long" = "8"; then
+    int64_t_fmt='#define SWITCH_INT64_T_FMT "lld"'
+    uint64_t_fmt='#define SWITCH_UINT64_T_FMT "llu"'
+    int64_value="long long"
+    long_value="long long"
+elif test "$ac_cv_sizeof_longlong" = "8"; then
+    int64_t_fmt='#define SWITCH_INT64_T_FMT "qd"'
+    uint64_t_fmt='#define SWITCH_UINT64_T_FMT "qu"'
+    int64_value="__int64"
+    long_value="__int64"
+else
+    AC_ERROR([could not detect a 64-bit integer type])
+fi
+
+if test "$ac_cv_type_size_t" = "yes"; then
+    size_t_value="size_t"
+else
+    size_t_value="switch_int32_t"
+fi
+
+if test "$ac_cv_type_ssize_t" = "yes"; then
+    ssize_t_value="ssize_t"
+else
+    ssize_t_value="switch_int32_t"
+fi
+
+APR_CHECK_SIZEOF_EXTENDED([#include <sys/types.h>], ssize_t, 8)
+
+if test "$ac_cv_sizeof_ssize_t" = "$ac_cv_sizeof_int"; then
+    ssize_t_fmt='#define SWITCH_SSIZE_T_FMT "d"'
+elif test "$ac_cv_sizeof_ssize_t" = "$ac_cv_sizeof_long"; then
+    ssize_t_fmt='#define SWITCH_SSIZE_T_FMT "ld"'
+else
+    ssize_t_fmt='#error Can not determine the proper size for ssize_t'
+fi
+
+APR_CHECK_SIZEOF_EXTENDED([#include <stddef.h>], size_t, 8)
+
+if test "$ac_cv_sizeof_size_t" = "$ac_cv_sizeof_int"; then
+    size_t_fmt='#define SWITCH_SIZE_T_FMT "d"'
+elif test "$ac_cv_sizeof_size_t" = "$ac_cv_sizeof_long"; then
+    size_t_fmt='#define SWITCH_SIZE_T_FMT "ld"'
+else
+    size_t_fmt='#error Can not determine the proper size for size_t'
+fi
+
+# Basically, we have tried to figure out the correct format strings
+# for SWITCH types which vary between platforms, but we don't always get 
+# it right.  If you find that we don't get it right for your platform, 
+# you can override our decision below.
+# NOTE: borrowed much of this logic from apr.
+case $host in
+   s390*linux*)
+       # uniquely, the 31-bit Linux/s390 uses "unsigned long int"
+       # for size_t rather than "unsigned int":
+       size_t_fmt='#define SWITCH_SIZE_T_FMT "lu"'
+       ssize_t_fmt='#define SWITCH_SSIZE_T_FMT "ld"'
+       ;;
+   *-os2*)
+       size_t_fmt='#define SWITCH_SIZE_T_FMT "lu"'
+       ;;
+   *aix4*|*aix5*)
+       ssize_t_fmt='#define SWITCH_SSIZE_T_FMT "ld"'
+       size_t_fmt='#define SWITCH_SIZE_T_FMT "ld"'
+       ;;
+    *beos*)
+        ssize_t_fmt='#define SWITCH_SSIZE_T_FMT "ld"'
+        size_t_fmt='#define SWITCH_SIZE_T_FMT "ld"'
+        ;;
+    *apple-darwin*)
+        osver=`uname -r`
+        case $osver in
+           [0-7].*)
+              ssize_t_fmt='#define SWITCH_SSIZE_T_FMT "d"'
+              ;;
+           *)
+              ssize_t_fmt='#define SWITCH_SSIZE_T_FMT "ld"'
+              ;;
+        esac
+        size_t_fmt='#define SWITCH_SIZE_T_FMT "lu"'
+        ;;
+esac
+
+AC_SUBST(voidp_size)
+AC_SUBST(short_value)
+AC_SUBST(int_value)
+AC_SUBST(long_value)
+AC_SUBST(int64_value)
+AC_SUBST(size_t_value)
+AC_SUBST(ssize_t_value)
+AC_SUBST(int64_t_fmt) 
+AC_SUBST(uint64_t_fmt) 
+AC_SUBST(ssize_t_fmt) 
+AC_SUBST(size_t_fmt)
+
+AC_PATH_PROGS(ZCAT, gunzip gzcat gzip zcat)
+AC_PATH_PROGS(TAR, gtar tar)
+AC_PATH_PROGS(WGET, wget)
+AC_PATH_PROGS(CURL, curl)
+GETLIB="cd $switch_srcdir/libs && ${SHELL} $switch_srcdir/build/getlib.sh"
+AC_SUBST(GETLIB)
+
+
+LIBCURL_CHECK_CONFIG([yes], [7.13.0], [LIBCURL_DEPS=''], [LIBCURL_DEPS='${switch_srcdir}/libs/curl/lib/libcurl.la';LIBCURL='${switch_srcdir}/libs/curl/lib/libcurl.la';LIBCURL_CPPFLAGS='-I${switch_srcdir}/libs/curl/include'])
+AC_SUBST(LIBCURL_DEPS)
+
 AC_ARG_ENABLE(crash-protection,     
 	[  --enable-crash-protection         Compile with CRASH Protection],,[enable_crash_prot="no"])
 
+AC_ARG_ENABLE(core-odbc-support,     
+	[  --enable-core-odbc-support         Compile with ODBC Support],,[enable_core_odbc_support="no"])
+
+#AX_LIB_MYSQL([MINIMUM-VERSION]) 
+AX_LIB_MYSQL
+
 AM_CONDITIONAL([CRASHPROT],[test "x$enable_crash_prot" != "xno"])
+AM_CONDITIONAL([ADD_ODBC],[test "x$enable_core_odbc_support" != "xno"])
+AM_CONDITIONAL([HAVE_MYSQL],[test "$found_mysql" = "yes"])
 
-AC_CONFIG_FILES([Makefile])
+AC_CONFIG_FILES([Makefile
+                src/Makefile
+                src/mod/Makefile
+                src/mod/event_handlers/mod_cdr/Makefile
+                src/include/switch_am_config.h
+                build/getlib.sh
+                build/modmake.rules])
 
 AM_CONDITIONAL(ISLINUX, [test `uname -s` = Linux])
 AM_CONDITIONAL(ISMAC, [test `uname -s` = Darwin])
 AM_CONDITIONAL(IS64BITLINUX, [test `uname -m` = x86_64])
 
-AC_OUTPUT([src/include/switch_version.h])
+#some vars to sub into the Makefile.am's
+#LIBS+=> core.log || error="yes";if test -n "$(VERBOSE)" -o "$$error" = "yes";then cat core.log;fi;if test "$$error" = "yes";then exit 1;fi
+LIBTOOL='`if test -z "$(VERBOSE)" ; then echo $(SHELL) $(switch_builddir)/quiet_libtool ;else echo $(switch_builddir)/libtool; fi;`'
+TOUCH_TARGET='if test -f "$@";then touch "$@";fi;'
+CONF_MODULES='\`grep -v "\#" $(switch_builddir)/modules.conf | sed -e "s|^.*/||" \`'
+OUR_MODS='`if test -z "$(MODULES)" ; then tmp_mods="$(CONF_MODULES)"; else tmp_mods="$(MODULES)" ; fi ; mods=\`for i in $$tmp_mods ; do echo $$i-all ; done \`; echo $$mods `'
+OUR_CLEAN_MODS='`if test -z "$(MODULES)" ; then tmp_mods="$(CONF_MODULES)"; else tmp_mods="$(MODULES)" ; fi ; mods=\`for i in $$tmp_mods ; do echo $$i-clean ; done \`; echo $$mods `'
+OUR_INSTALL_MODS='`if test -z "$(MODULES)" ; then tmp_mods="$(CONF_MODULES)"; else tmp_mods="$(MODULES)" ; fi ; mods=\`for i in $$tmp_mods ; do echo $$i-install ; done\`; echo $$mods `'
+OUR_UNINSTALL_MODS='`if test -z "$(MODULES)" ; then tmp_mods="$(CONF_MODULES)"; else tmp_mods="$(MODULES)" ; fi ; mods=\`for i in $$tmp_mods ; do echo $$i-uninstall ; done\`; echo $$mods `'
+AM_MAKEFLAGS='"OUR_MODULES=$(OUR_MODS)" "OUR_CLEAN_MODULES=$(OUR_CLEAN_MODS)" "OUR_INSTALL_MODULES=$(OUR_INSTALL_MODS)" "OUR_UNINSTALL_MODULES=$(OUR_UNINSTALL_MODS)" `test -n "$(VERBOSE)" || echo -s`'
+#AM_MAKEFLAGS='`test -n "$(VERBOSE)" || echo -s`'
+AC_SUBST(LIBTOOL)
+AC_SUBST(TOUCH_TARGET)
+AC_SUBST(CONF_MODULES)
+AC_SUBST(OUR_MODS)
+AC_SUBST(OUR_CLEAN_MODS)
+AC_SUBST(OUR_INSTALL_MODS)
+AC_SUBST(OUR_UNINSTALL_MODS)
+AC_SUBST(AM_MAKEFLAGS)
+
+# Run configure in all the subdirs
+AC_CONFIG_SUBDIRS(libs/srtp)
+AC_CONFIG_SUBDIRS(libs/sqlite)
+AC_CONFIG_SUBDIRS(libs/libresample)
+AC_CONFIG_SUBDIRS(libs/pcre)
+AC_CONFIG_SUBDIRS(libs/apr)
+AC_CONFIG_SUBDIRS(libs/apr-util)
+AC_CONFIG_SUBDIRS(libs/codec/g7xx)
+AC_CONFIG_SUBDIRS(libs/codec/g726)
+AC_CONFIG_SUBDIRS(libs/codec/gsm)
+AC_CONFIG_SUBDIRS(libs/codec/ilbc)
+AC_CONFIG_SUBDIRS(libs/codec/lpc10)
+AC_CONFIG_SUBDIRS(libs/curl)
+AC_CONFIG_SUBDIRS(libs/iax)
+AC_CONFIG_SUBDIRS(libs/iksemel)
+AC_CONFIG_SUBDIRS(libs/js/nsprpub)
+AC_CONFIG_SUBDIRS(libs/js)
+AC_CONFIG_SUBDIRS(libs/libdingaling)
+AC_CONFIG_SUBDIRS(libs/libetpan)
+AC_CONFIG_SUBDIRS(libs/libsndfile)
+AC_CONFIG_SUBDIRS(libs/sofia-sip)
+AC_CONFIG_SUBDIRS(libs/speex)
+AC_CONFIG_SUBDIRS(libs/xmlrpc-c)
+AC_CONFIG_SUBDIRS(libs/portaudio)
+
+AC_OUTPUT

Modified: freeswitch/branches/cparker/libs/apr-util/build-outputs.mk
==============================================================================
--- freeswitch/branches/cparker/libs/apr-util/build-outputs.mk	(original)
+++ freeswitch/branches/cparker/libs/apr-util/build-outputs.mk	Tue Apr 24 10:14:28 2007
@@ -1,52 +1,51 @@
 # DO NOT EDIT. AUTOMATICALLY GENERATED.
 
-buckets/apr_buckets_pipe.lo: buckets/apr_buckets_pipe.c .make.dirs include/apr_buckets.h
-buckets/apr_buckets_flush.lo: buckets/apr_buckets_flush.c .make.dirs include/apr_buckets.h
-buckets/apr_buckets_alloc.lo: buckets/apr_buckets_alloc.c .make.dirs include/apr_buckets.h
-buckets/apr_buckets_pool.lo: buckets/apr_buckets_pool.c .make.dirs include/apr_buckets.h
-buckets/apr_buckets_socket.lo: buckets/apr_buckets_socket.c .make.dirs include/apr_buckets.h
-buckets/apr_buckets_heap.lo: buckets/apr_buckets_heap.c .make.dirs include/apr_buckets.h
-buckets/apr_buckets_simple.lo: buckets/apr_buckets_simple.c .make.dirs include/apr_buckets.h
 buckets/apr_buckets_file.lo: buckets/apr_buckets_file.c .make.dirs include/apr_buckets.h
-buckets/apr_buckets.lo: buckets/apr_buckets.c .make.dirs include/apr_buckets.h
+buckets/apr_brigade.lo: buckets/apr_brigade.c .make.dirs include/apr_buckets.h
 buckets/apr_buckets_mmap.lo: buckets/apr_buckets_mmap.c .make.dirs include/apr_buckets.h
+buckets/apr_buckets_heap.lo: buckets/apr_buckets_heap.c .make.dirs include/apr_buckets.h
+buckets/apr_buckets.lo: buckets/apr_buckets.c .make.dirs include/apr_buckets.h
+buckets/apr_buckets_socket.lo: buckets/apr_buckets_socket.c .make.dirs include/apr_buckets.h
+buckets/apr_buckets_pool.lo: buckets/apr_buckets_pool.c .make.dirs include/apr_buckets.h
+buckets/apr_buckets_alloc.lo: buckets/apr_buckets_alloc.c .make.dirs include/apr_buckets.h
+buckets/apr_buckets_pipe.lo: buckets/apr_buckets_pipe.c .make.dirs include/apr_buckets.h
 buckets/apr_buckets_eos.lo: buckets/apr_buckets_eos.c .make.dirs include/apr_buckets.h
-buckets/apr_brigade.lo: buckets/apr_brigade.c .make.dirs include/apr_buckets.h
+buckets/apr_buckets_flush.lo: buckets/apr_buckets_flush.c .make.dirs include/apr_buckets.h
 buckets/apr_buckets_refcount.lo: buckets/apr_buckets_refcount.c .make.dirs include/apr_buckets.h
-crypto/apr_sha1.lo: crypto/apr_sha1.c .make.dirs include/apr_xlate.h include/apr_sha1.h include/apr_base64.h
+buckets/apr_buckets_simple.lo: buckets/apr_buckets_simple.c .make.dirs include/apr_buckets.h
+crypto/apr_md5.lo: crypto/apr_md5.c .make.dirs include/apr_xlate.h include/apr_md5.h include/apr_sha1.h
 crypto/uuid.lo: crypto/uuid.c .make.dirs include/apr_uuid.h
+crypto/apr_sha1.lo: crypto/apr_sha1.c .make.dirs include/apr_xlate.h include/apr_sha1.h include/apr_base64.h
 crypto/getuuid.lo: crypto/getuuid.c .make.dirs include/apr_uuid.h include/apr_md5.h include/apr_xlate.h
-crypto/apr_md5.lo: crypto/apr_md5.c .make.dirs include/apr_xlate.h include/apr_md5.h include/apr_sha1.h
 crypto/apr_md4.lo: crypto/apr_md4.c .make.dirs include/apr_md4.h include/apr_xlate.h
-dbm/apr_dbm.lo: dbm/apr_dbm.c .make.dirs include/apr_dbm.h
 dbm/apr_dbm_berkeleydb.lo: dbm/apr_dbm_berkeleydb.c .make.dirs 
 dbm/apr_dbm_gdbm.lo: dbm/apr_dbm_gdbm.c .make.dirs 
 dbm/apr_dbm_ndbm.lo: dbm/apr_dbm_ndbm.c .make.dirs 
+dbm/apr_dbm.lo: dbm/apr_dbm.c .make.dirs include/apr_dbm.h
 dbm/apr_dbm_sdbm.lo: dbm/apr_dbm_sdbm.c .make.dirs include/apr_sdbm.h
-dbm/sdbm/sdbm_pair.lo: dbm/sdbm/sdbm_pair.c .make.dirs include/apr_sdbm.h
-dbm/sdbm/sdbm.lo: dbm/sdbm/sdbm.c .make.dirs include/apr_sdbm.h
 dbm/sdbm/sdbm_hash.lo: dbm/sdbm/sdbm_hash.c .make.dirs include/apr_sdbm.h
+dbm/sdbm/sdbm.lo: dbm/sdbm/sdbm.c .make.dirs include/apr_sdbm.h
 dbm/sdbm/sdbm_lock.lo: dbm/sdbm/sdbm_lock.c .make.dirs include/apr_sdbm.h
+dbm/sdbm/sdbm_pair.lo: dbm/sdbm/sdbm_pair.c .make.dirs include/apr_sdbm.h
 encoding/apr_base64.lo: encoding/apr_base64.c .make.dirs include/apr_base64.h include/apr_xlate.h
 hooks/apr_hooks.lo: hooks/apr_hooks.c .make.dirs include/apr_optional_hooks.h include/apr_optional.h include/apr_hooks.h
-ldap/apr_ldap_url.lo: ldap/apr_ldap_url.c .make.dirs 
 ldap/apr_ldap_option.lo: ldap/apr_ldap_option.c .make.dirs 
 ldap/apr_ldap_init.lo: ldap/apr_ldap_init.c .make.dirs 
+ldap/apr_ldap_url.lo: ldap/apr_ldap_url.c .make.dirs 
 misc/apr_reslist.lo: misc/apr_reslist.c .make.dirs include/apr_reslist.h
-misc/apu_version.lo: misc/apu_version.c .make.dirs include/apu_version.h
-misc/apr_date.lo: misc/apr_date.c .make.dirs include/apr_date.h
 misc/apr_rmm.lo: misc/apr_rmm.c .make.dirs include/apr_rmm.h include/apr_anylock.h
+misc/apr_date.lo: misc/apr_date.c .make.dirs include/apr_date.h
+misc/apu_version.lo: misc/apu_version.c .make.dirs include/apu_version.h
 misc/apr_queue.lo: misc/apr_queue.c .make.dirs include/apr_queue.h
 uri/apr_uri.lo: uri/apr_uri.c .make.dirs include/apr_uri.h
-xml/apr_xml.lo: xml/apr_xml.c .make.dirs include/apr_xml.h include/apr_xlate.h
 strmatch/apr_strmatch.lo: strmatch/apr_strmatch.c .make.dirs include/apr_strmatch.h
 xlate/xlate.lo: xlate/xlate.c .make.dirs include/apr_xlate.h
-dbd/apr_dbd.lo: dbd/apr_dbd.c .make.dirs include/apr_dbd.h
 dbd/apr_dbd_sqlite2.lo: dbd/apr_dbd_sqlite2.c .make.dirs 
-dbd/apr_dbd_sqlite3.lo: dbd/apr_dbd_sqlite3.c .make.dirs 
 dbd/apr_dbd_pgsql.lo: dbd/apr_dbd_pgsql.c .make.dirs 
+dbd/apr_dbd.lo: dbd/apr_dbd.c .make.dirs include/apr_dbd.h
+dbd/apr_dbd_sqlite3.lo: dbd/apr_dbd_sqlite3.c .make.dirs 
 
-OBJECTS_all = buckets/apr_buckets_pipe.lo buckets/apr_buckets_flush.lo buckets/apr_buckets_alloc.lo buckets/apr_buckets_pool.lo buckets/apr_buckets_socket.lo buckets/apr_buckets_heap.lo buckets/apr_buckets_simple.lo buckets/apr_buckets_file.lo buckets/apr_buckets.lo buckets/apr_buckets_mmap.lo buckets/apr_buckets_eos.lo buckets/apr_brigade.lo buckets/apr_buckets_refcount.lo crypto/apr_sha1.lo crypto/uuid.lo crypto/getuuid.lo crypto/apr_md5.lo crypto/apr_md4.lo dbm/apr_dbm.lo dbm/apr_dbm_berkeleydb.lo dbm/apr_dbm_gdbm.lo dbm/apr_dbm_ndbm.lo dbm/apr_dbm_sdbm.lo dbm/sdbm/sdbm_pair.lo dbm/sdbm/sdbm.lo dbm/sdbm/sdbm_hash.lo dbm/sdbm/sdbm_lock.lo encoding/apr_base64.lo hooks/apr_hooks.lo ldap/apr_ldap_url.lo ldap/apr_ldap_option.lo ldap/apr_ldap_init.lo misc/apr_reslist.lo misc/apu_version.lo misc/apr_date.lo misc/apr_rmm.lo misc/apr_queue.lo uri/apr_uri.lo xml/apr_xml.lo strmatch/apr_strmatch.lo xlate/xlate.lo dbd/apr_dbd.lo dbd/apr_dbd_sqlite2.lo dbd/apr_dbd_sqlite3.lo dbd/apr_dbd_pgsql.lo
+OBJECTS_all = buckets/apr_buckets_file.lo buckets/apr_brigade.lo buckets/apr_buckets_mmap.lo buckets/apr_buckets_heap.lo buckets/apr_buckets.lo buckets/apr_buckets_socket.lo buckets/apr_buckets_pool.lo buckets/apr_buckets_alloc.lo buckets/apr_buckets_pipe.lo buckets/apr_buckets_eos.lo buckets/apr_buckets_flush.lo buckets/apr_buckets_refcount.lo buckets/apr_buckets_simple.lo crypto/apr_md5.lo crypto/uuid.lo crypto/apr_sha1.lo crypto/getuuid.lo crypto/apr_md4.lo dbm/apr_dbm_berkeleydb.lo dbm/apr_dbm_gdbm.lo dbm/apr_dbm_ndbm.lo dbm/apr_dbm.lo dbm/apr_dbm_sdbm.lo dbm/sdbm/sdbm_hash.lo dbm/sdbm/sdbm.lo dbm/sdbm/sdbm_lock.lo dbm/sdbm/sdbm_pair.lo encoding/apr_base64.lo hooks/apr_hooks.lo ldap/apr_ldap_option.lo ldap/apr_ldap_init.lo ldap/apr_ldap_url.lo misc/apr_reslist.lo misc/apr_rmm.lo misc/apr_date.lo misc/apu_version.lo misc/apr_queue.lo uri/apr_uri.lo strmatch/apr_strmatch.lo xlate/xlate.lo dbd/apr_dbd_sqlite2.lo dbd/apr_dbd_pgsql.lo dbd/apr_dbd.lo dbd/apr_dbd_sqlite3.lo
 
 OBJECTS_unix = $(OBJECTS_all)
 
@@ -58,11 +57,11 @@
 
 OBJECTS_os390 = $(OBJECTS_all)
 
-HEADERS = $(top_srcdir)/include/apr_ldap_url.h $(top_srcdir)/include/apr_uuid.h $(top_srcdir)/include/apr_xml.h $(top_srcdir)/include/apr_queue.h $(top_srcdir)/include/apr_anylock.h $(top_srcdir)/include/apr_rmm.h $(top_srcdir)/include/apr_strmatch.h $(top_srcdir)/include/apr_date.h $(top_srcdir)/include/apr_xlate.h $(top_srcdir)/include/apr_hooks.h $(top_srcdir)/include/apr_ldap_init.h $(top_srcdir)/include/apr_sha1.h $(top_srcdir)/include/apr_optional.h $(top_srcdir)/include/apr_base64.h $(top_srcdir)/include/apr_ldap_option.h $(top_srcdir)/include/apr_reslist.h $(top_srcdir)/include/apr_sdbm.h $(top_srcdir)/include/apr_uri.h $(top_srcdir)/include/apr_optional_hooks.h $(top_srcdir)/include/apu_version.h $(top_srcdir)/include/apr_md4.h $(top_srcdir)/include/apr_buckets.h $(top_srcdir)/include/apr_dbd.h $(top_srcdir)/include/apr_md5.h $(top_srcdir)/include/apr_dbm.h
+HEADERS = $(top_srcdir)/include/apr_optional.h $(top_srcdir)/include/apu_version.h $(top_srcdir)/include/apr_dbm.h $(top_srcdir)/include/apr_strmatch.h $(top_srcdir)/include/apr_buckets.h $(top_srcdir)/include/apr_optional_hooks.h $(top_srcdir)/include/apr_sdbm.h $(top_srcdir)/include/apr_md4.h $(top_srcdir)/include/apr_reslist.h $(top_srcdir)/include/apr_base64.h $(top_srcdir)/include/apr_ldap_option.h $(top_srcdir)/include/apr_anylock.h $(top_srcdir)/include/apr_rmm.h $(top_srcdir)/include/apr_ldap_init.h $(top_srcdir)/include/apr_ldap_url.h $(top_srcdir)/include/apr_md5.h $(top_srcdir)/include/apr_date.h $(top_srcdir)/include/apr_hooks.h $(top_srcdir)/include/apr_xlate.h $(top_srcdir)/include/apr_queue.h $(top_srcdir)/include/apr_uri.h $(top_srcdir)/include/apr_uuid.h $(top_srcdir)/include/apr_sha1.h $(top_srcdir)/include/apr_dbd.h
 
-SOURCE_DIRS = xml dbd dbm encoding hooks buckets misc crypto uri strmatch dbm/sdbm ldap xlate $(EXTRA_SOURCE_DIRS)
+SOURCE_DIRS = dbd dbm encoding hooks buckets misc crypto uri strmatch dbm/sdbm ldap xlate $(EXTRA_SOURCE_DIRS)
 
-BUILD_DIRS = buckets crypto dbd dbm dbm/sdbm encoding hooks ldap misc strmatch uri xlate xml
+BUILD_DIRS = buckets crypto dbd dbm dbm/sdbm encoding hooks ldap misc strmatch uri xlate
 
 .make.dirs: $(srcdir)/build-outputs.mk
 	@for d in $(BUILD_DIRS); do test -d $$d || mkdir $$d; done

Modified: freeswitch/branches/cparker/libs/apr-util/build.conf
==============================================================================
--- freeswitch/branches/cparker/libs/apr-util/build.conf	(original)
+++ freeswitch/branches/cparker/libs/apr-util/build.conf	Tue Apr 24 10:14:28 2007
@@ -15,10 +15,10 @@
   ldap/*.c
   misc/*.c
   uri/apr_uri.c
-  xml/*.c
   strmatch/*.c
   xlate/*.c
   dbd/*.c
+#  xml/*.c
 
 # we have no platform-specific subdirs
 platform_dirs =

Modified: freeswitch/branches/cparker/libs/apr-util/buildconf
==============================================================================
--- freeswitch/branches/cparker/libs/apr-util/buildconf	(original)
+++ freeswitch/branches/cparker/libs/apr-util/buildconf	Tue Apr 24 10:14:28 2007
@@ -82,7 +82,7 @@
 # Generate build-outputs.mk for the build systme
 #
 echo "Generating 'make' outputs ..."
-$apr_src_dir/build/gen-build.py make
+#$apr_src_dir/build/gen-build.py make
 
 #
 # If Expat has been bundled, then go and configure the thing

Modified: freeswitch/branches/cparker/libs/apr-util/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/apr-util/configure.in	(original)
+++ freeswitch/branches/cparker/libs/apr-util/configure.in	Tue Apr 24 10:14:28 2007
@@ -5,7 +5,7 @@
 AC_PREREQ(2.50)
 AC_INIT(export_vars.sh.in)
 
-AC_CONFIG_HEADER(include/private/apu_config.h)
+AC_CONFIG_HEADERS(include/private/apu_config.h)
 AC_CONFIG_AUX_DIR(build)
 
 sinclude(build/apu-conf.m4)
@@ -122,7 +122,7 @@
 APU_CHECK_DBD_MYSQL
 APU_CHECK_DBD_SQLITE3
 APU_CHECK_DBD_SQLITE2
-APU_FIND_EXPAT
+#APU_FIND_EXPAT
 APU_FIND_ICONV
 
 AC_SEARCH_LIBS(crypt, crypt ufc)

Modified: freeswitch/branches/cparker/libs/apr-util/xml/expat/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/apr-util/xml/expat/configure.in	(original)
+++ freeswitch/branches/cparker/libs/apr-util/xml/expat/configure.in	Tue Apr 24 10:14:28 2007
@@ -86,9 +86,19 @@
 if test "$cross_compiling" = "no"; then
   AC_C_BIGENDIAN
 else
-  AC_DEFINE(AP_UNKNOWN_BYTE_ORDER,1,
-                [byte order is unknown due to cross-compilation])
+  AC_DEFINE(AP_UNKNOWN_BYTE_ORDER,1,[byte order is unknown due to cross-compilation])
 fi
+
+if test "$ac_cv_c_bigendian" = "yes"; then
+  AC_DEFINE(XML_BYTE_ORDER,21,[21 for big endian or 12 for little])
+else
+  AC_DEFINE(XML_BYTE_ORDER,12,[z])
+fi
+
+AC_DEFINE(XML_NS,,[Define me])
+AC_DEFINE(XML_DTD,,[Define me])
+AC_DEFINE(XML_CONTEXT_BYTES,1024,[1024])
+
 AC_C_CONST
 AC_TYPE_OFF_T
 AC_TYPE_SIZE_T

Modified: freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/config.guess
==============================================================================
--- freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/config.guess	(original)
+++ freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/config.guess	Tue Apr 24 10:14:28 2007
@@ -1,9 +1,9 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002 Free Software Foundation, Inc.
+#   2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
 
-timestamp='2002-03-20'
+timestamp='2005-12-13'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -17,17 +17,14 @@
 #
 # 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.
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
 #
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
 # configuration script generated by Autoconf, you may include it under
 # the same distribution terms that you use for the rest of that program.
 
-#####################################################################
-# This file contains changes for Apache, clearly marked below.
-# These changes are hereby donated to the public domain.
-#####################################################################
 
 # Originally written by Per Bothner <per at bothner.com>.
 # Please send patches to <config-patches at gnu.org>.  Submit a context
@@ -58,7 +55,7 @@
 GNU config.guess ($timestamp)
 
 Originally written by Per Bothner.
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
@@ -71,11 +68,11 @@
 while test $# -gt 0 ; do
   case $1 in
     --time-stamp | --time* | -t )
-       echo "$timestamp" ; exit 0 ;;
+       echo "$timestamp" ; exit ;;
     --version | -v )
-       echo "$version" ; exit 0 ;;
+       echo "$version" ; exit ;;
     --help | --h* | -h )
-       echo "$usage"; exit 0 ;;
+       echo "$usage"; exit ;;
     -- )     # Stop option processing
        shift; break ;;
     - )	# Use stdin as input.
@@ -93,30 +90,42 @@
   exit 1
 fi
 
+trap 'exit 1' 1 2 15
 
-dummy=dummy-$$
-trap 'rm -f $dummy.c $dummy.o $dummy.rel $dummy; exit 1' 1 2 15
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
 
-# CC_FOR_BUILD -- compiler used by this script.
 # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
 # use `HOST_CC' if defined, but it is deprecated.
 
-set_cc_for_build='case $CC_FOR_BUILD,$HOST_CC,$CC in
- ,,)    echo "int dummy(){}" > $dummy.c ;
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,)    echo "int x;" > $dummy.c ;
 	for c in cc gcc c89 c99 ; do
-	  ($c $dummy.c -c -o $dummy.o) >/dev/null 2>&1 ;
-	  if test $? = 0 ; then
+	  if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
 	     CC_FOR_BUILD="$c"; break ;
 	  fi ;
 	done ;
-	rm -f $dummy.c $dummy.o $dummy.rel ;
 	if test x"$CC_FOR_BUILD" = x ; then
 	  CC_FOR_BUILD=no_compiler_found ;
 	fi
 	;;
  ,,*)   CC_FOR_BUILD=$CC ;;
  ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
-esac'
+esac ; set_cc_for_build= ;'
 
 # This is needed to find uname on a Pyramid OSx when run in the BSD universe.
 # (ghazi at noc.rutgers.edu 1994-08-24)
@@ -147,6 +156,7 @@
 	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
 	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
 	case "${UNAME_MACHINE_ARCH}" in
+	    armeb) machine=armeb-unknown ;;
 	    arm*) machine=arm-unknown ;;
 	    sh3el) machine=shl-unknown ;;
 	    sh3eb) machine=sh-unknown ;;
@@ -172,159 +182,125 @@
 		;;
 	esac
 	# The OS release
-	release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+	# Debian GNU/NetBSD machines have a different userland, and
+	# thus, need a distinct triplet. However, they do not need
+	# kernel version information, so it can be replaced with a
+	# suitable tag, in the style of linux-gnu.
+	case "${UNAME_VERSION}" in
+	    Debian*)
+		release='-gnu'
+		;;
+	    *)
+		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+		;;
+	esac
 	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
 	# contains redundant information, the shorter form:
 	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
 	echo "${machine}-${os}${release}"
-	exit 0 ;;
-    amiga:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    arc:OpenBSD:*:*)
-	echo mipsel-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    hp300:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    mac68k:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    macppc:OpenBSD:*:*)
-	echo powerpc-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    mvme68k:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    mvme88k:OpenBSD:*:*)
-	echo m88k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    mvmeppc:OpenBSD:*:*)
-	echo powerpc-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    pmax:OpenBSD:*:*)
-	echo mipsel-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    sgi:OpenBSD:*:*)
-	echo mipseb-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    sun3:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    wgrisc:OpenBSD:*:*)
-	echo mipsel-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:OpenBSD:*:*)
-	echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
+	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+	exit ;;
+    *:ekkoBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+	exit ;;
+    macppc:MirBSD:*:*)
+	echo powerppc-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    *:MirBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
     alpha:OSF1:*:*)
-	if test $UNAME_RELEASE = "V4.0"; then
+	case $UNAME_RELEASE in
+	*4.0)
 		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
-	fi
+		;;
+	*5.*)
+	        UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+		;;
+	esac
+	# According to Compaq, /usr/sbin/psrinfo has been available on
+	# OSF/1 and Tru64 systems produced since 1995.  I hope that
+	# covers most systems running today.  This code pipes the CPU
+	# types through head -n 1, so we only detect the type of CPU 0.
+	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+	case "$ALPHA_CPU_TYPE" in
+	    "EV4 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV4.5 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "LCA4 (21066/21068)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV5 (21164)")
+		UNAME_MACHINE="alphaev5" ;;
+	    "EV5.6 (21164A)")
+		UNAME_MACHINE="alphaev56" ;;
+	    "EV5.6 (21164PC)")
+		UNAME_MACHINE="alphapca56" ;;
+	    "EV5.7 (21164PC)")
+		UNAME_MACHINE="alphapca57" ;;
+	    "EV6 (21264)")
+		UNAME_MACHINE="alphaev6" ;;
+	    "EV6.7 (21264A)")
+		UNAME_MACHINE="alphaev67" ;;
+	    "EV6.8CB (21264C)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8AL (21264B)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8CX (21264D)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.9A (21264/EV69A)")
+		UNAME_MACHINE="alphaev69" ;;
+	    "EV7 (21364)")
+		UNAME_MACHINE="alphaev7" ;;
+	    "EV7.9 (21364A)")
+		UNAME_MACHINE="alphaev79" ;;
+	esac
+	# A Pn.n version is a patched version.
 	# A Vn.n version is a released version.
 	# A Tn.n version is a released field test version.
 	# A Xn.n version is an unreleased experimental baselevel.
 	# 1.2 uses "1.2" for uname -r.
-	cat <<EOF >$dummy.s
-	.data
-\$Lformat:
-	.byte 37,100,45,37,120,10,0	# "%d-%x\n"
-
-	.text
-	.globl main
-	.align 4
-	.ent main
-main:
-	.frame \$30,16,\$26,0
-	ldgp \$29,0(\$27)
-	.prologue 1
-	.long 0x47e03d80 # implver \$0
-	lda \$2,-1
-	.long 0x47e20c21 # amask \$2,\$1
-	lda \$16,\$Lformat
-	mov \$0,\$17
-	not \$1,\$18
-	jsr \$26,printf
-	ldgp \$29,0(\$26)
-	mov 0,\$16
-	jsr \$26,exit
-	.end main
-EOF
-	eval $set_cc_for_build
-	$CC_FOR_BUILD $dummy.s -o $dummy 2>/dev/null
-	if test "$?" = 0 ; then
-		case `./$dummy` in
-			0-0)
-				UNAME_MACHINE="alpha"
-				;;
-			1-0)
-				UNAME_MACHINE="alphaev5"
-				;;
-			1-1)
-				UNAME_MACHINE="alphaev56"
-				;;
-			1-101)
-				UNAME_MACHINE="alphapca56"
-				;;
-			2-303)
-				UNAME_MACHINE="alphaev6"
-				;;
-			2-307)
-				UNAME_MACHINE="alphaev67"
-				;;
-			2-1307)
-				UNAME_MACHINE="alphaev68"
-				;;
-		esac
-	fi
-	rm -f $dummy.s $dummy
-	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-	exit 0 ;;
+	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	exit ;;
     Alpha\ *:Windows_NT*:*)
 	# How do we know it's Interix rather than the generic POSIX subsystem?
 	# Should we change UNAME_MACHINE based on the output of uname instead
 	# of the specific Alpha model?
 	echo alpha-pc-interix
-	exit 0 ;;
+	exit ;;
     21064:Windows_NT:50:3)
 	echo alpha-dec-winnt3.5
-	exit 0 ;;
+	exit ;;
     Amiga*:UNIX_System_V:4.0:*)
 	echo m68k-unknown-sysv4
-	exit 0;;
+	exit ;;
     *:[Aa]miga[Oo][Ss]:*:*)
 	echo ${UNAME_MACHINE}-unknown-amigaos
-	exit 0 ;;
+	exit ;;
     *:[Mm]orph[Oo][Ss]:*:*)
 	echo ${UNAME_MACHINE}-unknown-morphos
-	exit 0 ;;
-#########################
-# Apache changes
-#
-#   *:OS/390:*:*)
-#      echo i370-ibm-openedition
-#      exit 0 ;;
-    *:OS390:*:* | *:OS/390:*:*)
-       echo s390-ibm-os390
-       exit 0 ;; 
-    *:OS400:*:* | *:OS/400:*:*) 
-       echo as400-ibm-os400
-       exit 0 ;;
-    *:OS/2:*:*)
-       echo "i386-pc-os2_emx"
-       exit 0;;
-#
-# end Apache changes
-#########################
+	exit ;;
     *:OS/390:*:*)
 	echo i370-ibm-openedition
-	exit 0 ;;
+	exit ;;
+    *:z/VM:*:*)
+	echo s390-ibm-zvmoe
+	exit ;;
+    *:OS400:*:*)
+        echo powerpc-ibm-os400
+	exit ;;
     arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
 	echo arm-acorn-riscix${UNAME_RELEASE}
-	exit 0;;
+	exit ;;
+    arm:riscos:*:*|arm:RISCOS:*:*)
+	echo arm-unknown-riscos
+	exit ;;
     SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
 	echo hppa1.1-hitachi-hiuxmpp
-	exit 0;;
+	exit ;;
     Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
 	# akee at wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
 	if test "`(/bin/universe) 2>/dev/null`" = att ; then
@@ -332,25 +308,32 @@
 	else
 		echo pyramid-pyramid-bsd
 	fi
-	exit 0 ;;
+	exit ;;
     NILE*:*:*:dcosx)
 	echo pyramid-pyramid-svr4
-	exit 0 ;;
+	exit ;;
+    DRS?6000:unix:4.0:6*)
+	echo sparc-icl-nx6
+	exit ;;
+    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+	case `/usr/bin/uname -p` in
+	    sparc) echo sparc-icl-nx7; exit ;;
+	esac ;;
     sun4H:SunOS:5.*:*)
 	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
 	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     i86pc:SunOS:5.*:*)
 	echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     sun4*:SunOS:6*:*)
 	# According to config.sub, this is the proper way to canonicalize
 	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
 	# it's likely to be more like Solaris than SunOS4.
 	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     sun4*:SunOS:*:*)
 	case "`/usr/bin/arch -k`" in
 	    Series*|S4*)
@@ -359,10 +342,10 @@
 	esac
 	# Japanese Language versions have a version number like `4.1.3-JL'.
 	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
-	exit 0 ;;
+	exit ;;
     sun3*:SunOS:*:*)
 	echo m68k-sun-sunos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     sun*:*:4.2BSD:*)
 	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
 	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
@@ -374,10 +357,10 @@
 		echo sparc-sun-sunos${UNAME_RELEASE}
 		;;
 	esac
-	exit 0 ;;
+	exit ;;
     aushp:SunOS:*:*)
 	echo sparc-auspex-sunos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     # The situation for MiNT is a little confusing.  The machine name
     # can be virtually everything (everything which is not
     # "atarist" or "atariste" at least should have a processor
@@ -388,37 +371,40 @@
     # be no problem.
     atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
         echo m68k-atari-mint${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
 	echo m68k-atari-mint${UNAME_RELEASE}
-        exit 0 ;;
+        exit ;;
     *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
         echo m68k-atari-mint${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
         echo m68k-milan-mint${UNAME_RELEASE}
-        exit 0 ;;
+        exit ;;
     hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
         echo m68k-hades-mint${UNAME_RELEASE}
-        exit 0 ;;
+        exit ;;
     *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
         echo m68k-unknown-mint${UNAME_RELEASE}
-        exit 0 ;;
+        exit ;;
+    m68k:machten:*:*)
+	echo m68k-apple-machten${UNAME_RELEASE}
+	exit ;;
     powerpc:machten:*:*)
 	echo powerpc-apple-machten${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     RISC*:Mach:*:*)
 	echo mips-dec-mach_bsd4.3
-	exit 0 ;;
+	exit ;;
     RISC*:ULTRIX:*:*)
 	echo mips-dec-ultrix${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     VAX*:ULTRIX*:*:*)
 	echo vax-dec-ultrix${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     2020:CLIX:*:* | 2430:CLIX:*:*)
 	echo clipper-intergraph-clix${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     mips:*:*:UMIPS | mips:*:*:RISCos)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
@@ -442,27 +428,33 @@
 	  exit (-1);
 	}
 EOF
-	$CC_FOR_BUILD $dummy.c -o $dummy \
-	  && ./$dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \
-	  && rm -f $dummy.c $dummy && exit 0
-	rm -f $dummy.c $dummy
+	$CC_FOR_BUILD -o $dummy $dummy.c &&
+	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+	  SYSTEM_NAME=`$dummy $dummyarg` &&
+	    { echo "$SYSTEM_NAME"; exit; }
 	echo mips-mips-riscos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     Motorola:PowerMAX_OS:*:*)
 	echo powerpc-motorola-powermax
-	exit 0 ;;
+	exit ;;
+    Motorola:*:4.3:PL8-*)
+	echo powerpc-harris-powermax
+	exit ;;
+    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+	echo powerpc-harris-powermax
+	exit ;;
     Night_Hawk:Power_UNIX:*:*)
 	echo powerpc-harris-powerunix
-	exit 0 ;;
+	exit ;;
     m88k:CX/UX:7*:*)
 	echo m88k-harris-cxux7
-	exit 0 ;;
+	exit ;;
     m88k:*:4*:R4*)
 	echo m88k-motorola-sysv4
-	exit 0 ;;
+	exit ;;
     m88k:*:3*:R3*)
 	echo m88k-motorola-sysv3
-	exit 0 ;;
+	exit ;;
     AViiON:dgux:*:*)
         # DG/UX returns AViiON for all architectures
         UNAME_PROCESSOR=`/usr/bin/uname -p`
@@ -478,29 +470,29 @@
 	else
 	    echo i586-dg-dgux${UNAME_RELEASE}
 	fi
- 	exit 0 ;;
+ 	exit ;;
     M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
 	echo m88k-dolphin-sysv3
-	exit 0 ;;
+	exit ;;
     M88*:*:R3*:*)
 	# Delta 88k system running SVR3
 	echo m88k-motorola-sysv3
-	exit 0 ;;
+	exit ;;
     XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
 	echo m88k-tektronix-sysv3
-	exit 0 ;;
+	exit ;;
     Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
 	echo m68k-tektronix-bsd
-	exit 0 ;;
+	exit ;;
     *:IRIX*:*:*)
 	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
-	exit 0 ;;
+	exit ;;
     ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
-	echo romp-ibm-aix      # uname -m gives an 8 hex-code CPU id
-	exit 0 ;;              # Note that: echo "'`uname -s`'" gives 'AIX '
+	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
+	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
     i*86:AIX:*:*)
 	echo i386-ibm-aix
-	exit 0 ;;
+	exit ;;
     ia64:AIX:*:*)
 	if [ -x /usr/bin/oslevel ] ; then
 		IBM_REV=`/usr/bin/oslevel`
@@ -508,7 +500,7 @@
 		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
 	fi
 	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
-	exit 0 ;;
+	exit ;;
     *:AIX:2:3)
 	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
 		eval $set_cc_for_build
@@ -523,15 +515,18 @@
 			exit(0);
 			}
 EOF
-		$CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0
-		rm -f $dummy.c $dummy
-		echo rs6000-ibm-aix3.2.5
+		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+		then
+			echo "$SYSTEM_NAME"
+		else
+			echo rs6000-ibm-aix3.2.5
+		fi
 	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
 		echo rs6000-ibm-aix3.2.4
 	else
 		echo rs6000-ibm-aix3.2
 	fi
-	exit 0 ;;
+	exit ;;
     *:AIX:*:[45])
 	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
 	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
@@ -545,28 +540,28 @@
 		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
 	fi
 	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
-	exit 0 ;;
+	exit ;;
     *:AIX:*:*)
 	echo rs6000-ibm-aix
-	exit 0 ;;
+	exit ;;
     ibmrt:4.4BSD:*|romp-ibm:BSD:*)
 	echo romp-ibm-bsd4.4
-	exit 0 ;;
+	exit ;;
     ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
 	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
-	exit 0 ;;                           # report: romp-ibm BSD 4.3
+	exit ;;                             # report: romp-ibm BSD 4.3
     *:BOSX:*:*)
 	echo rs6000-bull-bosx
-	exit 0 ;;
+	exit ;;
     DPX/2?00:B.O.S.:*:*)
 	echo m68k-bull-sysv3
-	exit 0 ;;
+	exit ;;
     9000/[34]??:4.3bsd:1.*:*)
 	echo m68k-hp-bsd
-	exit 0 ;;
+	exit ;;
     hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
 	echo m68k-hp-bsd4.4
-	exit 0 ;;
+	exit ;;
     9000/[34678]??:HP-UX:*:*)
 	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
 	case "${UNAME_MACHINE}" in
@@ -622,17 +617,37 @@
                   exit (0);
               }
 EOF
-		    (CCOPTS= $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null) && HP_ARCH=`./$dummy`
-		    if test -z "$HP_ARCH"; then HP_ARCH=hppa; fi
-		    rm -f $dummy.c $dummy
+		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+		    test -z "$HP_ARCH" && HP_ARCH=hppa
 		fi ;;
 	esac
+	if [ ${HP_ARCH} = "hppa2.0w" ]
+	then
+	    eval $set_cc_for_build
+
+	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
+	    # generating 64-bit code.  GNU and HP use different nomenclature:
+	    #
+	    # $ CC_FOR_BUILD=cc ./config.guess
+	    # => hppa2.0w-hp-hpux11.23
+	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+	    # => hppa64-hp-hpux11.23
+
+	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+		grep __LP64__ >/dev/null
+	    then
+		HP_ARCH="hppa2.0w"
+	    else
+		HP_ARCH="hppa64"
+	    fi
+	fi
 	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
-	exit 0 ;;
+	exit ;;
     ia64:HP-UX:*:*)
 	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
 	echo ia64-hp-hpux${HPUX_REV}
-	exit 0 ;;
+	exit ;;
     3050*:HI-UX:*:*)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
@@ -660,134 +675,166 @@
 	  exit (0);
 	}
 EOF
-	$CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0
-	rm -f $dummy.c $dummy
+	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+		{ echo "$SYSTEM_NAME"; exit; }
 	echo unknown-hitachi-hiuxwe2
-	exit 0 ;;
+	exit ;;
     9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
 	echo hppa1.1-hp-bsd
-	exit 0 ;;
+	exit ;;
     9000/8??:4.3bsd:*:*)
 	echo hppa1.0-hp-bsd
-	exit 0 ;;
+	exit ;;
     *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
 	echo hppa1.0-hp-mpeix
-	exit 0 ;;
+	exit ;;
     hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
 	echo hppa1.1-hp-osf
-	exit 0 ;;
+	exit ;;
     hp8??:OSF1:*:*)
 	echo hppa1.0-hp-osf
-	exit 0 ;;
+	exit ;;
     i*86:OSF1:*:*)
 	if [ -x /usr/sbin/sysversion ] ; then
 	    echo ${UNAME_MACHINE}-unknown-osf1mk
 	else
 	    echo ${UNAME_MACHINE}-unknown-osf1
 	fi
-	exit 0 ;;
+	exit ;;
     parisc*:Lites*:*:*)
 	echo hppa1.1-hp-lites
-	exit 0 ;;
+	exit ;;
     C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
 	echo c1-convex-bsd
-        exit 0 ;;
+        exit ;;
     C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
 	if getsysinfo -f scalar_acc
 	then echo c32-convex-bsd
 	else echo c2-convex-bsd
 	fi
-        exit 0 ;;
+        exit ;;
     C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
 	echo c34-convex-bsd
-        exit 0 ;;
+        exit ;;
     C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
 	echo c38-convex-bsd
-        exit 0 ;;
+        exit ;;
     C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
 	echo c4-convex-bsd
-        exit 0 ;;
+        exit ;;
     CRAY*Y-MP:*:*:*)
 	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
     CRAY*[A-Z]90:*:*:*)
 	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
 	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
 	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
 	      -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
     CRAY*TS:*:*:*)
 	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
-    CRAY*T3D:*:*:*)
-	echo alpha-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
     CRAY*T3E:*:*:*)
 	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
     CRAY*SV1:*:*:*)
 	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit 0 ;;
+	exit ;;
+    *:UNICOS/mp:*:*)
+	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
     F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
 	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
         FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
         FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
         echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
-        exit 0 ;;
+        exit ;;
+    5000:UNIX_System_V:4.*:*)
+        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+        FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+        echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+	exit ;;
     i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
 	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     sparc*:BSD/OS:*:*)
 	echo sparc-unknown-bsdi${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:BSD/OS:*:*)
 	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:FreeBSD:*:*)
 	echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
-	exit 0 ;;
+	exit ;;
     i*:CYGWIN*:*)
 	echo ${UNAME_MACHINE}-pc-cygwin
-	exit 0 ;;
+	exit ;;
     i*:MINGW*:*)
 	echo ${UNAME_MACHINE}-pc-mingw32
-	exit 0 ;;
+	exit ;;
+    i*:windows32*:*)
+    	# uname -m includes "-pc" on this system.
+    	echo ${UNAME_MACHINE}-mingw32
+	exit ;;
     i*:PW*:*)
 	echo ${UNAME_MACHINE}-pc-pw32
-	exit 0 ;;
-    x86:Interix*:3*)
-	echo i386-pc-interix3
-	exit 0 ;;
+	exit ;;
+    x86:Interix*:[345]*)
+	echo i586-pc-interix${UNAME_RELEASE}|sed -e 's/\..*//'
+	exit ;;
+    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+	echo i${UNAME_MACHINE}-pc-mks
+	exit ;;
     i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
 	# How do we know it's Interix rather than the generic POSIX subsystem?
 	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
 	# UNAME_MACHINE based on the output of uname instead of i386?
-	echo i386-pc-interix
-	exit 0 ;;
+	echo i586-pc-interix
+	exit ;;
     i*:UWIN*:*)
 	echo ${UNAME_MACHINE}-pc-uwin
-	exit 0 ;;
+	exit ;;
+    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+	echo x86_64-unknown-cygwin
+	exit ;;
     p*:CYGWIN*:*)
 	echo powerpcle-unknown-cygwin
-	exit 0 ;;
+	exit ;;
     prep*:SunOS:5.*:*)
 	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
     *:GNU:*:*)
+	# the GNU system
 	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
-	exit 0 ;;
+	exit ;;
+    *:GNU/*:*:*)
+	# other systems with GNU libc and userland
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+	exit ;;
     i*86:Minix:*:*)
 	echo ${UNAME_MACHINE}-pc-minix
-	exit 0 ;;
+	exit ;;
     arm*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
+    cris:Linux:*:*)
+	echo cris-axis-linux-gnu
+	exit ;;
+    crisv32:Linux:*:*)
+	echo crisv32-axis-linux-gnu
+	exit ;;
+    frv:Linux:*:*)
+    	echo frv-unknown-linux-gnu
+	exit ;;
     ia64:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
+    m32r*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
     m68*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     mips:Linux:*:*)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
@@ -804,16 +851,37 @@
 	#endif
 	#endif
 EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
-	rm -f $dummy.c
-	test x"${CPU}" != x && echo "${CPU}-pc-linux-gnu" && exit 0
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '/^CPU/{s: ::g;p;}'`"
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	;;
+    mips64:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef mips64
+	#undef mips64el
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=mips64el
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=mips64
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '/^CPU/{s: ::g;p;}'`"
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
 	;;
+    or32:Linux:*:*)
+	echo or32-unknown-linux-gnu
+	exit ;;
     ppc:Linux:*:*)
 	echo powerpc-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     ppc64:Linux:*:*)
 	echo powerpc64-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     alpha:Linux:*:*)
 	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
 	  EV5)   UNAME_MACHINE=alphaev5 ;;
@@ -827,7 +895,7 @@
 	objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
 	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
 	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
-	exit 0 ;;
+	exit ;;
     parisc:Linux:*:* | hppa:Linux:*:*)
 	# Look for CPU level
 	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
@@ -835,22 +903,28 @@
 	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
 	  *)    echo hppa-unknown-linux-gnu ;;
 	esac
-	exit 0 ;;
+	exit ;;
     parisc64:Linux:*:* | hppa64:Linux:*:*)
 	echo hppa64-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     s390:Linux:*:* | s390x:Linux:*:*)
 	echo ${UNAME_MACHINE}-ibm-linux
-	exit 0 ;;
+	exit ;;
+    sh64*:Linux:*:*)
+    	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
     sh*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     sparc:Linux:*:* | sparc64:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
+    vax:Linux:*:*)
+	echo ${UNAME_MACHINE}-dec-linux-gnu
+	exit ;;
     x86_64:Linux:*:*)
 	echo x86_64-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
     i*86:Linux:*:*)
 	# The BFD linker knows what the default object file format is, so
 	# first see if it will tell us. cd to the root directory to prevent
@@ -868,15 +942,15 @@
 		;;
 	  a.out-i386-linux)
 		echo "${UNAME_MACHINE}-pc-linux-gnuaout"
-		exit 0 ;;		
+		exit ;;
 	  coff-i386)
 		echo "${UNAME_MACHINE}-pc-linux-gnucoff"
-		exit 0 ;;
+		exit ;;
 	  "")
 		# Either a pre-BFD a.out linker (linux-gnuoldld) or
 		# one that does not give us useful --help.
 		echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
-		exit 0 ;;
+		exit ;;
 	esac
 	# Determine whether the default compiler is a.out or elf
 	eval $set_cc_for_build
@@ -893,24 +967,29 @@
 	LIBC=gnulibc1
 	# endif
 	#else
-	#ifdef __INTEL_COMPILER
+	#if defined(__INTEL_COMPILER) || defined(__PGI)
 	LIBC=gnu
 	#else
 	LIBC=gnuaout
 	#endif
 	#endif
+	#ifdef __dietlibc__
+	LIBC=dietlibc
+	#endif
 EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=`
-	rm -f $dummy.c
-	test x"${LIBC}" != x && echo "${UNAME_MACHINE}-pc-linux-${LIBC}" && exit 0
-	test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '/^LIBC/{s: ::g;p;}'`"
+	test x"${LIBC}" != x && {
+		echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+		exit
+	}
+	test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; }
 	;;
     i*86:DYNIX/ptx:4*:*)
 	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
 	# earlier versions are messed up and put the nodename in both
 	# sysname and nodename.
 	echo i386-sequent-sysv4
-	exit 0 ;;
+	exit ;;
     i*86:UNIX_SV:4.2MP:2.*)
         # Unixware is an offshoot of SVR4, but it has its own version
         # number series starting with 2...
@@ -918,7 +997,27 @@
 	# I just have to hope.  -- rms.
         # Use sysv4.2uw... so that sysv4* matches it.
 	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
-	exit 0 ;;
+	exit ;;
+    i*86:OS/2:*:*)
+	# If we were able to find `uname', then EMX Unix compatibility
+	# is probably installed.
+	echo ${UNAME_MACHINE}-pc-os2-emx
+	exit ;;
+    i*86:XTS-300:*:STOP)
+	echo ${UNAME_MACHINE}-unknown-stop
+	exit ;;
+    i*86:atheos:*:*)
+	echo ${UNAME_MACHINE}-unknown-atheos
+	exit ;;
+    i*86:syllable:*:*)
+	echo ${UNAME_MACHINE}-pc-syllable
+	exit ;;
+    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
+	echo i386-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    i*86:*DOS:*:*)
+	echo ${UNAME_MACHINE}-pc-msdosdjgpp
+	exit ;;
     i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
 	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
 	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
@@ -926,99 +1025,100 @@
 	else
 		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
 	fi
-	exit 0 ;;
-    i*86:*:5:[78]*)
+	exit ;;
+    i*86:*:5:[678]*)
+    	# UnixWare 7.x, OpenUNIX and OpenServer 6.
 	case `/bin/uname -X | grep "^Machine"` in
 	    *486*)	     UNAME_MACHINE=i486 ;;
 	    *Pentium)	     UNAME_MACHINE=i586 ;;
 	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
 	esac
 	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
-	exit 0 ;;
+	exit ;;
     i*86:*:3.2:*)
 	if test -f /usr/options/cb.name; then
 		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
 		echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
 	elif /bin/uname -X 2>/dev/null >/dev/null ; then
-		UNAME_REL=`(/bin/uname -X|egrep Release|sed -e 's/.*= //')`
-		(/bin/uname -X|egrep i80486 >/dev/null) && UNAME_MACHINE=i486
-		(/bin/uname -X|egrep '^Machine.*Pentium' >/dev/null) \
+		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
 			&& UNAME_MACHINE=i586
-		(/bin/uname -X|egrep '^Machine.*Pent ?II' >/dev/null) \
+		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
 			&& UNAME_MACHINE=i686
-		(/bin/uname -X|egrep '^Machine.*Pentium Pro' >/dev/null) \
+		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
 			&& UNAME_MACHINE=i686
 		echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
 	else
 		echo ${UNAME_MACHINE}-pc-sysv32
 	fi
-	exit 0 ;;
-    i*86:*DOS:*:*)
-	echo ${UNAME_MACHINE}-pc-msdosdjgpp
-	exit 0 ;;
+	exit ;;
     pc:*:*:*)
 	# Left here for compatibility:
         # uname -m prints for DJGPP always 'pc', but it prints nothing about
         # the processor, so we play safe by assuming i386.
 	echo i386-pc-msdosdjgpp
-        exit 0 ;;
+        exit ;;
     Intel:Mach:3*:*)
 	echo i386-pc-mach3
-	exit 0 ;;
+	exit ;;
     paragon:*:*:*)
 	echo i860-intel-osf1
-	exit 0 ;;
+	exit ;;
     i860:*:4.*:*) # i860-SVR4
 	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
 	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
 	else # Add other i860-SVR4 vendors below as they are discovered.
 	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
 	fi
-	exit 0 ;;
+	exit ;;
     mini*:CTIX:SYS*5:*)
 	# "miniframe"
 	echo m68010-convergent-sysv
-	exit 0 ;;
-    M68*:*:R3V[567]*:*)
-	test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;;
-    3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0)
+	exit ;;
+    mc68k:UNIX:SYSTEM5:3.51m)
+	echo m68k-convergent-sysv
+	exit ;;
+    M680?0:D-NIX:5.3:*)
+	echo m68k-diab-dnix
+	exit ;;
+    M68*:*:R3V[5678]*:*)
+	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
 	OS_REL=''
 	test -r /etc/.relid \
 	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
 	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-	  && echo i486-ncr-sysv4.3${OS_REL} && exit 0
+	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
 	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
-	  && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;;
+	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
     3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
         /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-          && echo i486-ncr-sysv4 && exit 0 ;;
+          && { echo i486-ncr-sysv4; exit; } ;;
     m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
 	echo m68k-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     mc68030:UNIX_System_V:4.*:*)
 	echo m68k-atari-sysv4
-	exit 0 ;;
-    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
-	echo i386-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     TSUNAMI:LynxOS:2.*:*)
 	echo sparc-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     rs6000:LynxOS:2.*:*)
 	echo rs6000-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
 	echo powerpc-unknown-lynxos${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     SM[BE]S:UNIX_SV:*:*)
 	echo mips-dde-sysv${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     RM*:ReliantUNIX-*:*:*)
 	echo mips-sni-sysv4
-	exit 0 ;;
+	exit ;;
     RM*:SINIX-*:*:*)
 	echo mips-sni-sysv4
-	exit 0 ;;
+	exit ;;
     *:SINIX-*:*:*)
 	if uname -p 2>/dev/null >/dev/null ; then
 		UNAME_MACHINE=`(uname -p) 2>/dev/null`
@@ -1026,61 +1126,72 @@
 	else
 		echo ns32k-sni-sysv
 	fi
-	exit 0 ;;
+	exit ;;
     PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
                       # says <Richard.M.Bartel at ccMail.Census.GOV>
         echo i586-unisys-sysv4
-        exit 0 ;;
+        exit ;;
     *:UNIX_System_V:4*:FTX*)
 	# From Gerald Hewes <hewes at openmarket.com>.
 	# How about differentiating between stratus architectures? -djm
 	echo hppa1.1-stratus-sysv4
-	exit 0 ;;
+	exit ;;
     *:*:*:FTX*)
 	# From seanf at swdc.stratus.com.
 	echo i860-stratus-sysv4
-	exit 0 ;;
+	exit ;;
+    i*86:VOS:*:*)
+	# From Paul.Green at stratus.com.
+	echo ${UNAME_MACHINE}-stratus-vos
+	exit ;;
     *:VOS:*:*)
 	# From Paul.Green at stratus.com.
 	echo hppa1.1-stratus-vos
-	exit 0 ;;
+	exit ;;
     mc68*:A/UX:*:*)
 	echo m68k-apple-aux${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     news*:NEWS-OS:6*:*)
 	echo mips-sony-newsos6
-	exit 0 ;;
+	exit ;;
     R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
 	if [ -d /usr/nec ]; then
 	        echo mips-nec-sysv${UNAME_RELEASE}
 	else
 	        echo mips-unknown-sysv${UNAME_RELEASE}
 	fi
-        exit 0 ;;
+        exit ;;
     BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
 	echo powerpc-be-beos
-	exit 0 ;;
+	exit ;;
     BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
 	echo powerpc-apple-beos
-	exit 0 ;;
+	exit ;;
     BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
 	echo i586-pc-beos
-	exit 0 ;;
+	exit ;;
     SX-4:SUPER-UX:*:*)
 	echo sx4-nec-superux${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     SX-5:SUPER-UX:*:*)
 	echo sx5-nec-superux${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
+    SX-6:SUPER-UX:*:*)
+	echo sx6-nec-superux${UNAME_RELEASE}
+	exit ;;
     Power*:Rhapsody:*:*)
 	echo powerpc-apple-rhapsody${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:Rhapsody:*:*)
 	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:Darwin:*:*)
-	echo `uname -p`-apple-darwin${UNAME_RELEASE}
-	exit 0 ;;
+	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+	case $UNAME_PROCESSOR in
+	    unknown) UNAME_PROCESSOR=powerpc ;;
+	esac
+	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+	exit ;;
     *:procnto*:*:* | *:QNX:[0123456789]*:*)
 	UNAME_PROCESSOR=`uname -p`
 	if test "$UNAME_PROCESSOR" = "x86"; then
@@ -1088,22 +1199,25 @@
 		UNAME_MACHINE=pc
 	fi
 	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:QNX:*:4*)
 	echo i386-pc-qnx
-	exit 0 ;;
-    NSR-[GKLNPTVW]:NONSTOP_KERNEL:*:*)
+	exit ;;
+    NSE-?:NONSTOP_KERNEL:*:*)
+	echo nse-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    NSR-?:NONSTOP_KERNEL:*:*)
 	echo nsr-tandem-nsk${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:NonStop-UX:*:*)
 	echo mips-compaq-nonstopux
-	exit 0 ;;
+	exit ;;
     BS2000:POSIX*:*:*)
 	echo bs2000-siemens-sysv
-	exit 0 ;;
+	exit ;;
     DS/*:UNIX_System_V:*:*)
 	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:Plan9:*:*)
 	# "uname -m" is not consistent, so use $cputype instead. 386
 	# is converted to i386 for consistency with other x86
@@ -1114,36 +1228,47 @@
 	    UNAME_MACHINE="$cputype"
 	fi
 	echo ${UNAME_MACHINE}-unknown-plan9
-	exit 0 ;;
-    i*86:OS/2:*:*)
-	# If we were able to find `uname', then EMX Unix compatibility
-	# is probably installed.
-	echo ${UNAME_MACHINE}-pc-os2-emx
-	exit 0 ;;
+	exit ;;
     *:TOPS-10:*:*)
 	echo pdp10-unknown-tops10
-	exit 0 ;;
+	exit ;;
     *:TENEX:*:*)
 	echo pdp10-unknown-tenex
-	exit 0 ;;
+	exit ;;
     KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
 	echo pdp10-dec-tops20
-	exit 0 ;;
+	exit ;;
     XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
 	echo pdp10-xkl-tops20
-	exit 0 ;;
+	exit ;;
     *:TOPS-20:*:*)
 	echo pdp10-unknown-tops20
-	exit 0 ;;
+	exit ;;
     *:ITS:*:*)
 	echo pdp10-unknown-its
-	exit 0 ;;
-    i*86:XTS-300:*:STOP)
-	echo ${UNAME_MACHINE}-unknown-stop
-	exit 0 ;;
-    i*86:atheos:*:*)
-	echo ${UNAME_MACHINE}-unknown-atheos
-	exit 0 ;;
+	exit ;;
+    SEI:*:*:SEIUX)
+        echo mips-sei-seiux${UNAME_RELEASE}
+	exit ;;
+    *:DragonFly:*:*)
+	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+	exit ;;
+    *:*VMS:*:*)
+    	UNAME_MACHINE=`(uname -p) 2>/dev/null`
+	case "${UNAME_MACHINE}" in
+	    A*) echo alpha-dec-vms ; exit ;;
+	    I*) echo ia64-dec-vms ; exit ;;
+	    V*) echo vax-dec-vms ; exit ;;
+	esac ;;
+    *:XENIX:*:SysV)
+	echo i386-pc-xenix
+	exit ;;
+    i*86:skyos:*:*)
+	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+	exit ;;
+    i*86:rdos:*:*)
+	echo ${UNAME_MACHINE}-pc-rdos
+	exit ;;
 esac
 
 #echo '(No uname command or uname output not recognized.)' 1>&2
@@ -1175,7 +1300,7 @@
 #endif
 
 #if defined (__arm) && defined (__acorn) && defined (__unix)
-  printf ("arm-acorn-riscix"); exit (0);
+  printf ("arm-acorn-riscix\n"); exit (0);
 #endif
 
 #if defined (hp300) && !defined (hpux)
@@ -1264,12 +1389,12 @@
 }
 EOF
 
-$CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy && rm -f $dummy.c $dummy && exit 0
-rm -f $dummy.c $dummy
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
+	{ echo "$SYSTEM_NAME"; exit; }
 
 # Apollos put the system type in the environment.
 
-test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; }
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
 
 # Convex versions that predate uname can use getsysinfo(1)
 
@@ -1278,22 +1403,22 @@
     case `getsysinfo -f cpu_type` in
     c1*)
 	echo c1-convex-bsd
-	exit 0 ;;
+	exit ;;
     c2*)
 	if getsysinfo -f scalar_acc
 	then echo c32-convex-bsd
 	else echo c2-convex-bsd
 	fi
-	exit 0 ;;
+	exit ;;
     c34*)
 	echo c34-convex-bsd
-	exit 0 ;;
+	exit ;;
     c38*)
 	echo c38-convex-bsd
-	exit 0 ;;
+	exit ;;
     c4*)
 	echo c4-convex-bsd
-	exit 0 ;;
+	exit ;;
     esac
 fi
 
@@ -1304,7 +1429,9 @@
 the operating system you are using. It is advised that you
 download the most up to date version of the config scripts from
 
-    ftp://ftp.gnu.org/pub/gnu/config/
+  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess
+and
+  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub
 
 If the version you run ($0) is already up to date, please
 send the following data and any information you think might be

Modified: freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/config.sub
==============================================================================
--- freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/config.sub	(original)
+++ freeswitch/branches/cparker/libs/apr-util/xml/expat/conftools/config.sub	Tue Apr 24 10:14:28 2007
@@ -1,9 +1,9 @@
 #! /bin/sh
 # Configuration validation subroutine script.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002 Free Software Foundation, Inc.
+#   2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
 
-timestamp='2002-03-07'
+timestamp='2005-12-11'
 
 # This file is (in principle) common to ALL GNU software.
 # The presence of a machine in this file suggests that SOME GNU software
@@ -21,18 +21,14 @@
 #
 # 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.
-
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
 # configuration script generated by Autoconf, you may include it under
 # the same distribution terms that you use for the rest of that program.
 
-#####################################################################
-# This file contains changes for Apache, clearly marked below.
-# These changes are hereby donated to the public domain.
-#####################################################################
 
 # Please send patches to <config-patches at gnu.org>.  Submit a context
 # diff and a properly formatted ChangeLog entry.
@@ -75,7 +71,7 @@
 version="\
 GNU config.sub ($timestamp)
 
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
@@ -88,11 +84,11 @@
 while test $# -gt 0 ; do
   case $1 in
     --time-stamp | --time* | -t )
-       echo "$timestamp" ; exit 0 ;;
+       echo "$timestamp" ; exit ;;
     --version | -v )
-       echo "$version" ; exit 0 ;;
+       echo "$version" ; exit ;;
     --help | --h* | -h )
-       echo "$usage"; exit 0 ;;
+       echo "$usage"; exit ;;
     -- )     # Stop option processing
        shift; break ;;
     - )	# Use stdin as input.
@@ -104,7 +100,7 @@
     *local*)
        # First pass through any local machine types.
        echo $1
-       exit 0;;
+       exit ;;
 
     * )
        break ;;
@@ -123,28 +119,12 @@
 # Here we must recognize all the valid KERNEL-OS combinations.
 maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
 case $maybe_os in
-  nto-qnx* | linux-gnu* | storm-chaos* | os2-emx* | windows32-* | rtmk-nova*)
+  nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \
+  uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \
+  storm-chaos* | os2-emx* | rtmk-nova*)
     os=-$maybe_os
     basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
     ;;
-########################
-# changes for Apache
-#
-  tpf | os390 | vmcms)
-    os=-$maybe_os
-    basic_machine=s390;
-    ;;
-  os400)
-    os=-$maybe_os
-    basic_machine=as400;
-    ;;
-  mvs)
-    os=-mvs
-    basic_machine=i370;
-    ;;
-#
-# end Apache changes
-########################
   *)
     basic_machine=`echo $1 | sed 's/-[^-]*$//'`
     if [ $basic_machine != $1 ]
@@ -167,7 +147,7 @@
 	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
 	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
 	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
-	-apple | -axis)
+	-apple | -axis | -knuth | -cray)
 		os=
 		basic_machine=$1
 		;;
@@ -192,6 +172,10 @@
 	-hiux*)
 		os=-hiuxwe2
 		;;
+	-sco6)
+		os=-sco5v6
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
 	-sco5)
 		os=-sco3.2v5
 		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
@@ -208,6 +192,10 @@
 		# Don't forget version if it is 3.2v4 or newer.
 		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
 		;;
+	-sco5v6*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
 	-sco*)
 		os=-sco3.2v2
 		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
@@ -251,34 +239,55 @@
 	| a29k \
 	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
 	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+	| am33_2.0 \
 	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \
+	| bfin \
 	| c4x | clipper \
-	| d10v | d30v | dsp16xx \
-	| fr30 \
+	| d10v | d30v | dlx | dsp16xx \
+	| fr30 | frv \
 	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
 	| i370 | i860 | i960 | ia64 \
-	| m32r | m68000 | m68k | m88k | mcore \
-	| mips | mips16 | mips64 | mips64el | mips64orion | mips64orionel \
-	| mips64vr4100 | mips64vr4100el | mips64vr4300 \
-	| mips64vr4300el | mips64vr5000 | mips64vr5000el \
-	| mipsbe | mipseb | mipsel | mipsle | mipstx39 | mipstx39el \
-	| mipsisa32 | mipsisa64 \
+	| ip2k | iq2000 \
+	| m32r | m32rle | m68000 | m68k | m88k | maxq | mcore \
+	| mips | mipsbe | mipseb | mipsel | mipsle \
+	| mips16 \
+	| mips64 | mips64el \
+	| mips64vr | mips64vrel \
+	| mips64orion | mips64orionel \
+	| mips64vr4100 | mips64vr4100el \
+	| mips64vr4300 | mips64vr4300el \
+	| mips64vr5000 | mips64vr5000el \
+	| mips64vr5900 | mips64vr5900el \
+	| mipsisa32 | mipsisa32el \
+	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa64 | mipsisa64el \
+	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64sb1 | mipsisa64sb1el \
+	| mipsisa64sr71k | mipsisa64sr71kel \
+	| mipstx39 | mipstx39el \
 	| mn10200 | mn10300 \
+	| mt \
+	| msp430 \
 	| ns16k | ns32k \
-	| openrisc | or32 \
+	| or32 \
 	| pdp10 | pdp11 | pj | pjl \
 	| powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
 	| pyramid \
-	| sh | sh[34] | sh[34]eb | shbe | shle | sh64 \
-	| sparc | sparc64 | sparc86x | sparclet | sparclite | sparcv9 | sparcv9b \
+	| sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \
+	| sh64 | sh64le \
+	| sparc | sparc64 | sparc64b | sparc86x | sparclet | sparclite \
+	| sparcv8 | sparcv9 | sparcv9b \
 	| strongarm \
-	| tahoe | thumb | tic80 | tron \
+	| tahoe | thumb | tic4x | tic80 | tron \
 	| v850 | v850e \
 	| we32k \
-	| x86 | xscale | xstormy16 | xtensa \
+	| x86 | xscale | xscalee[bl] | xstormy16 | xtensa \
 	| z8k)
 		basic_machine=$basic_machine-unknown
 		;;
+	m32c)
+		basic_machine=$basic_machine-unknown
+		;;
 	m6811 | m68hc11 | m6812 | m68hc12)
 		# Motorola 68HC11/12.
 		basic_machine=$basic_machine-unknown
@@ -286,6 +295,9 @@
 		;;
 	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
 		;;
+	ms1)
+		basic_machine=mt-unknown
+		;;
 
 	# We use `pc' rather than `unknown'
 	# because (1) that's what they normally are, and
@@ -304,41 +316,63 @@
 	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
 	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
 	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
-	| arm-*  | armbe-* | armle-* | armv*-* \
+	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
 	| avr-* \
-	| bs2000-* \
-	| c[123]* | c30-* | [cjt]90-* | c54x-* \
-	| clipper-* | cydra-* \
-	| d10v-* | d30v-* \
+	| bfin-* | bs2000-* \
+	| c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
+	| clipper-* | craynv-* | cydra-* \
+	| d10v-* | d30v-* | dlx-* \
 	| elxsi-* \
-	| f30[01]-* | f700-* | fr30-* | fx80-* \
+	| f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
 	| h8300-* | h8500-* \
 	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
 	| i*86-* | i860-* | i960-* | ia64-* \
-	| m32r-* \
+	| ip2k-* | iq2000-* \
+	| m32r-* | m32rle-* \
 	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
-	| m88110-* | m88k-* | mcore-* \
-	| mips-* | mips16-* | mips64-* | mips64el-* | mips64orion-* \
-	| mips64orionel-* | mips64vr4100-* | mips64vr4100el-* \
-	| mips64vr4300-* | mips64vr4300el-* | mipsbe-* | mipseb-* \
-	| mipsle-* | mipsel-* | mipstx39-* | mipstx39el-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* \
+	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+	| mips16-* \
+	| mips64-* | mips64el-* \
+	| mips64vr-* | mips64vrel-* \
+	| mips64orion-* | mips64orionel-* \
+	| mips64vr4100-* | mips64vr4100el-* \
+	| mips64vr4300-* | mips64vr4300el-* \
+	| mips64vr5000-* | mips64vr5000el-* \
+	| mips64vr5900-* | mips64vr5900el-* \
+	| mipsisa32-* | mipsisa32el-* \
+	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa64-* | mipsisa64el-* \
+	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64sb1-* | mipsisa64sb1el-* \
+	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+	| mipstx39-* | mipstx39el-* \
+	| mmix-* \
+	| mt-* \
+	| msp430-* \
 	| none-* | np1-* | ns16k-* | ns32k-* \
 	| orion-* \
 	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
 	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
 	| pyramid-* \
 	| romp-* | rs6000-* \
-	| sh-* | sh[34]-* | sh[34]eb-* | shbe-* | shle-* | sh64-* \
-	| sparc-* | sparc64-* | sparc86x-* | sparclet-* | sparclite-* \
-	| sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \
-	| tahoe-* | thumb-* | tic30-* | tic54x-* | tic80-* | tron-* \
+	| sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | shbe-* \
+	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+	| sparc-* | sparc64-* | sparc64b-* | sparc86x-* | sparclet-* \
+	| sparclite-* \
+	| sparcv8-* | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \
+	| tahoe-* | thumb-* \
+	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+	| tron-* \
 	| v850-* | v850e-* | vax-* \
 	| we32k-* \
-	| x86-* | x86_64-* | xps100-* | xscale-* | xstormy16-* \
-	| xtensa-* \
+	| x86-* | x86_64-* | xps100-* | xscale-* | xscalee[bl]-* \
+	| xstormy16-* | xtensa-* \
 	| ymp-* \
 	| z8k-*)
 		;;
+	m32c-*)
+		;;
 	# Recognize the various machine names and aliases which stand
 	# for a CPU type and a company and sometimes even an OS.
 	386bsd)
@@ -355,6 +389,9 @@
 		basic_machine=a29k-amd
 		os=-udi
 		;;
+    	abacus)
+		basic_machine=abacus-unknown
+		;;
 	adobe68k)
 		basic_machine=m68010-adobe
 		os=-scout
@@ -369,6 +406,12 @@
 		basic_machine=a29k-none
 		os=-bsd
 		;;
+	amd64)
+		basic_machine=x86_64-pc
+		;;
+	amd64-*)
+		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
 	amdahl)
 		basic_machine=580-amdahl
 		os=-sysv
@@ -428,12 +471,27 @@
 		basic_machine=j90-cray
 		os=-unicos
 		;;
+	craynv)
+		basic_machine=craynv-cray
+		os=-unicosmp
+		;;
+	cr16c)
+		basic_machine=cr16c-unknown
+		os=-elf
+		;;
 	crds | unos)
 		basic_machine=m68k-crds
 		;;
+	crisv32 | crisv32-* | etraxfs*)
+		basic_machine=crisv32-axis
+		;;
 	cris | cris-* | etrax*)
 		basic_machine=cris-axis
 		;;
+	crx)
+		basic_machine=crx-unknown
+		os=-elf
+		;;
 	da30 | da30-*)
 		basic_machine=m68k-da30
 		;;
@@ -456,6 +514,10 @@
 		basic_machine=m88k-motorola
 		os=-sysv3
 		;;
+	djgpp)
+		basic_machine=i586-pc
+		os=-msdosdjgpp
+		;;
 	dpx20 | dpx20-*)
 		basic_machine=rs6000-bull
 		os=-bosx
@@ -634,10 +696,6 @@
 	mips3*)
 		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
 		;;
-	mmix*)
-		basic_machine=mmix-knuth
-		os=-mmixware
-		;;
 	monitor)
 		basic_machine=m68k-rom68k
 		os=-coff
@@ -650,6 +708,9 @@
 		basic_machine=i386-pc
 		os=-msdos
 		;;
+	ms1-*)
+		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+		;;
 	mvs)
 		basic_machine=i370-ibm
 		os=-mvs
@@ -725,9 +786,12 @@
 		basic_machine=hppa1.1-oki
 		os=-proelf
 		;;
-	or32 | or32-*)
+	openrisc | openrisc-*)
 		basic_machine=or32-unknown
-		os=-coff
+		;;
+	os400)
+		basic_machine=powerpc-ibm
+		os=-os400
 		;;
 	OSE68000 | ose68000)
 		basic_machine=m68000-ericsson
@@ -751,49 +815,55 @@
 	pbb)
 		basic_machine=m68k-tti
 		;;
-        pc532 | pc532-*)
+	pc532 | pc532-*)
 		basic_machine=ns32k-pc532
 		;;
 	pentium | p5 | k5 | k6 | nexgen | viac3)
 		basic_machine=i586-pc
 		;;
-	pentiumpro | p6 | 6x86 | athlon)
+	pentiumpro | p6 | 6x86 | athlon | athlon_*)
 		basic_machine=i686-pc
 		;;
-	pentiumii | pentium2)
+	pentiumii | pentium2 | pentiumiii | pentium3)
 		basic_machine=i686-pc
 		;;
+	pentium4)
+		basic_machine=i786-pc
+		;;
 	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
 		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
 	pentiumpro-* | p6-* | 6x86-* | athlon-*)
 		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
-	pentiumii-* | pentium2-*)
+	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
 		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
+	pentium4-*)
+		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
 	pn)
 		basic_machine=pn-gould
 		;;
 	power)	basic_machine=power-ibm
 		;;
 	ppc)	basic_machine=powerpc-unknown
-	        ;;
+		;;
 	ppc-*)	basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
 	ppcle | powerpclittle | ppc-le | powerpc-little)
 		basic_machine=powerpcle-unknown
-	        ;;
+		;;
 	ppcle-* | powerpclittle-*)
 		basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
 	ppc64)	basic_machine=powerpc64-unknown
-	        ;;
+		;;
 	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
 	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
 		basic_machine=powerpc64le-unknown
-	        ;;
+		;;
 	ppc64le-* | powerpc64little-*)
 		basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
@@ -804,6 +874,10 @@
 		basic_machine=i586-unknown
 		os=-pw32
 		;;
+	rdos)
+		basic_machine=i386-pc
+		os=-rdos
+		;;
 	rom68k)
 		basic_machine=m68k-rom68k
 		os=-coff
@@ -824,15 +898,16 @@
 		basic_machine=a29k-amd
 		os=-udi
 		;;
-########################
-# changes for Apache
-#
-	as400*)
-		basic_machine=as400-ibm
+	sb1)
+		basic_machine=mipsisa64sb1-unknown
+		;;
+	sb1el)
+		basic_machine=mipsisa64sb1el-unknown
+		;;
+	sei)
+		basic_machine=mips-sei
+		os=-seiux
 		;;
-# 
-# end Apache changes
-########################
 	sequent)
 		basic_machine=i386-sequent
 		;;
@@ -840,6 +915,9 @@
 		basic_machine=sh-hitachi
 		os=-hms
 		;;
+	sh64)
+		basic_machine=sh64-unknown
+		;;
 	sparclite-wrs | simso-wrs)
 		basic_machine=sparclite-wrs
 		os=-vxworks
@@ -898,7 +976,7 @@
 	sun386 | sun386i | roadrunner)
 		basic_machine=i386-sun
 		;;
-        sv1)
+	sv1)
 		basic_machine=sv1-cray
 		os=-unicos
 		;;
@@ -906,10 +984,6 @@
 		basic_machine=i386-sequent
 		os=-dynix
 		;;
-	t3d)
-		basic_machine=alpha-cray
-		os=-unicos
-		;;
 	t3e)
 		basic_machine=alphaev5-cray
 		os=-unicos
@@ -922,6 +996,14 @@
 		basic_machine=tic54x-unknown
 		os=-coff
 		;;
+	tic55x | c55x*)
+		basic_machine=tic55x-unknown
+		os=-coff
+		;;
+	tic6x | c6x*)
+		basic_machine=tic6x-unknown
+		os=-coff
+		;;
 	tx39)
 		basic_machine=mipstx39-unknown
 		;;
@@ -935,6 +1017,10 @@
 	tower | tower-32)
 		basic_machine=m68k-ncr
 		;;
+	tpf)
+		basic_machine=s390x-ibm
+		os=-tpf
+		;;
 	udi29k)
 		basic_machine=a29k-amd
 		os=-udi
@@ -956,8 +1042,8 @@
 		os=-vms
 		;;
 	vpp*|vx|vx-*)
-               basic_machine=f301-fujitsu
-               ;;
+		basic_machine=f301-fujitsu
+		;;
 	vxworks960)
 		basic_machine=i960-wrs
 		os=-vxworks
@@ -978,11 +1064,11 @@
 		basic_machine=hppa1.1-winbond
 		os=-proelf
 		;;
-	windows32)
-		basic_machine=i386-pc
-		os=-windows32-msvcrt
+	xbox)
+		basic_machine=i686-pc
+		os=-mingw32
 		;;
-        xps | xps100)
+	xps | xps100)
 		basic_machine=xps100-honeywell
 		;;
 	ymp)
@@ -1012,6 +1098,9 @@
 	romp)
 		basic_machine=romp-ibm
 		;;
+	mmix)
+		basic_machine=mmix-knuth
+		;;
 	rs6000)
 		basic_machine=rs6000-ibm
 		;;
@@ -1028,16 +1117,13 @@
 	we32k)
 		basic_machine=we32k-att
 		;;
-	sh3 | sh4 | sh3eb | sh4eb)
+	sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele)
 		basic_machine=sh-unknown
 		;;
-	sh64)
-		basic_machine=sh64-unknown
-		;;
-	sparc | sparcv9 | sparcv9b)
+	sparc | sparcv8 | sparcv9 | sparcv9b)
 		basic_machine=sparc-sun
 		;;
-        cydra)
+	cydra)
 		basic_machine=cydra-cydrome
 		;;
 	orion)
@@ -1052,10 +1138,6 @@
 	pmac | pmac-mpw)
 		basic_machine=powerpc-apple
 		;;
-	c4x*)
-		basic_machine=c4x-none
-		os=-coff
-		;;
 	*-unknown)
 		# Make sure to match an already-canonicalized machine name.
 		;;
@@ -1100,14 +1182,6 @@
 	-gnu/linux*)
 		os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
 		;;
-########################
-# changes for Apache
-#
-	-os2_emx | -tpf* | -os390* | -vmcms* | -os400* )
-        	;;
-#
-# end Apache changes
-########################
 	# First accept the basic system types.
 	# The portable systems comes first.
 	# Each alternative MUST END IN A *, to match a version number.
@@ -1119,18 +1193,22 @@
 	      | -aos* \
 	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
 	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
-	      | -hiux* | -386bsd* | -netbsd* | -openbsd* | -freebsd* | -riscix* \
-	      | -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* | -openbsd* \
+	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
 	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
 	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
 	      | -chorusos* | -chorusrdb* \
 	      | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
-	      | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \
-	      | -interix* | -uwin* | -rhapsody* | -darwin* | -opened* \
+	      | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
 	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
 	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
 	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
-	      | -morphos* | -superux* | -rtmk* | -rtmk-nova*)
+	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+	      | -skyos* | -haiku* | -rdos*)
 	# Remember, each alternative MUST END IN *, to match a version number.
 		;;
 	-qnx*)
@@ -1142,16 +1220,21 @@
 			;;
 		esac
 		;;
+	-nto-qnx*)
+		;;
 	-nto*)
-		os=-nto-qnx
+		os=`echo $os | sed -e 's|nto|nto-qnx|'`
 		;;
 	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
-	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* \
+	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
 	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
 		;;
 	-mac*)
 		os=`echo $os | sed -e 's|mac|macos|'`
 		;;
+	-linux-dietlibc)
+		os=-linux-dietlibc
+		;;
 	-linux*)
 		os=`echo $os | sed -e 's|linux|linux-gnu|'`
 		;;
@@ -1164,6 +1247,9 @@
 	-opened*)
 		os=-openedition
 		;;
+        -os400*)
+		os=-os400
+		;;
 	-wince*)
 		os=-wince
 		;;
@@ -1185,6 +1271,9 @@
 	-atheos*)
 		os=-atheos
 		;;
+	-syllable*)
+		os=-syllable
+		;;
 	-386bsd)
 		os=-bsd
 		;;
@@ -1195,7 +1284,7 @@
 		os=-rtmk-nova
 		;;
 	-ns2 )
-	        os=-nextstep2
+		os=-nextstep2
 		;;
 	-nsk*)
 		os=-nsk
@@ -1207,6 +1296,9 @@
 	-sinix*)
 		os=-sysv4
 		;;
+        -tpf*)
+		os=-tpf
+		;;
 	-triton*)
 		os=-sysv3
 		;;
@@ -1234,8 +1326,17 @@
 	-xenix)
 		os=-xenix
 		;;
-        -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
-	        os=-mint
+	-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+		os=-mint
+		;;
+	-aros*)
+		os=-aros
+		;;
+	-kaos*)
+		os=-kaos
+		;;
+	-zvmoe)
+		os=-zvmoe
 		;;
 	-none)
 		;;
@@ -1268,11 +1369,14 @@
 	arm*-semi)
 		os=-aout
 		;;
+    c4x-* | tic4x-*)
+        os=-coff
+        ;;
 	# This must come before the *-dec entry.
 	pdp10-*)
 		os=-tops20
 		;;
-        pdp11-*)
+	pdp11-*)
 		os=-none
 		;;
 	*-dec | vax-*)
@@ -1311,33 +1415,15 @@
 	*-be)
 		os=-beos
 		;;
-########################
-# changes for Apache
-#
-#	*-ibm)
-#		os=-aix
-#		;;
-#
+	*-haiku)
+		os=-haiku
+		;;
 	*-ibm)
-		case $basic_machine in
-			s390*)
-				os=-os390;
-				;;
-			i370*)
-				os=-mvs;
-				;;
-			as400*)
-				os=-os400;
-				;;
-			*)
-				os=-aix
-				;;
-		esac
-                ;;
-# 
-# end Apache changes
-########################
-
+		os=-aix
+		;;
+    	*-knuth)
+		os=-mmixware
+		;;
 	*-wec)
 		os=-proelf
 		;;
@@ -1389,19 +1475,19 @@
 	*-next)
 		os=-nextstep3
 		;;
-        *-gould)
+	*-gould)
 		os=-sysv
 		;;
-        *-highlevel)
+	*-highlevel)
 		os=-bsd
 		;;
 	*-encore)
 		os=-bsd
 		;;
-        *-sgi)
+	*-sgi)
 		os=-irix
 		;;
-        *-siemens)
+	*-siemens)
 		os=-sysv4
 		;;
 	*-masscomp)
@@ -1470,10 +1556,16 @@
 			-mvs* | -opened*)
 				vendor=ibm
 				;;
+			-os400*)
+				vendor=ibm
+				;;
 			-ptx*)
 				vendor=sequent
 				;;
-			-vxsim* | -vxworks*)
+			-tpf*)
+				vendor=ibm
+				;;
+			-vxsim* | -vxworks* | -windiss*)
 				vendor=wrs
 				;;
 			-aux*)
@@ -1497,7 +1589,7 @@
 esac
 
 echo $basic_machine$os
-exit 0
+exit
 
 # Local variables:
 # eval: (add-hook 'write-file-hooks 'time-stamp)

Modified: freeswitch/branches/cparker/libs/apr-util/xml/expat/lib/winconfig.h
==============================================================================
--- freeswitch/branches/cparker/libs/apr-util/xml/expat/lib/winconfig.h	(original)
+++ freeswitch/branches/cparker/libs/apr-util/xml/expat/lib/winconfig.h	Tue Apr 24 10:14:28 2007
@@ -23,5 +23,6 @@
 #define XML_DTD 1
 #define XML_BYTE_ORDER 12
 #define XML_CONTEXT_BYTES 1024
+#define HAVE_MEMMOVE
 
 #endif /* ndef WINCONFIG_H */

Modified: freeswitch/branches/cparker/libs/apr-util/xml/expat/lib/xmlparse.c
==============================================================================
--- freeswitch/branches/cparker/libs/apr-util/xml/expat/lib/xmlparse.c	(original)
+++ freeswitch/branches/cparker/libs/apr-util/xml/expat/lib/xmlparse.c	Tue Apr 24 10:14:28 2007
@@ -14,6 +14,14 @@
 #else
 #include <config.h>
 
+#ifndef HAVE_MEMMOVE
+#ifdef HAVE_BCOPY
+#define memmove(d,s,l) bcopy((s),(d),(l))
+#else
+#define memmove(d,s,l) ;punting on memmove;
+#endif
+#endif
+
 #ifdef HAVE_STRING_H
 #  include <string.h>
 #endif

Modified: freeswitch/branches/cparker/libs/apr/build/apr_common.m4
==============================================================================
--- freeswitch/branches/cparker/libs/apr/build/apr_common.m4	(original)
+++ freeswitch/branches/cparker/libs/apr/build/apr_common.m4	Tue Apr 24 10:14:28 2007
@@ -23,7 +23,7 @@
 dnl
 dnl Saves a snapshot of the configure command-line for later reuse
 dnl
-AC_DEFUN(APR_CONFIG_NICE,[
+AC_DEFUN([APR_CONFIG_NICE],[
   rm -f $1
   cat >$1<<EOF
 #! /bin/sh
@@ -80,7 +80,7 @@
 
 dnl APR_MKDIR_P_CHECK(fallback-mkdir-p)
 dnl checks whether mkdir -p works
-AC_DEFUN(APR_MKDIR_P_CHECK,[
+AC_DEFUN([APR_MKDIR_P_CHECK],[
   AC_CACHE_CHECK(for working mkdir -p, ac_cv_mkdir_p,[
     test -d conftestdir && rm -rf conftestdir
     mkdir -p conftestdir/somedir >/dev/null 2>&1
@@ -118,7 +118,7 @@
 dnl Trying to optimize this is left as an exercise to the reader who wants
 dnl to put up with more autoconf craziness.  I give up.
 dnl
-AC_DEFUN(APR_SUBDIR_CONFIG, [
+AC_DEFUN([APR_SUBDIR_CONFIG], [
   # save our work to this point; this allows the sub-package to use it
   AC_CACHE_SAVE
 
@@ -186,7 +186,7 @@
 dnl
 dnl Stores the variable (usually a Makefile macro) for later restoration
 dnl
-AC_DEFUN(APR_SAVE_THE_ENVIRONMENT,[
+AC_DEFUN([APR_SAVE_THE_ENVIRONMENT],[
   apr_ste_save_$1="$$1"
 ])dnl
 
@@ -198,7 +198,7 @@
 dnl and restoring the original variable contents.  This makes it possible
 dnl for a user to override configure when it does something stupid.
 dnl
-AC_DEFUN(APR_RESTORE_THE_ENVIRONMENT,[
+AC_DEFUN([APR_RESTORE_THE_ENVIRONMENT],[
 if test "x$apr_ste_save_$1" = "x"; then
   $2$1="$$1"
   $1=
@@ -222,7 +222,7 @@
 dnl
 dnl  Set variable iff it's currently null
 dnl
-AC_DEFUN(APR_SETIFNULL,[
+AC_DEFUN([APR_SETIFNULL],[
   if test -z "$$1"; then
     test "x$silent" != "xyes" && echo "  setting $1 to \"$2\""
     $1="$2"
@@ -234,7 +234,7 @@
 dnl
 dnl  Set variable no matter what
 dnl
-AC_DEFUN(APR_SETVAR,[
+AC_DEFUN([APR_SETVAR],[
   test "x$silent" != "xyes" && echo "  forcing $1 to \"$2\""
   $1="$2"
 ])dnl
@@ -244,7 +244,7 @@
 dnl
 dnl  Add value to variable
 dnl
-AC_DEFUN(APR_ADDTO,[
+AC_DEFUN([APR_ADDTO],[
   if test "x$$1" = "x"; then
     test "x$silent" != "xyes" && echo "  setting $1 to \"$2\""
     $1="$2"
@@ -271,7 +271,7 @@
 dnl
 dnl Remove a value from a variable
 dnl
-AC_DEFUN(APR_REMOVEFROM,[
+AC_DEFUN([APR_REMOVEFROM],[
   if test "x$$1" = "x$2"; then
     test "x$silent" != "xyes" && echo "  nulling $1"
     $1=""
@@ -295,7 +295,7 @@
 dnl
 dnl APR_CHECK_DEFINE_FILES( symbol, header_file [header_file ...] )
 dnl
-AC_DEFUN(APR_CHECK_DEFINE_FILES,[
+AC_DEFUN([APR_CHECK_DEFINE_FILES],[
   AC_CACHE_CHECK([for $1 in $2],ac_cv_define_$1,[
     ac_cv_define_$1=no
     for curhdr in $2
@@ -317,7 +317,7 @@
 dnl
 dnl APR_CHECK_DEFINE(symbol, header_file)
 dnl
-AC_DEFUN(APR_CHECK_DEFINE,[
+AC_DEFUN([APR_CHECK_DEFINE],[
   AC_CACHE_CHECK([for $1 in $2],ac_cv_define_$1,[
     AC_EGREP_CPP(YES_IS_DEFINED, [
 #include <$2>
@@ -334,7 +334,7 @@
 dnl
 dnl APR_CHECK_APR_DEFINE( symbol )
 dnl
-AC_DEFUN(APR_CHECK_APR_DEFINE,[
+AC_DEFUN([APR_CHECK_APR_DEFINE],[
 apr_old_cppflags=$CPPFLAGS
 CPPFLAGS="$CPPFLAGS $INCLUDES"
 AC_EGREP_CPP(YES_IS_DEFINED, [
@@ -450,7 +450,7 @@
 dnl A variant of AC_CHECK_SIZEOF which allows the checking of
 dnl sizes of non-builtin types
 dnl
-AC_DEFUN(APR_CHECK_SIZEOF_EXTENDED,
+AC_DEFUN([APR_CHECK_SIZEOF_EXTENDED],
 [changequote(<<,>>)dnl
 dnl The name to #define
 define(<<AC_TYPE_NAME>>, translit(sizeof_$2, [a-z *], [A-Z_P]))dnl
@@ -511,7 +511,7 @@
 dnl  string.
 dnl
 dnl
-AC_DEFUN(APR_CHECK_STRERROR_R_RC,[
+AC_DEFUN([APR_CHECK_STRERROR_R_RC],[
 AC_MSG_CHECKING(for type of return code from strerror_r)
 AC_TRY_RUN([
 #include <errno.h>
@@ -546,7 +546,7 @@
 dnl  structure on this platform.  Single UNIX Spec says d_ino,
 dnl  BSD uses d_fileno.  Undef to find the real beast.
 dnl
-AC_DEFUN(APR_CHECK_DIRENT_INODE, [
+AC_DEFUN([APR_CHECK_DIRENT_INODE], [
 AC_CACHE_CHECK([for inode member of struct dirent], apr_cv_dirent_inode, [
 apr_cv_dirent_inode=no
 AC_TRY_COMPILE([
@@ -584,7 +584,7 @@
 dnl  Note that this is worthless without DT_xxx macros, so
 dnl  look for one while we are at it.
 dnl
-AC_DEFUN(APR_CHECK_DIRENT_TYPE,[
+AC_DEFUN([APR_CHECK_DIRENT_TYPE],[
 AC_CACHE_CHECK([for file type member of struct dirent], apr_cv_dirent_type,[
 apr_cv_dirent_type=no
 AC_TRY_COMPILE([
@@ -633,7 +633,7 @@
 dnl  all "." and "-" chars. If the 3rd parameter is "yes" then instead of
 dnl  setting to 1 or 0, we set FLAG-TO-SET to yes or no.
 dnl  
-AC_DEFUN(APR_FLAG_HEADERS,[
+AC_DEFUN([APR_FLAG_HEADERS],[
 AC_CHECK_HEADERS($1)
 for aprt_i in $1
 do
@@ -654,7 +654,7 @@
 dnl  is "yes" then instead of setting to 1 or 0, we set FLAG-TO-SET
 dnl  to yes or no.
 dnl
-AC_DEFUN(APR_FLAG_FUNCS,[
+AC_DEFUN([APR_FLAG_FUNCS],[
 AC_CHECK_FUNCS($1)
 for aprt_j in $1
 do
@@ -679,7 +679,7 @@
 dnl APR_EXPAND_VAR(fraz, $baz)
 dnl   $fraz is now "1/2/3"
 dnl 
-AC_DEFUN(APR_EXPAND_VAR,[
+AC_DEFUN([APR_EXPAND_VAR],[
 ap_last=
 ap_cur="$2"
 while test "x${ap_cur}" != "x${ap_last}";
@@ -698,7 +698,7 @@
 dnl orig_path="${prefix}/bar"
 dnl APR_PATH_RELATIVE(final_path, $orig_path, $prefix)
 dnl    $final_path now contains "bar"
-AC_DEFUN(APR_PATH_RELATIVE,[
+AC_DEFUN([APR_PATH_RELATIVE],[
 ap_stripped=`echo $2 | sed -e "s#^$3##"`
 # check if the stripping was successful
 if test "x$2" != "x${ap_stripped}"; then
@@ -716,12 +716,12 @@
 dnl Note: this define must be on one line so that it can be properly returned
 dnl as the help string.  When using this macro with a multi-line RHS, ensure
 dnl that you surround the macro invocation with []s
-AC_DEFUN(APR_HELP_STRING,[ifelse(regexp(AC_ACVERSION, 2\.1), -1, AC_HELP_STRING([$1],[$2]),[  ][$1] substr([                       ],len($1))[$2])])
+AC_DEFUN([APR_HELP_STRING],[ifelse(regexp(AC_ACVERSION, 2\.1), -1, AC_HELP_STRING([$1],[$2]),[  ][$1] substr([                       ],len($1))[$2])])
 
 dnl
 dnl APR_LAYOUT(configlayout, layoutname [, extravars])
 dnl
-AC_DEFUN(APR_LAYOUT,[
+AC_DEFUN([APR_LAYOUT],[
   if test ! -f $srcdir/config.layout; then
     echo "** Error: Layout file $srcdir/config.layout not found"
     echo "** Error: Cannot use undefined layout '$LAYOUT'"
@@ -784,7 +784,7 @@
 dnl
 dnl APR_ENABLE_LAYOUT(default layout name [, extra vars])
 dnl
-AC_DEFUN(APR_ENABLE_LAYOUT,[
+AC_DEFUN([APR_ENABLE_LAYOUT],[
 AC_ARG_ENABLE(layout,
 [  --enable-layout=LAYOUT],[
   LAYOUT=$enableval
@@ -805,7 +805,7 @@
 dnl a reimplementation of autoconf's argument parser,
 dnl used here to allow us to co-exist layouts and argument based
 dnl set ups.
-AC_DEFUN(APR_PARSE_ARGUMENTS,[
+AC_DEFUN([APR_PARSE_ARGUMENTS],[
 ac_prev=
 # Retrieve the command-line arguments.  The eval is needed because
 # the arguments are quoted to preserve accuracy.
@@ -931,7 +931,7 @@
 dnl
 dnl Determine what program we can use to generate .deps-style dependencies
 dnl
-AC_DEFUN(APR_CHECK_DEPEND,[
+AC_DEFUN([APR_CHECK_DEPEND],[
 dnl Try to determine what depend program we can use
 dnl All GCC-variants should have -MM.
 dnl If not, then we can check on those, too.

Modified: freeswitch/branches/cparker/libs/apr/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/apr/configure.in	(original)
+++ freeswitch/branches/cparker/libs/apr/configure.in	Tue Apr 24 10:14:28 2007
@@ -529,6 +529,7 @@
 AC_SEARCH_LIBS(crypt, crypt ufc)
 AC_CHECK_LIB(truerand, main)
 AC_SEARCH_LIBS(modf, m)
+AC_CHECK_LIB(dl, dlopen)
 
 dnl ----------------------------- Checking for Threads
 echo "${nl}Checking for Threads..."
@@ -737,6 +738,11 @@
 haveshmgetanon="0"
 havemmapzero="0"
 havemmapanon="0"
+
+case $host in
+  *-*-cygwin | *-*-mingw* | *-*-pw32*)
+     ;;
+    *)	
 APR_BEGIN_DECISION([anonymous shared memory allocation method])
 APR_IFALLYES(header:sys/ipc.h header:sys/shm.h header:sys/file.h dnl
              func:shmget func:shmat func:shmdt func:shmctl,
@@ -772,6 +778,10 @@
         ;;
 esac
 APR_END_DECISION
+
+        ;;
+esac
+
 AC_DEFINE_UNQUOTED($ac_decision)
 
 useshmgetanon="0"
@@ -803,6 +813,11 @@
 haveshmget="0"
 havebeosarea="0"
 haveos2shm="0"
+
+case $host in
+  *-*-cygwin | *-*-mingw* | *-*-pw32*)
+     ;;
+    *)	
 APR_BEGIN_DECISION([namebased memory allocation method])
 APR_IFALLYES(header:sys/mman.h func:mmap func:munmap,
              [havemmaptmp="1"
@@ -836,6 +851,8 @@
         ;;
 esac
 APR_END_DECISION
+        ;;
+esac
 AC_DEFINE_UNQUOTED($ac_decision)
 
 usemmaptmp="0"

Modified: freeswitch/branches/cparker/libs/apr/include/apr.h.in
==============================================================================
--- freeswitch/branches/cparker/libs/apr/include/apr.h.in	(original)
+++ freeswitch/branches/cparker/libs/apr/include/apr.h.in	Tue Apr 24 10:14:28 2007
@@ -385,6 +385,8 @@
 #define APR_PATH_MAX       PATH_MAX
 #elif defined(_POSIX_PATH_MAX)
 #define APR_PATH_MAX       _POSIX_PATH_MAX
+#elif defined(_XOPEN_PATH_MAX)
+#define APR_PATH_MAX       _XOPEN_PATH_MAX
 #else
 #error no decision has been made on APR_PATH_MAX for your platform
 #endif

Modified: freeswitch/branches/cparker/libs/codec/g726/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/codec/g726/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/codec/g726/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -3,9 +3,9 @@
 AUTOMAKE_OPTS= gnu
 NAME=libg726
 
-AM_CC=gcc
-AM_CFLAGS	= -Wall -O3 -funroll-loops
+AM_CFLAGS   = $(new_AM_CFLAGS) -I./src/include
 AM_CPPFLAGS = $(AM_CFLAGS)
+AM_LDFLAGS  = $(new_AM_LDFLAGS) -lm
 
 lib_LTLIBRARIES		= libg726.la
 libg726_la_SOURCES	= src/g726_16.c \

Modified: freeswitch/branches/cparker/libs/codec/g726/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/codec/g726/configure.in	(original)
+++ freeswitch/branches/cparker/libs/codec/g726/configure.in	Tue Apr 24 10:14:28 2007
@@ -3,15 +3,93 @@
 
 AC_PREREQ(2.59)
 AC_INIT(FULL-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS)
+AC_CONFIG_AUX_DIR(build)
 AM_INIT_AUTOMAKE(libg726,0.1)
 AC_CONFIG_SRCDIR([src])
 
+#Set default language
+AC_LANG_C
 # Checks for programs.
 AC_PROG_CC
 AC_PROG_MAKE_SET
 AC_PROG_LIBTOOL
 AC_PROG_INSTALL
 
+#Check for compiler vendor
+AX_COMPILER_VENDOR
+
+#  Optimize
+AC_ARG_ENABLE(optimization,
+[AC_HELP_STRING([--enable-optimization],[Set if you want us to add max optimising compiler flags])],[enable_optimizer="$enableval"],[enable_optimizer="no"])
+
+if test "${enable_optimizer}" = "yes" ; then
+        AC_DEFINE([OPTIMZER],[],[Enable Optimization.])
+        AX_CC_MAXOPT
+fi
+
+#  Enable debugging
+AC_ARG_ENABLE(debug,
+[AC_HELP_STRING([--enable-debug],[build with debug information])],[enable_debug="$enable_debug"],[enable_debug="yes"])
+
+if test "${enable_debug}" = "yes"; then
+        AC_DEFINE([DEBUG],[],[Enable extra debugging.])
+        AX_CFLAGS_WARN_ALL_ANSI
+fi
+
+AM_CONDITIONAL([WANT_DEBUG],[test "${enable_debug}" = "yes"])
+
+
+case "$host" in
+                *-solaris2*)
+                        if test "x${ax_cv_c_compiler_vendor}"  =  "xsun" ; then
+                                SOLINK="-Bdynamic -dy -G"
+                                new_AM_CFLAGS="-KPIC -DPIC"
+                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
+                        elif test "x${ax_cv_c_compiler_vendor}" = "xgnu" ; then
+                                SOLINK="-Bdynamic -dy -G"
+                                new_AM_CFLAGS="-fPIC"
+                                new_AM_LDFLAGS=""
+                        fi
+                        DYNAMIC_LIB_EXTEN="so"
+                ;;
+                *-darwin*)
+                        if test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
+                                SOLINK="-dynamic -bundle -force-flat-namespace"
+                                new_AM_CFLAGS="-DMACOSX"
+                                new_AM_LDFLAGS=""
+                        fi
+                        DYNAMIC_LIB_EXTEN="dylib"
+                ;;
+                x86_64-*-linux-gnu)
+                        if test "x${ax_cv_c_compiler_vendor}" = "xsun" ; then
+                                SOLINK="-Bdynamic -dy -G"
+                                new_AM_CFLAGS="-KPIC -DPIC"
+                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
+                        elif test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
+                                SOLINK="-shared -Xlinker -x"
+                                new_AM_CFLAGS="-fPIC"
+                                new_AM_LDFLAGS=""
+                        fi
+                        DYNAMIC_LIB_EXTEN="so"
+                ;;
+                i*6-*-linux-gnu)
+                        if test "x${ax_cv_c_compiler_vendor}" = "xsun" ; then
+                                SOLINK="-Bdynamic -dy -G"
+                                new_AM_CFLAGS="-KPIC -DPIC"
+                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
+                        elif test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
+                                SOLINK="-shared -Xlinker -x"
+                                new_AM_CFLAGS="-fpic"
+                                new_AM_LDFLAGS=""
+                        fi
+                        DYNAMIC_LIB_EXTEN="so"
+                ;;
+esac
+AC_SUBST(new_AM_CFLAGS)
+AC_SUBST(new_AM_LDFLAGS)
+AC_SUBST(SOLINK)
+AC_SUBST(DYNAMIC_LIB_EXTEN)
+
 # Checks for header files.
 AC_HEADER_DIRENT
 AC_HEADER_STDC

Modified: freeswitch/branches/cparker/libs/codec/gsm/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/codec/gsm/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/codec/gsm/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -4,7 +4,7 @@
 NAME=libgsm
 
 AM_CC=gcc
-AM_CFLAGS	=  -I./inc -DNeedFunctionPrototypes=1 -funroll-loops  -fPIC -DSASR -DNDEBUG -DWAV49
+AM_CFLAGS	=  -I./inc -DNeedFunctionPrototypes=1   -fPIC -DSASR -DNDEBUG -DWAV49
 AM_CPPFLAGS = $(AM_CFLAGS)
 
 lib_LTLIBRARIES		= libgsm.la

Modified: freeswitch/branches/cparker/libs/codec/gsm/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/codec/gsm/configure.in	(original)
+++ freeswitch/branches/cparker/libs/codec/gsm/configure.in	Tue Apr 24 10:14:28 2007
@@ -5,7 +5,6 @@
 AC_INIT(FULL-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS)
 AM_INIT_AUTOMAKE(libgsm,0.1)
 AC_CONFIG_SRCDIR([src])
-#AC_CONFIG_HEADER([])
 
 # Checks for programs.
 AC_PROG_CC

Modified: freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_decode.h
==============================================================================
--- freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_decode.h	(original)
+++ freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_decode.h	Tue Apr 24 10:14:28 2007
@@ -1,40 +1,30 @@
-   
-   /******************************************************************
-   
-       iLBC Speech Coder ANSI-C Source Code
-   
-       iLBC_decode.h    
-   
-       Copyright (C) The Internet Society (2004). 
-       All Rights Reserved.
-   
-   ******************************************************************/
-   
-   #ifndef __iLBC_ILBCDECODE_H
-   #define __iLBC_ILBCDECODE_H
-   
-   #include "iLBC_define.h"
-   
-   short initDecode(                   /* (o) Number of decoded 
-                                              samples */
-       iLBC_Dec_Inst_t *iLBCdec_inst,  /* (i/o) Decoder instance */
-       int mode,                       /* (i) frame size mode */
-       int use_enhancer                /* (i) 1 to use enhancer
-                                              0 to run without 
-                                                enhancer */
-   );
-   
-   void iLBC_decode( 
-       float *decblock,            /* (o) decoded signal block */
-       unsigned char *bytes,           /* (i) encoded signal bits */
-       iLBC_Dec_Inst_t *iLBCdec_inst,  /* (i/o) the decoder state 
-                                                structure */
-       int mode                    /* (i) 0: bad packet, PLC, 
-                                              1: normal */
-   );
-   
-   
-   
-   #endif
-   
-   
+/******************************************************************
+
+iLBC Speech Coder ANSI-C Source Code
+
+iLBC_decode.h    
+
+Copyright (C) The Internet Society (2004). 
+All Rights Reserved.
+
+******************************************************************/
+
+#ifndef __iLBC_ILBCDECODE_H
+#define __iLBC_ILBCDECODE_H
+
+#include "iLBC_define.h"
+
+short initDecode(								/* (o) Number of decoded samples */
+				 iLBC_Dec_Inst_t *iLBCdec_inst,	/* (i/o) Decoder instance */
+				 int mode,						/* (i) frame size mode */
+				 int use_enhancer				/* (i) 1 to use enhancer 0 to run without enhancer */
+				 );
+
+void iLBC_decode( 
+				 float *decblock,				/* (o) decoded signal block */
+				 unsigned char *bytes,			/* (i) encoded signal bits */
+				 iLBC_Dec_Inst_t *iLBCdec_inst,	/* (i/o) the decoder state structure */
+				 int mode						/* (i) 0: bad packet, PLC, 1: normal */
+				 );
+
+#endif

Modified: freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_define.h
==============================================================================
--- freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_define.h	(original)
+++ freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_define.h	Tue Apr 24 10:14:28 2007
@@ -1,204 +1,204 @@
-   
-   /******************************************************************
-   
-       iLBC Speech Coder ANSI-C Source Code
-   
-       iLBC_define.h    
-   
-       Copyright (C) The Internet Society (2004). 
-       All Rights Reserved.
-   
-   ******************************************************************/
-   #include <string.h>
-   
-   #ifndef __iLBC_ILBCDEFINE_H
-   #define __iLBC_ILBCDEFINE_H
-   
-   /* general codec settings */
-   
-   #define FS                      (float)8000.0
-   #define BLOCKL_20MS             160
-   #define BLOCKL_30MS             240
-   #define BLOCKL_MAX              240
-   #define NSUB_20MS               4
-   #define NSUB_30MS               6
-   #define NSUB_MAX            6
-   #define NASUB_20MS              2
-   #define NASUB_30MS              4
-   #define NASUB_MAX               4
-   #define SUBL                40
-   #define STATE_LEN               80
-   #define STATE_SHORT_LEN_30MS    58
-   #define STATE_SHORT_LEN_20MS    57
-   
-   /* LPC settings */
-   
-   #define LPC_FILTERORDER         10
-   #define LPC_CHIRP_SYNTDENUM     (float)0.9025
-   #define LPC_CHIRP_WEIGHTDENUM   (float)0.4222
-   #define LPC_LOOKBACK        60
-   #define LPC_N_20MS              1
-   #define LPC_N_30MS              2
-   #define LPC_N_MAX               2
-   #define LPC_ASYMDIFF        20
-   #define LPC_BW                  (float)60.0
-   #define LPC_WN                  (float)1.0001
-   #define LSF_NSPLIT              3
-   
-   
-   #define LSF_NUMBER_OF_STEPS     4
-   #define LPC_HALFORDER           (LPC_FILTERORDER/2)
-   
-   /* cb settings */
-   
-   #define CB_NSTAGES              3
-   #define CB_EXPAND               2
-   #define CB_MEML                 147
-   #define CB_FILTERLEN        2*4
-   #define CB_HALFFILTERLEN    4
-   #define CB_RESRANGE             34
-   #define CB_MAXGAIN              (float)1.3 
-   
-   /* enhancer */
-   
-   #define ENH_BLOCKL              80  /* block length */
-   #define ENH_BLOCKL_HALF         (ENH_BLOCKL/2)
-   #define ENH_HL                  3   /* 2*ENH_HL+1 is number blocks
-                                          in said second sequence */
-   #define ENH_SLOP            2   /* max difference estimated and
-                                          correct pitch period */
-   #define ENH_PLOCSL              20  /* pitch-estimates and pitch-
-                                          locations buffer length */
-   #define ENH_OVERHANG        2
-   #define ENH_UPS0            4   /* upsampling rate */
-   #define ENH_FL0                 3   /* 2*FLO+1 is the length of 
-                                          each filter */
-   #define ENH_VECTL               (ENH_BLOCKL+2*ENH_FL0)
-   #define ENH_CORRDIM             (2*ENH_SLOP+1)
-   #define ENH_NBLOCKS             (BLOCKL_MAX/ENH_BLOCKL)
-   #define ENH_NBLOCKS_EXTRA       5
-   #define ENH_NBLOCKS_TOT         8   /* ENH_NBLOCKS + 
-                                          ENH_NBLOCKS_EXTRA */
-   #define ENH_BUFL            (ENH_NBLOCKS_TOT)*ENH_BLOCKL
-   #define ENH_ALPHA0              (float)0.05
-   
-   /* Down sampling */
-   
-   #define FILTERORDER_DS          7
-   #define DELAY_DS            3
-   #define FACTOR_DS               2
-   
-   /* bit stream defs */
-   
-   #define NO_OF_BYTES_20MS    38
-   #define NO_OF_BYTES_30MS    50
-   #define NO_OF_WORDS_20MS    19
-   #define NO_OF_WORDS_30MS    25
-   #define STATE_BITS              3
-   #define BYTE_LEN            8
-   #define ULP_CLASSES             3
-   
-   /* help parameters */
-   
-   
-   
-   #define FLOAT_MAX               (float)1.0e37
-   #define EPS                     (float)2.220446049250313e-016
-   #define PI                      (float)3.14159265358979323846
-   #define MIN_SAMPLE              -32768
-   #define MAX_SAMPLE              32767
-   #define TWO_PI                  (float)6.283185307
-   #define PI2                     (float)0.159154943
-   
-   /* type definition encoder instance */
-   typedef struct iLBC_ULP_Inst_t_ {
-       int lsf_bits[6][ULP_CLASSES+2];
-       int start_bits[ULP_CLASSES+2];
-       int startfirst_bits[ULP_CLASSES+2];
-       int scale_bits[ULP_CLASSES+2];
-       int state_bits[ULP_CLASSES+2];
-       int extra_cb_index[CB_NSTAGES][ULP_CLASSES+2];
-       int extra_cb_gain[CB_NSTAGES][ULP_CLASSES+2];
-       int cb_index[NSUB_MAX][CB_NSTAGES][ULP_CLASSES+2];
-       int cb_gain[NSUB_MAX][CB_NSTAGES][ULP_CLASSES+2];
-   } iLBC_ULP_Inst_t;
-   
-   /* type definition encoder instance */
-   typedef struct iLBC_Enc_Inst_t_ {
-   
-       /* flag for frame size mode */
-       int mode;
-   
-       /* basic parameters for different frame sizes */
-       int blockl;
-       int nsub;
-       int nasub;
-       int no_of_bytes, no_of_words;
-       int lpc_n;
-       int state_short_len;
-       const iLBC_ULP_Inst_t *ULP_inst;
-   
-       /* analysis filter state */
-       float anaMem[LPC_FILTERORDER];
-   
-       /* old lsf parameters for interpolation */
-       float lsfold[LPC_FILTERORDER];
-       float lsfdeqold[LPC_FILTERORDER];
-   
-       /* signal buffer for LP analysis */
-       float lpc_buffer[LPC_LOOKBACK + BLOCKL_MAX];
-   
-       /* state of input HP filter */
-       float hpimem[4];
-   
-   } iLBC_Enc_Inst_t;
-   
-   /* type definition decoder instance */
-   typedef struct iLBC_Dec_Inst_t_ {
-   
-   
-   
-       /* flag for frame size mode */
-       int mode;
-   
-       /* basic parameters for different frame sizes */
-       int blockl;
-       int nsub;
-       int nasub;
-       int no_of_bytes, no_of_words;
-       int lpc_n;
-       int state_short_len;
-       const iLBC_ULP_Inst_t *ULP_inst;
-   
-       /* synthesis filter state */
-       float syntMem[LPC_FILTERORDER];
-   
-       /* old LSF for interpolation */
-       float lsfdeqold[LPC_FILTERORDER];
-   
-       /* pitch lag estimated in enhancer and used in PLC */
-       int last_lag;
-   
-       /* PLC state information */
-       int prevLag, consPLICount, prevPLI, prev_enh_pl;
-       float prevLpc[LPC_FILTERORDER+1];
-       float prevResidual[NSUB_MAX*SUBL];
-       float per;
-       unsigned long seed;
-   
-       /* previous synthesis filter parameters */
-       float old_syntdenum[(LPC_FILTERORDER + 1)*NSUB_MAX];
-   
-       /* state of output HP filter */
-       float hpomem[4];
-   
-       /* enhancer state information */
-       int use_enhancer;
-       float enh_buf[ENH_BUFL];
-       float enh_period[ENH_NBLOCKS_TOT];
-   
-   } iLBC_Dec_Inst_t;
-   
-   #endif
-   
-   
+
+/******************************************************************
+
+iLBC Speech Coder ANSI-C Source Code
+
+iLBC_define.h    
+
+Copyright (C) The Internet Society (2004). 
+All Rights Reserved.
+
+******************************************************************/
+#include <string.h>
+
+#ifndef __iLBC_ILBCDEFINE_H
+#define __iLBC_ILBCDEFINE_H
+
+/* general codec settings */
+
+#define FS                      (float)8000.0
+#define BLOCKL_20MS             160
+#define BLOCKL_30MS             240
+#define BLOCKL_MAX              240
+#define NSUB_20MS               4
+#define NSUB_30MS               6
+#define NSUB_MAX            6
+#define NASUB_20MS              2
+#define NASUB_30MS              4
+#define NASUB_MAX               4
+#define SUBL                40
+#define STATE_LEN               80
+#define STATE_SHORT_LEN_30MS    58
+#define STATE_SHORT_LEN_20MS    57
+
+/* LPC settings */
+
+#define LPC_FILTERORDER         10
+#define LPC_CHIRP_SYNTDENUM     (float)0.9025
+#define LPC_CHIRP_WEIGHTDENUM   (float)0.4222
+#define LPC_LOOKBACK        60
+#define LPC_N_20MS              1
+#define LPC_N_30MS              2
+#define LPC_N_MAX               2
+#define LPC_ASYMDIFF        20
+#define LPC_BW                  (float)60.0
+#define LPC_WN                  (float)1.0001
+#define LSF_NSPLIT              3
+
+
+#define LSF_NUMBER_OF_STEPS     4
+#define LPC_HALFORDER           (LPC_FILTERORDER/2)
+
+/* cb settings */
+
+#define CB_NSTAGES              3
+#define CB_EXPAND               2
+#define CB_MEML                 147
+#define CB_FILTERLEN        2*4
+#define CB_HALFFILTERLEN    4
+#define CB_RESRANGE             34
+#define CB_MAXGAIN              (float)1.3 
+
+/* enhancer */
+
+#define ENH_BLOCKL              80  /* block length */
+#define ENH_BLOCKL_HALF         (ENH_BLOCKL/2)
+#define ENH_HL                  3   /* 2*ENH_HL+1 is number blocks
+in said second sequence */
+#define ENH_SLOP            2   /* max difference estimated and
+correct pitch period */
+#define ENH_PLOCSL              20  /* pitch-estimates and pitch-
+locations buffer length */
+#define ENH_OVERHANG        2
+#define ENH_UPS0            4   /* upsampling rate */
+#define ENH_FL0                 3   /* 2*FLO+1 is the length of 
+each filter */
+#define ENH_VECTL               (ENH_BLOCKL+2*ENH_FL0)
+#define ENH_CORRDIM             (2*ENH_SLOP+1)
+#define ENH_NBLOCKS             (BLOCKL_MAX/ENH_BLOCKL)
+#define ENH_NBLOCKS_EXTRA       5
+#define ENH_NBLOCKS_TOT         8   /* ENH_NBLOCKS + 
+ENH_NBLOCKS_EXTRA */
+#define ENH_BUFL            (ENH_NBLOCKS_TOT)*ENH_BLOCKL
+#define ENH_ALPHA0              (float)0.05
+
+/* Down sampling */
+
+#define FILTERORDER_DS          7
+#define DELAY_DS            3
+#define FACTOR_DS               2
+
+/* bit stream defs */
+
+#define NO_OF_BYTES_20MS    38
+#define NO_OF_BYTES_30MS    50
+#define NO_OF_WORDS_20MS    19
+#define NO_OF_WORDS_30MS    25
+#define STATE_BITS              3
+#define BYTE_LEN            8
+#define ULP_CLASSES             3
+
+/* help parameters */
+
+
+
+#define FLOAT_MAX               (float)1.0e37
+#define EPS                     (float)2.220446049250313e-016
+#define PI                      (float)3.14159265358979323846
+#define MIN_SAMPLE              -32768
+#define MAX_SAMPLE              32767
+#define TWO_PI                  (float)6.283185307
+#define PI2                     (float)0.159154943
+
+/* type definition encoder instance */
+typedef struct iLBC_ULP_Inst_t_ {
+	int lsf_bits[6][ULP_CLASSES+2];
+	int start_bits[ULP_CLASSES+2];
+	int startfirst_bits[ULP_CLASSES+2];
+	int scale_bits[ULP_CLASSES+2];
+	int state_bits[ULP_CLASSES+2];
+	int extra_cb_index[CB_NSTAGES][ULP_CLASSES+2];
+	int extra_cb_gain[CB_NSTAGES][ULP_CLASSES+2];
+	int cb_index[NSUB_MAX][CB_NSTAGES][ULP_CLASSES+2];
+	int cb_gain[NSUB_MAX][CB_NSTAGES][ULP_CLASSES+2];
+} iLBC_ULP_Inst_t;
+
+/* type definition encoder instance */
+typedef struct iLBC_Enc_Inst_t_ {
+
+	/* flag for frame size mode */
+	int mode;
+
+	/* basic parameters for different frame sizes */
+	int blockl;
+	int nsub;
+	int nasub;
+	int no_of_bytes, no_of_words;
+	int lpc_n;
+	int state_short_len;
+	const iLBC_ULP_Inst_t *ULP_inst;
+
+	/* analysis filter state */
+	float anaMem[LPC_FILTERORDER];
+
+	/* old lsf parameters for interpolation */
+	float lsfold[LPC_FILTERORDER];
+	float lsfdeqold[LPC_FILTERORDER];
+
+	/* signal buffer for LP analysis */
+	float lpc_buffer[LPC_LOOKBACK + BLOCKL_MAX];
+
+	/* state of input HP filter */
+	float hpimem[4];
+
+} iLBC_Enc_Inst_t;
+
+/* type definition decoder instance */
+typedef struct iLBC_Dec_Inst_t_ {
+
+
+
+	/* flag for frame size mode */
+	int mode;
+
+	/* basic parameters for different frame sizes */
+	int blockl;
+	int nsub;
+	int nasub;
+	int no_of_bytes, no_of_words;
+	int lpc_n;
+	int state_short_len;
+	const iLBC_ULP_Inst_t *ULP_inst;
+
+	/* synthesis filter state */
+	float syntMem[LPC_FILTERORDER];
+
+	/* old LSF for interpolation */
+	float lsfdeqold[LPC_FILTERORDER];
+
+	/* pitch lag estimated in enhancer and used in PLC */
+	int last_lag;
+
+	/* PLC state information */
+	int prevLag, consPLICount, prevPLI, prev_enh_pl;
+	float prevLpc[LPC_FILTERORDER+1];
+	float prevResidual[NSUB_MAX*SUBL];
+	float per;
+	unsigned long seed;
+
+	/* previous synthesis filter parameters */
+	float old_syntdenum[(LPC_FILTERORDER + 1)*NSUB_MAX];
+
+	/* state of output HP filter */
+	float hpomem[4];
+
+	/* enhancer state information */
+	int use_enhancer;
+	float enh_buf[ENH_BUFL];
+	float enh_period[ENH_NBLOCKS_TOT];
+
+} iLBC_Dec_Inst_t;
+
+#endif
+
+

Modified: freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_encode.h
==============================================================================
--- freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_encode.h	(original)
+++ freeswitch/branches/cparker/libs/codec/ilbc/src/iLBC_encode.h	Tue Apr 24 10:14:28 2007
@@ -1,37 +1,32 @@
-   
-   /******************************************************************
-   
-       iLBC Speech Coder ANSI-C Source Code
-   
-       iLBC_encode.h    
-   
-       Copyright (C) The Internet Society (2004). 
-       All Rights Reserved.
-   
-   ******************************************************************/
-   
-   #ifndef __iLBC_ILBCENCODE_H
-   #define __iLBC_ILBCENCODE_H
-   
-   #include "iLBC_define.h"
-   
-   short initEncode(                   /* (o) Number of bytes 
-                                              encoded */
-       iLBC_Enc_Inst_t *iLBCenc_inst,  /* (i/o) Encoder instance */
-       int mode                    /* (i) frame size mode */
-   );
-   
-   void iLBC_encode(
-   
-   
-       unsigned char *bytes,           /* (o) encoded data bits iLBC */
-       float *block,                   /* (o) speech vector to 
-                                              encode */
-       iLBC_Enc_Inst_t *iLBCenc_inst   /* (i/o) the general encoder 
-                                              state */
-   );
-   
-   #endif
-   
+
+/******************************************************************
+
+iLBC Speech Coder ANSI-C Source Code
+
+iLBC_encode.h    
+
+Copyright (C) The Internet Society (2004). 
+All Rights Reserved.
+
+******************************************************************/
+
+#ifndef __iLBC_ILBCENCODE_H
+#define __iLBC_ILBCENCODE_H
+
+#include "iLBC_define.h"
+
+short initEncode(								/* (o) Number of bytes encoded */
+				 iLBC_Enc_Inst_t *iLBCenc_inst,	/* (i/o) Encoder instance */
+				 int mode						/* (i) frame size mode */
+				 );
+
+void iLBC_encode(
+				 unsigned char *bytes,			/* (o) encoded data bits iLBC */
+				 float *block,					/* (o) speech vector to encode */
+				 iLBC_Enc_Inst_t *iLBCenc_inst	/* (i/o) the general encoder state */
+				 );
+
+#endif
+
 
 

Modified: freeswitch/branches/cparker/libs/codec/lpc10/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/codec/lpc10/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/codec/lpc10/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -3,20 +3,23 @@
 AUTOMAKE_OPTS= gnu
 NAME=liblpc10
 
-AM_CC=gcc
-AM_CFLAGS	= -Wall -O3 -funroll-loops
+AM_CFLAGS   = $(new_AM_CFLAGS)
 AM_CPPFLAGS = $(AM_CFLAGS)
+AM_LDFLAGS  = $(new_AM_LDFLAGS) -lm
 
-lib_LTLIBRARIES		= libg7xx.la
-liblpc10_la_SOURCES = analys.c  dcbias.c  difmag.c  energy.c  hp100.c   ivfilt.c  lpcini.c  mload.c   placea.c  prepro.c  synths.c  vparms.c \
-bsynz.c   decode.c  dyptrk.c  f2clib.c  invert.c  lpcdec.c  lpfilt.c  onset.c   placev.c  random.c  tbdm.c \
-chanwr.c  deemp.c   encode.c  ham84.c   irc2pc.c  lpcenc.c  median.c  pitsyn.c  preemp.c  rcchk.c   voicin.c 
+lib_LTLIBRARIES		= liblpc10.la
+liblpc10_la_SOURCES = src/analys.c src/dcbias.c src/difmag.c src/energy.c src/hp100.c \
+src/ivfilt.c src/lpcini.c src/mload.c src/placea.c src/prepro.c src/synths.c \
+src/vparms.c src/bsynz.c src/decode.c src/dyptrk.c src/f2clib.c src/invert.c \
+src/lpcdec.c src/lpfilt.c src/onset.c src/placev.c src/random.c src/tbdm.c \
+src/chanwr.c src/deemp.c src/encode.c src/ham84.c src/irc2pc.c src/lpcenc.c \
+src/median.c src/pitsyn.c src/preemp.c src/rcchk.c src/voicin.c 
 
 liblpc10_la_CFLAGS	= $(AM_CFLAGS)
 liblpc10_la_LDFLAGS	= 
 
-library_includedir	= $(prefix)/include/lpc10
-library_include_HEADERS =  f2c.h  lpc10.h
+library_includedir	= $(prefix)/include
+library_include_HEADERS =  src/f2c.h  src/lpc10.h
 
 
 

Modified: freeswitch/branches/cparker/libs/codec/lpc10/configure.ac
==============================================================================
--- freeswitch/branches/cparker/libs/codec/lpc10/configure.ac	(original)
+++ freeswitch/branches/cparker/libs/codec/lpc10/configure.ac	Tue Apr 24 10:14:28 2007
@@ -3,15 +3,91 @@
 
 AC_PREREQ(2.59)
 AC_INIT(liblpc10, 1.0, liblpc10)
+AC_CONFIG_AUX_DIR(build)
 AM_INIT_AUTOMAKE(liblpc10,1.0)
-AC_CONFIG_SRCDIR([f2clib.c])
 
+#Set default language
+AC_LANG_C
 # Checks for programs.
 AC_PROG_CC
 AC_PROG_MAKE_SET
 AC_PROG_LIBTOOL
 AC_PROG_INSTALL
 
+#Check for compiler vendor
+AX_COMPILER_VENDOR
+
+#  Optimize
+AC_ARG_ENABLE(optimization,
+[AC_HELP_STRING([--enable-optimization],[Set if you want us to add max optimising compiler flags])],[enable_optimizer="$enableval"],[enable_optimizer="no"])
+
+if test "${enable_optimizer}" = "yes" ; then
+        AC_DEFINE([OPTIMZER],[],[Enable Optimization.])
+        AX_CC_MAXOPT
+fi
+
+#  Enable debugging
+AC_ARG_ENABLE(debug,
+[AC_HELP_STRING([--enable-debug],[build with debug information])],[enable_debug="$enable_debug"],[enable_debug="yes"])
+
+if test "${enable_debug}" = "yes"; then
+        AC_DEFINE([DEBUG],[],[Enable extra debugging.])
+        AX_CFLAGS_WARN_ALL_ANSI
+fi
+
+AM_CONDITIONAL([WANT_DEBUG],[test "${enable_debug}" = "yes"])
+
+
+case "$host" in
+                *-solaris2*)
+                        if test "x${ax_cv_c_compiler_vendor}"  =  "xsun" ; then                                SOLINK="-Bdynamic -dy -G"
+                                new_AM_CFLAGS="-KPIC -DPIC"
+                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
+                        elif test "x${ax_cv_c_compiler_vendor}" = "xgnu" ; then                                SOLINK="-Bdynamic -dy -G"
+                                new_AM_CFLAGS="-fPIC"
+                                new_AM_LDFLAGS=""
+                                IN_LINE=inline
+                        fi
+                        DYNAMIC_LIB_EXTEN="so"
+                ;;
+                *-darwin*)
+                        if test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
+                                SOLINK="-dynamic -bundle -force-flat-namespace"
+                                new_AM_CFLAGS="-DMACOSX"
+                                new_AM_LDFLAGS=""
+                        fi
+                        DYNAMIC_LIB_EXTEN="dylib"
+                ;;
+                x86_64-*-linux-gnu)
+                        if test "x${ax_cv_c_compiler_vendor}" = "xsun" ; then
+                                SOLINK="-Bdynamic -dy -G"
+                                new_AM_CFLAGS="-KPIC -DPIC"
+                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
+                        elif test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
+                                SOLINK="-shared -Xlinker -x"
+                                new_AM_CFLAGS="-fPIC"
+                                new_AM_LDFLAGS=""
+                        fi
+                        DYNAMIC_LIB_EXTEN="so"
+                ;;
+                i*6-*-linux-gnu)
+                        if test "x${ax_cv_c_compiler_vendor}" = "xsun" ; then
+                                SOLINK="-Bdynamic -dy -G"
+                                new_AM_CFLAGS="-KPIC -DPIC"
+                                new_AM_LDFLAGS="-L${prefix}/lib -R${prefix}/lib"
+                        elif test "x${ax_cv_c_compiler_vendor}"="xgnu" ; then
+                                SOLINK="-shared -Xlinker -x"
+                                new_AM_CFLAGS="-fpic"
+                                new_AM_LDFLAGS=""
+                        fi
+                        DYNAMIC_LIB_EXTEN="so"
+                ;;
+esac
+AC_SUBST(new_AM_CFLAGS)
+AC_SUBST(new_AM_LDFLAGS)
+AC_SUBST(SOLINK)
+AC_SUBST(DYNAMIC_LIB_EXTEN)
+
 # Checks for libraries.
 
 # Checks for header files.

Modified: freeswitch/branches/cparker/libs/curl/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/curl/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/curl/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -29,13 +29,12 @@
 bin_SCRIPTS = curl-config
 
 SUBDIRS = lib src
-DIST_SUBDIRS = $(SUBDIRS) tests include packages docs
+DIST_SUBDIRS = $(SUBDIRS) include packages
 
 pkgconfigdir = $(libdir)/pkgconfig
 pkgconfig_DATA = libcurl.pc
 
 dist-hook:
-	rm -rf $(top_builddir)/tests/log
 	find $(distdir) -name "*.dist" -exec rm {} \;
 	(distit=`find $(srcdir) -name "*.dist"`; \
 	for file in $$distit; do \
@@ -43,88 +42,11 @@
 	  cp $$file $(distdir)$$strip; \
 	done)
 
-html:
-	cd docs; make html
-
-pdf:
-	cd docs; make pdf
-
-check: test
-
-if CROSSCOMPILING
-test-full: test
-test-torture: test
-
-test:
-	@echo "NOTICE: we can't run the tests when cross-compiling!"
-
-else
-
-test:
-	@(cd tests; $(MAKE) all quiet-test)
-
-test-full:
-	@(cd tests; $(MAKE) all full-test)
-
-test-torture:
-	@(cd tests; $(MAKE) all torture-test)
-
-endif
-
-#
-# Build source and binary rpms. For rpm-3.0 and above, the ~/.rpmmacros
-# must contain the following line:
-# %_topdir /home/loic/local/rpm
-# and that /home/loic/local/rpm contains the directory SOURCES, BUILD etc.
-#
-# cd /home/loic/local/rpm ; mkdir -p SOURCES BUILD RPMS/i386 SPECS SRPMS
-#
-# If additional configure flags are needed to build the package, add the
-# following in ~/.rpmmacros
-# %configure CFLAGS="%{optflags}" ./configure %{_target_platform} --prefix=%{_prefix} ${AM_CONFIGFLAGS}
-# and run make rpm in the following way:
-# AM_CONFIGFLAGS='--with-uri=/home/users/loic/local/RedHat-6.2' make rpm
-#
-
-rpms:
-	$(MAKE) RPMDIST=curl rpm
-	$(MAKE) RPMDIST=curl-ssl rpm
-
-rpm:
-	RPM_TOPDIR=`rpm --showrc | $(PERL) -n -e 'print if(s/.*_topdir\s+(.*)/$$1/)'` ; \
-	cp $(srcdir)/packages/Linux/RPM/$(RPMDIST).spec $$RPM_TOPDIR/SPECS ; \
-	cp $(PACKAGE)-$(VERSION).tar.gz $$RPM_TOPDIR/SOURCES ; \
-	rpm -ba --clean --rmsource $$RPM_TOPDIR/SPECS/$(RPMDIST).spec ; \
-	mv $$RPM_TOPDIR/RPMS/i386/$(RPMDIST)-*.rpm . ; \
-	mv $$RPM_TOPDIR/SRPMS/$(RPMDIST)-*.src.rpm .
-
-#
-# Build a Solaris pkkgadd format file
-# run 'make pkgadd' once you've done './configure' and 'make' to make a Solaris pkgadd format
-# file (which ends up back in this directory).
-# The pkgadd file is in 'pkgtrans' format, so to install on Solaris, do
-# pkgadd -d ./HAXXcurl-*
-#
-
-# gak - libtool requires an absoulte directory, hence the pwd below...
-pkgadd:
-	umask 022 ; \
-	make install DESTDIR=`/bin/pwd`/packages/Solaris/root ; \
-	cat COPYING > $(srcdir)/packages/Solaris/copyright ; \
-	cd $(srcdir)/packages/Solaris && $(MAKE) package
-
-#
-# Build a cygwin binary tarball installation file
-# resulting .tar.bz2 file will end up at packages/Win32/cygwin
-cygwinbin:
-	$(MAKE) -C packages/Win32/cygwin cygwinbin
-
 # We extend the standard install with a custom hook:
 install-data-hook:
 	cd include && $(MAKE) install
-	cd docs && $(MAKE) install
 
 # We extend the standard uninstall with a custom hook:
 uninstall-hook:
 	cd include && $(MAKE) uninstall
-	cd docs && $(MAKE) uninstall
+

Modified: freeswitch/branches/cparker/libs/curl/configure.ac
==============================================================================
--- freeswitch/branches/cparker/libs/curl/configure.ac	(original)
+++ freeswitch/branches/cparker/libs/curl/configure.ac	Tue Apr 24 10:14:28 2007
@@ -34,7 +34,7 @@
 
 AC_CONFIG_SRCDIR([lib/urldata.h])
 AM_CONFIG_HEADER(lib/config.h src/config.h)
-AM_MAINTAINER_MODE
+#AM_MAINTAINER_MODE
 
 dnl SED is needed by some of the tools
 AC_PATH_PROG( SED, sed, sed-was-not-found-by-configure,
@@ -2038,17 +2038,10 @@
 AM_CONDITIONAL(CROSSCOMPILING, test x$cross_compiling = xyes)
 
 AC_CONFIG_FILES([Makefile \
-	   docs/Makefile \
-           docs/examples/Makefile \
-           docs/libcurl/Makefile \
 	   include/Makefile \
 	   include/curl/Makefile \
 	   src/Makefile \
            lib/Makefile \
-           tests/Makefile \
-           tests/data/Makefile \
-           tests/server/Makefile \
-           tests/libtest/Makefile \
 	   packages/Makefile \
 	   packages/Win32/Makefile \
 	   packages/Win32/cygwin/Makefile \

Modified: freeswitch/branches/cparker/libs/curl/lib/config.h.in
==============================================================================
--- freeswitch/branches/cparker/libs/curl/lib/config.h.in	(original)
+++ freeswitch/branches/cparker/libs/curl/lib/config.h.in	Tue Apr 24 10:14:28 2007
@@ -621,16 +621,16 @@
 /* Define to the function return type for send. */
 #undef SEND_TYPE_RETV
 
-/* The size of `curl_off_t', as computed by sizeof. */
+/* The size of a `curl_off_t', as computed by sizeof. */
 #undef SIZEOF_CURL_OFF_T
 
-/* The size of `long', as computed by sizeof. */
+/* The size of a `long', as computed by sizeof. */
 #undef SIZEOF_LONG
 
-/* The size of `size_t', as computed by sizeof. */
+/* The size of a `size_t', as computed by sizeof. */
 #undef SIZEOF_SIZE_T
 
-/* The size of `time_t', as computed by sizeof. */
+/* The size of a `time_t', as computed by sizeof. */
 #undef SIZEOF_TIME_T
 
 /* Define to 1 if you have the ANSI C header files. */
@@ -685,7 +685,7 @@
 /* type to use in place of in_addr_t if not defined */
 #undef in_addr_t
 
-/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* Define to `unsigned' if <sys/types.h> does not define. */
 #undef size_t
 
 /* type to use in place of socklen_t if not defined */

Modified: freeswitch/branches/cparker/libs/curl/src/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/curl/src/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/curl/src/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -33,50 +33,11 @@
            -I$(top_srcdir)/lib     \
            -I$(top_srcdir)/src
 
-bin_PROGRAMS = curl
-
 include Makefile.inc
 
-curl_LDADD = ../lib/libcurl.la
-curl_DEPENDENCIES = ../lib/libcurl.la
-BUILT_SOURCES = hugehelp.c
-CLEANFILES = hugehelp.c
-NROFF=@NROFF@ @MANOPT@ # figured out by the configure script
-
 EXTRA_DIST = mkhelp.pl makefile.dj Makefile.vc6 Makefile.b32 Makefile.m32 \
 	Makefile.riscos config.h.in macos/curl.mcp.xml.sit.hqx		  \
 	macos/MACINSTALL.TXT macos/src/curl_GUSIConfig.cpp		  \
 	macos/src/macos_main.cpp config-amigaos.h makefile.amiga curl.rc  \
 	Makefile.netware Makefile.inc Makefile.Watcom
 
-MANPAGE=$(top_srcdir)/docs/curl.1
-README=$(top_srcdir)/docs/MANUAL
-MKHELP=$(top_srcdir)/src/mkhelp.pl
-HUGE=hugehelp.c
-
-if USE_MANUAL
-# Here are the stuff to create a built-in manual
-
-if HAVE_LIBZ
-# This generates the hugehelp.c file in both uncompressed and compressed formats
-$(HUGE): $(README) $(MANPAGE)  mkhelp.pl
-	echo '#include "setup.h"' > $(HUGE)
-	echo '#ifndef HAVE_LIBZ' >> $(HUGE)
-	$(NROFF) $(MANPAGE) | $(PERL) $(MKHELP) $(README) >> $(HUGE)
-	echo '#else' >> $(HUGE)
-	$(NROFF) $(MANPAGE) | $(PERL) $(MKHELP) -c $(README) >> $(HUGE)
-	echo '#endif /* HAVE_LIBZ */' >> $(HUGE)
-else # HAVE_LIBZ
-# This generates the hugehelp.c file uncompressed only
-$(HUGE): $(README) $(MANPAGE)  mkhelp.pl
-	echo '#include "setup.h"' > $(HUGE)
-	$(NROFF) $(MANPAGE) | $(PERL) $(MKHELP) $(README) >> $(HUGE)
-endif
-
-else # USE_MANUAL
-# built-in manual has been disabled, make a blank file
-$(HUGE):
-	echo "/* built-in manual is disabled, blank function */" > $(HUGE)
-	echo '#include "hugehelp.h"' >> $(HUGE)
-	echo "void hugehelp(void) {}" >>$(HUGE)
-endif

Modified: freeswitch/branches/cparker/libs/curl/src/Makefile.inc
==============================================================================
--- freeswitch/branches/cparker/libs/curl/src/Makefile.inc	(original)
+++ freeswitch/branches/cparker/libs/curl/src/Makefile.inc	Tue Apr 24 10:14:28 2007
@@ -5,13 +5,13 @@
 CURLX_ONES =  $(top_srcdir)/lib/strtoofft.c $(top_srcdir)/lib/timeval.c \
 	$(top_srcdir)/lib/strdup.c 
 
-CURL_SOURCES = main.c hugehelp.c urlglob.c writeout.c writeenv.c \
-	getpass.c homedir.c
+#CURL_SOURCES = main.c hugehelp.c urlglob.c writeout.c writeenv.c \
+#	getpass.c homedir.c
 
 CURL_HFILES = hugehelp.h setup.h config-win32.h config-mac.h \
 	config-riscos.h urlglob.h version.h \
 	writeout.h writeenv.h getpass.h homedir.h
 
-curl_SOURCES = $(CURL_SOURCES) $(CURLX_ONES) $(CURL_HFILES)
+#curl_SOURCES = $(CURL_SOURCES) $(CURLX_ONES) $(CURL_HFILES)
 
 

Modified: freeswitch/branches/cparker/libs/iax/.update
==============================================================================
--- freeswitch/branches/cparker/libs/iax/.update	(original)
+++ freeswitch/branches/cparker/libs/iax/.update	Tue Apr 24 10:14:28 2007
@@ -1 +1 @@
-Mon Feb 19 12:03:56 EST 2007
\ No newline at end of file
+Sat Mar 10 12:59:56 EST 2007
\ No newline at end of file

Modified: freeswitch/branches/cparker/libs/iax/src/iax-mutex.c
==============================================================================
--- freeswitch/branches/cparker/libs/iax/src/iax-mutex.c	(original)
+++ freeswitch/branches/cparker/libs/iax/src/iax-mutex.c	Tue Apr 24 10:14:28 2007
@@ -5,15 +5,15 @@
  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  * copies of the Software, and permit persons to whom the Software is
  * furnished to do so.
- *
- * This work is provided under this license on an "as is" basis, without warranty of any kind,
- * either expressed or implied, including, without limitation, warranties that the covered code
- * is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire
- * risk as to the quality and performance of the covered code is with you. Should any covered
- * code prove defective in any respect, you (not the initial developer or any other contributor)
- * assume the cost of any necessary servicing, repair or correction. This disclaimer of warranty
- * constitutes an essential part of this license. No use of any covered code is authorized hereunder
- * except under this disclaimer. 
+ *
+ * This work is provided under this license on an "as is" basis, without warranty of any kind,
+ * either expressed or implied, including, without limitation, warranties that the covered code
+ * is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire
+ * risk as to the quality and performance of the covered code is with you. Should any covered
+ * code prove defective in any respect, you (not the initial developer or any other contributor)
+ * assume the cost of any necessary servicing, repair or correction. This disclaimer of warranty
+ * constitutes an essential part of this license. No use of any covered code is authorized hereunder
+ * except under this disclaimer. 
  *
  */
 
@@ -38,68 +38,68 @@
 #endif
 
 
-mutex_status_t mutex_create(mutex_t **mutex)
-{
-	mutex_t *check = NULL;
-
-	check = (mutex_t *)malloc(sizeof(**mutex));
-	if (!check)
-		return MUTEX_FAILURE;
-#ifdef WIN32
-	InitializeCriticalSection(&check->mutex);
-#else
-	if (pthread_mutex_init(&check->mutex, NULL))
-		return MUTEX_FAILURE;
-
-#endif
-
-	*mutex = check;
-
-	return MUTEX_SUCCESS;
-}
-
-mutex_status_t mutex_destroy(mutex_t *mutex)
-{
-#ifdef WIN32
-	DeleteCriticalSection(&mutex->mutex);
-#else
-	if (pthread_mutex_destroy(&mutex->mutex))
-		return MUTEX_FAILURE;
-#endif
-	free(mutex);
-	return MUTEX_SUCCESS;
-}
-
-mutex_status_t mutex_lock(mutex_t *mutex)
-{
-#ifdef WIN32
-	EnterCriticalSection(&mutex->mutex);
-#else
-	if (pthread_mutex_lock(&mutex->mutex))
-		return MUTEX_FAILURE;
-#endif
-	return MUTEX_SUCCESS;
-}
-
-mutex_status_t mutex_trylock(mutex_t *mutex)
-{
-#ifdef WIN32
-	if (!TryEnterCriticalSection(&mutex->mutex))
-		return MUTEX_FAILURE;
-#else
-	if (pthread_mutex_trylock(&mutex->mutex))
-		return MUTEX_FAILURE;
-#endif
-	return MUTEX_SUCCESS;
-}
-
-mutex_status_t mutex_unlock(mutex_t *mutex)
-{
-#ifdef WIN32
-	LeaveCriticalSection(&mutex->mutex);
-#else
-	if (pthread_mutex_unlock(&mutex->mutex))
-		return MUTEX_FAILURE;
-#endif
-	return MUTEX_SUCCESS;
-}
+mutex_status_t iax_mutex_create(mutex_t **mutex)
+{
+	mutex_t *check = NULL;
+
+	check = (mutex_t *)malloc(sizeof(**mutex));
+	if (!check)
+		return MUTEX_FAILURE;
+#ifdef WIN32
+	InitializeCriticalSection(&check->mutex);
+#else
+	if (pthread_mutex_init(&check->mutex, NULL))
+		return MUTEX_FAILURE;
+
+#endif
+
+	*mutex = check;
+
+	return MUTEX_SUCCESS;
+}
+
+mutex_status_t iax_mutex_destroy(mutex_t *mutex)
+{
+#ifdef WIN32
+	DeleteCriticalSection(&mutex->mutex);
+#else
+	if (pthread_mutex_destroy(&mutex->mutex))
+		return MUTEX_FAILURE;
+#endif
+	free(mutex);
+	return MUTEX_SUCCESS;
+}
+
+mutex_status_t iax_mutex_lock(mutex_t *mutex)
+{
+#ifdef WIN32
+	EnterCriticalSection(&mutex->mutex);
+#else
+	if (pthread_mutex_lock(&mutex->mutex))
+		return MUTEX_FAILURE;
+#endif
+	return MUTEX_SUCCESS;
+}
+
+mutex_status_t iax_mutex_trylock(mutex_t *mutex)
+{
+#ifdef WIN32
+	if (!TryEnterCriticalSection(&mutex->mutex))
+		return MUTEX_FAILURE;
+#else
+	if (pthread_mutex_trylock(&mutex->mutex))
+		return MUTEX_FAILURE;
+#endif
+	return MUTEX_SUCCESS;
+}
+
+mutex_status_t iax_mutex_unlock(mutex_t *mutex)
+{
+#ifdef WIN32
+	LeaveCriticalSection(&mutex->mutex);
+#else
+	if (pthread_mutex_unlock(&mutex->mutex))
+		return MUTEX_FAILURE;
+#endif
+	return MUTEX_SUCCESS;
+}

Modified: freeswitch/branches/cparker/libs/iax/src/iax-mutex.h
==============================================================================
--- freeswitch/branches/cparker/libs/iax/src/iax-mutex.h	(original)
+++ freeswitch/branches/cparker/libs/iax/src/iax-mutex.h	Tue Apr 24 10:14:28 2007
@@ -5,33 +5,33 @@
  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  * copies of the Software, and permit persons to whom the Software is
  * furnished to do so.
- *
- * This work is provided under this license on an "as is" basis, without warranty of any kind,
- * either expressed or implied, including, without limitation, warranties that the covered code
- * is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire
- * risk as to the quality and performance of the covered code is with you. Should any covered
- * code prove defective in any respect, you (not the initial developer or any other contributor)
- * assume the cost of any necessary servicing, repair or correction. This disclaimer of warranty
- * constitutes an essential part of this license. No use of any covered code is authorized hereunder
- * except under this disclaimer. 
+ *
+ * This work is provided under this license on an "as is" basis, without warranty of any kind,
+ * either expressed or implied, including, without limitation, warranties that the covered code
+ * is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire
+ * risk as to the quality and performance of the covered code is with you. Should any covered
+ * code prove defective in any respect, you (not the initial developer or any other contributor)
+ * assume the cost of any necessary servicing, repair or correction. This disclaimer of warranty
+ * constitutes an essential part of this license. No use of any covered code is authorized hereunder
+ * except under this disclaimer. 
  *
  */
-
-
-#ifndef _SIMPLE_ABSTRACT_MUTEX_H
-#define _SIMPLE_ABSTRACT_MUTEX_H
-
-typedef struct mutex mutex_t;
-
-typedef enum mutex_status {
-	MUTEX_SUCCESS,
-	MUTEX_FAILURE
-} mutex_status_t;
-
-mutex_status_t mutex_create(mutex_t **mutex);
-mutex_status_t mutex_destroy(mutex_t *mutex);
-mutex_status_t mutex_lock(mutex_t *mutex);
-mutex_status_t mutex_trylock(mutex_t *mutex);
-mutex_status_t mutex_unlock(mutex_t *mutex);
-
-#endif
+
+
+#ifndef _SIMPLE_ABSTRACT_MUTEX_H
+#define _SIMPLE_ABSTRACT_MUTEX_H
+
+typedef struct mutex mutex_t;
+
+typedef enum mutex_status {
+	MUTEX_SUCCESS,
+	MUTEX_FAILURE
+} mutex_status_t;
+
+mutex_status_t iax_mutex_create(mutex_t **mutex);
+mutex_status_t iax_mutex_destroy(mutex_t *mutex);
+mutex_status_t iax_mutex_lock(mutex_t *mutex);
+mutex_status_t iax_mutex_trylock(mutex_t *mutex);
+mutex_status_t iax_mutex_unlock(mutex_t *mutex);
+
+#endif

Modified: freeswitch/branches/cparker/libs/iksemel/configure.ac
==============================================================================
--- freeswitch/branches/cparker/libs/iksemel/configure.ac	(original)
+++ freeswitch/branches/cparker/libs/iksemel/configure.ac	Tue Apr 24 10:14:28 2007
@@ -1,9 +1,10 @@
 dnl Process this file with autoconf to produce a configure script.
 AC_INIT
 AC_PREREQ(2.50)
+AC_CONFIG_AUX_DIR(build)
 AC_CONFIG_SRCDIR([configure.ac])
 AM_INIT_AUTOMAKE(iksemel,1.2)
-AM_CONFIG_HEADER(include/config.h)
+AC_CONFIG_HEADERS(include/config.h)
 
 AC_CANONICAL_HOST
 
@@ -45,7 +46,7 @@
 AC_CHECK_FUNCS(getopt_long)
 AC_CHECK_FUNCS(getaddrinfo)
 
-AM_PATH_LIBGNUTLS(,AC_DEFINE(HAVE_GNUTLS,,"Use libgnutls"))
+AX_PATH_LIBGNUTLS(,AC_DEFINE(HAVE_GNUTLS,,"Use libgnutls"))
 
 dnl Check -Wall flag of GCC
 if test "x$GCC" = "xyes"; then

Modified: freeswitch/branches/cparker/libs/iksemel/include/iksemel.h
==============================================================================
--- freeswitch/branches/cparker/libs/iksemel/include/iksemel.h	(original)
+++ freeswitch/branches/cparker/libs/iksemel/include/iksemel.h	Tue Apr 24 10:14:28 2007
@@ -24,12 +24,13 @@
 char *iks_stack_strdup (ikstack *s, const char *src, size_t len);
 char *iks_stack_strcat (ikstack *s, char *old, size_t old_len, const char *src, size_t src_len);
 void iks_stack_stat (ikstack *s, size_t *allocated, size_t *used);
-void iks_stack_delete (ikstack *s);
+void iks_stack_delete (ikstack **sp);
+
 
 /*****  utilities  *****/
 
 void *iks_malloc (size_t size);
-void iks_free (void *ptr);
+void iks_real_free (void *ptr);
 void iks_set_mem_funcs (void *(*malloc_func)(size_t size), void (*free_func)(void *ptr));
 
 char *iks_strdup (const char *src);
@@ -42,6 +43,8 @@
 char *iks_escape (ikstack *s, char *src, size_t len);
 char *iks_unescape (ikstack *s, char *src, size_t len);
 
+#define iks_free(p) if (p) {iks_real_free(p) ; p = NULL;}
+
 /*****  dom tree  *****/
 
 enum ikstype {

Modified: freeswitch/branches/cparker/libs/iksemel/ltmain.sh
==============================================================================
--- freeswitch/branches/cparker/libs/iksemel/ltmain.sh	(original)
+++ freeswitch/branches/cparker/libs/iksemel/ltmain.sh	Tue Apr 24 10:14:28 2007
@@ -1,7 +1,7 @@
 # ltmain.sh - Provide generalized library-building support services.
 # NOTE: Changing this file will not affect anything until you rerun configure.
 #
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005
 # Free Software Foundation, Inc.
 # Originally by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
 #
@@ -17,7 +17,7 @@
 #
 # 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.
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 #
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
@@ -43,9 +43,14 @@
 
 PROGRAM=ltmain.sh
 PACKAGE=libtool
-VERSION=1.5.6
-TIMESTAMP=" (1.1220.2.95 2004/04/11 05:50:42) Debian$Rev: 203 $"
+VERSION=1.5.22
+TIMESTAMP=" (1.1220.2.365 2005/12/18 22:14:06)"
 
+# See if we are running on zsh, and set the options which allow our
+# commands through without removal of \ escapes.
+if test -n "${ZSH_VERSION+set}" ; then
+  setopt NO_GLOB_SUBST
+fi
 
 # Check that we have a working $echo.
 if test "X$1" = X--no-reexec; then
@@ -83,14 +88,15 @@
 Xsed="${SED}"' -e 1s/^X//'
 sed_quote_subst='s/\([\\`\\"$\\\\]\)/\\\1/g'
 # test EBCDIC or ASCII
-case `echo A|tr A '\301'` in
- A) # EBCDIC based system
-  SP2NL="tr '\100' '\n'"
-  NL2SP="tr '\r\n' '\100\100'"
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+  SP2NL='tr \040 \012'
+  NL2SP='tr \015\012 \040\040'
   ;;
- *) # Assume ASCII based system
-  SP2NL="tr '\040' '\012'"
-  NL2SP="tr '\015\012' '\040\040'"
+ *) # EBCDIC based system
+  SP2NL='tr \100 \n'
+  NL2SP='tr \r\n \100\100'
   ;;
 esac
 
@@ -107,8 +113,9 @@
 fi
 
 # Make sure IFS has a sensible default
-: ${IFS=" 	
-"}
+lt_nl='
+'
+IFS=" 	$lt_nl"
 
 if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
   $echo "$modename: not configured to build any kind of library" 1>&2
@@ -125,6 +132,8 @@
 show="$echo"
 show_help=
 execute_dlfiles=
+duplicate_deps=no
+preserve_args=
 lo2o="s/\\.lo\$/.${objext}/"
 o2lo="s/\\.${objext}\$/.lo/"
 
@@ -132,13 +141,51 @@
 # Shell function definitions:
 # This seems to be the best place for them
 
+# func_mktempdir [string]
+# Make a temporary directory that won't clash with other running
+# libtool processes, and avoids race conditions if possible.  If
+# given, STRING is the basename for that directory.
+func_mktempdir ()
+{
+    my_template="${TMPDIR-/tmp}/${1-$progname}"
+
+    if test "$run" = ":"; then
+      # Return a directory name, but don't create it in dry-run mode
+      my_tmpdir="${my_template}-$$"
+    else
+
+      # If mktemp works, use that first and foremost
+      my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
+
+      if test ! -d "$my_tmpdir"; then
+	# Failing that, at least try and use $RANDOM to avoid a race
+	my_tmpdir="${my_template}-${RANDOM-0}$$"
+
+	save_mktempdir_umask=`umask`
+	umask 0077
+	$mkdir "$my_tmpdir"
+	umask $save_mktempdir_umask
+      fi
+
+      # If we're not in dry-run mode, bomb out on failure
+      test -d "$my_tmpdir" || {
+        $echo "cannot create temporary directory \`$my_tmpdir'" 1>&2
+	exit $EXIT_FAILURE
+      }
+    fi
+
+    $echo "X$my_tmpdir" | $Xsed
+}
+
+
 # func_win32_libid arg
 # return the library type of file 'arg'
 #
 # Need a lot of goo to handle *both* DLLs and import libs
 # Has to be a shell function in order to 'eat' the argument
 # that is supplied when $file_magic_command is called.
-func_win32_libid () {
+func_win32_libid ()
+{
   win32_libid_type="unknown"
   win32_fileres=`file -L $1 2>/dev/null`
   case $win32_fileres in
@@ -149,12 +196,11 @@
     if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \
       $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then
       win32_nmres=`eval $NM -f posix -A $1 | \
-	sed -n -e '1,100{/ I /{x;/import/!{s/^/import/;h;p;};x;};}'`
-      if test "X$win32_nmres" = "Ximport" ; then
-        win32_libid_type="x86 archive import"
-      else
-        win32_libid_type="x86 archive static"
-      fi
+	$SED -n -e '1,100{/ I /{s,.*,import,;p;q;};}'`
+      case $win32_nmres in
+      import*)  win32_libid_type="x86 archive import";;
+      *)        win32_libid_type="x86 archive static";;
+      esac
     fi
     ;;
   *DLL*)
@@ -178,7 +224,8 @@
 # Only attempt this if the compiler in the base compile
 # command doesn't match the default compiler.
 # arg is usually of the form 'gcc ...'
-func_infer_tag () {
+func_infer_tag ()
+{
     if test -n "$available_tags" && test -z "$tagname"; then
       CC_quoted=
       for arg in $CC; do
@@ -235,12 +282,116 @@
       esac
     fi
 }
+
+
+# func_extract_an_archive dir oldlib
+func_extract_an_archive ()
+{
+    f_ex_an_ar_dir="$1"; shift
+    f_ex_an_ar_oldlib="$1"
+
+    $show "(cd $f_ex_an_ar_dir && $AR x $f_ex_an_ar_oldlib)"
+    $run eval "(cd \$f_ex_an_ar_dir && $AR x \$f_ex_an_ar_oldlib)" || exit $?
+    if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
+     :
+    else
+      $echo "$modename: ERROR: object name conflicts: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" 1>&2
+      exit $EXIT_FAILURE
+    fi
+}
+
+# func_extract_archives gentop oldlib ...
+func_extract_archives ()
+{
+    my_gentop="$1"; shift
+    my_oldlibs=${1+"$@"}
+    my_oldobjs=""
+    my_xlib=""
+    my_xabs=""
+    my_xdir=""
+    my_status=""
+
+    $show "${rm}r $my_gentop"
+    $run ${rm}r "$my_gentop"
+    $show "$mkdir $my_gentop"
+    $run $mkdir "$my_gentop"
+    my_status=$?
+    if test "$my_status" -ne 0 && test ! -d "$my_gentop"; then
+      exit $my_status
+    fi
+
+    for my_xlib in $my_oldlibs; do
+      # Extract the objects.
+      case $my_xlib in
+	[\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
+	*) my_xabs=`pwd`"/$my_xlib" ;;
+      esac
+      my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'`
+      my_xdir="$my_gentop/$my_xlib"
+
+      $show "${rm}r $my_xdir"
+      $run ${rm}r "$my_xdir"
+      $show "$mkdir $my_xdir"
+      $run $mkdir "$my_xdir"
+      exit_status=$?
+      if test "$exit_status" -ne 0 && test ! -d "$my_xdir"; then
+	exit $exit_status
+      fi
+      case $host in
+      *-darwin*)
+	$show "Extracting $my_xabs"
+	# Do not bother doing anything if just a dry run
+	if test -z "$run"; then
+	  darwin_orig_dir=`pwd`
+	  cd $my_xdir || exit $?
+	  darwin_archive=$my_xabs
+	  darwin_curdir=`pwd`
+	  darwin_base_archive=`$echo "X$darwin_archive" | $Xsed -e 's%^.*/%%'`
+	  darwin_arches=`lipo -info "$darwin_archive" 2>/dev/null | $EGREP Architectures 2>/dev/null`
+	  if test -n "$darwin_arches"; then 
+	    darwin_arches=`echo "$darwin_arches" | $SED -e 's/.*are://'`
+	    darwin_arch=
+	    $show "$darwin_base_archive has multiple architectures $darwin_arches"
+	    for darwin_arch in  $darwin_arches ; do
+	      mkdir -p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+	      lipo -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
+	      cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+	      func_extract_an_archive "`pwd`" "${darwin_base_archive}"
+	      cd "$darwin_curdir"
+	      $rm "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
+	    done # $darwin_arches
+      ## Okay now we have a bunch of thin objects, gotta fatten them up :)
+	    darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print| xargs basename | sort -u | $NL2SP`
+	    darwin_file=
+	    darwin_files=
+	    for darwin_file in $darwin_filelist; do
+	      darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP`
+	      lipo -create -output "$darwin_file" $darwin_files
+	    done # $darwin_filelist
+	    ${rm}r unfat-$$
+	    cd "$darwin_orig_dir"
+	  else
+	    cd "$darwin_orig_dir"
+ 	    func_extract_an_archive "$my_xdir" "$my_xabs"
+	  fi # $darwin_arches
+	fi # $run
+	;;
+      *)
+        func_extract_an_archive "$my_xdir" "$my_xabs"
+        ;;
+      esac
+      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
+    done
+    func_extract_archives_result="$my_oldobjs"
+}
 # End of Shell function definitions
 #####################################
 
 # Darwin sucks
 eval std_shrext=\"$shrext_cmds\"
 
+disable_libs=no
+
 # Parse our command line options once, thoroughly.
 while test "$#" -gt 0
 do
@@ -305,10 +456,10 @@
   --version)
     $echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP"
     $echo
-    $echo "Copyright (C) 2003  Free Software Foundation, Inc."
+    $echo "Copyright (C) 2005  Free Software Foundation, Inc."
     $echo "This is free software; see the source for copying conditions.  There is NO"
     $echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-    exit $EXIT_SUCCESS
+    exit $?
     ;;
 
   --config)
@@ -317,7 +468,7 @@
     for tagname in $taglist; do
       ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath"
     done
-    exit $EXIT_SUCCESS
+    exit $?
     ;;
 
   --debug)
@@ -342,7 +493,7 @@
     else
       $echo "disable static libraries"
     fi
-    exit $EXIT_SUCCESS
+    exit $?
     ;;
 
   --finish) mode="finish" ;;
@@ -357,7 +508,11 @@
     preserve_args="$preserve_args $arg"
     ;;
 
-  --tag) prevopt="--tag" prev=tag ;;
+  --tag)
+    prevopt="--tag"
+    prev=tag
+    preserve_args="$preserve_args --tag"
+    ;;
   --tag=*)
     set tag "$optarg" ${1+"$@"}
     shift
@@ -389,6 +544,18 @@
   exit $EXIT_FAILURE
 fi
 
+case $disable_libs in
+no) 
+  ;;
+shared)
+  build_libtool_libs=no
+  build_old_libs=yes
+  ;;
+static)
+  build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
+  ;;
+esac
+
 # If this variable is set in any of the actions, the command in it
 # will be execed at the end.  This prevents here-documents from being
 # left over by shells.
@@ -399,7 +566,7 @@
   # Infer the operation mode.
   if test -z "$mode"; then
     $echo "*** Warning: inferring the mode of operation is deprecated." 1>&2
-    $echo "*** Future versions of Libtool will require -mode=MODE be specified." 1>&2
+    $echo "*** Future versions of Libtool will require --mode=MODE be specified." 1>&2
     case $nonopt in
     *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*)
       mode=link
@@ -465,7 +632,7 @@
 
     for arg
     do
-      case "$arg_mode" in
+      case $arg_mode in
       arg  )
 	# do not "continue".  Instead, add this to base_compile
 	lastarg="$arg"
@@ -547,7 +714,10 @@
       case $lastarg in
       # Double-quote args containing other shell metacharacters.
       # Many Bourne shells cannot handle close brackets correctly
-      # in scan sets, so we specify it separately.
+      # in scan sets, and some SunOS ksh mistreat backslash-escaping
+      # in scan sets (worked around with variable expansion),
+      # and furthermore cannot handle '|' '&' '(' ')' in scan sets 
+      # at all, so we specify them separately.
       *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
 	lastarg="\"$lastarg\""
 	;;
@@ -621,6 +791,14 @@
       esac
     done
 
+    qlibobj=`$echo "X$libobj" | $Xsed -e "$sed_quote_subst"`
+    case $qlibobj in
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+	qlibobj="\"$qlibobj\"" ;;
+    esac
+    test "X$libobj" != "X$qlibobj" \
+	&& $echo "X$libobj" | grep '[]~#^*{};<>?"'"'"' 	&()|`$[]' \
+	&& $echo "$modename: libobj name \`$libobj' may not contain shell special characters."
     objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
     xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'`
     if test "X$xdir" = "X$obj"; then
@@ -693,12 +871,17 @@
 	$run $rm $removelist
 	exit $EXIT_FAILURE
       fi
-      $echo $srcfile > "$lockfile"
+      $echo "$srcfile" > "$lockfile"
     fi
 
     if test -n "$fix_srcfile_path"; then
       eval srcfile=\"$fix_srcfile_path\"
     fi
+    qsrcfile=`$echo "X$srcfile" | $Xsed -e "$sed_quote_subst"`
+    case $qsrcfile in
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+      qsrcfile="\"$qsrcfile\"" ;;
+    esac
 
     $run $rm "$libobj" "${libobj}T"
 
@@ -720,18 +903,18 @@
       fbsd_hideous_sh_bug=$base_compile
 
       if test "$pic_mode" != no; then
-	command="$base_compile $srcfile $pic_flag"
+	command="$base_compile $qsrcfile $pic_flag"
       else
 	# Don't build PIC code
-	command="$base_compile $srcfile"
+	command="$base_compile $qsrcfile"
       fi
 
       if test ! -d "${xdir}$objdir"; then
 	$show "$mkdir ${xdir}$objdir"
 	$run $mkdir ${xdir}$objdir
-	status=$?
-	if test "$status" -ne 0 && test ! -d "${xdir}$objdir"; then
-	  exit $status
+	exit_status=$?
+	if test "$exit_status" -ne 0 && test ! -d "${xdir}$objdir"; then
+	  exit $exit_status
 	fi
       fi
 
@@ -803,9 +986,9 @@
     if test "$build_old_libs" = yes; then
       if test "$pic_mode" != yes; then
 	# Don't build PIC code
-	command="$base_compile $srcfile"
+	command="$base_compile $qsrcfile"
       else
-	command="$base_compile $srcfile $pic_flag"
+	command="$base_compile $qsrcfile $pic_flag"
       fi
       if test "$compiler_c_o" = yes; then
 	command="$command -o $obj"
@@ -934,6 +1117,7 @@
     no_install=no
     objs=
     non_pic_objects=
+    notinst_path= # paths that contain not-installed libtool libraries
     precious_files_regex=
     prefer_static_libs=no
     preload=no
@@ -962,14 +1146,15 @@
 	  if test -n "$link_static_flag"; then
 	    dlopen_self=$dlopen_self_static
 	  fi
+	  prefer_static_libs=yes
 	else
 	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
 	    dlopen_self=$dlopen_self_static
 	  fi
+	  prefer_static_libs=built
 	fi
 	build_libtool_libs=no
 	build_old_libs=yes
-	prefer_static_libs=yes
 	break
 	;;
       esac
@@ -1144,6 +1329,11 @@
 		  if test -z "$pic_object" || test "$pic_object" = none ; then
 		    arg="$non_pic_object"
 		  fi
+		else
+		  # If the PIC object exists, use it instead.
+		  # $xdir was prepended to $pic_object above.
+		  non_pic_object="$pic_object"
+		  non_pic_objects="$non_pic_objects $non_pic_object"
 		fi
 	      else
 		# Only an error if not doing a dry-run.
@@ -1227,6 +1417,13 @@
 	  prev=
 	  continue
 	  ;;
+	darwin_framework|darwin_framework_skip)
+	  test "$prev" = "darwin_framework" && compiler_flags="$compiler_flags $arg"
+	  compile_command="$compile_command $arg"
+	  finalize_command="$finalize_command $arg"
+	  prev=
+	  continue
+	  ;;
 	*)
 	  eval "$prev=\"\$arg\""
 	  prev=
@@ -1285,6 +1482,18 @@
 	continue
 	;;
 
+      -framework|-arch|-isysroot)
+	case " $CC " in
+	  *" ${arg} ${1} "* | *" ${arg}	${1} "*) 
+		prev=darwin_framework_skip ;;
+	  *) compiler_flags="$compiler_flags $arg"
+	     prev=darwin_framework ;;
+	esac
+	compile_command="$compile_command $arg"
+	finalize_command="$finalize_command $arg"
+	continue
+	;;
+
       -inst-prefix-dir)
 	prev=inst_prefix
 	continue
@@ -1311,7 +1520,8 @@
 	  absdir=`cd "$dir" && pwd`
 	  if test -z "$absdir"; then
 	    $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2
-	    exit $EXIT_FAILURE
+	    absdir="$dir"
+	    notinst_path="$notinst_path $dir"
 	  fi
 	  dir="$absdir"
 	  ;;
@@ -1325,10 +1535,15 @@
 	esac
 	case $host in
 	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+	  testbindir=`$echo "X$dir" | $Xsed -e 's*/lib$*/bin*'`
 	  case :$dllsearchpath: in
 	  *":$dir:"*) ;;
 	  *) dllsearchpath="$dllsearchpath:$dir";;
 	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  *) dllsearchpath="$dllsearchpath:$testbindir";;
+	  esac
 	  ;;
 	esac
 	continue
@@ -1337,15 +1552,15 @@
       -l*)
 	if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
 	  case $host in
-	  *-*-cygwin* | *-*-pw32* | *-*-beos*)
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*)
 	    # These systems don't actually have a C or math library (as such)
 	    continue
 	    ;;
-	  *-*-mingw* | *-*-os2*)
+	  *-*-os2*)
 	    # These systems don't actually have a C library (as such)
 	    test "X$arg" = "X-lc" && continue
 	    ;;
-	  *-*-openbsd* | *-*-freebsd*)
+	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
 	    # Do not include libc due to us having libc/libc_r.
 	    test "X$arg" = "X-lc" && continue
 	    ;;
@@ -1353,10 +1568,19 @@
 	    # Rhapsody C and math libraries are in the System framework
 	    deplibs="$deplibs -framework System"
 	    continue
+	    ;;
+	  *-*-sco3.2v5* | *-*-sco5v6*)
+	    # Causes problems with __ctype
+	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+	    # Compiler inserts libc in the correct place for threads to work
+	    test "X$arg" = "X-lc" && continue
+	    ;;
 	  esac
 	elif test "X$arg" = "X-lc_r"; then
 	 case $host in
-	 *-*-openbsd* | *-*-freebsd*)
+	 *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
 	   # Do not include libc_r directly, use -pthread flag.
 	   continue
 	   ;;
@@ -1366,8 +1590,20 @@
 	continue
 	;;
 
+      # Tru64 UNIX uses -model [arg] to determine the layout of C++
+      # classes, name mangling, and exception handling.
+      -model)
+	compile_command="$compile_command $arg"
+	compiler_flags="$compiler_flags $arg"
+	finalize_command="$finalize_command $arg"
+	prev=xcompiler
+	continue
+	;;
+
      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe)
-	deplibs="$deplibs $arg"
+	compiler_flags="$compiler_flags $arg"
+	compile_command="$compile_command $arg"
+	finalize_command="$finalize_command $arg"
 	continue
 	;;
 
@@ -1376,13 +1612,19 @@
 	continue
 	;;
 
-      # gcc -m* arguments should be passed to the linker via $compiler_flags
-      # in order to pass architecture information to the linker
-      # (e.g. 32 vs 64-bit).  This may also be accomplished via -Wl,-mfoo
-      # but this is not reliable with gcc because gcc may use -mfoo to
-      # select a different linker, different libraries, etc, while
-      # -Wl,-mfoo simply passes -mfoo to the linker.
-      -m*)
+      # -64, -mips[0-9] enable 64-bit mode on the SGI compiler
+      # -r[0-9][0-9]* specifies the processor on the SGI compiler
+      # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler
+      # +DA*, +DD* enable 64-bit mode on the HP compiler
+      # -q* pass through compiler args for the IBM compiler
+      # -m* pass through architecture-specific compiler args for GCC
+      # -m*, -t[45]*, -txscale* pass through architecture-specific
+      # compiler args for GCC
+      # -pg pass through profiling flag for GCC
+      # @file GCC response files
+      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*|-pg| \
+      -t[45]*|-txscale*|@*)
+
 	# Unknown arguments in both finalize_command and compile_command need
 	# to be aesthetically quoted because they are evaled later.
 	arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
@@ -1393,9 +1635,7 @@
 	esac
         compile_command="$compile_command $arg"
         finalize_command="$finalize_command $arg"
-        if test "$with_gcc" = "yes" ; then
-          compiler_flags="$compiler_flags $arg"
-        fi
+        compiler_flags="$compiler_flags $arg"
         continue
         ;;
 
@@ -1633,6 +1873,11 @@
 	    if test -z "$pic_object" || test "$pic_object" = none ; then
 	      arg="$non_pic_object"
 	    fi
+	  else
+	    # If the PIC object exists, use it instead.
+	    # $xdir was prepended to $pic_object above.
+	    non_pic_object="$pic_object"
+	    non_pic_objects="$non_pic_objects $non_pic_object"
 	  fi
 	else
 	  # Only an error if not doing a dry-run.
@@ -1738,9 +1983,9 @@
     if test ! -d "$output_objdir"; then
       $show "$mkdir $output_objdir"
       $run $mkdir $output_objdir
-      status=$?
-      if test "$status" -ne 0 && test ! -d "$output_objdir"; then
-	exit $status
+      exit_status=$?
+      if test "$exit_status" -ne 0 && test ! -d "$output_objdir"; then
+	exit $exit_status
       fi
     fi
 
@@ -1803,7 +2048,6 @@
     newlib_search_path=
     need_relink=no # whether we're linking any uninstalled libtool libraries
     notinst_deplibs= # not-installed libtool libraries
-    notinst_path= # paths that contain not-installed libtool libraries
     case $linkmode in
     lib)
 	passes="conv link"
@@ -1838,10 +2082,7 @@
 	case $pass in
 	dlopen) libs="$dlfiles" ;;
 	dlpreopen) libs="$dlprefiles" ;;
-	link)
-	  libs="$deplibs %DEPLIBS%"
-	  test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs"
-	  ;;
+	link) libs="$deplibs %DEPLIBS% $dependency_libs" ;;
 	esac
       fi
       if test "$pass" = dlopen; then
@@ -1858,7 +2099,7 @@
 	    compile_deplibs="$deplib $compile_deplibs"
 	    finalize_deplibs="$deplib $finalize_deplibs"
 	  else
-	    deplibs="$deplib $deplibs"
+	    compiler_flags="$compiler_flags $deplib"
 	  fi
 	  continue
 	  ;;
@@ -1867,10 +2108,6 @@
 	    $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2
 	    continue
 	  fi
-	  if test "$pass" = conv; then
-	    deplibs="$deplib $deplibs"
-	    continue
-	  fi
 	  name=`$echo "X$deplib" | $Xsed -e 's/^-l//'`
 	  for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do
 	    for search_ext in .la $std_shrext .so .a; do
@@ -1981,7 +2218,22 @@
 	  fi
 	  case $linkmode in
 	  lib)
-	    if test "$deplibs_check_method" != pass_all; then
+	    valid_a_lib=no
+	    case $deplibs_check_method in
+	      match_pattern*)
+		set dummy $deplibs_check_method
+	        match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+		if eval $echo \"$deplib\" 2>/dev/null \
+		    | $SED 10q \
+		    | $EGREP "$match_pattern_regex" > /dev/null; then
+		  valid_a_lib=yes
+		fi
+		;;
+	      pass_all)
+		valid_a_lib=yes
+		;;
+            esac
+	    if test "$valid_a_lib" != yes; then
 	      $echo
 	      $echo "*** Warning: Trying to link with static lib archive $deplib."
 	      $echo "*** I have the capability to make that library automatically link in when"
@@ -2031,7 +2283,7 @@
 	esac # case $deplib
 	if test "$found" = yes || test -f "$lib"; then :
 	else
-	  $echo "$modename: cannot find the library \`$lib'" 1>&2
+	  $echo "$modename: cannot find the library \`$lib' or unhandled argument \`$deplib'" 1>&2
 	  exit $EXIT_FAILURE
 	fi
 
@@ -2055,6 +2307,8 @@
 	# it will not redefine variables installed, or shouldnotlink
 	installed=yes
 	shouldnotlink=no
+	avoidtemprpath=
+
 
 	# Read the .la file
 	case $lib in
@@ -2153,11 +2407,19 @@
 	    dir="$libdir"
 	    absdir="$libdir"
 	  fi
+	  test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
 	else
-	  dir="$ladir/$objdir"
-	  absdir="$abs_ladir/$objdir"
-	  # Remove this search path later
-	  notinst_path="$notinst_path $abs_ladir"
+	  if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	    dir="$ladir"
+	    absdir="$abs_ladir"
+	    # Remove this search path later
+	    notinst_path="$notinst_path $abs_ladir"
+	  else
+	    dir="$ladir/$objdir"
+	    absdir="$abs_ladir/$objdir"
+	    # Remove this search path later
+	    notinst_path="$notinst_path $abs_ladir"
+	  fi
 	fi # $installed = yes
 	name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
 
@@ -2230,12 +2492,12 @@
 	  if test -n "$library_names" &&
 	     { test "$prefer_static_libs" = no || test -z "$old_library"; }; then
 	    # We need to hardcode the library path
-	    if test -n "$shlibpath_var"; then
+	    if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
 	      # Make sure the rpath contains only unique directories.
 	      case "$temp_rpath " in
 	      *" $dir "*) ;;
 	      *" $absdir "*) ;;
-	      *) temp_rpath="$temp_rpath $dir" ;;
+	      *) temp_rpath="$temp_rpath $absdir" ;;
 	      esac
 	    fi
 
@@ -2272,8 +2534,12 @@
 	fi
 
 	link_static=no # Whether the deplib will be linked statically
+	use_static_libs=$prefer_static_libs
+	if test "$use_static_libs" = built && test "$installed" = yes ; then
+	  use_static_libs=no
+	fi
 	if test -n "$library_names" &&
-	   { test "$prefer_static_libs" = no || test -z "$old_library"; }; then
+	   { test "$use_static_libs" = no || test -z "$old_library"; }; then
 	  if test "$installed" = no; then
 	    notinst_deplibs="$notinst_deplibs $lib"
 	    need_relink=yes
@@ -2386,11 +2652,15 @@
 	      if test "$hardcode_direct" = no; then
 		add="$dir/$linklib"
 		case $host in
-		  *-*-sco3.2v5* ) add_dir="-L$dir" ;;
+		  *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
+		  *-*-sysv4*uw2*) add_dir="-L$dir" ;;
+		  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
+		    *-*-unixware7*) add_dir="-L$dir" ;;
 		  *-*-darwin* )
 		    # if the lib is a module then we can not link against
 		    # it, someone is ignoring the new warnings I added
-		    if /usr/bin/file -L $add 2> /dev/null | $EGREP "bundle" >/dev/null ; then
+		    if /usr/bin/file -L $add 2> /dev/null |
+                      $EGREP ": [^:]* bundle" >/dev/null ; then
 		      $echo "** Warning, lib $linklib is a module, not a shared library"
 		      if test -z "$old_library" ; then
 		        $echo
@@ -2421,7 +2691,7 @@
 		add_dir="-L$dir"
 		# Try looking first in the location we're being installed to.
 		if test -n "$inst_prefix_dir"; then
-		  case "$libdir" in
+		  case $libdir in
 		    [\\/]*)
 		      add_dir="$add_dir -L$inst_prefix_dir$libdir"
 		      ;;
@@ -2494,7 +2764,7 @@
 	      add_dir="-L$libdir"
 	      # Try looking first in the location we're being installed to.
 	      if test -n "$inst_prefix_dir"; then
-		case "$libdir" in
+		case $libdir in
 		  [\\/]*)
 		    add_dir="$add_dir -L$inst_prefix_dir$libdir"
 		    ;;
@@ -2555,8 +2825,6 @@
 	      fi
 	    fi
 	  else
-	    convenience="$convenience $dir/$old_library"
-	    old_convenience="$old_convenience $dir/$old_library"
 	    deplibs="$dir/$old_library $deplibs"
 	    link_static=yes
 	  fi
@@ -2674,12 +2942,12 @@
 	      *) continue ;;
 	      esac
 	      case " $deplibs " in
-	      *" $depdepl "*) ;;
-	      *) deplibs="$depdepl $deplibs" ;;
+	      *" $path "*) ;;
+	      *) deplibs="$path $deplibs" ;;
 	      esac
 	      case " $deplibs " in
-	      *" $path "*) ;;
-	      *) deplibs="$deplibs $path" ;;
+	      *" $depdepl "*) ;;
+	      *) deplibs="$depdepl $deplibs" ;;
 	      esac
 	    done
 	  fi # link_all_deplibs != no
@@ -2944,27 +3212,27 @@
 
 	# Check that each of the things are valid numbers.
 	case $current in
-	0 | [1-9] | [1-9][0-9] | [1-9][0-9][0-9]) ;;
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
 	*)
-	  $echo "$modename: CURRENT \`$current' is not a nonnegative integer" 1>&2
+	  $echo "$modename: CURRENT \`$current' must be a nonnegative integer" 1>&2
 	  $echo "$modename: \`$vinfo' is not valid version information" 1>&2
 	  exit $EXIT_FAILURE
 	  ;;
 	esac
 
 	case $revision in
-	0 | [1-9] | [1-9][0-9] | [1-9][0-9][0-9]) ;;
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
 	*)
-	  $echo "$modename: REVISION \`$revision' is not a nonnegative integer" 1>&2
+	  $echo "$modename: REVISION \`$revision' must be a nonnegative integer" 1>&2
 	  $echo "$modename: \`$vinfo' is not valid version information" 1>&2
 	  exit $EXIT_FAILURE
 	  ;;
 	esac
 
 	case $age in
-	0 | [1-9] | [1-9][0-9] | [1-9][0-9][0-9]) ;;
+	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
 	*)
-	  $echo "$modename: AGE \`$age' is not a nonnegative integer" 1>&2
+	  $echo "$modename: AGE \`$age' must be a nonnegative integer" 1>&2
 	  $echo "$modename: \`$vinfo' is not valid version information" 1>&2
 	  exit $EXIT_FAILURE
 	  ;;
@@ -2990,7 +3258,7 @@
 	  versuffix="$major.$age.$revision"
 	  # Darwin ld doesn't like 0 for these options...
 	  minor_current=`expr $current + 1`
-	  verstring="-compatibility_version $minor_current -current_version $minor_current.$revision"
+	  verstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
 	  ;;
 
 	freebsd-aout)
@@ -3143,9 +3411,9 @@
 
       # Eliminate all temporary directories.
       for path in $notinst_path; do
-	lib_search_path=`$echo "$lib_search_path " | ${SED} -e 's% $path % %g'`
-	deplibs=`$echo "$deplibs " | ${SED} -e 's% -L$path % %g'`
-	dependency_libs=`$echo "$dependency_libs " | ${SED} -e 's% -L$path % %g'`
+	lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"`
+	deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"`
+	dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"`
       done
 
       if test -n "$xrpath"; then
@@ -3196,9 +3464,14 @@
 	  *-*-netbsd*)
 	    # Don't link with libc until the a.out ld.so is fixed.
 	    ;;
-	  *-*-openbsd* | *-*-freebsd*)
+	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
 	    # Do not include libc due to us having libc/libc_r.
-	    test "X$arg" = "X-lc" && continue
+	    ;;
+	  *-*-sco3.2v5* | *-*-sco5v6*)
+	    # Causes problems with __ctype
+	    ;;
+	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+	    # Compiler inserts libc in the correct place for threads to work
 	    ;;
  	  *)
 	    # Add libc to deplibs on all other systems if necessary.
@@ -3242,11 +3515,11 @@
 	  int main() { return 0; }
 EOF
 	  $rm conftest
-	  $LTCC -o conftest conftest.c $deplibs
+	  $LTCC $LTCFLAGS -o conftest conftest.c $deplibs
 	  if test "$?" -eq 0 ; then
 	    ldd_output=`ldd conftest`
 	    for i in $deplibs; do
-	      name="`expr $i : '-l\(.*\)'`"
+	      name=`expr $i : '-l\(.*\)'`
 	      # If $name is empty we are operating on a -L argument.
               if test "$name" != "" && test "$name" -ne "0"; then
 		if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
@@ -3283,11 +3556,11 @@
 	    # Error occurred in the first compile.  Let's try to salvage
 	    # the situation: Compile a separate program for each library.
 	    for i in $deplibs; do
-	      name="`expr $i : '-l\(.*\)'`"
+	      name=`expr $i : '-l\(.*\)'`
 	      # If $name is empty we are operating on a -L argument.
               if test "$name" != "" && test "$name" != "0"; then
 		$rm conftest
-		$LTCC -o conftest conftest.c $i
+		$LTCC $LTCFLAGS -o conftest conftest.c $i
 		# Did it work?
 		if test "$?" -eq 0 ; then
 		  ldd_output=`ldd conftest`
@@ -3335,7 +3608,7 @@
 	  set dummy $deplibs_check_method
 	  file_magic_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
 	  for a_deplib in $deplibs; do
-	    name="`expr $a_deplib : '-l\(.*\)'`"
+	    name=`expr $a_deplib : '-l\(.*\)'`
 	    # If $name is empty we are operating on a -L argument.
             if test "$name" != "" && test  "$name" != "0"; then
 	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
@@ -3404,7 +3677,7 @@
 	  set dummy $deplibs_check_method
 	  match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
 	  for a_deplib in $deplibs; do
-	    name="`expr $a_deplib : '-l\(.*\)'`"
+	    name=`expr $a_deplib : '-l\(.*\)'`
 	    # If $name is empty we are operating on a -L argument.
 	    if test -n "$name" && test "$name" != "0"; then
 	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
@@ -3534,6 +3807,35 @@
 	deplibs=$newdeplibs
       fi
 
+
+      # move library search paths that coincide with paths to not yet
+      # installed libraries to the beginning of the library search list
+      new_libs=
+      for path in $notinst_path; do
+	case " $new_libs " in
+	*" -L$path/$objdir "*) ;;
+	*)
+	  case " $deplibs " in
+	  *" -L$path/$objdir "*)
+	    new_libs="$new_libs -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) new_libs="$new_libs $deplib" ;;
+	  esac
+	  ;;
+	*) new_libs="$new_libs $deplib" ;;
+	esac
+      done
+      deplibs="$new_libs"
+
+
       # All the library-specific variables (install_libdir is set above).
       library_names=
       old_library=
@@ -3617,6 +3919,7 @@
 	fi
 
 	lib="$output_objdir/$realname"
+	linknames=
 	for link
 	do
 	  linknames="$linknames $link"
@@ -3645,6 +3948,9 @@
 	        # The command line is too long to execute in one step.
 	        $show "using reloadable object file for export list..."
 	        skipped_export=:
+		# Break out early, otherwise skipped_export may be
+		# set to false by a later but shorter cmd.
+		break
 	      fi
 	    done
 	    IFS="$save_ifs"
@@ -3678,67 +3984,13 @@
 	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
 	  else
 	    gentop="$output_objdir/${outputname}x"
-	    $show "${rm}r $gentop"
-	    $run ${rm}r "$gentop"
-	    $show "$mkdir $gentop"
-	    $run $mkdir "$gentop"
-	    status=$?
-	    if test "$status" -ne 0 && test ! -d "$gentop"; then
-	      exit $status
-	    fi
 	    generated="$generated $gentop"
 
-	    for xlib in $convenience; do
-	      # Extract the objects.
-	      case $xlib in
-	      [\\/]* | [A-Za-z]:[\\/]*) xabs="$xlib" ;;
-	      *) xabs=`pwd`"/$xlib" ;;
-	      esac
-	      xlib=`$echo "X$xlib" | $Xsed -e 's%^.*/%%'`
-	      xdir="$gentop/$xlib"
-
-	      $show "${rm}r $xdir"
-	      $run ${rm}r "$xdir"
-	      $show "$mkdir $xdir"
-	      $run $mkdir "$xdir"
-	      status=$?
-	      if test "$status" -ne 0 && test ! -d "$xdir"; then
-		exit $status
-	      fi
-	      # We will extract separately just the conflicting names and we will no
-	      # longer touch any unique names. It is faster to leave these extract
-	      # automatically by $AR in one run.
-	      $show "(cd $xdir && $AR x $xabs)"
-	      $run eval "(cd \$xdir && $AR x \$xabs)" || exit $?
-	      if ($AR t "$xabs" | sort | sort -uc >/dev/null 2>&1); then
-		:
-	      else
-		$echo "$modename: warning: object name conflicts; renaming object files" 1>&2
-		$echo "$modename: warning: to ensure that they will not overwrite" 1>&2
-		$AR t "$xabs" | sort | uniq -cd | while read -r count name
-		do
-		  i=1
-		  while test "$i" -le "$count"
-		  do
-		   # Put our $i before any first dot (extension)
-		   # Never overwrite any file
-		   name_to="$name"
-		   while test "X$name_to" = "X$name" || test -f "$xdir/$name_to"
-		   do
-		     name_to=`$echo "X$name_to" | $Xsed -e "s/\([^.]*\)/\1-$i/"`
-		   done
-		   $show "(cd $xdir && $AR xN $i $xabs '$name' && $mv '$name' '$name_to')"
-		   $run eval "(cd \$xdir && $AR xN $i \$xabs '$name' && $mv '$name' '$name_to')" || exit $?
-		   i=`expr $i + 1`
-		  done
-		done
-	      fi
-
-	      libobjs="$libobjs "`find $xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
-	    done
+	    func_extract_archives $gentop $convenience
+	    libobjs="$libobjs $func_extract_archives_result"
 	  fi
 	fi
-
+	
 	if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
 	  eval flag=\"$thread_safe_flag_spec\"
 	  linker_flags="$linker_flags $flag"
@@ -3768,7 +4020,8 @@
 	  fi
 	fi
 
-	if test "X$skipped_export" != "X:" && len=`expr "X$test_cmds" : ".*"` &&
+	if test "X$skipped_export" != "X:" &&
+	   len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
 	   test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
 	  :
 	else
@@ -3787,6 +4040,7 @@
 	    save_libobjs=$libobjs
 	  fi
 	  save_output=$output
+	  output_la=`$echo "X$output" | $Xsed -e "$basename"`
 
 	  # Clear the reloadable object creation command queue and
 	  # initialize k to one.
@@ -3796,13 +4050,13 @@
 	  delfiles=
 	  last_robj=
 	  k=1
-	  output=$output_objdir/$save_output-${k}.$objext
+	  output=$output_objdir/$output_la-${k}.$objext
 	  # Loop over the list of objects to be linked.
 	  for obj in $save_libobjs
 	  do
 	    eval test_cmds=\"$reload_cmds $objlist $last_robj\"
 	    if test "X$objlist" = X ||
-	       { len=`expr "X$test_cmds" : ".*"` &&
+	       { len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
 		 test "$len" -le "$max_cmd_len"; }; then
 	      objlist="$objlist $obj"
 	    else
@@ -3816,9 +4070,9 @@
 		# the last one created.
 		eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj\"
 	      fi
-	      last_robj=$output_objdir/$save_output-${k}.$objext
+	      last_robj=$output_objdir/$output_la-${k}.$objext
 	      k=`expr $k + 1`
-	      output=$output_objdir/$save_output-${k}.$objext
+	      output=$output_objdir/$output_la-${k}.$objext
 	      objlist=$obj
 	      len=1
 	    fi
@@ -3838,13 +4092,13 @@
 	    eval concat_cmds=\"\$concat_cmds~$export_symbols_cmds\"
           fi
 
-	  # Set up a command to remove the reloadale object files
+	  # Set up a command to remove the reloadable object files
 	  # after they are used.
 	  i=0
 	  while test "$i" -lt "$k"
 	  do
 	    i=`expr $i + 1`
-	    delfiles="$delfiles $output_objdir/$save_output-${i}.$objext"
+	    delfiles="$delfiles $output_objdir/$output_la-${i}.$objext"
 	  done
 
 	  $echo "creating a temporary reloadable object file: $output"
@@ -3892,13 +4146,30 @@
 	  IFS="$save_ifs"
 	  eval cmd=\"$cmd\"
 	  $show "$cmd"
-	  $run eval "$cmd" || exit $?
+	  $run eval "$cmd" || {
+	    lt_exit=$?
+
+	    # Restore the uninstalled library and exit
+	    if test "$mode" = relink; then
+	      $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
+	    fi
+
+	    exit $lt_exit
+	  }
 	done
 	IFS="$save_ifs"
 
 	# Restore the uninstalled library and exit
 	if test "$mode" = relink; then
 	  $run eval '(cd $output_objdir && $rm ${realname}T && $mv $realname ${realname}T && $mv "$realname"U $realname)' || exit $?
+
+	  if test -n "$convenience"; then
+	    if test -z "$whole_archive_flag_spec"; then
+	      $show "${rm}r $gentop"
+	      $run ${rm}r "$gentop"
+	    fi
+	  fi
+
 	  exit $EXIT_SUCCESS
 	fi
 
@@ -3976,64 +4247,10 @@
 	  eval reload_conv_objs=\"\$reload_objs $whole_archive_flag_spec\"
 	else
 	  gentop="$output_objdir/${obj}x"
-	  $show "${rm}r $gentop"
-	  $run ${rm}r "$gentop"
-	  $show "$mkdir $gentop"
-	  $run $mkdir "$gentop"
-	  status=$?
-	  if test "$status" -ne 0 && test ! -d "$gentop"; then
-	    exit $status
-	  fi
 	  generated="$generated $gentop"
 
-	  for xlib in $convenience; do
-	    # Extract the objects.
-	    case $xlib in
-	    [\\/]* | [A-Za-z]:[\\/]*) xabs="$xlib" ;;
-	    *) xabs=`pwd`"/$xlib" ;;
-	    esac
-	    xlib=`$echo "X$xlib" | $Xsed -e 's%^.*/%%'`
-	    xdir="$gentop/$xlib"
-
-	    $show "${rm}r $xdir"
-	    $run ${rm}r "$xdir"
-	    $show "$mkdir $xdir"
-	    $run $mkdir "$xdir"
-	    status=$?
-	    if test "$status" -ne 0 && test ! -d "$xdir"; then
-	      exit $status
-	    fi
-	    # We will extract separately just the conflicting names and we will no
-	    # longer touch any unique names. It is faster to leave these extract
-	    # automatically by $AR in one run.
-	    $show "(cd $xdir && $AR x $xabs)"
-	    $run eval "(cd \$xdir && $AR x \$xabs)" || exit $?
-	    if ($AR t "$xabs" | sort | sort -uc >/dev/null 2>&1); then
-	      :
-	    else
-	      $echo "$modename: warning: object name conflicts; renaming object files" 1>&2
-	      $echo "$modename: warning: to ensure that they will not overwrite" 1>&2
-	      $AR t "$xabs" | sort | uniq -cd | while read -r count name
-	      do
-		i=1
-		while test "$i" -le "$count"
-		do
-		 # Put our $i before any first dot (extension)
-		 # Never overwrite any file
-		 name_to="$name"
-		 while test "X$name_to" = "X$name" || test -f "$xdir/$name_to"
-		 do
-		   name_to=`$echo "X$name_to" | $Xsed -e "s/\([^.]*\)/\1-$i/"`
-		 done
-		 $show "(cd $xdir && $AR xN $i $xabs '$name' && $mv '$name' '$name_to')"
-		 $run eval "(cd \$xdir && $AR xN $i \$xabs '$name' && $mv '$name' '$name_to')" || exit $?
-		 i=`expr $i + 1`
-		done
-	      done
-	    fi
-
-	    reload_conv_objs="$reload_objs "`find $xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
-	  done
+	  func_extract_archives $gentop $convenience
+	  reload_conv_objs="$reload_objs $func_extract_archives_result"
 	fi
       fi
 
@@ -4134,6 +4351,35 @@
         ;;
       esac
 
+
+      # move library search paths that coincide with paths to not yet
+      # installed libraries to the beginning of the library search list
+      new_libs=
+      for path in $notinst_path; do
+	case " $new_libs " in
+	*" -L$path/$objdir "*) ;;
+	*)
+	  case " $compile_deplibs " in
+	  *" -L$path/$objdir "*)
+	    new_libs="$new_libs -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $compile_deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) new_libs="$new_libs $deplib" ;;
+	  esac
+	  ;;
+	*) new_libs="$new_libs $deplib" ;;
+	esac
+      done
+      compile_deplibs="$new_libs"
+
+
       compile_command="$compile_command $compile_deplibs"
       finalize_command="$finalize_command $finalize_deplibs"
 
@@ -4178,10 +4424,15 @@
 	fi
 	case $host in
 	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+	  testbindir=`$echo "X$libdir" | $Xsed -e 's*/lib$*/bin*'`
 	  case :$dllsearchpath: in
 	  *":$libdir:"*) ;;
 	  *) dllsearchpath="$dllsearchpath:$libdir";;
 	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  *) dllsearchpath="$dllsearchpath:$testbindir";;
+	  esac
 	  ;;
 	esac
       done
@@ -4295,13 +4546,25 @@
 
 	    # Prepare the list of exported symbols
 	    if test -z "$export_symbols"; then
-	      export_symbols="$output_objdir/$output.exp"
+	      export_symbols="$output_objdir/$outputname.exp"
 	      $run $rm $export_symbols
-	      $run eval "${SED} -n -e '/^: @PROGRAM@$/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+	      $run eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+              case $host in
+              *cygwin* | *mingw* )
+	        $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+		$run eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
+                ;;
+              esac
 	    else
-	      $run eval "${SED} -e 's/\([][.*^$]\)/\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$output.exp"'
-	      $run eval 'grep -f "$output_objdir/$output.exp" < "$nlist" > "$nlist"T'
+	      $run eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
+	      $run eval 'grep -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
 	      $run eval 'mv "$nlist"T "$nlist"'
+              case $host in
+              *cygwin* | *mingw* )
+	        $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+		$run eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+                ;;
+              esac
 	    fi
 	  fi
 
@@ -4352,7 +4615,26 @@
 #endif
 
 /* The mapping between symbol names and symbols. */
+"
+
+	    case $host in
+	    *cygwin* | *mingw* )
+	  $echo >> "$output_objdir/$dlsyms" "\
+/* DATA imports from DLLs on WIN32 can't be const, because
+   runtime relocations are performed -- see ld's documentation
+   on pseudo-relocs */
+struct {
+"
+	      ;;
+	    * )
+	  $echo >> "$output_objdir/$dlsyms" "\
 const struct {
+"
+	      ;;
+	    esac
+
+
+	  $echo >> "$output_objdir/$dlsyms" "\
   const char *name;
   lt_ptr address;
 }
@@ -4399,16 +4681,29 @@
 	  esac
 
 	  # Now compile the dynamic symbol file.
-	  $show "(cd $output_objdir && $LTCC -c$no_builtin_flag$pic_flag_for_symtable \"$dlsyms\")"
-	  $run eval '(cd $output_objdir && $LTCC -c$no_builtin_flag$pic_flag_for_symtable "$dlsyms")' || exit $?
+	  $show "(cd $output_objdir && $LTCC  $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable \"$dlsyms\")"
+	  $run eval '(cd $output_objdir && $LTCC  $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable "$dlsyms")' || exit $?
 
 	  # Clean up the generated files.
 	  $show "$rm $output_objdir/$dlsyms $nlist ${nlist}S ${nlist}T"
 	  $run $rm "$output_objdir/$dlsyms" "$nlist" "${nlist}S" "${nlist}T"
 
 	  # Transform the symbol file into the correct name.
-	  compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
-	  finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
+          case $host in
+          *cygwin* | *mingw* )
+            if test -f "$output_objdir/${outputname}.def" ; then
+              compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"`
+              finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"`
+            else
+              compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
+              finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
+             fi
+            ;;
+          * )
+            compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
+            finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
+            ;;
+          esac
 	  ;;
 	*)
 	  $echo "$modename: unknown suffix for \`$dlsyms'" 1>&2
@@ -4433,7 +4728,7 @@
 	# We have no uninstalled library dependencies, so finalize right now.
 	$show "$link_command"
 	$run eval "$link_command"
-	status=$?
+	exit_status=$?
 
 	# Delete the generated files.
 	if test -n "$dlsyms"; then
@@ -4441,7 +4736,7 @@
 	  $run $rm "$output_objdir/${outputname}S.${objext}"
 	fi
 
-	exit $status
+	exit $exit_status
       fi
 
       if test -n "$shlibpath_var"; then
@@ -4581,10 +4876,12 @@
 	esac
 	case $host in
 	  *cygwin* | *mingw* )
-	    cwrappersource=`$echo ${objdir}/lt-${output}.c`
-	    cwrapper=`$echo ${output}.exe`
-	    $rm $cwrappersource $cwrapper
-	    trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
+            output_name=`basename $output`
+            output_path=`dirname $output`
+            cwrappersource="$output_path/$objdir/lt-$output_name.c"
+            cwrapper="$output_path/$output_name.exe"
+            $rm $cwrappersource $cwrapper
+            trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
 
 	    cat > $cwrappersource <<EOF
 
@@ -4609,6 +4906,9 @@
 #include <malloc.h>
 #include <stdarg.h>
 #include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <sys/stat.h>
 
 #if defined(PATH_MAX)
 # define LT_PATHMAX PATH_MAX
@@ -4619,15 +4919,19 @@
 #endif
 
 #ifndef DIR_SEPARATOR
-#define DIR_SEPARATOR '/'
+# define DIR_SEPARATOR '/'
+# define PATH_SEPARATOR ':'
 #endif
 
 #if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
   defined (__OS2__)
-#define HAVE_DOS_BASED_FILE_SYSTEM
-#ifndef DIR_SEPARATOR_2
-#define DIR_SEPARATOR_2 '\\'
-#endif
+# define HAVE_DOS_BASED_FILE_SYSTEM
+# ifndef DIR_SEPARATOR_2
+#  define DIR_SEPARATOR_2 '\\'
+# endif
+# ifndef PATH_SEPARATOR_2
+#  define PATH_SEPARATOR_2 ';'
+# endif
 #endif
 
 #ifndef DIR_SEPARATOR_2
@@ -4637,17 +4941,32 @@
         (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
 #endif /* DIR_SEPARATOR_2 */
 
+#ifndef PATH_SEPARATOR_2
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
+#else /* PATH_SEPARATOR_2 */
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
+#endif /* PATH_SEPARATOR_2 */
+
 #define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))
 #define XFREE(stale) do { \
   if (stale) { free ((void *) stale); stale = 0; } \
 } while (0)
 
+/* -DDEBUG is fairly common in CFLAGS.  */
+#undef DEBUG
+#if defined DEBUGWRAPPER
+# define DEBUG(format, ...) fprintf(stderr, format, __VA_ARGS__)
+#else
+# define DEBUG(format, ...)
+#endif
+
 const char *program_name = NULL;
 
 void * xmalloc (size_t num);
 char * xstrdup (const char *string);
-char * basename (const char *name);
-char * fnqualify(const char *path);
+const char * base_name (const char *name);
+char * find_executable(const char *wrapper);
+int    check_executable(const char *path);
 char * strendzap(char *str, const char *pat);
 void lt_fatal (const char *message, ...);
 
@@ -4657,29 +4976,51 @@
   char **newargz;
   int i;
 
-  program_name = (char *) xstrdup ((char *) basename (argv[0]));
+  program_name = (char *) xstrdup (base_name (argv[0]));
+  DEBUG("(main) argv[0]      : %s\n",argv[0]);
+  DEBUG("(main) program_name : %s\n",program_name);
   newargz = XMALLOC(char *, argc+2);
 EOF
 
-	    cat >> $cwrappersource <<EOF
-  newargz[0] = "$SHELL";
+            cat >> $cwrappersource <<EOF
+  newargz[0] = (char *) xstrdup("$SHELL");
 EOF
 
-	    cat >> $cwrappersource <<"EOF"
-  newargz[1] = fnqualify(argv[0]);
+            cat >> $cwrappersource <<"EOF"
+  newargz[1] = find_executable(argv[0]);
+  if (newargz[1] == NULL)
+    lt_fatal("Couldn't find %s", argv[0]);
+  DEBUG("(main) found exe at : %s\n",newargz[1]);
   /* we know the script has the same name, without the .exe */
   /* so make sure newargz[1] doesn't end in .exe */
   strendzap(newargz[1],".exe");
   for (i = 1; i < argc; i++)
     newargz[i+1] = xstrdup(argv[i]);
   newargz[argc+1] = NULL;
+
+  for (i=0; i<argc+1; i++)
+  {
+    DEBUG("(main) newargz[%d]   : %s\n",i,newargz[i]);
+    ;
+  }
+
 EOF
 
-	    cat >> $cwrappersource <<EOF
+            case $host_os in
+              mingw*)
+                cat >> $cwrappersource <<EOF
+  execv("$SHELL",(char const **)newargz);
+EOF
+              ;;
+              *)
+                cat >> $cwrappersource <<EOF
   execv("$SHELL",newargz);
 EOF
+              ;;
+            esac
 
-	    cat >> $cwrappersource <<"EOF"
+            cat >> $cwrappersource <<"EOF"
+  return 127;
 }
 
 void *
@@ -4699,48 +5040,148 @@
 ;
 }
 
-char *
-basename (const char *name)
+const char *
+base_name (const char *name)
 {
   const char *base;
 
 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
   /* Skip over the disk name in MSDOS pathnames. */
-  if (isalpha (name[0]) && name[1] == ':')
+  if (isalpha ((unsigned char)name[0]) && name[1] == ':')
     name += 2;
 #endif
 
   for (base = name; *name; name++)
     if (IS_DIR_SEPARATOR (*name))
       base = name + 1;
-  return (char *) base;
+  return base;
+}
+
+int
+check_executable(const char * path)
+{
+  struct stat st;
+
+  DEBUG("(check_executable)  : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!");
+  if ((!path) || (!*path))
+    return 0;
+
+  if ((stat (path, &st) >= 0) &&
+      (
+        /* MinGW & native WIN32 do not support S_IXOTH or S_IXGRP */
+#if defined (S_IXOTH)
+       ((st.st_mode & S_IXOTH) == S_IXOTH) ||
+#endif
+#if defined (S_IXGRP)
+       ((st.st_mode & S_IXGRP) == S_IXGRP) ||
+#endif
+       ((st.st_mode & S_IXUSR) == S_IXUSR))
+      )
+    return 1;
+  else
+    return 0;
 }
 
+/* Searches for the full path of the wrapper.  Returns
+   newly allocated full path name if found, NULL otherwise */
 char *
-fnqualify(const char *path)
+find_executable (const char* wrapper)
 {
-  size_t size;
-  char *p;
+  int has_slash = 0;
+  const char* p;
+  const char* p_next;
+  /* static buffer for getcwd */
   char tmp[LT_PATHMAX + 1];
+  int tmp_len;
+  char* concat_name;
 
-  assert(path != NULL);
+  DEBUG("(find_executable)  : %s\n", wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!");
 
-  /* Is it qualified already? */
+  if ((wrapper == NULL) || (*wrapper == '\0'))
+    return NULL;
+
+  /* Absolute path? */
 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
-  if (isalpha (path[0]) && path[1] == ':')
-    return xstrdup (path);
+  if (isalpha ((unsigned char)wrapper[0]) && wrapper[1] == ':')
+  {
+    concat_name = xstrdup (wrapper);
+    if (check_executable(concat_name))
+      return concat_name;
+    XFREE(concat_name);
+  }
+  else
+  {
+#endif
+    if (IS_DIR_SEPARATOR (wrapper[0]))
+    {
+      concat_name = xstrdup (wrapper);
+      if (check_executable(concat_name))
+        return concat_name;
+      XFREE(concat_name);
+    }
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+  }
 #endif
-  if (IS_DIR_SEPARATOR (path[0]))
-    return xstrdup (path);
 
-  /* prepend the current directory */
-  /* doesn't handle '~' */
+  for (p = wrapper; *p; p++)
+    if (*p == '/')
+    {
+      has_slash = 1;
+      break;
+    }
+  if (!has_slash)
+  {
+    /* no slashes; search PATH */
+    const char* path = getenv ("PATH");
+    if (path != NULL)
+    {
+      for (p = path; *p; p = p_next)
+      {
+        const char* q;
+        size_t p_len;
+        for (q = p; *q; q++)
+          if (IS_PATH_SEPARATOR(*q))
+            break;
+        p_len = q - p;
+        p_next = (*q == '\0' ? q : q + 1);
+        if (p_len == 0)
+        {
+          /* empty path: current directory */
+          if (getcwd (tmp, LT_PATHMAX) == NULL)
+            lt_fatal ("getcwd failed");
+          tmp_len = strlen(tmp);
+          concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
+          memcpy (concat_name, tmp, tmp_len);
+          concat_name[tmp_len] = '/';
+          strcpy (concat_name + tmp_len + 1, wrapper);
+        }
+        else
+        {
+          concat_name = XMALLOC(char, p_len + 1 + strlen(wrapper) + 1);
+          memcpy (concat_name, p, p_len);
+          concat_name[p_len] = '/';
+          strcpy (concat_name + p_len + 1, wrapper);
+        }
+        if (check_executable(concat_name))
+          return concat_name;
+        XFREE(concat_name);
+      }
+    }
+    /* not found in PATH; assume curdir */
+  }
+  /* Relative path | not found in path: prepend cwd */
   if (getcwd (tmp, LT_PATHMAX) == NULL)
     lt_fatal ("getcwd failed");
-  size = strlen(tmp) + 1 + strlen(path) + 1; /* +2 for '/' and '\0' */
-  p = XMALLOC(char, size);
-  sprintf(p, "%s%c%s", tmp, DIR_SEPARATOR, path);
-  return p;
+  tmp_len = strlen(tmp);
+  concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
+  memcpy (concat_name, tmp, tmp_len);
+  concat_name[tmp_len] = '/';
+  strcpy (concat_name + tmp_len + 1, wrapper);
+
+  if (check_executable(concat_name))
+    return concat_name;
+  XFREE(concat_name);
+  return NULL;
 }
 
 char *
@@ -4784,16 +5225,16 @@
   va_end (ap);
 }
 EOF
-	  # we should really use a build-platform specific compiler
-	  # here, but OTOH, the wrappers (shell script and this C one)
-	  # are only useful if you want to execute the "real" binary.
-	  # Since the "real" binary is built for $host, then this
-	  # wrapper might as well be built for $host, too.
-	  $run $LTCC -s -o $cwrapper $cwrappersource
-	  ;;
-	esac
-	$rm $output
-	trap "$rm $output; exit $EXIT_FAILURE" 1 2 15
+          # we should really use a build-platform specific compiler
+          # here, but OTOH, the wrappers (shell script and this C one)
+          # are only useful if you want to execute the "real" binary.
+          # Since the "real" binary is built for $host, then this
+          # wrapper might as well be built for $host, too.
+          $run $LTCC $LTCFLAGS -s -o $cwrapper $cwrappersource
+          ;;
+        esac
+        $rm $output
+        trap "$rm $output; exit $EXIT_FAILURE" 1 2 15
 
 	$echo > $output "\
 #! $SHELL
@@ -4814,7 +5255,7 @@
 
 # The HP-UX ksh and POSIX shell print the target directory to stdout
 # if CDPATH is set.
-if test \"\${CDPATH+set}\" = set; then CDPATH=:; export CDPATH; fi
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
 
 relink_command=\"$relink_command\"
 
@@ -4943,13 +5384,13 @@
 	# Backslashes separate directories on plain windows
 	*-*-mingw | *-*-os2*)
 	  $echo >> $output "\
-      exec \$progdir\\\\\$program \${1+\"\$@\"}
+      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
 "
 	  ;;
 
 	*)
 	  $echo >> $output "\
-      exec \$progdir/\$program \${1+\"\$@\"}
+      exec \"\$progdir/\$program\" \${1+\"\$@\"}
 "
 	  ;;
 	esac
@@ -4959,7 +5400,7 @@
     fi
   else
     # The program doesn't exist.
-    \$echo \"\$0: error: \$progdir/\$program does not exist\" 1>&2
+    \$echo \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
     \$echo \"This script is just a wrapper for \$program.\" 1>&2
     $echo \"See the $PACKAGE documentation for more information.\" 1>&2
     exit $EXIT_FAILURE
@@ -4991,71 +5432,73 @@
 
       if test -n "$addlibs"; then
 	gentop="$output_objdir/${outputname}x"
-	$show "${rm}r $gentop"
-	$run ${rm}r "$gentop"
-	$show "$mkdir $gentop"
-	$run $mkdir "$gentop"
-	status=$?
-	if test "$status" -ne 0 && test ! -d "$gentop"; then
-	  exit $status
-	fi
 	generated="$generated $gentop"
 
-	# Add in members from convenience archives.
-	for xlib in $addlibs; do
-	  # Extract the objects.
-	  case $xlib in
-	  [\\/]* | [A-Za-z]:[\\/]*) xabs="$xlib" ;;
-	  *) xabs=`pwd`"/$xlib" ;;
-	  esac
-	  xlib=`$echo "X$xlib" | $Xsed -e 's%^.*/%%'`
-	  xdir="$gentop/$xlib"
-
-	  $show "${rm}r $xdir"
-	  $run ${rm}r "$xdir"
-	  $show "$mkdir $xdir"
-	  $run $mkdir "$xdir"
-	  status=$?
-	  if test "$status" -ne 0 && test ! -d "$xdir"; then
-	    exit $status
-	  fi
-	  # We will extract separately just the conflicting names and we will no
-	  # longer touch any unique names. It is faster to leave these extract
-	  # automatically by $AR in one run.
-	  $show "(cd $xdir && $AR x $xabs)"
-	  $run eval "(cd \$xdir && $AR x \$xabs)" || exit $?
-	  if ($AR t "$xabs" | sort | sort -uc >/dev/null 2>&1); then
-	    :
-	  else
-	    $echo "$modename: warning: object name conflicts; renaming object files" 1>&2
-	    $echo "$modename: warning: to ensure that they will not overwrite" 1>&2
-	    $AR t "$xabs" | sort | uniq -cd | while read -r count name
-	    do
-	      i=1
-	      while test "$i" -le "$count"
-	      do
-	       # Put our $i before any first dot (extension)
-	       # Never overwrite any file
-	       name_to="$name"
-	       while test "X$name_to" = "X$name" || test -f "$xdir/$name_to"
-	       do
-		 name_to=`$echo "X$name_to" | $Xsed -e "s/\([^.]*\)/\1-$i/"`
-	       done
-	       $show "(cd $xdir && $AR xN $i $xabs '$name' && $mv '$name' '$name_to')"
-	       $run eval "(cd \$xdir && $AR xN $i \$xabs '$name' && $mv '$name' '$name_to')" || exit $?
-	       i=`expr $i + 1`
-	      done
-	    done
-	  fi
-
-	  oldobjs="$oldobjs "`find $xdir -name \*.${objext} -print -o -name \*.lo -print | $NL2SP`
-	done
+	func_extract_archives $gentop $addlibs
+	oldobjs="$oldobjs $func_extract_archives_result"
       fi
 
       # Do each command in the archive commands.
       if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
        cmds=$old_archive_from_new_cmds
       else
+	# POSIX demands no paths to be encoded in archives.  We have
+	# to avoid creating archives with duplicate basenames if we
+	# might have to extract them afterwards, e.g., when creating a
+	# static archive out of a convenience library, or when linking
+	# the entirety of a libtool archive into another (currently
+	# not supported by libtool).
+	if (for obj in $oldobjs
+	    do
+	      $echo "X$obj" | $Xsed -e 's%^.*/%%'
+	    done | sort | sort -uc >/dev/null 2>&1); then
+	  :
+	else
+	  $echo "copying selected object files to avoid basename conflicts..."
+
+	  if test -z "$gentop"; then
+	    gentop="$output_objdir/${outputname}x"
+	    generated="$generated $gentop"
+
+	    $show "${rm}r $gentop"
+	    $run ${rm}r "$gentop"
+	    $show "$mkdir $gentop"
+	    $run $mkdir "$gentop"
+	    exit_status=$?
+	    if test "$exit_status" -ne 0 && test ! -d "$gentop"; then
+	      exit $exit_status
+	    fi
+	  fi
+
+	  save_oldobjs=$oldobjs
+	  oldobjs=
+	  counter=1
+	  for obj in $save_oldobjs
+	  do
+	    objbase=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
+	    case " $oldobjs " in
+	    " ") oldobjs=$obj ;;
+	    *[\ /]"$objbase "*)
+	      while :; do
+		# Make sure we don't pick an alternate name that also
+		# overlaps.
+		newobj=lt$counter-$objbase
+		counter=`expr $counter + 1`
+		case " $oldobjs " in
+		*[\ /]"$newobj "*) ;;
+		*) if test ! -f "$gentop/$newobj"; then break; fi ;;
+		esac
+	      done
+	      $show "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
+	      $run ln "$obj" "$gentop/$newobj" ||
+	      $run cp "$obj" "$gentop/$newobj"
+	      oldobjs="$oldobjs $gentop/$newobj"
+	      ;;
+	    *) oldobjs="$oldobjs $obj" ;;
+	    esac
+	  done
+	fi
+
 	eval cmds=\"$old_archive_cmds\"
 
 	if len=`expr "X$cmds" : ".*"` &&
@@ -5069,20 +5512,7 @@
 	  objlist=
 	  concat_cmds=
 	  save_oldobjs=$oldobjs
-	  # GNU ar 2.10+ was changed to match POSIX; thus no paths are
-	  # encoded into archives.  This makes 'ar r' malfunction in
-	  # this piecewise linking case whenever conflicting object
-	  # names appear in distinct ar calls; check, warn and compensate.
-	    if (for obj in $save_oldobjs
-	    do
-	      $echo "X$obj" | $Xsed -e 's%^.*/%%'
-	    done | sort | sort -uc >/dev/null 2>&1); then
-	    :
-	  else
-	    $echo "$modename: warning: object name conflicts; overriding AR_FLAGS to 'cq'" 1>&2
-	    $echo "$modename: warning: to ensure that POSIX-compatible ar will work" 1>&2
-	    AR_FLAGS=cq
-	  fi
+
 	  # Is there a better way of finding the last object in the list?
 	  for obj in $save_oldobjs
 	  do
@@ -5093,7 +5523,7 @@
 	    oldobjs="$objlist $obj"
 	    objlist="$objlist $obj"
 	    eval test_cmds=\"$old_archive_cmds\"
-	    if len=`expr "X$test_cmds" : ".*"` &&
+	    if len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
 	       test "$len" -le "$max_cmd_len"; then
 	      :
 	    else
@@ -5290,11 +5720,11 @@
     # install_prog (especially on Windows NT).
     if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
        # Allow the use of GNU shtool's install command.
-       $echo "X$nonopt" | $Xsed | grep shtool > /dev/null; then
+       $echo "X$nonopt" | grep shtool > /dev/null; then
       # Aesthetically quote it.
       arg=`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"`
       case $arg in
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*)
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
 	arg="\"$arg\""
 	;;
       esac
@@ -5303,14 +5733,14 @@
       shift
     else
       install_prog=
-      arg="$nonopt"
+      arg=$nonopt
     fi
 
     # The real first argument should be the name of the installation program.
     # Aesthetically quote it.
     arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
     case $arg in
-    *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*)
+    *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
       arg="\"$arg\""
       ;;
     esac
@@ -5328,28 +5758,31 @@
     do
       if test -n "$dest"; then
 	files="$files $dest"
-	dest="$arg"
+	dest=$arg
 	continue
       fi
 
       case $arg in
       -d) isdir=yes ;;
-      -f) prev="-f" ;;
-      -g) prev="-g" ;;
-      -m) prev="-m" ;;
-      -o) prev="-o" ;;
+      -f) 
+      	case " $install_prog " in
+	*[\\\ /]cp\ *) ;;
+	*) prev=$arg ;;
+	esac
+	;;
+      -g | -m | -o) prev=$arg ;;
       -s)
 	stripme=" -s"
 	continue
 	;;
-      -*) ;;
-
+      -*)
+	;;
       *)
 	# If the previous option needed an argument, then skip it.
 	if test -n "$prev"; then
 	  prev=
 	else
-	  dest="$arg"
+	  dest=$arg
 	  continue
 	fi
 	;;
@@ -5358,7 +5791,7 @@
       # Aesthetically quote the argument.
       arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
       case $arg in
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*)
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
 	arg="\"$arg\""
 	;;
       esac
@@ -5527,11 +5960,14 @@
 
 	  if test "$#" -gt 0; then
 	    # Delete the old symlinks, and create new ones.
+	    # Try `ln -sf' first, because the `ln' binary might depend on
+	    # the symlink we replace!  Solaris /bin/ln does not understand -f,
+	    # so we also need to try rm && ln -s.
 	    for linkname
 	    do
 	      if test "$linkname" != "$realname"; then
-		$show "(cd $destdir && $rm $linkname && $LN_S $realname $linkname)"
-		$run eval "(cd $destdir && $rm $linkname && $LN_S $realname $linkname)"
+                $show "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
+                $run eval "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
 	      fi
 	    done
 	  fi
@@ -5544,7 +5980,16 @@
 	    IFS="$save_ifs"
 	    eval cmd=\"$cmd\"
 	    $show "$cmd"
-	    $run eval "$cmd" || exit $?
+	    $run eval "$cmd" || {
+	      lt_exit=$?
+
+	      # Restore the uninstalled library and exit
+	      if test "$mode" = relink; then
+		$run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
+	      fi
+
+	      exit $lt_exit
+	    }
 	  done
 	  IFS="$save_ifs"
 	fi
@@ -5638,17 +6083,15 @@
 	  notinst_deplibs=
 	  relink_command=
 
-	  # To insure that "foo" is sourced, and not "foo.exe",
-	  # finese the cygwin/MSYS system by explicitly sourcing "foo."
-	  # which disallows the automatic-append-.exe behavior.
-	  case $build in
-	  *cygwin* | *mingw*) wrapperdot=${wrapper}. ;;
-	  *) wrapperdot=${wrapper} ;;
-	  esac
+	  # Note that it is not necessary on cygwin/mingw to append a dot to
+	  # foo even if both foo and FILE.exe exist: automatic-append-.exe
+	  # behavior happens only for exec(3), not for open(2)!  Also, sourcing
+	  # `FILE.' does not work on cygwin managed mounts.
+	  #
 	  # If there is no directory component, then add one.
-	  case $file in
-	  */* | *\\*) . ${wrapperdot} ;;
-	  *) . ./${wrapperdot} ;;
+	  case $wrapper in
+	  */* | *\\*) . ${wrapper} ;;
+	  *) . ./${wrapper} ;;
 	  esac
 
 	  # Check the variables that should have been set.
@@ -5676,34 +6119,21 @@
 	  done
 
 	  relink_command=
-	  # To insure that "foo" is sourced, and not "foo.exe",
-	  # finese the cygwin/MSYS system by explicitly sourcing "foo."
-	  # which disallows the automatic-append-.exe behavior.
-	  case $build in
-	  *cygwin* | *mingw*) wrapperdot=${wrapper}. ;;
-	  *) wrapperdot=${wrapper} ;;
-	  esac
+	  # Note that it is not necessary on cygwin/mingw to append a dot to
+	  # foo even if both foo and FILE.exe exist: automatic-append-.exe
+	  # behavior happens only for exec(3), not for open(2)!  Also, sourcing
+	  # `FILE.' does not work on cygwin managed mounts.
+	  #
 	  # If there is no directory component, then add one.
-	  case $file in
-	  */* | *\\*) . ${wrapperdot} ;;
-	  *) . ./${wrapperdot} ;;
+	  case $wrapper in
+	  */* | *\\*) . ${wrapper} ;;
+	  *) . ./${wrapper} ;;
 	  esac
 
 	  outputname=
 	  if test "$fast_install" = no && test -n "$relink_command"; then
 	    if test "$finalize" = yes && test -z "$run"; then
-	      tmpdir="/tmp"
-	      test -n "$TMPDIR" && tmpdir="$TMPDIR"
-	      tmpdir="$tmpdir/libtool-$$"
-	      save_umask=`umask`
-	      umask 0077
-	      if $mkdir "$tmpdir"; then
-	        umask $save_umask
-	      else
-	        umask $save_umask
-		$echo "$modename: error: cannot create temporary directory \`$tmpdir'" 1>&2
-		continue
-	      fi
+	      tmpdir=`func_mktempdir`
 	      file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'`
 	      outputname="$tmpdir/$file"
 	      # Replace the output file specification.
@@ -5727,7 +6157,7 @@
 	fi
 
 	# remove .exe since cygwin /usr/bin/install will append another
-	# one anyways
+	# one anyway 
 	case $install_prog,$host in
 	*/usr/bin/install*,*cygwin*)
 	  case $file:$destfile in
@@ -5827,7 +6257,7 @@
     # Exit here if they wanted silent mode.
     test "$show" = : && exit $EXIT_SUCCESS
 
-    $echo "----------------------------------------------------------------------"
+    $echo "X----------------------------------------------------------------------" | $Xsed
     $echo "Libraries have been installed in:"
     for libdir in $libdirs; do
       $echo "   $libdir"
@@ -5860,7 +6290,7 @@
     $echo
     $echo "See any operating system documentation about shared libraries for"
     $echo "more information, such as the ld(1) and ld.so(8) manual pages."
-    $echo "----------------------------------------------------------------------"
+    $echo "X----------------------------------------------------------------------" | $Xsed
     exit $EXIT_SUCCESS
     ;;
 
@@ -6077,9 +6507,17 @@
 	    rmfiles="$rmfiles $objdir/$n"
 	  done
 	  test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library"
-	  test "$mode" = clean && rmfiles="$rmfiles $objdir/$name $objdir/${name}i"
 
-	  if test "$mode" = uninstall; then
+	  case "$mode" in
+	  clean)
+	    case "  $library_names " in
+	    # "  " in the beginning catches empty $dlname
+	    *" $dlname "*) ;;
+	    *) rmfiles="$rmfiles $objdir/$dlname" ;;
+	    esac
+	     test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i"
+	    ;;
+	  uninstall)
 	    if test -n "$library_names"; then
 	      # Do each command in the postuninstall commands.
 	      cmds=$postuninstall_cmds
@@ -6112,7 +6550,8 @@
 	      IFS="$save_ifs"
 	    fi
 	    # FIXME: should reinstall the best remaining shared library.
-	  fi
+	    ;;
+	  esac
 	fi
 	;;
 
@@ -6397,7 +6836,7 @@
 $echo
 $echo "Try \`$modename --help' for more information about other modes."
 
-exit $EXIT_SUCCESS
+exit $?
 
 # The TAGs below are defined such that we never get into a situation
 # in which we disable both kinds of libraries.  Given conflicting
@@ -6411,12 +6850,11 @@
 # configuration.  But we'll never go from static-only to shared-only.
 
 # ### BEGIN LIBTOOL TAG CONFIG: disable-shared
-build_libtool_libs=no
-build_old_libs=yes
+disable_libs=shared
 # ### END LIBTOOL TAG CONFIG: disable-shared
 
 # ### BEGIN LIBTOOL TAG CONFIG: disable-static
-build_old_libs=`case $build_libtool_libs in yes) $echo no;; *) $echo yes;; esac`
+disable_libs=static
 # ### END LIBTOOL TAG CONFIG: disable-static
 
 # Local Variables:

Modified: freeswitch/branches/cparker/libs/iksemel/src/filter.c
==============================================================================
--- freeswitch/branches/cparker/libs/iksemel/src/filter.c	(original)
+++ freeswitch/branches/cparker/libs/iksemel/src/filter.c	Tue Apr 24 10:14:28 2007
@@ -96,7 +96,7 @@
 	if (rule->next) rule->next->prev = rule->prev;
 	if (f->rules == rule) f->rules = rule->next;
 	if (f->last_rule == rule) f->last_rule = rule->prev;
-	iks_stack_delete (rule->s);
+	iks_stack_delete (&rule->s);
 }
 
 void
@@ -174,7 +174,7 @@
 	rule = f->rules;
 	while (rule) {
 		tmp = rule->next;
-		iks_stack_delete (rule->s);
+		iks_stack_delete (&rule->s);
 		rule = tmp;
 	}
 	iks_free (f);

Modified: freeswitch/branches/cparker/libs/iksemel/src/iks.c
==============================================================================
--- freeswitch/branches/cparker/libs/iksemel/src/iks.c	(original)
+++ freeswitch/branches/cparker/libs/iksemel/src/iks.c	Tue Apr 24 10:14:28 2007
@@ -60,7 +60,7 @@
 	if (!s) return NULL;
 	x = iks_new_within (name, s);
 	if (!x) {
-		iks_stack_delete (s);
+		iks_stack_delete (&s);
 		return NULL;
 	}
 	return x;
@@ -202,7 +202,7 @@
 void
 iks_delete (iks *x)
 {
-	if (x) iks_stack_delete (x->s);
+	if (x) iks_stack_delete (&x->s);
 }
 
 /*****  Node Traversing  *****/
@@ -379,7 +379,7 @@
 iks_name (iks *x)
 {
 	if (x) {
-		if (IKS_TAG == x->type)
+		if (IKS_TAG == x->type) 
 			return IKS_TAG_NAME (x);
 		else
 			return IKS_ATTRIB_NAME (x);

Modified: freeswitch/branches/cparker/libs/iksemel/src/ikstack.c
==============================================================================
--- freeswitch/branches/cparker/libs/iksemel/src/ikstack.c	(original)
+++ freeswitch/branches/cparker/libs/iksemel/src/ikstack.c	Tue Apr 24 10:14:28 2007
@@ -182,10 +182,20 @@
 }
 
 void
-iks_stack_delete (ikstack *s)
+iks_stack_delete (ikstack **sp)
 {
 	ikschunk *c, *tmp;
+	ikstack *s;
 
+	if (!sp) {
+		return;
+	}
+
+	s = *sp;
+	
+	if (!s) {
+		return;
+	}
 	c = s->meta->next;
 	while (c) {
 		tmp = c->next;
@@ -199,4 +209,5 @@
 		c = tmp;
 	}
 	iks_free (s);
+	*sp = NULL;
 }

Modified: freeswitch/branches/cparker/libs/iksemel/src/io-posix.c
==============================================================================
--- freeswitch/branches/cparker/libs/iksemel/src/io-posix.c	(original)
+++ freeswitch/branches/cparker/libs/iksemel/src/io-posix.c	Tue Apr 24 10:14:28 2007
@@ -110,8 +110,36 @@
 	tv.tv_sec = timeout;
 	if (timeout != -1) tvptr = &tv; else tvptr = NULL;
 	if (select (sock + 1, &fds, NULL, NULL, tvptr) > 0) {
+		memset(buffer, 0, buf_len);
 		len = recv (sock, buffer, buf_len, 0);
 		if (len > 0) {
+			char *p, *e = NULL, *t = NULL;
+			for (p = buffer; p && *p; p++) {
+
+				if (*p == '>') {
+					e = p;
+					t = p+1;
+					if (*t == '<') {
+						continue;
+					}
+					while(t && *t) {
+						if (*t != ' ' && *t != '<') {
+							t = e = NULL;
+							break;
+						}
+						if (*t == '<') {
+							p = t;
+							*(p-1) = '>';
+							*e = ' ';
+							e = NULL;
+							break;
+						}
+
+						t++;
+
+					}
+				}
+			}
 			return len;
 		} else if (len <= 0) {
 			return -1;

Modified: freeswitch/branches/cparker/libs/iksemel/src/sax.c
==============================================================================
--- freeswitch/branches/cparker/libs/iksemel/src/sax.c	(original)
+++ freeswitch/branches/cparker/libs/iksemel/src/sax.c	Tue Apr 24 10:14:28 2007
@@ -629,5 +629,5 @@
 	if (prs->deleteHook) prs->deleteHook (prs->user_data);
 	if (prs->stack) iks_free (prs->stack);
 	if (prs->atts) iks_free (prs->atts);
-	if (prs->s) iks_stack_delete (prs->s); else iks_free (prs);
+	if (prs->s) iks_stack_delete (&prs->s); else iks_free (prs);
 }

Modified: freeswitch/branches/cparker/libs/iksemel/src/utility.c
==============================================================================
--- freeswitch/branches/cparker/libs/iksemel/src/utility.c	(original)
+++ freeswitch/branches/cparker/libs/iksemel/src/utility.c	Tue Apr 24 10:14:28 2007
@@ -22,7 +22,7 @@
 }
 
 void
-iks_free (void *ptr)
+iks_real_free (void *ptr)
 {
 	if (my_free_func)
 		my_free_func (ptr);

Modified: freeswitch/branches/cparker/libs/js/.update
==============================================================================
--- freeswitch/branches/cparker/libs/js/.update	(original)
+++ freeswitch/branches/cparker/libs/js/.update	Tue Apr 24 10:14:28 2007
@@ -1 +1 @@
-Wed Feb 14 17:04:43 EST 2007
+Mon Apr 23 14:11:42 EDT 2007

Modified: freeswitch/branches/cparker/libs/js/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/js/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -32,7 +32,6 @@
 srcdir       = @srcdir@
 top_srcdir   = @top_srcdir@
 
-DESTDIR      =
 prefix       = @prefix@
 exec_prefix  = @exec_prefix@
 datarootdir  = @datarootdir@
@@ -51,6 +50,7 @@
 CLI_CPPFLAGS = @CLI_CPPFLAGS@
 CLI_LDFLAGS  = @CLI_LDFLAGS@
 CLI_LIBS     = @CLI_LIBS@
+LIBPATH      = @LIBPATH@
 
 RM           = rm -f
 CP           = cp
@@ -168,7 +168,7 @@
 $(LIB_OBJS): src/jsautocfg.h
 src/jsautocfg.h: jscpucfg
 	-rm -f $@ src/jsautocfg.h
-	$(LIBTOOL) --mode=execute ./jscpucfg >src/jsautocfg.h
+	$(LIBPATH) $(LIBTOOL) --mode=execute ./jscpucfg >src/jsautocfg.h
 jscpucfg.o: src/jscpucfg.c
 	$(CC) $(CPPFLAGS) $(CFLAGS) -o $@ -c $<
 jscpucfg: jscpucfg.o

Modified: freeswitch/branches/cparker/libs/js/configure.ac
==============================================================================
--- freeswitch/branches/cparker/libs/js/configure.ac	(original)
+++ freeswitch/branches/cparker/libs/js/configure.ac	Tue Apr 24 10:14:28 2007
@@ -169,8 +169,9 @@
 AC_CACHE_CHECK([whether to build with NSPR], [ac_cv_with_nspr], [ac_cv_with_nspr=no])
 if test ".$ac_cv_with_nspr" = ".yes"; then
     sinclude(nsprpub/config/nspr.m4)
-    CPPFLAGS="$CPPFLAGS -DJS_THREADSAFE=1 -Insprpub/dist/include/nspr"
-    LDFLAGS="$LDFLAGS -L$prefix/lib -lnspr4"
+    CPPFLAGS="$CPPFLAGS -DJS_THREADSAFE=1 -Insprpub/dist/include/nspr -Insprpub/pr/include"
+    LDFLAGS="$LDFLAGS -L$prefix/lib -L./nsprpub/dist/lib -lnspr4"
+    LIBPATH="LD_LIBRARY_PATH=./nsprpub/dist/lib DYLD_LIBRARY_PATH=./nsprpub/dist/lib" 
 fi
 
 AC_SUBST(CLI_CFLAGS)
@@ -178,9 +179,9 @@
 AC_SUBST(CLI_LDFLAGS)
 AC_SUBST(CLI_LIBS)
 AC_SUBST(CLI_OBJS)
+AC_SUBST(LIBPATH)
 
 with_tags=""
-sinclude(libtool.m4)
 
 AC_PROG_LIBTOOL
 

Modified: freeswitch/branches/cparker/libs/js/nsprpub/config/nspr.m4
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/config/nspr.m4	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/config/nspr.m4	Tue Apr 24 10:14:28 2007
@@ -5,7 +5,7 @@
 
 dnl AM_PATH_NSPR([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]])
 dnl Test for NSPR, and define NSPR_CFLAGS and NSPR_LIBS
-AC_DEFUN(AM_PATH_NSPR,
+AC_DEFUN([AM_PATH_NSPR],
 [dnl
 
 AC_ARG_WITH(nspr-prefix,

Modified: freeswitch/branches/cparker/libs/js/nsprpub/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/configure.in	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/configure.in	Tue Apr 24 10:14:28 2007
@@ -35,10 +35,10 @@
 dnl GPL.
 dnl 
 
-AC_PREREQ(2.12)
+AC_PREREQ(2.59)
 AC_INIT(config/libc_r.h)
 
-AC_CONFIG_AUX_DIR(${srcdir}/build/autoconf)
+AC_CONFIG_AUX_DIR(build/autoconf)
 AC_CANONICAL_SYSTEM
 
 dnl ========================================================
@@ -405,8 +405,8 @@
 
     AC_MSG_CHECKING([whether the $host compiler ($HOST_CC $HOST_CFLAGS $HOST_LDFLAGS) works])
     AC_TRY_COMPILE([], [return(0);], 
-        [ac_cv_prog_host_cc_works=1 AC_MSG_RESULT([yes])],
-        AC_MSG_ERROR([installation or configuration problem: $host compiler $HOST_CC cannot create executables.]) )
+        [ac_cv_prog_host_cc_works=1; AC_MSG_RESULT([yes])],
+        [AC_MSG_ERROR([installation or configuration problem: $host compiler $HOST_CC cannot create executables.])] )
 
     CC=$_SAVE_CC
     CFLAGS=$_SAVE_CFLAGS
@@ -1391,15 +1391,13 @@
         AC_DEFINE(LINUX)
         ;;
     esac
-    CFLAGS="$CFLAGS -Wall"
-    CXXFLAGS="$CXXFLAGS -Wall"
     MDCPUCFG_H=_linux.cfg
     PR_MD_CSRCS=linux.c
     MKSHLIB='$(CC) $(DSO_LDOPTS) -o $@'
     DSO_CFLAGS=-fPIC
     DSO_LDOPTS='-shared -Wl,-soname -Wl,$(notdir $@)'
     _OPTIMIZE_FLAGS=-O2
-    _DEBUG_FLAGS="-g -fno-inline"  # most people on linux use gcc/gdb, and that
+    _DEBUG_FLAGS="-g"  # most people on linux use gcc/gdb, and that
                                    # combo is not yet good at debugging inlined
                                    # functions (even when using DWARF2 as the
                                    # debugging format)
@@ -1872,7 +1870,7 @@
 *-sunos*)
     AC_DEFINE(XP_UNIX)
     AC_DEFINE(SUNOS4)
-    CFLAGS="$CFLAGS -Wall -Wno-format"
+#    CFLAGS="$CFLAGS -Wall -Wno-format"
     if test "$USE_MDUPDATE"; then
         CFLAGS="$CFLAGS -MDupdate \$(DEPENDENCIES)"
     fi
@@ -2167,8 +2165,7 @@
     ;;
 *)
     AC_CHECK_LIB(dl, dlopen,
-        AC_CHECK_HEADER(dlfcn.h,
-            OS_LIBS="-ldl $OS_LIBS"))
+        [AC_CHECK_HEADER(dlfcn.h, OS_LIBS="-ldl $OS_LIBS")])
     ;;
 esac
 
@@ -2200,6 +2197,7 @@
 dnl Checks for library functions.
 dnl ========================================================
 AC_PROG_GCC_TRADITIONAL
+AC_PROG_LIBTOOL
 AC_CHECK_FUNCS(lchown strerror)
 
 dnl AC_FUNC_MEMCMP
@@ -2266,7 +2264,7 @@
 dnl using it
 dnl
 dnl MOZ_CHECK_PTHREADS(lib, success, failure)
-AC_DEFUN(MOZ_CHECK_PTHREADS,
+AC_DEFUN([MOZ_CHECK_PTHREADS],
 [
 AC_MSG_CHECKING([for pthread_create in -l$1])
 echo "
@@ -2297,10 +2295,10 @@
     _HAVE_PTHREADS=1
     ;;
 *)
-    MOZ_CHECK_PTHREADS(pthreads,
-        _HAVE_PTHREADS=1 _PTHREAD_LDFLAGS="-lpthreads",
-        MOZ_CHECK_PTHREADS(pthread,
-            _HAVE_PTHREADS=1 _PTHREAD_LDFLAGS="-lpthread",
+    MOZ_CHECK_PTHREADS(pthread,
+        _HAVE_PTHREADS=1 _PTHREAD_LDFLAGS="-lpthread",
+        MOZ_CHECK_PTHREADS(pthreads,
+            _HAVE_PTHREADS=1 _PTHREAD_LDFLAGS="-lpthreads",
             MOZ_CHECK_PTHREADS(c_r,
                 _HAVE_PTHREADS=1 _PTHREAD_LDFLAGS="-lc_r",
                 MOZ_CHECK_PTHREADS(c,
@@ -2452,12 +2450,6 @@
     *-freebsd*)
 	    AC_DEFINE(_REENTRANT)
 	    AC_DEFINE(_THREAD_SAFE)
-	    dnl -pthread links in -lc_r, so don't specify it explicitly.
-	    if test "$ac_cv_have_dash_pthread" = "yes"; then
-	        _PTHREAD_LDFLAGS="-pthread"
-	    else
-	        _PTHREAD_LDFLAGS="-lc_r"
-	    fi
 	    ;;
     *-netbsd*)
 	    if test "$ac_cv_have_dash_pthread" = "yes"; then

Modified: freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plarena.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plarena.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plarena.c	Tue Apr 24 10:14:28 2007
@@ -103,7 +103,7 @@
     PR_Unlock( arenaLock );
     return;
 } /* end UnlockArena() */
-
+#if 0
 PR_IMPLEMENT(void) PL_InitArenaPool(
     PLArenaPool *pool, const char *name, PRUint32 size, PRUint32 align)
 {
@@ -126,7 +126,7 @@
     arena_stats_list = &pool->stats;
 #endif
 }
-
+#endif
 
 /*
 ** PL_ArenaAllocate() -- allocate space from an arena pool

Modified: freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plds.def
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plds.def	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plds.def	Tue Apr 24 10:14:28 2007
@@ -70,8 +70,6 @@
 PL_HashTableRawLookup;
 PL_HashTableRawRemove;
 PL_HashTableRemove;
-PL_InitArenaPool;
-PL_NewHashTable;
 libVersionPoint;
 ;+    local: *;
 ;+};

Modified: freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plhash.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plhash.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/lib/ds/plhash.c	Tue Apr 24 10:14:28 2007
@@ -107,7 +107,7 @@
     DefaultAllocTable, DefaultFreeTable,
     DefaultAllocEntry, DefaultFreeEntry
 };
-
+#if 0
 PR_IMPLEMENT(PLHashTable *)
 PL_NewHashTable(PRUint32 n, PLHashFunction keyHash,
                 PLHashComparator keyCompare, PLHashComparator valueCompare,
@@ -153,7 +153,7 @@
     ht->allocPriv = allocPriv;
     return ht;
 }
-
+#endif
 PR_IMPLEMENT(void)
 PL_HashTableDestroy(PLHashTable *ht)
 {

Modified: freeswitch/branches/cparker/libs/js/nsprpub/lib/libc/src/plc.def
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/lib/libc/src/plc.def	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/lib/libc/src/plc.def	Tue Apr 24 10:14:28 2007
@@ -55,9 +55,7 @@
 PL_Base64Encode;
 PL_CreateOptState;
 PL_DestroyOptState;
-PL_FPrintError;
 PL_GetNextOpt;
-PL_PrintError;
 PL_strcasecmp;
 PL_strcaserstr;
 PL_strcasestr;

Modified: freeswitch/branches/cparker/libs/js/nsprpub/lib/libc/src/plerror.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/lib/libc/src/plerror.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/lib/libc/src/plerror.c	Tue Apr 24 10:14:28 2007
@@ -46,6 +46,7 @@
 #include "prprf.h"
 #include "prerror.h"
 
+#if 0
 PR_IMPLEMENT(void) PL_FPrintError(PRFileDesc *fd, const char *msg)
 {
 static const char *tags[] =
@@ -148,7 +149,7 @@
 	if (NULL == fd) fd = PR_GetSpecialFD(PR_StandardError);
 	PL_FPrintError(fd, msg);
 }  /* PL_PrintError */
-
+#endif
 #if defined(WIN16)
 /*
 ** libmain() is a required function for win16

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -46,7 +46,7 @@
 
 include $(topsrcdir)/config/config.mk
 
-DIRS = io linking malloc md memory misc threads
+DIRS = io malloc md memory misc threads
 
 # For VAC++ 4 geticcdata rule in config/OS2.mk
 ifeq ($(MOZ_OS2_TOOLS),VACPP)
@@ -62,7 +62,7 @@
 endif
 
 ifeq ($(USE_CPLUS), 1)
-	DIRS += cplus
+#	DIRS += cplus
 endif
 
 #
@@ -222,50 +222,29 @@
     $(OBJDIR)/prvrsion.$(OBJ_SUFFIX) \
     io/$(OBJDIR)/prfdcach.$(OBJ_SUFFIX) \
     io/$(OBJDIR)/prmwait.$(OBJ_SUFFIX) \
-    io/$(OBJDIR)/prmapopt.$(OBJ_SUFFIX) \
     io/$(OBJDIR)/priometh.$(OBJ_SUFFIX) \
-    io/$(OBJDIR)/pripv6.$(OBJ_SUFFIX) \
+    io/$(OBJDIR)/prmapopt.$(OBJ_SUFFIX) \
     io/$(OBJDIR)/prlayer.$(OBJ_SUFFIX) \
     io/$(OBJDIR)/prlog.$(OBJ_SUFFIX) \
     io/$(OBJDIR)/prmmap.$(OBJ_SUFFIX) \
-    io/$(OBJDIR)/prpolevt.$(OBJ_SUFFIX) \
+    io/$(OBJDIR)/pripv6.$(OBJ_SUFFIX) \
     io/$(OBJDIR)/prprf.$(OBJ_SUFFIX) \
-    io/$(OBJDIR)/prscanf.$(OBJ_SUFFIX) \
-    io/$(OBJDIR)/prstdio.$(OBJ_SUFFIX) \
-    threads/$(OBJDIR)/prcmon.$(OBJ_SUFFIX) \
-	threads/$(OBJDIR)/prrwlock.$(OBJ_SUFFIX) \
 	threads/$(OBJDIR)/prtpd.$(OBJ_SUFFIX) \
-    linking/$(OBJDIR)/prlink.$(OBJ_SUFFIX) \
     malloc/$(OBJDIR)/prmem.$(OBJ_SUFFIX) \
     md/$(OBJDIR)/prosdep.$(OBJ_SUFFIX) \
-    memory/$(OBJDIR)/prshm.$(OBJ_SUFFIX) \
-    memory/$(OBJDIR)/prshma.$(OBJ_SUFFIX) \
     memory/$(OBJDIR)/prseg.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/pralarm.$(OBJ_SUFFIX) \
+    misc/$(OBJDIR)/prnetdb.$(OBJ_SUFFIX) \
     misc/$(OBJDIR)/pratom.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prcountr.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prdtoa.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prenv.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prerr.$(OBJ_SUFFIX) \
     misc/$(OBJDIR)/prerror.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prerrortable.$(OBJ_SUFFIX) \
     misc/$(OBJDIR)/prinit.$(OBJ_SUFFIX) \
+   misc/$(OBJDIR)/pripc.$(OBJ_SUFFIX) \
     misc/$(OBJDIR)/prinrval.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/pripc.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prlog2.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prlong.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prnetdb.$(OBJ_SUFFIX) \
     misc/$(OBJDIR)/prolock.$(OBJ_SUFFIX)	 \
-    misc/$(OBJDIR)/prrng.$(OBJ_SUFFIX)	 \
-    misc/$(OBJDIR)/prsystem.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prthinfo.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prtpool.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/prtrace.$(OBJ_SUFFIX) \
     misc/$(OBJDIR)/prtime.$(OBJ_SUFFIX)
 
 # ilib now rejects empty objects
 ifneq ($(MOZ_OS2_TOOLS),VACPP)
-OBJS += malloc/$(OBJDIR)/prmalloc.$(OBJ_SUFFIX)
+#OBJS += malloc/$(OBJDIR)/prmalloc.$(OBJ_SUFFIX)
 endif
 
 ifdef USE_PTHREADS
@@ -278,16 +257,12 @@
 OBJS += \
     io/$(OBJDIR)/prdir.$(OBJ_SUFFIX) \
     io/$(OBJDIR)/prfile.$(OBJ_SUFFIX) \
-    io/$(OBJDIR)/prio.$(OBJ_SUFFIX) \
-    io/$(OBJDIR)/prsocket.$(OBJ_SUFFIX) \
-    misc/$(OBJDIR)/pripcsem.$(OBJ_SUFFIX)
+    io/$(OBJDIR)/prio.$(OBJ_SUFFIX) 
+
 
 ifndef USE_BTHREADS
 OBJS += \
 	threads/$(OBJDIR)/prcthr.$(OBJ_SUFFIX) \
-	threads/$(OBJDIR)/prdump.$(OBJ_SUFFIX) \
-	threads/$(OBJDIR)/prmon.$(OBJ_SUFFIX) \
-	threads/$(OBJDIR)/prsem.$(OBJ_SUFFIX) \
 	threads/combined/$(OBJDIR)/prucpu.$(OBJ_SUFFIX) \
 	threads/combined/$(OBJDIR)/prucv.$(OBJ_SUFFIX) \
 	threads/combined/$(OBJDIR)/prulock.$(OBJ_SUFFIX) \

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -58,14 +58,11 @@
     prmwait.c \
     priometh.c \
     pripv6.c \
-	prmapopt.c \
+    prmapopt.c \
     prlayer.c \
     prlog.c \
 	prmmap.c \
-    prpolevt.c \
 	prprf.c \
-	prscanf.c \
-	prstdio.c  \
 	$(NULL)
 
 ifndef USE_PTHREADS
@@ -73,7 +70,6 @@
 	    prdir.c \
 	    prfile.c \
 	    prio.c \
-	    prsocket.c \
 	    $(NULL)
 endif
 

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/prfdcach.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/prfdcach.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/prfdcach.c	Tue Apr 24 10:14:28 2007
@@ -259,8 +259,8 @@
     ** be overridden at runtime using environment variables
     ** or a super-wiz-bang API.
     */
-    const char *low = PR_GetEnv("NSPR_FD_CACHE_SIZE_LOW");
-    const char *high = PR_GetEnv("NSPR_FD_CACHE_SIZE_HIGH");
+    //const char *low = PR_GetEnv("NSPR_FD_CACHE_SIZE_LOW");
+    //const char *high = PR_GetEnv("NSPR_FD_CACHE_SIZE_HIGH");
 
     /* 
     ** _low is allowed to be zero, _high is not.
@@ -274,8 +274,8 @@
     _pr_fd_cache.limit_high = 0;
 #endif  /* defined(DEBUG) */
 
-    if (NULL != low) _pr_fd_cache.limit_low = atoi(low);
-    if (NULL != high) _pr_fd_cache.limit_high = atoi(high);
+    //if (NULL != low) _pr_fd_cache.limit_low = atoi(low);
+    //if (NULL != high) _pr_fd_cache.limit_high = atoi(high);
 
     if (_pr_fd_cache.limit_high < _pr_fd_cache.limit_low)
         _pr_fd_cache.limit_high = _pr_fd_cache.limit_low;

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/pripv6.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/pripv6.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/pripv6.c	Tue Apr 24 10:14:28 2007
@@ -279,7 +279,6 @@
 
 #if defined(_PR_INET6_PROBE)
 PRBool _pr_ipv6_is_present;
-extern PRBool _pr_test_ipv6_socket(void);
 
 #if !defined(_PR_INET6) && defined(_PR_HAVE_GETIPNODEBYNAME)
 extern PRStatus _pr_find_getipnodebyname(void);
@@ -292,17 +291,7 @@
 static PRBool
 _pr_probe_ipv6_presence(void)
 {
-#if !defined(_PR_INET6) && defined(_PR_HAVE_GETIPNODEBYNAME)
-    if (_pr_find_getipnodebyname() != PR_SUCCESS)
         return PR_FALSE;
-#endif
-
-#if !defined(_PR_INET6) && defined(_PR_HAVE_GETADDRINFO)
-    if (_pr_find_getaddrinfo() != PR_SUCCESS)
-        return PR_FALSE;
-#endif
-
-    return _pr_test_ipv6_socket();
 }
 #endif  /* _PR_INET6_PROBE */
 

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/prlog.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/prlog.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/io/prlog.c	Tue Apr 24 10:14:28 2007
@@ -204,11 +204,11 @@
 
 void _PR_InitLog(void)
 {
-    char *ev;
+    char *ev = NULL;
 
     _pr_logLock = PR_NewLock();
 
-    ev = PR_GetEnv("NSPR_LOG_MODULES");
+//    ev = PR_GetEnv("NSPR_LOG_MODULES");
     if (ev && ev[0]) {
         char module[64];  /* Security-Critical: If you change this
                            * size, you must also change the sscanf
@@ -255,7 +255,7 @@
         }
         PR_SetLogBuffering(isSync ? bufSize : 0);
 
-        ev = PR_GetEnv("NSPR_LOG_FILE");
+        //ev = PR_GetEnv("NSPR_LOG_FILE");
         if (ev && ev[0]) {
             if (!PR_SetLogFile(ev)) {
 #ifdef XP_PC
@@ -316,9 +316,9 @@
 
 static void _PR_SetLogModuleLevel( PRLogModuleInfo *lm )
 {
-    char *ev;
+    char *ev = NULL;
 
-    ev = PR_GetEnv("NSPR_LOG_MODULES");
+    //ev = PR_GetEnv("NSPR_LOG_MODULES");
     if (ev && ev[0]) {
         char module[64];  /* Security-Critical: If you change this
                            * size, you must also change the sscanf

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/malloc/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/malloc/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/malloc/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -59,7 +59,7 @@
 
 DEFINES += -D_NSPR_BUILD_
 
-CSRCS = prmalloc.c prmem.c
+CSRCS =  prmem.c
 
 include $(topsrcdir)/config/rules.mk
 

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/malloc/prmem.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/malloc/prmem.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/malloc/prmem.c	Tue Apr 24 10:14:28 2007
@@ -210,25 +210,6 @@
     return;
 }
 
-PR_IMPLEMENT(void)
-PR_FPrintZoneStats(PRFileDesc *debug_out)
-{
-    int i, j;
-
-    for (j = 0; j < THREAD_POOLS; j++) {
-        for (i = 0; i < MEM_ZONES; i++) {
-            MemoryZone   *mz   = &zones[i][j];
-            MemoryZone    zone = *mz;
-            if (zone.elements || zone.misses || zone.hits) {
-                PR_fprintf(debug_out,
-"pool: %d, zone: %d, size: %d, free: %d, hit: %d, miss: %d, contend: %d\n",
-                    j, i, zone.blockSize, zone.elements,
-                    zone.hits, zone.misses, zone.contention);
-            }
-	}
-    }
-}
-
 static void *
 pr_ZoneMalloc(PRUint32 size)
 {

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -49,8 +49,6 @@
 	unix.c    \
 	unix_errors.c    \
 	uxproces.c \
-	uxrng.c \
-	uxshm.c \
 	uxwrap.c \
 	$(NULL)
 

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/objs.mk
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/objs.mk	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/objs.mk	Tue Apr 24 10:14:28 2007
@@ -42,8 +42,6 @@
 	unix.c    \
 	unix_errors.c \
 	uxproces.c \
-	uxrng.c \
-	uxshm.c \
 	uxwrap.c \
 	$(NULL)
 

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/os_Linux_x86_64.s
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/os_Linux_x86_64.s	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/md/unix/os_Linux_x86_64.s	Tue Apr 24 10:14:28 2007
@@ -91,4 +91,4 @@
     ret
 
 / Magic indicating no need for an executable stack
-.section .note.GNU-stack, "", @progbits ; .previous
+/.section .note.GNU-stack, "", @progbits ; .previous

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/memory/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/memory/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/memory/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -46,7 +46,7 @@
 
 include $(topsrcdir)/config/config.mk
 
-CSRCS = prseg.c prshm.c prshma.c
+CSRCS = prseg.c
 
 ifdef GC_LEAK_DETECTOR
 CSRCS += prgcleak.c

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/misc/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/misc/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/misc/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -47,35 +47,16 @@
 include $(topsrcdir)/config/config.mk
 
 CSRCS = \
-	pralarm.c  \
 	pratom.c   \
-	prcountr.c \
-	prdtoa.c   \
-	prenv.c    \
-	prerr.c  \
 	prerror.c  \
-	prerrortable.c  \
+        pripc.c \
 	prinit.c   \
+	prnetdb.c   \
 	prinrval.c \
-	pripc.c \
-	prlog2.c   \
-	prlong.c   \
-	prnetdb.c  \
 	prolock.c  \
-	prrng.c    \
-	prsystem.c \
 	prtime.c   \
-	prthinfo.c \
-	prtpool.c \
-	prtrace.c  \
 	$(NULL)
 
-ifndef USE_PTHREADS
-CSRCS += \
-	pripcsem.c \
-	$(NULL)
-endif
-
 TARGETS	= $(OBJS)
 
 INCLUDES = -I$(dist_includedir) -I$(topsrcdir)/pr/include -I$(topsrcdir)/pr/include/private

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/misc/prinit.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/misc/prinit.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/misc/prinit.c	Tue Apr 24 10:14:28 2007
@@ -202,7 +202,7 @@
     _PR_InitSegs();
     _PR_InitStacks();
 	_PR_InitTPD();
-    _PR_InitEnv();
+    //_PR_InitEnv();
     _PR_InitLayerCache();
     _PR_InitClock();
 
@@ -234,20 +234,20 @@
     _PR_InitMem();
 #endif
 
-    _PR_InitCMon();
+    //_PR_InitCMon();
     _PR_InitIO();
-    _PR_InitNet();
+    //_PR_InitNet();
     _PR_InitLog();
-    _PR_InitLinker();
+    //_PR_InitLinker();
     _PR_InitCallOnce();
-    _PR_InitDtoa();
+    //_PR_InitDtoa();
     _PR_InitMW();
-    _PR_InitRWLocks();
+    //_PR_InitRWLocks();
 
-    nspr_InitializePRErrorTable();
+    //nspr_InitializePRErrorTable();
 
 #if !defined(_PR_INET6) || defined(_PR_INET6_PROBE)
-	_pr_init_ipv6();
+	//_pr_init_ipv6();
 #endif
 	
     _PR_MD_FINAL_INIT();
@@ -420,9 +420,9 @@
 #endif
 
         _PR_CleanupMW();
-        _PR_CleanupDtoa();
+        //_PR_CleanupDtoa();
         _PR_CleanupCallOnce();
-		_PR_ShutdownLinker();
+		//_PR_ShutdownLinker();
         /* Release the primordial thread's private data, etc. */
         _PR_CleanupThread(me);
 
@@ -452,7 +452,7 @@
          * Ideally, for each _PR_InitXXX(), there should be a corresponding
          * _PR_XXXCleanup() that we can call here.
          */
-        _PR_CleanupNet();
+        //_PR_CleanupNet();
         _PR_CleanupIO();
 #ifdef WINNT
         _PR_CleanupCPUs();
@@ -461,7 +461,7 @@
         PR_DestroyLock(_pr_sleeplock);
         _pr_sleeplock = NULL;
         _PR_CleanupLayerCache();
-        _PR_CleanupEnv();
+        //_PR_CleanupEnv();
         _PR_CleanupStacks();
         _PR_CleanupBeforeExit();
         _pr_initialized = PR_FALSE;
@@ -543,25 +543,6 @@
     }
 }
 
-/*
- * OBSOLETE
- */
-PR_IMPLEMENT(void)
-PR_SetStdioRedirect(
-    PRProcessAttr *attr,
-    PRSpecialFD stdioFd,
-    PRFileDesc *redirectFd)
-{
-#if defined(DEBUG)
-    static PRBool warn = PR_TRUE;
-    if (warn) {
-        warn = _PR_Obsolete("PR_SetStdioRedirect()",
-                "PR_ProcessAttrSetStdioRedirect()");
-    }
-#endif
-    PR_ProcessAttrSetStdioRedirect(attr, stdioFd, redirectFd);
-}
-
 PR_IMPLEMENT(PRStatus)
 PR_ProcessAttrSetCurrentDirectory(
     PRProcessAttr *attr,
@@ -659,75 +640,6 @@
     return PR_SUCCESS;
 }
 
-PR_IMPLEMENT(PRFileDesc *) PR_GetInheritedFD(
-    const char *name)
-{
-    PRFileDesc *fd;
-    const char *envVar;
-    const char *ptr;
-    int len = strlen(name);
-    PROsfd osfd;
-    int nColons;
-    PRIntn fileType;
-
-    envVar = PR_GetEnv("NSPR_INHERIT_FDS");
-    if (NULL == envVar || '\0' == envVar[0]) {
-        PR_SetError(PR_UNKNOWN_ERROR, 0);
-        return NULL;
-    }
-
-    ptr = envVar;
-    while (1) {
-        if ((ptr[len] == ':') && (strncmp(ptr, name, len) == 0)) {
-            ptr += len + 1;
-            PR_sscanf(ptr, "%d:0x%" PR_SCNxOSFD, &fileType, &osfd);
-            switch ((PRDescType)fileType) {
-                case PR_DESC_FILE:
-                    fd = PR_ImportFile(osfd);
-                    break;
-                case PR_DESC_PIPE:
-                    fd = PR_ImportPipe(osfd);
-                    break;
-                case PR_DESC_SOCKET_TCP:
-                    fd = PR_ImportTCPSocket(osfd);
-                    break;
-                case PR_DESC_SOCKET_UDP:
-                    fd = PR_ImportUDPSocket(osfd);
-                    break;
-                default:
-                    PR_ASSERT(0);
-                    PR_SetError(PR_UNKNOWN_ERROR, 0);
-                    fd = NULL;
-                    break;
-            }
-            if (fd) {
-                /*
-                 * An inherited FD is inheritable by default.
-                 * The child process needs to call PR_SetFDInheritable
-                 * to make it non-inheritable if so desired.
-                 */
-                fd->secret->inheritable = _PR_TRI_TRUE;
-            }
-            return fd;
-        }
-        /* Skip three colons */
-        nColons = 0;
-        while (*ptr) {
-            if (*ptr == ':') {
-                if (++nColons == 3) {
-                    break;
-                }
-            }
-            ptr++;
-        }
-        if (*ptr == '\0') {
-            PR_SetError(PR_UNKNOWN_ERROR, 0);
-            return NULL;
-        }
-        ptr++;
-    }
-}
-
 PR_IMPLEMENT(PRProcess*) PR_CreateProcess(
     const char *path,
     char *const *argv,
@@ -850,19 +762,9 @@
     }
     return once->status;
 }
-
 PRBool _PR_Obsolete(const char *obsolete, const char *preferred)
 {
-#if defined(DEBUG)
-#ifndef XP_MAC
-    PR_fprintf(
-        PR_STDERR, "'%s' is obsolete. Use '%s' instead.\n",
-        obsolete, (NULL == preferred) ? "something else" : preferred);
-#else
-#pragma unused (obsolete, preferred)
-#endif
-#endif
-    return PR_FALSE;
+  return PR_FALSE;
 }  /* _PR_Obsolete */
 
 /* prinit.c */

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/nspr.def
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/nspr.def	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/nspr.def	Tue Apr 24 10:14:28 2007
@@ -52,11 +52,7 @@
 ;+	global:
 LIBRARY nspr4 ;-
 EXPORTS ;-
-		LL_MaxInt;
-		LL_MinInt;
-		LL_Zero;
 		PR_Abort;
-		PR_AddToCounter;
 		PR_Accept;
 		PR_AcceptRead;
 		PR_Access;
@@ -67,25 +63,16 @@
 		PR_AtomicDecrement;
 		PR_AtomicIncrement;
 		PR_AtomicSet;
-		PR_AttachSharedMemory;
 		PR_AttachThread;
 		PR_Available;
 		PR_Available64;
 		PR_Bind;
 		PR_BlockClockInterrupts;
 		PR_BlockInterrupt;
-		PR_CEnterMonitor;
-		PR_CExitMonitor;
-		PR_CNotify;
-		PR_CNotifyAll;
-		PR_CSetOnMonitorRecycle;
-		PR_CWait;
 		PR_CallOnce;
 		PR_Calloc;
-		PR_CancelJob;
 		PR_CancelWaitFileDesc;
 		PR_CancelWaitGroup;
-		PR_CeilingLog2;
 		PR_ChangeFileDescNativeHandle;
 		PR_Cleanup;
 		PR_ClearInterrupt;
@@ -94,11 +81,8 @@
 		PR_CloseDir;
 		PR_CloseFileMap;
 		PR_CloseSemaphore;
-		PR_CloseSharedMemory;
 		PR_Connect;
-		PR_CreateCounter;
 		PR_ConvertIPv4AddrToIPv6;
-		PR_CreateAlarm;
 		PR_CreateFileMap;
 		PR_CreateIOLayerStub;
 		PR_CreateOrderedLock;
@@ -110,30 +94,20 @@
 		PR_CreateStack;
 		PR_CreateThread;
 		PR_CreateThreadGCAble;
-		PR_CreateTrace;
-		PR_CreateThreadPool;
-		PR_DecrementCounter;
 		PR_CreateWaitGroup;
 		PR_Delete;
 		PR_DeleteSemaphore;
-		PR_DeleteSharedMemory;
-		PR_DestroyAlarm;
-		PR_DestroyCounter;
 		PR_DestroyCondVar;
 		PR_DestroyLock;
 		PR_DestroyMWaitEnumerator;
 		PR_DestroyOrderedLock;
 		PR_DestroyMonitor;
-		PR_DestroyPollableEvent;
 		PR_DestroyProcessAttr;
-		PR_DestroyRWLock;
 		PR_DestroySem;
 		PR_DestroySocketPollFd;
-		PR_DestroyTrace;
 		PR_DestroyStack;
 		PR_DestroyWaitGroup;
 		PR_DetachProcess;
-		PR_DetachSharedMemory;
 		PR_DetachThread;
 		PR_DisableClockInterrupts;
 		PR_EnableClockInterrupts;
@@ -141,14 +115,8 @@
 		PR_EnumerateHostEnt;
 		PR_EnumerateThreads;
 		PR_EnumerateWaitGroup;
-		PR_ErrorInstallCallback;
-		PR_ErrorInstallTable;
-		PR_ErrorLanguages;
-		PR_ErrorToName;
-		PR_ErrorToString;
 		PR_ExitMonitor;
 		PR_ExplodeTime;
-		PR_ExportFileMapAsString;
 		PR_FD_CLR;
 		PR_FD_ISSET;
 		PR_FD_NCLR;
@@ -157,44 +125,25 @@
 		PR_FD_SET;
 		PR_FD_ZERO;
 		PR_FileDesc2NativeHandle;
-		PR_FindSymbol;
-		PR_FindSymbolAndLibrary;
-		PR_FloorLog2;
 		PR_FormatTime;
-		PR_FindNextCounterQname;
-		PR_FindNextCounterRname;
-		PR_FindNextTraceQname;
-		PR_FindNextTraceRname;
 		PR_FormatTimeUSEnglish;
 		PR_Free;
-		PR_FreeLibraryName;
 		PR_GMTParameters;
 		PR_GetConnectStatus;
 		PR_GetCurrentThread;
 		PR_GetDefaultIOMethods;
 		PR_GetDescType;
-		PR_GetDirectorySeparator;
-		PR_GetCounter;
-		PR_GetCounterHandleFromName;
-		PR_GetCounterNameFromHandle;
-		PR_GetDirectorySepartor;
-		PR_GetEnv;
 		PR_GetError;
 		PR_GetErrorText;
 		PR_GetErrorTextLength;
 		PR_GetFileInfo;
 		PR_GetFileInfo64;
 		PR_GetFileMethods;
-		PR_GetGCRegisters;
 		PR_GetHostByAddr;
 		PR_GetHostByName;
 		PR_GetIPNodeByName;
 		PR_GetIdentitiesLayer;
-		PR_GetInheritedFD;
-		PR_GetInheritedFileMap;
 		PR_GetLayersIdentity;
-		PR_GetLibraryName;
-		PR_GetLibraryPath;
 		PR_GetMonitorEntryCount;
 		PR_GetNameForIdentity;
 		PR_GetOSError;
@@ -206,14 +155,11 @@
 		PR_GetPipeMethods;
 		PR_GetProtoByName;
 		PR_GetProtoByNumber;
-		PR_GetRandomNoise;
 		PR_GetSP;
 		PR_GetSockName;
 		PR_GetSocketOption;
 		PR_GetSpecialFD;
-		PR_GetStackSpaceLeft;
 		PR_GetSysfdTableMax;
-		PR_GetSystemInfo;
 		PR_GetTCPMethods;
 		PR_GetThreadAffinityMask;
 		PR_GetThreadID;
@@ -226,13 +172,8 @@
 		PR_GetUniqueIdentity;
 		PR_ImplodeTime;
 		PR_ImportFile;
-		PR_ImportFileMapFromString;
 		PR_ImportTCPSocket;
 		PR_ImportUDPSocket;
-		PR_GetTraceEntries;
-		PR_GetTraceHandleFromName;
-		PR_GetTraceNameFromHandle;
-		PR_GetTraceOption;
 		PR_Init;
 		PR_Initialize;
 		PR_InitializeNetAddr;
@@ -241,17 +182,11 @@
 		PR_IntervalNow;
 		PR_IntervalToMicroseconds;
 		PR_IntervalToMilliseconds;
-		PR_IncrementCounter;
 		PR_IntervalToSeconds;
 		PR_IsNetAddrType;
-		PR_JoinJob;
 		PR_JoinThread;
-		PR_JoinThreadPool;
 		PR_KillProcess;
 		PR_Listen;
-		PR_LoadLibrary;
-		PR_LoadLibraryWithFlags;
-		PR_LoadStaticLibrary;
 		PR_LocalTimeParameters;
 		PR_Lock;
 		PR_LockFile;
@@ -271,14 +206,10 @@
 		PR_NewLogModule;
 		PR_NewMonitor;
 		PR_NewNamedMonitor;
-		PR_NewPollableEvent;
 		PR_NewProcessAttr;
-		PR_NewRWLock;
 		PR_NewSem;
-		PR_NewTCPSocket;
 		PR_NewTCPSocketPair;
 		PR_NewThreadPrivateIndex;
-		PR_NewUDPSocket;
 		PR_NormalizeTime;
 		PR_Notify;
 		PR_NotifyAll;
@@ -286,13 +217,9 @@
 		PR_NotifyCondVar;
 		PR_Now;
 		PR_Open;
-		PR_OpenAnonFileMap;
 		PR_OpenDir;
 		PR_OpenFile;
 		PR_OpenSemaphore;
-		PR_OpenSharedMemory;
-		PR_OpenTCPSocket;
-		PR_OpenUDPSocket;
 		PR_ParseTimeString;
 		PR_Poll;
 		PR_PopIOLayer;
@@ -300,31 +227,18 @@
 		PR_PostSemaphore;
 		PR_ProcessAttrSetCurrentDirectory;
 		PR_ProcessAttrSetInheritableFD;
-		PR_ProcessAttrSetInheritableFileMap;
 		PR_ProcessAttrSetStdioRedirect;
 		PR_ProcessExit;
 		PR_PushIOLayer;
-		PR_QueueJob;
-		PR_QueueJob_Accept;
-		PR_QueueJob_Connect;
-		PR_QueueJob_Read;
-		PR_QueueJob_Timer;
-		PR_QueueJob_Write;
-		PR_RWLock_Rlock;
-		PR_RWLock_Unlock;
-		PR_RWLock_Wlock;
 		PR_Read;
 		PR_ReadDir;
 		PR_Realloc;
 		PR_Recv;
 		PR_RecvFrom;
 		PR_Rename;
-		PR_ResetAlarm;
 		PR_ResetProcessAttr;
 		PR_ResumeAll;
 		PR_RmDir;
-		PR_ScanStackPointers;
-		PR_RecordTraceEntries;
 		PR_SecondsToInterval;
 		PR_Seek;
 		PR_Seek64;
@@ -332,20 +246,15 @@
 		PR_Send;
 		PR_SendFile;
 		PR_SendTo;
-		PR_SetAlarm;
 		PR_SetConcurrency;
 		PR_SetError;
 		PR_SetErrorText;
 		PR_SetFDCacheSize;
 		PR_SetFDInheritable;
-		PR_SetLibraryPath;
 		PR_SetLogBuffering;
 		PR_SetLogFile;
 		PR_SetNetAddr;
-		PR_SetPollableEvent;
 		PR_SetSocketOption;
-		PR_SetCounter;
-		PR_SetStdioRedirect;
 		PR_SetSysfdTableSize;
 		PR_SetThreadAffinityMask;
 		PR_SetThreadDumpProc;
@@ -354,9 +263,7 @@
 		PR_SetThreadPrivate;
 		PR_SetThreadRecycleMode;
 		PR_Shutdown;
-		PR_ShutdownThreadPool;
 		PR_Sleep;
-		PR_Socket;
 		PR_StackPop;
 		PR_StackPush;
 		PR_Stat;
@@ -364,22 +271,16 @@
 		PR_SuspendAll;
 		PR_Sync;
 		PR_TLockFile;
-		PR_ThreadScanStackPointers;
-		PR_SetTraceOption;
 		PR_TicksPerSecond;
 		PR_TransmitFile;
 		PR_USPacificTimeParameters;
 		PR_UnblockClockInterrupts;
 		PR_UnblockInterrupt;
-		PR_UnloadLibrary;
-		PR_SubtractFromCounter;
 		PR_Unlock;
 		PR_UnlockFile;
 		PR_VersionCheck;
 		PR_Wait;
 		PR_WaitCondVar;
-		PR_WaitForPollableEvent;
-		PR_Trace;
 		PR_WaitProcess;
 		PR_WaitRecvReady;
 		PR_WaitSem;
@@ -388,9 +289,6 @@
 		PR_Writev;
 		PR_Yield;
 		PR_UnlockOrderedLock;
-		PR_cnvtf;
-		PR_dtoa;
-		PR_fprintf;
 		PR_htonl;
 		PR_htonll;
 		PR_htons;
@@ -401,10 +299,7 @@
 		PR_smprintf_free;
 		PR_snprintf;
 		PR_sprintf_append;
-		PR_sscanf;
-		PR_strtod;
 		PR_sxprintf;
-		PR_vfprintf;
 		PR_vsmprintf;
 		PR_vsnprintf;
 		PR_vsprintf_append;
@@ -433,35 +328,19 @@
 		PR_CreateIOLayer;
 		PR_EmulateAcceptRead;
 		PR_EmulateSendFile;
-		PR_FindFunctionSymbol;
-		PR_FindFunctionSymbolAndLibrary;
 		PR_GetMemMapAlignment;
-		PR_GetNumberOfProcessors;
 		PR_ImportPipe;
-		PR_SetEnv;
 ;+} NSPR_4.0;
 ;+
 ;+NSPR_4.3 {
 ;+	global:
-		LL_MaxUint;
 		PR_CallOnceWithArg;
-		PR_GetLibraryFilePathname;
 ;+} NSPR_4.1;
 ;+
-;+NSPR_4.4 {
-;+	global:
-		PR_GetPathSeparator;
-;+} NSPR_4.3;
-;+
 ;+NSPR_4.5 {
 ;+	global:
 		PR_EnumerateAddrInfo;
 		PR_FreeAddrInfo;
 		PR_GetAddrInfoByName;
 		PR_GetCanonNameFromAddrInfo;
-;+} NSPR_4.4;
-;+
-;+NSPR_4.6 {
-;+	global:
-		PR_GetPhysicalMemorySize;
-;+} NSPR_4.5;
+;+} NSPR_4.3;

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -55,8 +55,8 @@
 endif
 
 CSRCS = \
+        ptsynch.c \
 	ptio.c \
-	ptsynch.c \
 	ptthread.c \
 	ptmisc.c \
 	$(NULL)

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/ptio.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/ptio.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/ptio.c	Tue Apr 24 10:14:28 2007
@@ -374,46 +374,13 @@
 
 PTDebug pt_debug;  /* this is shared between several modules */
 
-PR_IMPLEMENT(void) PT_FPrintStats(PRFileDesc *debug_out, const char *msg)
-{
-    PTDebug stats;
-    char buffer[100];
-    PRExplodedTime tod;
-    PRInt64 elapsed, aMil;
-    stats = pt_debug;  /* a copy */
-    PR_ExplodeTime(stats.timeStarted, PR_LocalTimeParameters, &tod);
-    (void)PR_FormatTime(buffer, sizeof(buffer), "%T", &tod);
-
-    LL_SUB(elapsed, PR_Now(), stats.timeStarted);
-    LL_I2L(aMil, 1000000);
-    LL_DIV(elapsed, elapsed, aMil);
-    
-    if (NULL != msg) PR_fprintf(debug_out, "%s", msg);
-    PR_fprintf(
-        debug_out, "\tstarted: %s[%lld]\n", buffer, elapsed);
-    PR_fprintf(
-        debug_out, "\tlocks [created: %u, destroyed: %u]\n",
-        stats.locks_created, stats.locks_destroyed);
-    PR_fprintf(
-        debug_out, "\tlocks [acquired: %u, released: %u]\n",
-        stats.locks_acquired, stats.locks_released);
-    PR_fprintf(
-        debug_out, "\tcvars [created: %u, destroyed: %u]\n",
-        stats.cvars_created, stats.cvars_destroyed);
-    PR_fprintf(
-        debug_out, "\tcvars [notified: %u, delayed_delete: %u]\n",
-        stats.cvars_notified, stats.delayed_cv_deletes);
-}  /* PT_FPrintStats */
-
-#else
+#endif  /* DEBUG */
 
 PR_IMPLEMENT(void) PT_FPrintStats(PRFileDesc *debug_out, const char *msg)
 {
     /* do nothing */
 }  /* PT_FPrintStats */
 
-#endif  /* DEBUG */
-
 #if defined(_PR_POLL_WITH_SELECT)
 /*
  * OSF1 and HPUX report the POLLHUP event for a socket when the
@@ -3374,6 +3341,8 @@
     return fd;
 }  /* PR_AllocFileDesc */
 
+#if 0
+
 #if !defined(_PR_INET6) || defined(_PR_INET6_PROBE)
 PR_EXTERN(PRStatus) _pr_push_ipv6toipv4_layer(PRFileDesc *fd);
 #if defined(_PR_INET6_PROBE)
@@ -3484,7 +3453,7 @@
 #endif
     return fd;
 }  /* PR_Socket */
-
+#endif
 /*****************************************************************************/
 /****************************** I/O public methods ***************************/
 /*****************************************************************************/
@@ -4312,6 +4281,7 @@
     return &dir->d;
 }  /* PR_ReadDir */
 
+#if 0
 PR_IMPLEMENT(PRFileDesc*) PR_NewUDPSocket(void)
 {
     PRIntn domain = PF_INET;
@@ -4336,6 +4306,8 @@
     return PR_Socket(af, SOCK_STREAM, 0);
 }  /* PR_NewTCPSocket */
 
+#endif
+
 PR_IMPLEMENT(PRStatus) PR_NewTCPSocketPair(PRFileDesc *fds[2])
 {
     PRInt32 osfd[2];

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/ptthread.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/ptthread.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/pthreads/ptthread.c	Tue Apr 24 10:14:28 2007
@@ -938,9 +938,9 @@
         PR_Unlock(pt_book.ml);
 
         _PR_CleanupMW();
-        _PR_CleanupDtoa();
+        //_PR_CleanupDtoa();
         _PR_CleanupCallOnce();
-        _PR_ShutdownLinker();
+        //_PR_ShutdownLinker();
         _PR_LogCleanup();
         _PR_CleanupNet();
         /* Close all the fd's before calling _PR_CleanupIO */
@@ -963,7 +963,7 @@
         PR_DestroyLock(_pr_sleeplock);
         _pr_sleeplock = NULL;
         _PR_CleanupLayerCache();
-        _PR_CleanupEnv();
+        //_PR_CleanupEnv();
 #ifdef _PR_ZONE_ALLOCATOR
         _PR_DestroyZones();
 #endif

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/threads/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/threads/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/threads/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -58,24 +58,15 @@
 
 ifdef USE_PTHREADS
 CSRCS = \
-	prcmon.c \
-	prrwlock.c   \
 	prtpd.c \
 	$(NULL)
 else
 ifdef USE_BTHREADS
 CSRCS = \
-	prcmon.c \
-	prrwlock.c   \
 	prtpd.c \
 	$(NULL)
 else
 CSRCS =	\
-	prcmon.c  \
-	prdump.c  \
-	prmon.c   \
-	prsem.c   \
-	prrwlock.c   \
 	prcthr.c \
 	prtpd.c \
 	$(NULL)

Modified: freeswitch/branches/cparker/libs/js/nsprpub/pr/src/threads/prcthr.c
==============================================================================
--- freeswitch/branches/cparker/libs/js/nsprpub/pr/src/threads/prcthr.c	(original)
+++ freeswitch/branches/cparker/libs/js/nsprpub/pr/src/threads/prcthr.c	Tue Apr 24 10:14:28 2007
@@ -73,14 +73,6 @@
     thread->environment = NULL;
 }
 
-PR_IMPLEMENT(PRStatus) PR_Yield()
-{
-    static PRBool warning = PR_TRUE;
-    if (warning) warning = _PR_Obsolete(
-        "PR_Yield()", "PR_Sleep(PR_INTERVAL_NO_WAIT)");
-    return (PR_Sleep(PR_INTERVAL_NO_WAIT));
-}
-
 /*
 ** Make the current thread sleep until "timeout" ticks amount of time
 ** has expired. If "timeout" is PR_INTERVAL_NO_WAIT then the call is

Modified: freeswitch/branches/cparker/libs/js/src/jspubtd.h
==============================================================================
--- freeswitch/branches/cparker/libs/js/src/jspubtd.h	(original)
+++ freeswitch/branches/cparker/libs/js/src/jspubtd.h	Tue Apr 24 10:14:28 2007
@@ -552,7 +552,7 @@
  * JSEXN_NONE marks an unthrowable error.
  */
 typedef enum JSExnType {
-    JSEXN_NONE = -1,
+    JSEXN_NONE,
       JSEXN_ERR,
         JSEXN_INTERNALERR,
         JSEXN_EVALERR,

Modified: freeswitch/branches/cparker/libs/libdingaling/.update
==============================================================================
--- freeswitch/branches/cparker/libs/libdingaling/.update	(original)
+++ freeswitch/branches/cparker/libs/libdingaling/.update	Tue Apr 24 10:14:28 2007
@@ -1 +1 @@
-Tue Jan 30 10:12:18 EST 2007
+Fri Mar  9 17:53:09 CST 2007

Modified: freeswitch/branches/cparker/libs/libdingaling/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/libdingaling/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/libdingaling/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -1,30 +1,39 @@
 EXTRA_DIST =
 SUBDIRS = 
-AUTOMAKE_OPTS= gnu
+AUTOMAKE_OPTS=foreign
 NAME=dingaling
 PREFIX=$(prefix)
+TOUCH_TARGET=@if test -f "$@" ; then touch "$@" ; fi ;
 
 AM_CFLAGS   = $(new_AM_CFLAGS) -I./src -I$(prefix)/include
 AM_CPPFLAGS = $(AM_CFLAGS)
-AM_LDFLAGS  = $(new_AM_LDFLAGS) -liksemel
+AM_LDFLAGS  = $(new_AM_LDFLAGS)
 
-APR_CONFIG=$(prefix)/bin/apr-1-config
-APU_CONFIG=$(prefix)/bin/apu-1-config
-AM_CFLAGS  += -I$(PREFIX)/include $(shell $(APR_CONFIG) --cflags --cppflags --includes)
-AM_LDFLAGS += -L$(PREFIX)/lib
-AM_LDFLAGS += $(shell $(APR_CONFIG) --link-ld --libs )
-AM_CFLAGS  += $(shell $(APU_CONFIG) --includes) 
-AM_LDFLAGS += $(shell $(APU_CONFIG) --link-ld --libs )
+AM_CFLAGS  += `../apr/apr-1-config --cflags --cppflags --includes || $(prefix)/bin/apr-1-config --cflags --cppflags --includes`
+AM_CFLAGS  += `../apr-util/apu-1-config --includes || $(prefix)/bin/apu-1-config --includes`
+AM_CFLAGS  += -I../iksemel/include
 
 lib_LTLIBRARIES		= libdingaling.la
 libdingaling_la_SOURCES	= src/libdingaling.c src/sha1.c
 libdingaling_la_CFLAGS	= $(AM_CFLAGS)
-libdingaling_la_LDFLAGS	= 
-
+libdingaling_la_LDFLAGS	= $(AM_LDFLAGS)
+libdingaling_la_LIBADD  = ../iksemel/src/libiksemel.la ../apr/libapr-1.la ../apr-util/libaprutil-1.la
 library_includedir	= $(prefix)/include
 library_include_HEADERS = src/libdingaling.h
 
+$(libdingaling_la_SOURCES): $(libdingaling_la_LIBADD)
 
+../apr/libapr-1.la: ../apr ../apr/.update
+	cd ../apr && $(MAKE)
+	$(TOUCH_TARGET)
+
+../apr-util/libaprutil-1.la: ../apr-util ../apr-util/.update
+	cd ../apr-util && $(MAKE)
+	$(TOUCH_TARGET)
+
+../iksemel/src/libiksemel.la: ../iksemel ../iksemel/.update
+	cd ../iksemel && $(MAKE)
+	$(TOUCH_TARGET)
 
 dox:
 	cd docs && doxygen $(PWD)/docs/Doxygen.conf

Modified: freeswitch/branches/cparker/libs/libdingaling/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/libdingaling/configure.in	(original)
+++ freeswitch/branches/cparker/libs/libdingaling/configure.in	Tue Apr 24 10:14:28 2007
@@ -6,7 +6,7 @@
 AC_CONFIG_AUX_DIR(build)
 AM_INIT_AUTOMAKE(libdingaling,0.1)
 AC_CONFIG_SRCDIR([src])
-AC_CONFIG_HEADER([src/config.h])
+AC_CONFIG_HEADERS([src/config.h])
 
 #Set default language
 AC_LANG_C

Modified: freeswitch/branches/cparker/libs/libdingaling/src/libdingaling.c
==============================================================================
--- freeswitch/branches/cparker/libs/libdingaling/src/libdingaling.c	(original)
+++ freeswitch/branches/cparker/libs/libdingaling/src/libdingaling.c	Tue Apr 24 10:14:28 2007
@@ -31,6 +31,11 @@
 
 #ifndef  _MSC_VER
 #include <config.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
 #endif
 
 #include <string.h>
@@ -38,6 +43,7 @@
 #include <stdlib.h>
 #include <assert.h>
 #include <ctype.h>
+#include <fcntl.h>
 #include <iksemel.h>
 #include <apr.h>
 #include <apr_network_io.h>
@@ -67,13 +73,18 @@
 #include "sha1.h"
 
 #ifdef _MSC_VER
+#include <io.h>
 #pragma warning(disable:4127 4706)
 #endif
 
 #define microsleep(x) apr_sleep(x * 1000)
+#define LDL_CAPS_VER "1.0.0.1"
 
 static int opt_timeout = 30;
 
+static void sha1_hash(char *out, char *in, unsigned int len);
+static int b64encode(unsigned char *in, size_t ilen, unsigned char *out, size_t olen);
+static void ldl_random_string(char *buf, uint16_t len, char *set);
 
 static struct {
 	unsigned int flags;
@@ -82,6 +93,7 @@
 	apr_pool_t *memory_pool;
 	unsigned int id;
 	ldl_logger_t logger;
+	apr_hash_t *avatar_hash;
 	apr_thread_mutex_t *flag_mutex;
 } globals;
 
@@ -152,6 +164,42 @@
 	void *private_data;
 };
 
+static int on_disco_default(void *user_data, ikspak *pak);
+static int on_vcard(void *user_data, ikspak *pak);
+typedef int (*iks_filter_callback_t)(void *user_data, ikspak *pak);
+
+struct ldl_feature {
+	const char *name;
+	iks_filter_callback_t callback;
+};
+typedef struct ldl_feature ldl_feature_t;
+
+#define FEATURE_DISCO "http://jabber.org/protocol/disco"
+#define FEATURE_DISCO_INFO "http://jabber.org/protocol/disco#info"
+#define FEATURE_VERSION "jabber:iq:version"
+#define FEATURE_VCARD "vcard-temp"
+#define FEATURE_VOICE "http://www.google.com/xmpp/protocol/voice/v1"
+#define FEATURE_LAST "jabber:iq:last"
+
+static ldl_feature_t FEATURES[] = { 
+	{ FEATURE_DISCO, on_disco_default },
+	{ FEATURE_DISCO_INFO, on_disco_default },
+	{ FEATURE_VERSION, on_disco_default },
+	{ FEATURE_VCARD, on_vcard},
+	{ FEATURE_VOICE, on_disco_default },
+	{ FEATURE_LAST, on_disco_default },
+	{ NULL, NULL}
+};
+
+
+struct ldl_avatar {
+	char *path;
+	char *base64;
+	char hash[256];
+};
+
+typedef struct ldl_avatar ldl_avatar_t;
+
 
 static void lowercase(char *str) 
 {
@@ -368,11 +416,11 @@
 				dl_signal = LDL_SIGNAL_TRANSPORT_ACCEPT;
 			} else if (!strcasecmp(type, "reject")) {
 				dl_signal = LDL_SIGNAL_REJECT;
-			} else if (!strcasecmp(type, "transport-info")) {
+			} else if (!strcasecmp(type, "transport-info") || !strcasecmp(type, "candidates")) {
 				char *tid = iks_find_attrib(xml, "id");
 				dl_signal = LDL_SIGNAL_CANDIDATES;
 				tag = iks_child (xml);
-				
+				id = type;
 				if (tag && !strcasecmp(iks_name(tag), "transport")) {
 					tag = iks_child(tag);
 				}
@@ -480,6 +528,7 @@
 
 const char *marker = "TRUE";
 
+
 static int on_vcard(void *user_data, ikspak *pak)
 {
 	ldl_handle_t *handle = user_data;
@@ -493,206 +542,99 @@
 	return IKS_FILTER_EAT;
 }
 
-static int on_disco_info(void *user_data, ikspak *pak)
+
+static int on_disco_default(void *user_data, ikspak *pak)
 {
+	char *node = NULL;
+	char *ns = NULL;
 	ldl_handle_t *handle = user_data;
+	iks *iq, *query, *tag;
+	uint8_t send = 0;
+	int x;
 
-	if (pak->subtype == IKS_TYPE_RESULT) {
-		if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
-			char *from = iks_find_attrib(pak->x, "from");
-			char id[1024];
-			char *resource;
-			struct ldl_buffer *buffer;
-			size_t x;
-
-
-			apr_cpystrn(id, from, sizeof(id));
-			if ((resource = strchr(id, '/'))) {
-				*resource++ = '\0';
-			}
-
-			if (!apr_hash_get(handle->sub_hash, from, APR_HASH_KEY_STRING)) {
-				iks *msg;
-				apr_hash_set(handle->sub_hash, 	apr_pstrdup(handle->pool, from), APR_HASH_KEY_STRING, &marker);
-				msg = iks_make_s10n (IKS_TYPE_SUBSCRIBED, id, "Ding A Ling...."); 
-				apr_queue_push(handle->queue, msg);
-			}
-
-			
-
-			if (resource) {
-				for (x = 0; x < strlen(resource); x++) {
-					resource[x] = (char)tolower((int)resource[x]);
-				}
-			}
-
-			if (resource && strstr(resource, "talk") && (buffer = apr_hash_get(handle->probe_hash, id, APR_HASH_KEY_STRING))) {
-				apr_cpystrn(buffer->buf, from, buffer->len);
-				fflush(stderr);
-				buffer->hit = 1;
-			}
-		}
-		return IKS_FILTER_EAT;
-	}
-	
-	if (pak->subtype == IKS_TYPE_GET) {
-		iks *iq, *query, *tag;
-		uint8_t send = 0;
-
-		if ((iq = iks_new("iq"))) {
-			do {
-				iks_insert_attrib(iq, "from", handle->login);
-				iks_insert_attrib(iq, "to", pak->from->full);
-				iks_insert_attrib(iq, "id", pak->id);
-				iks_insert_attrib(iq, "type", "result");
-
-				if (!(query = iks_insert (iq, "query"))) {
-					break;
-				}
-				iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
-					
-				if (!(tag = iks_insert (query, "identity"))) {
-					break;
-				}
-				iks_insert_attrib(tag, "category", "client");
-				iks_insert_attrib(tag, "type", "voice");
-				iks_insert_attrib(tag, "name", "LibDingaLing");
-				
-
-				if (!(tag = iks_insert (query, "feature"))) {
-					break;
-				}
-				iks_insert_attrib(tag, "var", "http://jabber.org/protocol/disco#info");
-
-				if (!(tag = iks_insert (query, "feature"))) {
-					break;
-				}
-				iks_insert_attrib(tag, "var", "http://www.google.com/xmpp/protocol/voice/v1");
-				
-				iks_send(handle->parser, iq);
-				send = 1;
-			} while (0);
-
-			iks_delete(iq);
-		}
-
-		if (!send) {
-			globals.logger(DL_LOG_DEBUG, "Memory Error!\n");
-		}		
+	if (pak && pak->query) {
+		ns = iks_find_attrib(pak->query, "xmlns");
+		node = iks_find_attrib(pak->query, "node");
 	}
 
-	return IKS_FILTER_EAT;
-}
-
-static int on_component_disco_info(void *user_data, ikspak *pak)
-{
-	char *node = iks_find_attrib(pak->query, "node");
-	ldl_handle_t *handle = user_data;
-
 	if (pak->subtype == IKS_TYPE_RESULT) {
 		globals.logger(DL_LOG_DEBUG, "FixME!!! node=[%s]\n", node?node:"");		
 	} else if (pak->subtype == IKS_TYPE_GET) {
-		//	if (ldl_test_flag(handle, LDL_FLAG_COMPONENT)) {
-		if (node) {
+		if ((iq = iks_new("iq"))) {
+			int all = 0;
 			
-		} else {
-			iks *iq, *query, *tag;
-			uint8_t send = 0;
-
-			if ((iq = iks_new("iq"))) {
-				do {
-					iks_insert_attrib(iq, "from", handle->login);
-					iks_insert_attrib(iq, "to", pak->from->full);
-					iks_insert_attrib(iq, "id", pak->id);
-					iks_insert_attrib(iq, "type", "result");
-
-					if (!(query = iks_insert (iq, "query"))) {
-						break;
-					}
-					iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
+			iks_insert_attrib(iq, "from", handle->login);
+			iks_insert_attrib(iq, "to", pak->from->full);
+			iks_insert_attrib(iq, "id", pak->id);
+			iks_insert_attrib(iq, "type", "result");
 					
-					if (!(tag = iks_insert (query, "identity"))) {
-						break;
-					}
-					iks_insert_attrib(tag, "category", "gateway");
-					iks_insert_attrib(tag, "type", "voice");
-					iks_insert_attrib(tag, "name", "LibDingaLing");
-				
-
-					if (!(tag = iks_insert (query, "feature"))) {
-						break;
-					}
-					iks_insert_attrib(tag, "var", "http://jabber.org/protocol/disco");
-
-					if (!(tag = iks_insert (query, "feature"))) {
-						break;
-					}
-					iks_insert_attrib(tag, "var", "jabber:iq:register");
-				
-					/*
-					if (!(tag = iks_insert (query, "feature"))) {
-						break;
-					}
-					iks_insert_attrib(tag, "var", "http://jabber.org/protocol/commands");
-					*/
+			if (!(query = iks_insert (iq, "query"))) {
+				goto fail;
+			}
+			iks_insert_attrib(query, "xmlns", ns);
 
-					if (!(tag = iks_insert (query, "feature"))) {
-						break;
-					}
-					iks_insert_attrib(tag, "var", "jabber:iq:gateway");
+			if (!strcasecmp(ns, FEATURE_LAST)) {
+				iks_insert_attrib(query, "seconds", "1");
+			}
+			
+			if (!(tag = iks_insert (query, "identity"))) {
+				goto fail;
+			}
 
-					if (!(tag = iks_insert (query, "feature"))) {
-						break;
+			iks_insert_attrib(tag, "category", "gateway");
+			//iks_insert_attrib(tag, "type", "voice");
+			iks_insert_attrib(tag, "name", "LibDingaLing");
+			
+			if (!strcasecmp(ns, FEATURE_DISCO_INFO)) {
+				if (!node) {
+					all++;
+				} else {
+					char *p;
+
+					if ((p = strstr(node, "caps#"))) {
+						char *what = p + 5;
+
+						if (!strcasecmp(what, "voice-v1")) {
+							if (!(tag = iks_insert (query, "feature"))) {
+								goto fail;
+							}
+							iks_insert_attrib(tag, "var", FEATURE_VOICE);
+							goto done;
+						}
+						
 					}
-					iks_insert_attrib(tag, "var", "jabber:iq:version");
-
+				}
+			}
+			
+			for (x = 0; FEATURES[x].name; x++) {
+				if (all || !ns || !strcasecmp(ns, FEATURES[x].name)) {
 					if (!(tag = iks_insert (query, "feature"))) {
-						break;
+						goto fail;
 					}
-					iks_insert_attrib(tag, "var", "vcard-temp");
+					iks_insert_attrib(tag, "var", FEATURES[x].name);
+				}
+			}
 
-					if (!(tag = iks_insert (query, "feature"))) {
-						break;
-					}
-					iks_insert_attrib(tag, "var", "jabber:iq:search");
+		done:
 
-					iks_send(handle->parser, iq);
-					send = 1;
-				} while (0);
+			apr_queue_push(handle->queue, iq);
+			iq = NULL;
+			send = 1;
+		}
+	fail:
 
-				iks_delete(iq);
-			}
+		if (iq) {
+			iks_delete(iq);
+		}
 
-			if (!send) {
-				globals.logger(DL_LOG_DEBUG, "Memory Error!\n");
-			}
-			
+		if (!send) {
+			globals.logger(DL_LOG_DEBUG, "Memory Error!\n");
 		}
 	}
 
 	return IKS_FILTER_EAT;
 }
 
-
-
-static int on_disco_items(void *user_data, ikspak *pak)
-{
-	globals.logger(DL_LOG_DEBUG, "FixME!!!\n");
-	return IKS_FILTER_EAT;
-}
-
-static int on_disco_reg_in(void *user_data, ikspak *pak)
-{	
-	globals.logger(DL_LOG_DEBUG, "FixME!!!\n");
-	return IKS_FILTER_EAT;
-}
-
-static int on_disco_reg_out(void *user_data, ikspak *pak)
-{
-	globals.logger(DL_LOG_DEBUG, "FixME!!!\n");
-	return IKS_FILTER_EAT;
-}
-
 static int on_presence(void *user_data, ikspak *pak)
 {
 	ldl_handle_t *handle = user_data;
@@ -705,6 +647,8 @@
 	char *resource;
 	struct ldl_buffer *buffer;
 	ldl_signal_t dl_signal = LDL_SIGNAL_PRESENCE_IN;
+	
+
 
     if (type && *type) {
         if (!strcasecmp(type, "unavailable")) {
@@ -729,19 +673,21 @@
 		*resource++ = '\0';
 	}
 	
+
 	if (!apr_hash_get(handle->sub_hash, from, APR_HASH_KEY_STRING)) {
 		iks *msg;
 		apr_hash_set(handle->sub_hash, 	apr_pstrdup(handle->pool, from), APR_HASH_KEY_STRING, &marker);
-		msg = iks_make_s10n (IKS_TYPE_SUBSCRIBED, id, "Ding A Ling...."); 
-		apr_queue_push(handle->queue, msg);
+		if ((msg = iks_make_s10n (IKS_TYPE_SUBSCRIBED, id, "Ding A Ling...."))) {
+			apr_queue_push(handle->queue, msg);
+			msg = NULL;
+		}
 	}
 
-
-	if (resource && strstr(resource, "talk") && (buffer = apr_hash_get(handle->probe_hash, id, APR_HASH_KEY_STRING))) {
+	if (resource && (strstr(resource, "talk") || strstr(resource, "telepathy")) && (buffer = apr_hash_get(handle->probe_hash, id, APR_HASH_KEY_STRING))) {
 		apr_cpystrn(buffer->buf, from, buffer->len);
 		fflush(stderr);
 		buffer->hit = 1;
-	}
+	} 
 	
     if (handle->session_callback) {
         handle->session_callback(handle, NULL, dl_signal, to, id, status ? status : "n/a", show ? show : "n/a");
@@ -750,7 +696,82 @@
 	return IKS_FILTER_EAT;
 }
 
-static void do_presence(ldl_handle_t *handle, char *from, char *to, char *type, char *rpid, char *message) 
+static char *ldl_handle_strdup(ldl_handle_t *handle, char *str)
+{
+	char *dup;
+	apr_size_t len;
+
+	len = strlen(str) + 1;
+	dup = apr_palloc(handle->pool, len);
+	assert(dup != NULL);
+	strncpy(dup, str, len);
+	return dup;
+}
+
+static void ldl_strip_resource(char *in)
+{
+	char *p;
+
+	if ((p = strchr(in, '/'))) {
+		*p = '\0';
+	}
+}
+
+static ldl_avatar_t *ldl_get_avatar(ldl_handle_t *handle, char *path, char *from)
+{
+	ldl_avatar_t *ap;
+	uint8_t image[8192];
+	unsigned char base64[9216] = "";
+	int fd = -1;
+	size_t bytes;
+	char *key;
+	char hash[128] = "";
+
+	if (from && (ap = (ldl_avatar_t *) apr_hash_get(globals.avatar_hash, from, APR_HASH_KEY_STRING))) {
+		return ap;
+	}
+
+	if (path && from) {
+		if ((ap = (ldl_avatar_t *) apr_hash_get(globals.avatar_hash, path, APR_HASH_KEY_STRING))) {
+			key = ldl_handle_strdup(handle, from);
+			ldl_strip_resource(key);
+			apr_hash_set(globals.avatar_hash, key, APR_HASH_KEY_STRING, ap);
+			return ap;
+		}
+	}
+
+	if (!(path && from)) {
+		return NULL;
+	}
+
+	if ((fd = open(path, O_RDONLY, 0)) < 0) {
+		globals.logger(DL_LOG_ERR, "File %s does not exist!\n", path);
+		return NULL;
+	}
+	
+	bytes = read(fd, image, sizeof(image));
+	close(fd);
+	fd = -1;
+
+	ap = malloc(sizeof(*ap));
+	assert(ap != NULL);
+	memset(ap, 0, sizeof(*ap));
+	ldl_random_string(hash, sizeof(hash) -1, NULL);
+	sha1_hash(ap->hash, hash, (unsigned)strlen(hash));
+	ap->path = strdup(path);
+
+	key = ldl_handle_strdup(handle, from);
+	ldl_strip_resource(key);
+
+	b64encode((unsigned char *)image, bytes, base64, sizeof(base64));
+	ap->base64 = strdup((const char *)base64);
+	apr_hash_set(globals.avatar_hash, ap->path, APR_HASH_KEY_STRING, ap);
+	apr_hash_set(globals.avatar_hash, key, APR_HASH_KEY_STRING, ap);
+	return ap;
+}
+
+
+static void do_presence(ldl_handle_t *handle, char *from, char *to, char *type, char *rpid, char *message, char *avatar) 
 {
 	iks *pres;
 	char buf[512];
@@ -761,6 +782,11 @@
 		from = buf;
 	}
 
+	if (ldl_test_flag(handle, LDL_FLAG_COMPONENT) && ldl_jid_domcmp(from, to)) {
+		globals.logger(DL_LOG_ERR, "Refusal to send presence from and to the same domain in component mode [%s][%s]\n", from, to);
+		return;
+	}
+
 	if ((pres = iks_new("presence"))) {
 		iks_insert_attrib(pres, "xmlns", "jabber:client");
 		if (from) {
@@ -786,9 +812,23 @@
 		}
 
 		if (message || rpid) {
+			ldl_avatar_t *ap;
+
+			if (avatar) {
+				if ((ap = ldl_get_avatar(handle, avatar, from))) {
+					if ((tag = iks_insert(pres, "x"))) {
+						iks *hash;
+						iks_insert_attrib(tag, "xmlns", "vcard-temp:x:update");
+						if ((hash = iks_insert(tag, "photo"))) {
+							iks_insert_cdata(hash, ap->hash, 0);
+						}
+					}
+				}
+			}
+
 			if ((tag = iks_insert(pres, "c"))) {
 				iks_insert_attrib(tag, "node", "http://www.freeswitch.org/xmpp/client/caps");
-				iks_insert_attrib(tag, "ver", "1.0.0.1");
+				iks_insert_attrib(tag, "ver", LDL_CAPS_VER);
 				iks_insert_attrib(tag, "ext", "sidebar voice-v1");
 				iks_insert_attrib(tag, "client", "libdingaling");
 				iks_insert_attrib(tag, "xmlns", "http://jabber.org/protocol/caps");
@@ -796,6 +836,7 @@
 		}
 
 		apr_queue_push(handle->queue, pres);
+		pres = NULL;
 	}
 }
 
@@ -835,20 +876,24 @@
 		*r++ = '\0';
 	}
 
-	msg = iks_make_s10n (IKS_TYPE_SUBSCRIBED, id, "Ding A Ling....");
-	
-	if (to && ldl_test_flag(handle, LDL_FLAG_COMPONENT)) {
-		iks_insert_attrib(msg, "from", to);
+	if ((msg = iks_make_s10n (IKS_TYPE_SUBSCRIBED, id, "Ding A Ling...."))) {
+		if (to && ldl_test_flag(handle, LDL_FLAG_COMPONENT)) {
+			iks_insert_attrib(msg, "from", to);
+		}
+
+		apr_queue_push(handle->queue, msg);
+		msg = NULL;
 	}
 
-	apr_queue_push(handle->queue, msg);
-	msg = iks_make_s10n (IKS_TYPE_SUBSCRIBE, id, "Ding A Ling...."); 
+	if ((msg = iks_make_s10n (IKS_TYPE_SUBSCRIBE, id, "Ding A Ling...."))) {
 
-	if (to && ldl_test_flag(handle, LDL_FLAG_COMPONENT)) {
-		iks_insert_attrib(msg, "from", to);
-	}
+		if (to && ldl_test_flag(handle, LDL_FLAG_COMPONENT)) {
+			iks_insert_attrib(msg, "from", to);
+		}
 
-	apr_queue_push(handle->queue, msg);
+		apr_queue_push(handle->queue, msg);
+		msg = NULL;
+	}
 
 	if (handle->session_callback) {
 		handle->session_callback(handle, NULL, LDL_SIGNAL_SUBSCRIBE, to, from, NULL, NULL);
@@ -903,8 +948,8 @@
 					iks_insert_attrib(x, "xmlns:gr", "google:roster");
 					iks_insert_attrib(x, "gr:ext", "2");
 					iks_insert_attrib(x, "gr:include", "all");
-					iks_send(handle->parser, iq);
-					iks_delete(iq);
+					apr_queue_push(handle->queue, iq);
+					iq = NULL;
 					break;
 				}
 #endif
@@ -934,11 +979,13 @@
 			//printf("SESSION type=%s name=%s id=%s\n", type, name, id);
 			if (parse_session_code(handle, id, from, to, xml, strcasecmp(type, "error") ? NULL : type) == LDL_STATUS_SUCCESS) {
 				iks *reply;
-				reply = iks_make_iq(IKS_TYPE_RESULT, NULL); 
-				iks_insert_attrib(reply, "to", from);
-				iks_insert_attrib(reply, "from", to);
-				iks_insert_attrib(reply, "id", iqid);
-				apr_queue_push(handle->queue, reply);
+				if ((reply = iks_make_iq(IKS_TYPE_RESULT, NULL))) {
+					iks_insert_attrib(reply, "to", from);
+					iks_insert_attrib(reply, "from", to);
+					iks_insert_attrib(reply, "id", iqid);
+					apr_queue_push(handle->queue, reply);
+					reply = NULL;
+				}
 			}
 		}
 		xml = iks_child (xml);
@@ -954,25 +1001,28 @@
 	ldl_handle_t *handle = user_data;
 	iks *msg, *ctag;
 
-	msg = iks_make_pres (IKS_SHOW_AVAILABLE, handle->status_msg); 
-	ctag = iks_insert(msg, "c");
-	iks_insert_attrib(ctag, "node", "http://www.freeswitch.org/xmpp/client/caps");
-	iks_insert_attrib(ctag, "ver", "1.0.0.1");
-	iks_insert_attrib(ctag, "ext", "sidebar voice-v1");
-	iks_insert_attrib(ctag, "client", "libdingaling");
-	iks_insert_attrib(ctag, "xmlns", "http://jabber.org/protocol/caps");
+	if ((msg = iks_make_pres (IKS_SHOW_AVAILABLE, handle->status_msg))) {
+		ctag = iks_insert(msg, "c");
+		iks_insert_attrib(ctag, "node", "http://www.freeswitch.org/xmpp/client/caps");
+		iks_insert_attrib(ctag, "ver", "1.0.0.1");
+		iks_insert_attrib(ctag, "ext", "sidebar voice-v1");
+		iks_insert_attrib(ctag, "client", "libdingaling");
+		iks_insert_attrib(ctag, "xmlns", "http://jabber.org/protocol/caps");
 
-	apr_queue_push(handle->queue, msg);
-	ldl_set_flag_locked(handle, LDL_FLAG_READY);
+		apr_queue_push(handle->queue, msg);
+		msg = NULL;
+		ldl_set_flag_locked(handle, LDL_FLAG_READY);
+	}
 	return IKS_FILTER_EAT;
 }
 
 static const char c64[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 #define B64BUFFLEN 1024
 
-static int b64encode(unsigned char *in, uint32_t ilen, unsigned char *out, uint32_t olen) {
+static int b64encode(unsigned char *in, size_t ilen, unsigned char *out, size_t olen) 
+{
 	int y=0,bytes=0;
-	uint32_t x=0;
+	size_t x=0;
 	unsigned int b=0,l=0;
 
 	for(x=0;x<ilen;x++) {
@@ -983,7 +1033,7 @@
 			if(++y!=72) {
 				continue;
 			}
-			out[bytes++] = '\n';
+			//out[bytes++] = '\n';
 			y=0;
 		}
 	}
@@ -998,7 +1048,7 @@
 	return 0;
 }
 
-static void sha1_hash(char *out, char *in)
+static void sha1_hash(char *out, char *in, unsigned int len)
 {
 	sha_context_t sha;
 	char *p;
@@ -1007,7 +1057,7 @@
 
 	SHA1Init(&sha);
 	
-	SHA1Update(&sha, (unsigned char *) in, (unsigned int)strlen(in));
+	SHA1Update(&sha, (unsigned char *) in, len);
 
 	SHA1Final(digest, &sha);
 
@@ -1034,7 +1084,7 @@
 			char handshake[512] = "";
 
 			snprintf(secret, sizeof(secret), "%s%s", pak->id, handle->password);
-			sha1_hash(hash, secret);
+			sha1_hash(hash, secret, (unsigned)strlen(secret));
 			snprintf(handshake, sizeof(handshake), "<handshake>%s</handshake>", hash);
 			iks_send_raw(handle->parser, handshake);
 			handle->state = CS_START;
@@ -1105,15 +1155,17 @@
 			if (ldl_test_flag(handle, LDL_FLAG_CONNECTED)) {
 				iks *t;
 				if (handle->features & IKS_STREAM_BIND) {
-					t = iks_make_resource_bind(handle->acc);
-					iks_send(handle->parser, t);
-					iks_delete(t);
+					if ((t = iks_make_resource_bind(handle->acc))) {
+						apr_queue_push(handle->queue, t);
+						t = NULL;
+					}
 				}
 				if (handle->features & IKS_STREAM_SESSION) {
-					t = iks_make_session();
-					iks_insert_attrib(t, "id", "auth");
-					iks_send(handle->parser, t);
-					iks_delete(t);
+					if ((t = iks_make_session())) {
+						iks_insert_attrib(t, "id", "auth");
+						apr_queue_push(handle->queue, t);
+						t = NULL;
+					}
 				}
 			} else {
 				if (handle->features & IKS_STREAM_SASL_MD5) {
@@ -1133,8 +1185,8 @@
 						slen = (uint32_t)(strlen(handle->acc->user) + strlen(handle->password) + 2);
 						b64encode((unsigned char *)s, slen, (unsigned char *) base64, sizeof(base64));
 						iks_insert_cdata(x, base64, 0);
-						iks_send(handle->parser, x);
-						iks_delete(x);
+						apr_queue_push(handle->queue, x);
+						x = NULL;
 					} else {
 						globals.logger(DL_LOG_DEBUG, "Memory ERROR!\n");
 						break;
@@ -1218,19 +1270,20 @@
 
 static void on_log(ldl_handle_t *handle, const char *data, size_t size, int is_incoming)
 {
-	if (iks_is_secure(handle->parser)) {
-		fprintf(stderr, "Sec");
-	}
-	if (is_incoming) {
-		fprintf(stderr, "RECV");
-	} else {
-		fprintf(stderr, "SEND");
+	if (globals.debug) {
+		if (is_incoming) {
+			globals.logger(DL_LOG_INFO, "+xml:%s%s:%s", iks_is_secure(handle->parser) ? "Sec" : "", is_incoming ? "RECV" : "SEND", data);
+		} else {
+			globals.logger(DL_LOG_NOTICE, "+xml:%s%s:%s", iks_is_secure(handle->parser) ? "Sec" : "", is_incoming ? "RECV" : "SEND", data);
+		}
+						   
 	}
-	fprintf(stderr, "[%s]\n", data);
 }
 
 static void j_setup_filter(ldl_handle_t *handle)
 {
+	int x = 0;
+
 	if (handle->filter) {
 		iks_filter_delete(handle->filter);
 	}
@@ -1276,68 +1329,68 @@
 						IKS_RULE_TYPE, IKS_PAK_IQ,
 						IKS_RULE_SUBTYPE, IKS_TYPE_ERROR, IKS_RULE_ID, "auth", IKS_RULE_DONE);
 
-
-
-	if (ldl_test_flag(handle, LDL_FLAG_COMPONENT)) {
-		iks_filter_add_rule(handle->filter, on_component_disco_info, handle, 
-							IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
-		iks_filter_add_rule(handle->filter, on_disco_items, handle,
-							IKS_RULE_NS, "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
-		iks_filter_add_rule(handle->filter, on_disco_reg_in, handle,
-							IKS_RULE_SUBTYPE, IKS_TYPE_GET, IKS_RULE_NS, "jabber:iq:register", IKS_RULE_DONE);
-		iks_filter_add_rule(handle->filter, on_disco_reg_out, handle,
-							IKS_RULE_SUBTYPE, IKS_TYPE_SET, IKS_RULE_NS, "jabber:iq:register", IKS_RULE_DONE);
-		iks_filter_add_rule(handle->filter, on_vcard, handle,
-							IKS_RULE_SUBTYPE, IKS_TYPE_GET, IKS_RULE_NS, "vcard-temp", IKS_RULE_DONE);
-	} else {
-		iks_filter_add_rule(handle->filter, on_disco_info, handle, 
-							IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
+	for (x = 0; FEATURES[x].name; x++) {
+		iks_filter_add_rule(handle->filter, FEATURES[x].callback, handle, 
+							IKS_RULE_NS, FEATURES[x].name, IKS_RULE_DONE);
 	}
-	
 }
 
 static void ldl_flush_queue(ldl_handle_t *handle, int done)
 {
 	iks *msg;
-	void *pop;
+	void *pop = NULL;
 	unsigned int len = 0, x = 0;
 
+	apr_thread_mutex_lock(handle->lock);
+
 	while(apr_queue_trypop(handle->queue, &pop) == APR_SUCCESS) {
-		msg = (iks *) pop;
-		iks_send(handle->parser, msg);
-		iks_delete(msg);
+		if (pop) {
+			msg = (iks *) pop;
+			if (!done) iks_send(handle->parser, msg);
+			iks_delete(msg);
+			pop = NULL;
+		} else {
+			break;
+		}
 	}
 
 	len = apr_queue_size(handle->retry_queue); 
-
 	if (globals.debug && len) {
 		globals.logger(DL_LOG_DEBUG, "Processing %u packets in retry queue\n", len);
 	}
-	apr_thread_mutex_lock(handle->lock);		
+
+	pop = NULL;
+
 	while(x < len && apr_queue_trypop(handle->retry_queue, &pop) == APR_SUCCESS) {
-		struct packet_node *packet_node = (struct packet_node *) pop;
-		apr_time_t now = apr_time_now();
-		x++;
-
-		if (packet_node->next <= now) {
-			if (packet_node->retries > 0) {
-				packet_node->retries--;
-				if (globals.debug) {
-					globals.logger(DL_LOG_DEBUG, "Sending packet %s (%d left)\n", packet_node->id, packet_node->retries);
+		if (!pop) {
+			break;
+		} else {
+			struct packet_node *packet_node = (struct packet_node *) pop;
+			apr_time_t now = apr_time_now();
+			x++;
+
+			if (packet_node->next <= now) {
+				if (packet_node->retries > 0) {
+					packet_node->retries--;
+					if (globals.debug) {
+						globals.logger(DL_LOG_DEBUG, "Sending packet %s (%d left)\n", packet_node->id, packet_node->retries);
+					}
+					iks_send(handle->parser, packet_node->xml);
+					packet_node->next = now + 5000000;
 				}
-				iks_send(handle->parser, packet_node->xml);
-				packet_node->next = now + 5000000;
 			}
-		}
-		if (packet_node->retries == 0 || done) {
-			if (globals.debug) {
-				globals.logger(DL_LOG_DEBUG, "Discarding packet %s\n", packet_node->id);
+			if (packet_node->retries == 0 || done) {
+				if (globals.debug) {
+					globals.logger(DL_LOG_DEBUG, "Discarding packet %s\n", packet_node->id);
+				}
+				apr_hash_set(handle->retry_hash, packet_node->id, APR_HASH_KEY_STRING, NULL);
+				iks_delete(packet_node->xml);
+				free(packet_node);
+			} else {
+				apr_queue_push(handle->retry_queue, packet_node);
+				packet_node = NULL;
 			}
-			apr_hash_set(handle->retry_hash, packet_node->id, APR_HASH_KEY_STRING, NULL);
-			iks_delete(packet_node->xml);
-			free(packet_node);
-		} else {
-			apr_queue_push(handle->retry_queue, packet_node);
+			pop = NULL;
 		}
 	}
 	apr_thread_mutex_unlock(handle->lock);
@@ -1393,9 +1446,9 @@
 										handle,
 										(iksStreamHook *) (ldl_test_flag(handle, LDL_FLAG_COMPONENT) ? on_stream_component : on_stream));
 
-		if (globals.debug) {
-			iks_set_log_hook(handle->parser, (iksLogHook *) on_log);
-		}
+
+		iks_set_log_hook(handle->parser, (iksLogHook *) on_log);
+			
 		
 		strncpy(tmp, jabber_id, sizeof(tmp)-1);
 		sl = strchr(tmp, '/');
@@ -1423,16 +1476,18 @@
 			break;
 		case IKS_NET_NODNS:
 			globals.logger(DL_LOG_DEBUG, "hostname lookup failed\n");
+			microsleep(1000);
+			goto fail;
 		case IKS_NET_NOCONN:
 			globals.logger(DL_LOG_DEBUG, "connection failed\n");
+			microsleep(1000);
+			goto fail;
 		default:
-			globals.logger(DL_LOG_DEBUG, "io error %d\n", e);
-			microsleep(500);
-			continue;
+			globals.logger(DL_LOG_DEBUG, "io error 1 %d\n", e);
+			microsleep(1000);
+			goto fail;
 		}
 
-
-
 		handle->counter = opt_timeout;
 		if (ldl_test_flag(handle, LDL_FLAG_TLS)) {
 			launch_queue_thread(handle);
@@ -1456,9 +1511,9 @@
 			}
 
 			if (IKS_OK != e) {
-				globals.logger(DL_LOG_DEBUG, "io error %d\n", e);
-				microsleep(500);
-				break;
+				globals.logger(DL_LOG_DEBUG, "io error 2 %d\n", e);
+				microsleep(1000);
+				goto fail;
 			}
 
 			
@@ -1481,13 +1536,18 @@
 			}
 		}
 
+	fail:
 		iks_disconnect(handle->parser);
 		iks_parser_delete(handle->parser);
 		ldl_clear_flag_locked(handle, LDL_FLAG_CONNECTED);
 		ldl_clear_flag_locked(handle, LDL_FLAG_AUTHORIZED);
+		handle->state = CS_NEW;
 	}
 	ldl_clear_flag_locked(handle, LDL_FLAG_RUNNING);
-
+	if (!ldl_test_flag(handle, LDL_FLAG_TLS)) {
+		ldl_flush_queue(handle, 1);
+	}
+	
 	while(ldl_test_flag(handle, LDL_FLAG_QUEUE_RUNNING)) {
 		microsleep(100);
 	}
@@ -1551,8 +1611,9 @@
 		packet_node->xml = xml;
 		packet_node->retries = retries;
 		packet_node->next = apr_time_now();
-		apr_queue_push(handle->retry_queue, packet_node);
 		apr_hash_set(handle->retry_hash, packet_node->id, APR_HASH_KEY_STRING, packet_node);
+		apr_queue_push(handle->retry_queue, packet_node);
+		packet_node = NULL;
 	}
 	apr_thread_mutex_unlock(handle->lock);
 
@@ -1596,21 +1657,28 @@
 	myid = next_id();
     snprintf(idbuf, sizeof(idbuf), "%u", myid);
 
-	iq = iks_new("iq");
-	iks_insert_attrib(iq, "type", "set");
-	iks_insert_attrib(iq, "id", idbuf);
-	iks_insert_attrib(iq, "from", session->login);
-	iks_insert_attrib(iq, "to", session->them);
-	sess = iks_insert (iq, "session");
-    iks_insert_attrib(sess, "xmlns", "http://www.google.com/session");
-	iks_insert_attrib(sess, "type", "transport-accept");
-	iks_insert_attrib(sess, "id", candidate->tid);
-	iks_insert_attrib(sess, "xmlns", "http://www.google.com/session");
-	iks_insert_attrib(sess, "initiator", session->initiator ? session->initiator : session->them);
-	tp = iks_insert (sess, "transport");
-	iks_insert_attrib(tp, "xmlns", "http://www.google.com/transport/p2p");
+	if ((iq = iks_new("iq"))) {
+		if (!iks_insert_attrib(iq, "type", "set")) goto fail;
+		if (!iks_insert_attrib(iq, "id", idbuf)) goto fail;
+		if (!iks_insert_attrib(iq, "from", session->login)) goto fail;
+		if (!iks_insert_attrib(iq, "to", session->them)) goto fail;
+		if (!(sess = iks_insert (iq, "session"))) goto fail;
+		if (!iks_insert_attrib(sess, "xmlns", "http://www.google.com/session")) goto fail;
+		if (!iks_insert_attrib(sess, "type", "transport-accept")) goto fail;
+		if (!iks_insert_attrib(sess, "id", candidate->tid)) goto fail;
+		if (!iks_insert_attrib(sess, "xmlns", "http://www.google.com/session")) goto fail;
+		if (!iks_insert_attrib(sess, "initiator", session->initiator ? session->initiator : session->them)) goto fail;
+		if (!(tp = iks_insert (sess, "transport"))) goto fail;
+		if (!iks_insert_attrib(tp, "xmlns", "http://www.google.com/transport/p2p")) goto fail;
+		apr_queue_push(session->handle->queue, iq);
+		iq = NULL;
+	}
+
+ fail:
+	if (iq) {
+		iks_delete(iq);
+	}
 
-	apr_queue_push(session->handle->queue, iq);
 }
 
 void *ldl_handle_get_private(ldl_handle_t *handle)
@@ -1618,20 +1686,70 @@
 	return handle->private_info;
 }
 
-void *ldl_handle_get_login(ldl_handle_t *handle)
+char *ldl_handle_get_login(ldl_handle_t *handle)
 {
 	return handle->login;
 }
 
-void ldl_handle_send_presence(ldl_handle_t *handle, char *from, char *to, char *type, char *rpid, char *message)
+void ldl_handle_send_presence(ldl_handle_t *handle, char *from, char *to, char *type, char *rpid, char *message, char *avatar)
 {
-	do_presence(handle, from, to, type, rpid, message);
+	do_presence(handle, from, to, type, rpid, message, avatar);
 }
 
+static void ldl_random_string(char *buf, uint16_t len, char *set)
+{
+    char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+    int max;
+    uint16_t x;
+
+    if (!set) {
+        set = chars;
+    }
+
+    max = (int) strlen(set);
+
+    srand((unsigned int) time(NULL));
+
+    for (x = 0; x < len; x++) {
+        int j = (int) (max * 1.0 * rand() / (RAND_MAX + 1.0));
+        buf[x] = set[j];
+    }
+}
+
+
 void ldl_handle_send_vcard(ldl_handle_t *handle, char *from, char *to, char *id, char *vcard)
 {
 	iks *vxml, *iq;
 	int e = 0;
+	ldl_avatar_t *ap;
+
+	ap = ldl_get_avatar(handle, NULL, from);
+
+	if (!vcard) {
+		char text[8192];
+		char *ext;
+		if (!ap) {
+			return;
+		}
+		
+		if ((ext = strrchr(ap->path, '.'))) {
+			ext++;
+		} else {
+			ext = "png";
+		}
+
+		snprintf(text, sizeof(text),
+				 "<vCard xmlns='vcard-temp'><PHOTO><TYPE>image/%s</TYPE><BINVAL>%s</BINVAL></PHOTO></vCard>",
+				 ext,
+				 ap->base64
+				 );
+		vcard = text;
+	} else {
+		if (ap && (strstr(vcard, "photo") || strstr(vcard, "PHOTO"))) {
+			ldl_random_string(ap->hash, sizeof(ap->hash) -1, NULL);
+		}
+	}
+
 
 	if (!(vxml = iks_tree(vcard, 0, &e))) {
 		globals.logger(DL_LOG_ERR, "Parse returned error [%d]\n", e);
@@ -1643,16 +1761,24 @@
 		return;
 	}
 
-	iks_insert_attrib(iq, "to", to);
-	iks_insert_attrib(iq, "xmlns", "jabber:client");
-	iks_insert_attrib(iq,"from", from);
-	iks_insert_attrib(iq, "type", "result");
-	iks_insert_attrib(iq, "id", id);
-	iks_insert_node(iq, vxml);
-	
+	if (!iks_insert_attrib(iq, "to", to)) goto fail;
+	if (!iks_insert_attrib(iq, "xmlns", "jabber:client")) goto fail;
+	if (!iks_insert_attrib(iq,"from", from)) goto fail;
+	if (!iks_insert_attrib(iq, "type", "result")) goto fail;
+	if (!iks_insert_attrib(iq, "id", id)) goto fail;
+	if (!iks_insert_node(iq, vxml)) goto fail;
+
 	apr_queue_push(handle->queue, iq);
+	iq = NULL;
+	vxml = NULL;
 
-	iks_free(vxml);
+ fail:
+	if (iq) {
+		iks_delete(iq);
+	}
+	if (vxml) {
+		iks_delete(vxml);
+	}
 
 }
 
@@ -1708,9 +1834,19 @@
 	}
 
 	apr_queue_push(handle->queue, msg);
+	msg = NULL;
 	
 }
 
+int ldl_global_debug(int on)
+{
+	if (on > -1) {
+		globals.debug = on ? 1 : 0;
+	}
+
+	return globals.debug ? 1 : 0;
+}
+
 void ldl_global_set_logger(ldl_logger_t logger)
 {
 	globals.logger = logger;
@@ -1743,7 +1879,7 @@
 		iq = NULL;
 		sess = NULL;
 		id = 0;
-
+		
 		new_session_iq(session, &iq, &sess, &id, "transport-info");
 		tag = iks_insert(sess, "transport");
 		iks_insert_attrib(tag, "xmlns", "http://www.google.com/transport/p2p");
@@ -1792,42 +1928,34 @@
 	iks *pres, *msg;
 	char *lid = NULL, *low_id = NULL;
 	struct ldl_buffer buffer;
-	apr_time_t started;
-	unsigned int elapsed;
+	time_t started, elapsed, next = 0;
 	char *notice = "Call Me!";
-	int again = 0;
-
+	
 	buffer.buf = buf;
 	buffer.len = len;
 	buffer.hit = 0;
 
-	pres = iks_new("presence");
-	iks_insert_attrib(pres, "type", "probe");
-	iks_insert_attrib(pres, "from", from);
-	iks_insert_attrib(pres, "to", id);
-	
-
 	apr_hash_set(handle->probe_hash, id, APR_HASH_KEY_STRING, &buffer);
-	msg = iks_make_s10n (IKS_TYPE_SUBSCRIBE, id, notice); 
-	iks_insert_attrib(msg, "from", from);
-	apr_queue_push(handle->queue, msg);
-	msg = iks_make_s10n (IKS_TYPE_SUBSCRIBED, id, notice); 
-	iks_insert_attrib(msg, "from", from);
-	apr_queue_push(handle->queue, msg);
-	apr_queue_push(handle->queue, pres);
-
-	//schedule_packet(handle, next_id(), pres, LDL_RETRY);
 
-	started = apr_time_now();
+	started = time(NULL);
 	for(;;) {
-		elapsed = (unsigned int)((apr_time_now() - started) / 1000);
-		if (elapsed > 5000 && ! again) {
+		elapsed = time(NULL) - started;
+		if (elapsed == next) {
 			msg = iks_make_s10n (IKS_TYPE_SUBSCRIBE, id, notice); 
 			iks_insert_attrib(msg, "from", from);
 			apr_queue_push(handle->queue, msg);
-			again++;
+			msg = NULL;
+			
+			pres = iks_new("presence");
+			iks_insert_attrib(pres, "xmlns", "jabber:client");
+			iks_insert_attrib(pres, "type", "probe");
+			iks_insert_attrib(pres, "to", id);
+			iks_insert_attrib(pres, "from", from);
+			apr_queue_push(handle->queue, pres);
+			pres = NULL;
+			next += 5;
 		}
-		if (elapsed > 10000) {
+		if (elapsed >= 17) {
 			break;
 		}
 		if (buffer.hit) {
@@ -1886,9 +2014,12 @@
 	apr_hash_set(handle->probe_hash, id, APR_HASH_KEY_STRING, &buffer);
 	msg = iks_make_s10n (IKS_TYPE_SUBSCRIBE, id, notice); 
 	apr_queue_push(handle->queue, msg);
+	msg = NULL;
 	msg = iks_make_s10n (IKS_TYPE_SUBSCRIBED, id, notice); 
 	apr_queue_push(handle->queue, msg);
+	msg = NULL;
 	apr_queue_push(handle->queue, iq);
+	iq = NULL;
 
 	//schedule_packet(handle, next_id(), pres, LDL_RETRY);
 
@@ -1898,6 +2029,7 @@
 		if (elapsed > 5000 && ! again) {
 			msg = iks_make_s10n (IKS_TYPE_SUBSCRIBE, id, notice); 
 			apr_queue_push(handle->queue, msg);
+			msg = NULL;
 			again++;
 		}
 		if (elapsed > 10000) {
@@ -2010,6 +2142,7 @@
 	globals.debug = debug;
 	globals.id = 300;
 	globals.logger = default_logger;
+	globals.avatar_hash = apr_hash_make(globals.memory_pool);
 	ldl_set_flag_locked((&globals), LDL_FLAG_INIT);
 	
 	return LDL_STATUS_SUCCESS;
@@ -2017,10 +2150,10 @@
 
 ldl_status ldl_global_destroy(void)
 {
-	if (ldl_test_flag(&globals, LDL_FLAG_INIT)) {
+	if (!ldl_test_flag(&globals, LDL_FLAG_INIT)) {
 		return LDL_STATUS_FALSE;
 	}
-
+	
 	apr_pool_destroy(globals.memory_pool);
 	ldl_clear_flag(&globals, LDL_FLAG_INIT);
 	apr_terminate();

Modified: freeswitch/branches/cparker/libs/libdingaling/src/libdingaling.h
==============================================================================
--- freeswitch/branches/cparker/libs/libdingaling/src/libdingaling.h	(original)
+++ freeswitch/branches/cparker/libs/libdingaling/src/libdingaling.h	Tue Apr 24 10:14:28 2007
@@ -38,8 +38,9 @@
   \{
 */
 /* OMG */
-#ifdef WIN32
+#ifdef _MSC_VER
 #define __LDL_FUNC__ __FUNCTION__
+#define inline __inline
 #else
 #define __LDL_FUNC__ (const char *)__func__
 #endif
@@ -180,6 +181,59 @@
 #define ldl_yield(ms) apr_sleep(ms * 10); apr_thread_yield();
 
 /*!
+  \brief Test for a common domain in 2 jid
+  \param id_a the first id
+  \param id_b the second id
+  \return 1 if the domains match 0 if they dont or -1 if either id is invalid
+  \note the id may or may not contain a user and/or resource
+*/
+static inline int ldl_jid_domcmp(char *id_a, char *id_b)
+{
+    char *id_a_host, *id_b_host, *id_a_r, *id_b_r;
+
+	id_a_host = strchr(id_a, '@');
+	if (id_a_host) {
+		id_a_host++;
+	} else {
+		id_a_host = id_a;
+	}
+
+	id_b_host = strchr(id_b, '@');
+	if (id_b_host) {
+		id_b_host++;
+	} else {
+		id_b_host = id_b;
+	}
+
+    if (id_a_host && id_b_host) {
+        size_t id_a_len = 0, id_b_len = 0, len = 0;
+
+        id_a_r = strchr(id_a_host, '/');
+		if (id_a_r) {
+            id_a_len = id_a_r - id_a_host;
+        } else {
+            id_a_len = strlen(id_a_host);
+        }
+
+        id_b_r = strchr(id_b_host, '/');
+		if (id_b_r) {
+            id_b_len = id_b_r - id_b_host;
+        } else {
+            id_b_len = strlen(id_b_host);
+        }
+
+        if (id_a_len > id_b_len) {
+            len = id_b_len;
+        } else {
+            len = id_a_len;
+        }
+
+        return strncasecmp(id_a_host, id_b_host, len) ? 0 : 1;
+    }
+    return -1;
+}
+
+/*!
   \brief Test for the existance of a flag on an arbitary object
   \param obj the object to test
   \param flag the or'd list of flags to test
@@ -326,6 +380,13 @@
 void ldl_session_accept_candidate(ldl_session_t *session, ldl_candidate_t *candidate);
 
 /*!
+  \brief turn logging on/off
+  \param on (TRUE or FALSE)
+  \return current state
+*/
+int ldl_global_debug(int on);
+
+/*!
   \brief Set a custom logger
   \param logger the logger function
 */
@@ -372,7 +433,7 @@
   \param handle the conection handle
   \return the requested data
 */
-void *ldl_handle_get_login(ldl_handle_t *handle);
+char *ldl_handle_get_login(ldl_handle_t *handle);
 
 /*!
   \brief Send a message to a session
@@ -390,8 +451,9 @@
   \param type the type of presence
   \param rpid data for the icon
   \param message a status message
+  \param avatar the path to an avatar image
 */
-void ldl_handle_send_presence(ldl_handle_t *handle, char *from, char *to, char *type, char *rpid, char *message);
+void ldl_handle_send_presence(ldl_handle_t *handle, char *from, char *to, char *type, char *rpid, char *message, char *avatar);
 
 /*!
   \brief Send a vcard

Modified: freeswitch/branches/cparker/libs/libetpan/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/libetpan/configure.in	(original)
+++ freeswitch/branches/cparker/libs/libetpan/configure.in	Tue Apr 24 10:14:28 2007
@@ -30,7 +30,7 @@
 AC_SUBST(API_VERSION)
 
 AC_ARG_ENABLE(debug,   [  --enable-debug          setup flags (gcc) for debugging (default=no)],
-CFLAGS="$CFLAGS -O2 -g"
+CFLAGS="$CFLAGS -g"
 CPPFLAGS="$CPPFLAGS -DDEBUG"
 LDFLAGS="$LDFLAGS",)
 AC_ARG_ENABLE(optim,   [  --enable-optim          setup flags (gcc) for optimizations (default=no)],
@@ -41,10 +41,10 @@
 else
   AC_MSG_WARN([enable-optim and enable-debug are incompatible -- disabling optimizations])
 fi,)
-CFLAGS="$CFLAGS -W -Wall"
+CFLAGS="$CFLAGS"
 AC_ARG_ENABLE(syntax,   [  --enable-unstrict-syntax be lazy on syntax checking for protocols (default=no)], , [AC_DEFINE(UNSTRICT_SYNTAX, 1, [Define to be lazy on protocol syntax])])
 
-AC_CONFIG_HEADER(config.h)
+AC_CONFIG_HEADERS(config.h)
 
 AH_VERBATIM([CONFIG_H_FIRST], [/* Check for Linux's /usr/include/features.h
  */
@@ -429,7 +429,7 @@
 AC_SUBST(SASLLIBS)
 
 dnl IPv6 support
-AC_ARG_ENABLE(ipv6, AC_HELP_STRING([--disable-ipv6], [enable IPv6 support (default=yes)]), , enable_ipv6=yes)
+AC_ARG_ENABLE(ipv6, AC_HELP_STRING([--disable-ipv6], [enable IPv6 support (default=yes)]), , enable_ipv6=no)
 AC_MSG_CHECKING([whether to use IPv6])
 AC_MSG_RESULT($enable_ipv6)
 if test "x$enable_ipv6" = "xyes"; then

Modified: freeswitch/branches/cparker/libs/libresample/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/libresample/configure.in	(original)
+++ freeswitch/branches/cparker/libs/libresample/configure.in	Tue Apr 24 10:14:28 2007
@@ -111,7 +111,7 @@
 
 AC_CHECK_HEADERS(inttypes.h)
 
-AC_CONFIG_HEADER(src/config.h:src/configtemplate.h)
+AC_CONFIG_HEADERS(src/config.h:src/configtemplate.h)
 AC_OUTPUT([Makefile])
 
 echo ""

Modified: freeswitch/branches/cparker/libs/libsndfile/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/libsndfile/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/libsndfile/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -1,10 +1,11 @@
-## Process this file with automake to produce Makefile.in
+# Process this file with automake to produce Makefile.in
 
-SUBDIRS = man doc Win32 Octave src examples regtest tests
+SUBDIRS = Win32 Octave src
+# man doc Win32 examples regtest tests
 DIST_SUBDIRS = $(SUBDIRS)
 EXTRA_DIST = reconfigure.mk acinclude.m4 libsndfile.spec.in \
 			sndfile.pc.in Mingw-make-dist.sh
-			
+
 			 
 pkgconfigdir = $(libdir)/pkgconfig
 pkgconfig_DATA = sndfile.pc

Modified: freeswitch/branches/cparker/libs/libsndfile/acinclude.m4
==============================================================================
--- freeswitch/branches/cparker/libs/libsndfile/acinclude.m4	(original)
+++ freeswitch/branches/cparker/libs/libsndfile/acinclude.m4	Tue Apr 24 10:14:28 2007
@@ -557,6 +557,63 @@
 
 
 
+dnl PKG_CHECK_MODULES(GSTUFF, gtk+-2.0 >= 1.3 glib = 1.3.4, action-if, action-not)
+dnl defines GSTUFF_LIBS, GSTUFF_CFLAGS, see pkg-config man page
+dnl also defines GSTUFF_PKG_ERRORS on error
+AC_DEFUN([PKG_CHECK_MODULES], [
+  succeeded=no
+
+  if test -z "$PKG_CONFIG"; then
+    AC_PATH_PROG(PKG_CONFIG, pkg-config, no)
+  fi
+
+  if test "$PKG_CONFIG" = "no" ; then
+     echo "*** The pkg-config script could not be found. Make sure it is"
+     echo "*** in your path, or set the PKG_CONFIG environment variable"
+     echo "*** to the full path to pkg-config."
+     echo "*** Or see http://www.freedesktop.org/software/pkgconfig to get pkg-config."
+  else
+     PKG_CONFIG_MIN_VERSION=0.9.0
+     if $PKG_CONFIG --atleast-pkgconfig-version $PKG_CONFIG_MIN_VERSION; then
+        AC_MSG_CHECKING(for $2)
+
+        if $PKG_CONFIG --exists "$2" ; then
+            AC_MSG_RESULT(yes)
+            succeeded=yes
+
+            AC_MSG_CHECKING($1_CFLAGS)
+            $1_CFLAGS=`$PKG_CONFIG --cflags "$2"`
+            AC_MSG_RESULT($$1_CFLAGS)
+
+            AC_MSG_CHECKING($1_LIBS)
+            $1_LIBS=`$PKG_CONFIG --libs "$2"`
+            AC_MSG_RESULT($$1_LIBS)
+        else
+            $1_CFLAGS=""
+            $1_LIBS=""
+            ## If we have a custom action on failure, don't print errors, but 
+            ## do set a variable so people can do so.
+            $1_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"`
+            ifelse([$4], ,echo $$1_PKG_ERRORS,)
+        fi
+
+        AC_SUBST($1_CFLAGS)
+        AC_SUBST($1_LIBS)
+     else
+        echo "*** Your version of pkg-config is too old. You need version $PKG_CONFIG_MIN_VERSION or newer."
+        echo "*** See http://www.freedesktop.org/software/pkgconfig"
+     fi
+  fi
+
+  if test $succeeded = yes; then
+     ifelse([$3], , :, [$3])
+  else
+     ifelse([$4], , AC_MSG_ERROR([Library requirements ($2) not met; consider adjusting the PKG_CONFIG_PATH environment variable if your libraries are in a nonstandard prefix so pkg-config can find them.]), [$4])
+  fi
+])
+
+
+
 
 ifelse(dnl	
 

Modified: freeswitch/branches/cparker/libs/libsndfile/tests/utils.h
==============================================================================
--- freeswitch/branches/cparker/libs/libsndfile/tests/utils.h	(original)
+++ freeswitch/branches/cparker/libs/libsndfile/tests/utils.h	Tue Apr 24 10:14:28 2007
@@ -30,6 +30,8 @@
 #endif	/* __cplusplus */
 
 #include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
 
 #define SF_COUNT_TO_LONG(x)	((long) (x))
 #define	ARRAY_LEN(x)		((int) (sizeof (x)) / (sizeof ((x) [0])))

Modified: freeswitch/branches/cparker/libs/libspeakup/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/libspeakup/configure.in	(original)
+++ freeswitch/branches/cparker/libs/libspeakup/configure.in	Tue Apr 24 10:14:28 2007
@@ -5,9 +5,7 @@
 AC_CONFIG_AUX_DIR(build)
 AM_INIT_AUTOMAKE(libspeakup,0.1)
 AC_CONFIG_SRCDIR([src])
-#AC_CONFIG_HEADER([])
 
-AC_PREFIX_DEFAULT(/usr/local/freeswitch)
 # Checks for programs.
 AC_LANG_C
 AC_PROG_CC

Modified: freeswitch/branches/cparker/libs/libteletone/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/libteletone/configure.in	(original)
+++ freeswitch/branches/cparker/libs/libteletone/configure.in	Tue Apr 24 10:14:28 2007
@@ -6,7 +6,6 @@
 AC_CONFIG_AUX_DIR(build)
 AM_INIT_AUTOMAKE(libteletone,0.1)
 AC_CONFIG_SRCDIR([src])
-#AC_CONFIG_HEADER([])
 
 # Checks for programs.
 AC_PROG_CC

Modified: freeswitch/branches/cparker/libs/libteletone/src/libteletone.h
==============================================================================
--- freeswitch/branches/cparker/libs/libteletone/src/libteletone.h	(original)
+++ freeswitch/branches/cparker/libs/libteletone/src/libteletone.h	Tue Apr 24 10:14:28 2007
@@ -59,7 +59,7 @@
 #endif
 
 #ifdef _MSC_VER
-#define int16_t __int16
+typedef __int16 int16_t;
 #endif
 
 #include <libteletone_generate.h>

Modified: freeswitch/branches/cparker/libs/libteletone/src/libteletone_detect.c
==============================================================================
--- freeswitch/branches/cparker/libs/libteletone/src/libteletone_detect.c	(original)
+++ freeswitch/branches/cparker/libs/libteletone/src/libteletone_detect.c	Tue Apr 24 10:14:28 2007
@@ -217,7 +217,7 @@
 			gtest += teletone_goertzel_result (&mt->gs2[x]) < eng_all[x] ? 1 : 0;
 		}
 
-		if (gtest >= 2 && eng_sum > 42.0 * mt->energy) {
+		if ((gtest >= 2 || gtest == mt->tone_count) && eng_sum > 42.0 * mt->energy) {
 			if(mt->negatives) {
 				mt->negatives--;
 			}

Modified: freeswitch/branches/cparker/libs/libteletone/src/libteletone_detect.h
==============================================================================
--- freeswitch/branches/cparker/libs/libteletone/src/libteletone_detect.h	(original)
+++ freeswitch/branches/cparker/libs/libteletone/src/libteletone_detect.h	Tue Apr 24 10:14:28 2007
@@ -64,10 +64,12 @@
 	This module is responsible for tone detection specifics
 */
 
+#ifndef FALSE
 #define FALSE   0
 #ifndef TRUE
 #define TRUE    (!FALSE)
 #endif
+#endif
 
 /* Basic DTMF specs:
  *

Modified: freeswitch/branches/cparker/libs/pcre/INSTALL
==============================================================================
--- freeswitch/branches/cparker/libs/pcre/INSTALL	(original)
+++ freeswitch/branches/cparker/libs/pcre/INSTALL	Tue Apr 24 10:14:28 2007
@@ -183,3 +183,4 @@
      script, and exit.
 
 `configure' also accepts some other, not widely useful, options.
+  
\ No newline at end of file

Modified: freeswitch/branches/cparker/libs/portaudio/Makefile.in
==============================================================================
--- freeswitch/branches/cparker/libs/portaudio/Makefile.in	(original)
+++ freeswitch/branches/cparker/libs/portaudio/Makefile.in	Tue Apr 24 10:14:28 2007
@@ -57,61 +57,61 @@
 	src/common/pa_trace.o
 
 TESTS = \
-	bin/paqa_devs \
-	bin/paqa_errs \
-	bin/patest1 \
-	bin/patest_buffer \
-	bin/patest_callbackstop \
-	bin/patest_clip \
-	bin/patest_dither \
-	bin/patest_hang \
-	bin/patest_in_overflow \
-	bin/patest_latency \
-	bin/patest_leftright \
-	bin/patest_longsine \
-	bin/patest_many \
-	bin/patest_maxsines \
-	bin/patest_multi_sine \
-	bin/patest_out_underflow \
-	bin/patest_pink \
-	bin/patest_prime \
-	bin/patest_read_record \
-	bin/patest_read_write_wire \
-	bin/patest_record \
-	bin/patest_ringmix \
-	bin/patest_saw \
-	bin/patest_sine8 \
-	bin/patest_sine \
-	bin/patest_sine_formats \
-	bin/patest_sine_time \
-	bin/patest_start_stop \
-	bin/patest_stop \
-	bin/patest_stop_playout \
-	bin/patest_toomanysines \
-	bin/patest_underflow \
-	bin/patest_wire \
-	bin/patest_write_sine \
-	bin/pa_devs \
-	bin/pa_fuzz \
-	bin/pa_minlat
+	test/paqa_devs \
+	test/paqa_errs \
+	test/patest1 \
+	test/patest_buffer \
+	test/patest_callbackstop \
+	test/patest_clip \
+	test/patest_dither \
+	test/patest_hang \
+	test/patest_in_overflow \
+	test/patest_latency \
+	test/patest_leftright \
+	test/patest_longsine \
+	test/patest_many \
+	test/patest_maxsines \
+	test/patest_multi_sine \
+	test/patest_out_underflow \
+	test/patest_pink \
+	test/patest_prime \
+	test/patest_read_record \
+	test/patest_read_write_wire \
+	test/patest_record \
+	test/patest_ringmix \
+	test/patest_saw \
+	test/patest_sine8 \
+	test/patest_sine \
+	test/patest_sine_formats \
+	test/patest_sine_time \
+	test/patest_start_stop \
+	test/patest_stop \
+	test/patest_stop_playout \
+	test/patest_toomanysines \
+	test/patest_underflow \
+	test/patest_wire \
+	test/patest_write_sine \
+	test/pa_devs \
+	test/pa_fuzz \
+	test/pa_minlat
 
 # Most of these don't compile yet.  Put them in TESTS, above, if
 # you want to try to compile them...
 ALL_TESTS = \
 	$(TESTS) \
-	bin/patest_sync \
-	bin/debug_convert \
-	bin/debug_dither_calc \
-	bin/debug_dual \
-	bin/debug_multi_in \
-	bin/debug_multi_out \
-	bin/debug_record \
-	bin/debug_record_reuse \
-	bin/debug_sine_amp \
-	bin/debug_sine \
-	bin/debug_sine_formats \
-	bin/debug_srate \
-	bin/debug_test1
+	test/patest_sync \
+	test/debug_convert \
+	test/debug_dither_calc \
+	test/debug_dual \
+	test/debug_multi_in \
+	test/debug_multi_out \
+	test/debug_record \
+	test/debug_record_reuse \
+	test/debug_sine_amp \
+	test/debug_sine \
+	test/debug_sine_formats \
+	test/debug_srate \
+	test/debug_test1
 
 OBJS = $(COMMON_OBJS) $(OTHER_OBJS)
 
@@ -128,9 +128,8 @@
 lib/$(PALIB): lib-stamp $(LTOBJS) $(MAKEFILE) $(PAINC)
 	$(LIBTOOL) --mode=link $(CC) $(PA_LDFLAGS) -o lib/$(PALIB) $(LTOBJS) $(DLL_LIBS)
 
-$(ALL_TESTS): bin/%: lib/$(PALIB) $(MAKEFILE) $(PAINC) test/%.c
-	$(LIBTOOL) --mode=link $(CC) -o $@ $(CFLAGS) $(top_srcdir)/test/$*.c lib/$(PALIB) $(LIBS)
-
+$(ALL_TESTS): lib/$(PALIB) $(MAKEFILE) $(PAINC)
+	$(LIBTOOL) --mode=link $(CC) -o $@ $(CFLAGS) $(top_srcdir)/$@.c lib/$(PALIB) $(LIBS)
 
 install: lib/$(PALIB) portaudio-2.0.pc
 	$(INSTALL) -d $(DESTDIR)$(libdir)
@@ -164,16 +163,19 @@
 distclean: clean
 	rm -f config.log config.status Makefile libtool portaudio-2.0.pc
 
-%.o: %.c $(MAKEFILE) $(PAINC)
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .cpp
+
+.c.o: $(MAKEFILE) $(PAINC)
 	$(CC) -c $(CFLAGS) $< -o $@
 
-%.lo: %.c $(MAKEFILE) $(PAINC)
+.c.lo: $(MAKEFILE) $(PAINC)
 	$(LIBTOOL) --mode=compile $(CC) -c $(CFLAGS) $< -o $@
 
-%.o: %.cpp $(MAKEFILE) $(PAINC)
+.cpp.o: $(MAKEFILE) $(PAINC)
 	$(CXX) -c $(CXXFLAGS) $< -o $@
 
-%.o: %.asm
+.asm.o:
 	$(NASM) $(NASMOPT) -o $@ $<
 
 bin-stamp:

Modified: freeswitch/branches/cparker/libs/portaudio/configure
==============================================================================
--- freeswitch/branches/cparker/libs/portaudio/configure	(original)
+++ freeswitch/branches/cparker/libs/portaudio/configure	Tue Apr 24 10:14:28 2007
@@ -1,54 +1,25 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.61.
+# Generated by GNU Autoconf 2.59.
 #
-# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
-# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+# Copyright (C) 2003 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
+# Be Bourne compatible
 if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
   emulate sh
   NULLCMD=:
   # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
   # 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
-
-
-
-
-# PATH needs CR
-# 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
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
+elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
+  set -o posix
 fi
+DUALCASE=1; export DUALCASE # for MKS sh
 
 # Support unset when possible.
 if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
@@ -58,43 +29,8 @@
 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.)
-as_nl='
-'
-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
-  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  { (exit 1); exit 1; }
-fi
-
 # Work around bugs in pre-3.0 UWIN ksh.
-for as_var in ENV MAIL MAILPATH
-do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-done
+$as_unset ENV MAIL MAILPATH
 PS1='$ '
 PS2='> '
 PS4='+ '
@@ -108,19 +44,18 @@
   if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
     eval $as_var=C; export $as_var
   else
-    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+    $as_unset $as_var
   fi
 done
 
 # Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+if expr a : '\(a\)' >/dev/null 2>&1; then
   as_expr=expr
 else
   as_expr=false
 fi
 
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
   as_basename=basename
 else
   as_basename=false
@@ -128,388 +63,157 @@
 
 
 # Name of the executable.
-as_me=`$as_basename -- "$0" ||
+as_me=`$as_basename "$0" ||
 $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
 	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+	 X"$0" : 'X\(/\)$' \| \
+	 .     : '\(.\)' 2>/dev/null ||
 echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-
-# CDPATH.
-$as_unset CDPATH
-
+    sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
+  	  /^X\/\(\/\/\)$/{ s//\1/; q; }
+  	  /^X\/\(\/\).*/{ s//\1/; q; }
+  	  s/.*/./; q'`
 
-if test "x$CONFIG_SHELL" = x; then
-  if (eval ":") 2>/dev/null; then
-  as_have_required=yes
-else
-  as_have_required=no
-fi
-
-  if test $as_have_required = yes && 	 (eval ":
-(as_func_return () {
-  (exit \$1)
-}
-as_func_success () {
-  as_func_return 0
-}
-as_func_failure () {
-  as_func_return 1
-}
-as_func_ret_success () {
-  return 0
-}
-as_func_ret_failure () {
-  return 1
-}
 
-exitcode=0
-if as_func_success; then
-  :
-else
-  exitcode=1
-  echo as_func_success failed.
-fi
-
-if as_func_failure; then
-  exitcode=1
-  echo as_func_failure succeeded.
-fi
-
-if as_func_ret_success; then
-  :
-else
-  exitcode=1
-  echo as_func_ret_success failed.
-fi
+# PATH needs CR, and LINENO needs CR and PATH.
+# 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
 
-if as_func_ret_failure; then
-  exitcode=1
-  echo as_func_ret_failure succeeded.
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
 fi
 
-if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
-  :
-else
-  exitcode=1
-  echo positional parameters were not saved.
-fi
 
-test \$exitcode = 0) || { (exit 1); exit 1; }
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x$as_lineno_3"  = "x$as_lineno_2"  || {
+  # Find who we are.  Look in the path if we contain no path at all
+  # relative or not.
+  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
 
-(
-  as_lineno_1=\$LINENO
-  as_lineno_2=\$LINENO
-  test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" &&
-  test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; }
-") 2> /dev/null; then
-  :
-else
-  as_candidate_shells=
+       ;;
+  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
+    { echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2
+   { (exit 1); exit 1; }; }
+  fi
+  case $CONFIG_SHELL in
+  '')
     as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  case $as_dir in
+  for as_base in sh bash ksh sh5; do
+	 case $as_dir in
 	 /*)
-	   for as_base in sh bash ksh sh5; do
-	     as_candidate_shells="$as_candidate_shells $as_dir/$as_base"
-	   done;;
-       esac
-done
-IFS=$as_save_IFS
-
-
-      for as_shell in $as_candidate_shells $SHELL; do
-	 # Try only shells that exist, to save several forks.
-	 if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
-		{ ("$as_shell") 2> /dev/null <<\_ASEOF
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # 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
-
-
-:
-_ASEOF
-}; then
-  CONFIG_SHELL=$as_shell
-	       as_have_required=yes
-	       if { "$as_shell" 2> /dev/null <<\_ASEOF
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # 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_func_return () {
-  (exit $1)
-}
-as_func_success () {
-  as_func_return 0
-}
-as_func_failure () {
-  as_func_return 1
-}
-as_func_ret_success () {
-  return 0
-}
-as_func_ret_failure () {
-  return 1
-}
-
-exitcode=0
-if as_func_success; then
-  :
-else
-  exitcode=1
-  echo as_func_success failed.
-fi
-
-if as_func_failure; then
-  exitcode=1
-  echo as_func_failure succeeded.
-fi
-
-if as_func_ret_success; then
-  :
-else
-  exitcode=1
-  echo as_func_ret_success failed.
-fi
-
-if as_func_ret_failure; then
-  exitcode=1
-  echo as_func_ret_failure succeeded.
-fi
-
-if ( set x; as_func_ret_success y && test x = "$1" ); then
-  :
-else
-  exitcode=1
-  echo positional parameters were not saved.
-fi
-
-test $exitcode = 0) || { (exit 1); exit 1; }
-
-(
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; }
-
-_ASEOF
-}; then
-  break
-fi
-
-fi
-
-      done
-
-      if test "x$CONFIG_SHELL" != x; then
-  for as_var in BASH_ENV ENV
-        do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-        done
-        export CONFIG_SHELL
-        exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
-fi
-
-
-    if test $as_have_required = no; then
-  echo This script requires a shell more modern than all the
-      echo shells that I found on your system.  Please install a
-      echo modern shell, or manually run the script under such a
-      echo shell if you do have one.
-      { (exit 1); exit 1; }
-fi
-
-
-fi
-
-fi
-
-
-
-(eval "as_func_return () {
-  (exit \$1)
-}
-as_func_success () {
-  as_func_return 0
-}
-as_func_failure () {
-  as_func_return 1
-}
-as_func_ret_success () {
-  return 0
-}
-as_func_ret_failure () {
-  return 1
-}
-
-exitcode=0
-if as_func_success; then
-  :
-else
-  exitcode=1
-  echo as_func_success failed.
-fi
-
-if as_func_failure; then
-  exitcode=1
-  echo as_func_failure succeeded.
-fi
-
-if as_func_ret_success; then
-  :
-else
-  exitcode=1
-  echo as_func_ret_success failed.
-fi
-
-if as_func_ret_failure; then
-  exitcode=1
-  echo as_func_ret_failure succeeded.
-fi
-
-if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
-  :
-else
-  exitcode=1
-  echo positional parameters were not saved.
-fi
-
-test \$exitcode = 0") || {
-  echo No shell found that supports shell functions.
-  echo Please tell autoconf at gnu.org about your system,
-  echo including any error possibly output before this
-  echo message
-}
-
-
-
+	   if ("$as_dir/$as_base" -c '
   as_lineno_1=$LINENO
   as_lineno_2=$LINENO
+  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
   test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+  test "x$as_lineno_3"  = "x$as_lineno_2" ') 2>/dev/null; then
+	     $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
+	     $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
+	     CONFIG_SHELL=$as_dir/$as_base
+	     export CONFIG_SHELL
+	     exec "$CONFIG_SHELL" "$0" ${1+"$@"}
+	   fi;;
+	 esac
+       done
+done
+;;
+  esac
 
   # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
   # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line after each line using $LINENO; the second 'sed'
-  # does the real work.  The second script uses 'N' to pair each
-  # line-number line with the line containing $LINENO, and appends
-  # trailing '-' during substitution so that $LINENO is not a special
-  # case at line end.
+  # line-number line before each line; the second 'sed' does the real
+  # work.  The second script uses 'N' to pair each line-number line
+  # with the numbered line, and appends trailing '-' during
+  # substitution so that $LINENO is not a special case at line end.
   # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # scripts with optimization help from Paolo Bonzini.  Blame Lee
-  # E. McMahon (1931-1989) for sed's syntax.  :-)
-  sed -n '
-    p
-    /[$]LINENO/=
-  ' <$as_myself |
+  # second 'sed' script.  Blame Lee E. McMahon for sed's syntax.  :-)
+  sed '=' <$as_myself |
     sed '
-      s/[$]LINENO.*/&-/
-      t lineno
-      b
-      :lineno
       N
-      :loop
-      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      s,$,-,
+      : loop
+      s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
       t loop
-      s/-\n.*//
+      s,-$,,
+      s,^['$as_cr_digits']*\n,,
     ' >$as_me.lineno &&
-  chmod +x "$as_me.lineno" ||
+  chmod +x $as_me.lineno ||
     { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
    { (exit 1); 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"
+  # original and so on.  Autoconf is especially sensible to this).
+  . ./$as_me.lineno
   # Exit status is that of the last command.
   exit
 }
 
 
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in
--n*)
-  case `echo 'x\c'` in
-  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
-  *)   ECHO_C='\c';;
-  esac;;
-*)
-  ECHO_N='-n';;
+case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
+  *c*,-n*) ECHO_N= ECHO_C='
+' ECHO_T='	' ;;
+  *c*,*  ) ECHO_N=-n ECHO_C= ECHO_T= ;;
+  *)       ECHO_N= ECHO_C='\c' ECHO_T= ;;
 esac
 
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+if expr a : '\(a\)' >/dev/null 2>&1; then
   as_expr=expr
 else
   as_expr=false
 fi
 
 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
-fi
 echo >conf$$.file
 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 ||
+  # We could just check for DJGPP; but this test a) works b) is more generic
+  # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
+  if test -f conf$$.exe; then
+    # Don't use ln at all; we don't have any links
     as_ln_s='cp -p'
+  else
+    as_ln_s='ln -s'
+  fi
 elif ln conf$$.file conf$$ 2>/dev/null; then
   as_ln_s=ln
 else
   as_ln_s='cp -p'
 fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
+rm -f conf$$ conf$$.exe conf$$.file
 
 if mkdir -p . 2>/dev/null; then
   as_mkdir_p=:
@@ -518,28 +222,7 @@
   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
+as_executable_p="test -f"
 
 # 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'"
@@ -548,6 +231,15 @@
 as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
 
 
+# IFS
+# We need space, tab and new line, in precisely that order.
+as_nl='
+'
+IFS=" 	$as_nl"
+
+# CDPATH.
+$as_unset CDPATH
+
 
 
 # Check that we are running under the correct shell.
@@ -703,26 +395,29 @@
 
 tagnames=${tagnames+${tagnames},}F77
 
-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`
 
+exec 6>&1
+
 #
 # Initializations.
 #
 ac_default_prefix=/usr/local
-ac_clean_files=
 ac_config_libobj_dir=.
-LIBOBJS=
 cross_compiling=no
 subdirs=
 MFLAGS=
 MAKEFLAGS=
 SHELL=${CONFIG_SHELL-/bin/sh}
 
+# Maximum number of lines to put in a shell here document.
+# This variable seems obsolete.  It should probably be removed, and
+# only ac_max_sed_lines should be used.
+: ${ac_max_here_lines=38}
+
 # Identity of this package.
 PACKAGE_NAME=
 PACKAGE_TARNAME=
@@ -734,151 +429,43 @@
 # Factoring default headers for most tests.
 ac_includes_default="\
 #include <stdio.h>
-#ifdef HAVE_SYS_TYPES_H
+#if HAVE_SYS_TYPES_H
 # include <sys/types.h>
 #endif
-#ifdef HAVE_SYS_STAT_H
+#if HAVE_SYS_STAT_H
 # include <sys/stat.h>
 #endif
-#ifdef STDC_HEADERS
+#if STDC_HEADERS
 # include <stdlib.h>
 # include <stddef.h>
 #else
-# ifdef HAVE_STDLIB_H
+# if HAVE_STDLIB_H
 #  include <stdlib.h>
 # endif
 #endif
-#ifdef HAVE_STRING_H
-# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
+#if HAVE_STRING_H
+# if !STDC_HEADERS && HAVE_MEMORY_H
 #  include <memory.h>
 # endif
 # include <string.h>
 #endif
-#ifdef HAVE_STRINGS_H
+#if HAVE_STRINGS_H
 # include <strings.h>
 #endif
-#ifdef HAVE_INTTYPES_H
+#if HAVE_INTTYPES_H
 # include <inttypes.h>
+#else
+# if HAVE_STDINT_H
+#  include <stdint.h>
+# endif
 #endif
-#ifdef HAVE_STDINT_H
-# include <stdint.h>
-#endif
-#ifdef HAVE_UNISTD_H
+#if HAVE_UNISTD_H
 # include <unistd.h>
 #endif"
 
-ac_subst_vars='SHELL
-PATH_SEPARATOR
-PACKAGE_NAME
-PACKAGE_TARNAME
-PACKAGE_VERSION
-PACKAGE_STRING
-PACKAGE_BUGREPORT
-exec_prefix
-prefix
-program_transform_name
-bindir
-sbindir
-libexecdir
-datarootdir
-datadir
-sysconfdir
-sharedstatedir
-localstatedir
-includedir
-oldincludedir
-docdir
-infodir
-htmldir
-dvidir
-pdfdir
-psdir
-libdir
-localedir
-mandir
-DEFS
-ECHO_C
-ECHO_N
-ECHO_T
-LIBS
-build_alias
-host_alias
-target_alias
-CC
-CFLAGS
-LDFLAGS
-CPPFLAGS
-ac_ct_CC
-EXEEXT
-OBJEXT
-build
-build_cpu
-build_vendor
-build_os
-host
-host_cpu
-host_vendor
-host_os
-GREP
-EGREP
-LN_S
-ECHO
-AR
-RANLIB
-STRIP
-DLLTOOL
-AS
-OBJDUMP
-CPP
-CXX
-CXXFLAGS
-ac_ct_CXX
-CXXCPP
-F77
-FFLAGS
-ac_ct_F77
-LIBTOOL
-INSTALL_PROGRAM
-INSTALL_SCRIPT
-INSTALL_DATA
-PKG_CONFIG
-JACK_CFLAGS
-JACK_LIBS
-LT_CURRENT
-LT_REVISION
-LT_AGE
-OTHER_OBJS
-PADLL
-SHARED_FLAGS
-THREAD_CFLAGS
-DLL_LIBS
-NASM
-NASMOPT
-subdirs
-ENABLE_CXX_TRUE
-ENABLE_CXX_FALSE
-LIBOBJS
-LTLIBOBJS'
+ac_subdirs_all="$ac_subdirs_all bindings/cpp"
+ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS CC CFLAGS LDFLAGS CPPFLAGS ac_ct_CC EXEEXT OBJEXT build build_cpu build_vendor build_os host host_cpu host_vendor host_os EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB STRIP ac_ct_STRIP DLLTOOL ac_ct_DLLTOOL AS ac_ct_AS OBJDUMP ac_ct_OBJDUMP CPP CXX CXXFLAGS ac_ct_CXX CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA PKG_CONFIG ac_pt_PKG_CONFIG JACK_CFLAGS JACK_LIBS LT_CURRENT LT_REVISION LT_AGE OTHER_OBJS PADLL SHARED_FLAGS THREAD_CFLAGS DLL_LIBS NASM NASMOPT subdirs ENABLE_CXX_TRUE ENABLE_CXX_FALSE LIBOBJS LTLIBOBJS'
 ac_subst_files=''
-      ac_precious_vars='build_alias
-host_alias
-target_alias
-CC
-CFLAGS
-LDFLAGS
-LIBS
-CPPFLAGS
-CPP
-CXX
-CXXFLAGS
-CCC
-CXXCPP
-F77
-FFLAGS
-PKG_CONFIG
-JACK_CFLAGS
-JACK_LIBS'
-ac_subdirs_all='bindings/cpp'
 
 # Initialize some variables set by options.
 ac_init_help=
@@ -905,48 +492,34 @@
 # 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}'
+datadir='${prefix}/share'
 sysconfdir='${prefix}/etc'
 sharedstatedir='${prefix}/com'
 localstatedir='${prefix}/var'
+libdir='${exec_prefix}/lib'
 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'
+infodir='${prefix}/info'
+mandir='${prefix}/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
+    eval "$ac_prev=\$ac_option"
     ac_prev=
     continue
   fi
 
-  case $ac_option in
-  *=*)	ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
-  *)	ac_optarg=yes ;;
-  esac
+  ac_optarg=`expr "x$ac_option" : 'x[^=]*=\(.*\)'`
 
   # Accept the important Cygnus configure options, so we can diagnose typos.
 
-  case $ac_dashdash$ac_option in
-  --)
-    ac_dashdash=yes ;;
+  case $ac_option in
 
   -bindir | --bindir | --bindi | --bind | --bin | --bi)
     ac_prev=bindir ;;
@@ -968,45 +541,33 @@
   --config-cache | -C)
     cache_file=config.cache ;;
 
-  -datadir | --datadir | --datadi | --datad)
+  -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
     ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
+  | --da=*)
     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_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+    expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid feature name: $ac_feature" >&2
    { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
-    eval enable_$ac_feature=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 ;;
+    ac_feature=`echo $ac_feature | sed 's/-/_/g'`
+    eval "enable_$ac_feature=no" ;;
 
   -enable-* | --enable-*)
     ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+    expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid feature name: $ac_feature" >&2
    { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
-    eval enable_$ac_feature=\$ac_optarg ;;
+    ac_feature=`echo $ac_feature | sed 's/-/_/g'`
+    case $ac_option in
+      *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
+      *) ac_optarg=yes ;;
+    esac
+    eval "enable_$ac_feature='$ac_optarg'" ;;
 
   -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
   | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
@@ -1033,12 +594,6 @@
   -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 ;;
@@ -1063,16 +618,13 @@
   | --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)
+  | --localstate | --localstat | --localsta | --localst \
+  | --locals | --local | --loca | --loc | --lo)
     ac_prev=localstatedir ;;
   -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
+  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
     localstatedir=$ac_optarg ;;
 
   -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
@@ -1137,16 +689,6 @@
   | --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 ;;
@@ -1199,20 +741,24 @@
   -with-* | --with-*)
     ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+    expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid package name: $ac_package" >&2
    { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
-    eval with_$ac_package=\$ac_optarg ;;
+    ac_package=`echo $ac_package| sed 's/-/_/g'`
+    case $ac_option in
+      *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
+      *) ac_optarg=yes ;;
+    esac
+    eval "with_$ac_package='$ac_optarg'" ;;
 
   -without-* | --without-*)
     ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+    expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid package name: $ac_package" >&2
    { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
-    eval with_$ac_package=no ;;
+    ac_package=`echo $ac_package | sed 's/-/_/g'`
+    eval "with_$ac_package=no" ;;
 
   --x)
     # Obsolete; use --with-x.
@@ -1243,7 +789,8 @@
     expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
    { (exit 1); exit 1; }; }
-    eval $ac_envvar=\$ac_optarg
+    ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`
+    eval "$ac_envvar='$ac_optarg'"
     export $ac_envvar ;;
 
   *)
@@ -1263,19 +810,27 @@
    { (exit 1); exit 1; }; }
 fi
 
-# Be sure to have absolute directory names.
-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
+# Be sure to have absolute paths.
+for ac_var in exec_prefix prefix
 do
-  eval ac_val=\$$ac_var
+  eval ac_val=$`echo $ac_var`
   case $ac_val in
-    [\\/$]* | ?:[\\/]* )  continue;;
-    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+    [\\/$]* | ?:[\\/]* | NONE | '' ) ;;
+    *)  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+   { (exit 1); exit 1; }; };;
+  esac
+done
+
+# Be sure to have absolute paths.
+for ac_var in bindir sbindir libexecdir datadir sysconfdir sharedstatedir \
+	      localstatedir libdir includedir oldincludedir infodir mandir
+do
+  eval ac_val=$`echo $ac_var`
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* ) ;;
+    *)  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+   { (exit 1); exit 1; }; };;
   esac
-  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
-   { (exit 1); exit 1; }; }
 done
 
 # There might be people who depend on the old broken behavior: `$host'
@@ -1302,76 +857,106 @@
 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 .` ||
-  { echo "$as_me: error: Working directory cannot be determined" >&2
-   { (exit 1); exit 1; }; }
-test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
-  { echo "$as_me: error: pwd does not report name of working directory" >&2
-   { (exit 1); exit 1; }; }
-
-
 # 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 -- "$0" ||
+  # Try the directory containing this script, then its parent.
+  ac_confdir=`(dirname "$0") 2>/dev/null ||
 $as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
 	 X"$0" : 'X\(//\)[^/]' \| \
 	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+	 X"$0" : 'X\(/\)' \| \
+	 .     : '\(.\)' 2>/dev/null ||
 echo X"$0" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
+    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
+  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 .."
-  { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
+if test ! -r $srcdir/$ac_unique_file; then
+  if test "$ac_srcdir_defaulted" = yes; then
+    { echo "$as_me: error: cannot find sources ($ac_unique_file) in $ac_confdir or .." >&2
    { (exit 1); exit 1; }; }
+  else
+    { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
+   { (exit 1); exit 1; }; }
+  fi
 fi
-ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
-ac_abs_confdir=`(
-	cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2
+(cd $srcdir && test -r ./$ac_unique_file) 2>/dev/null ||
+  { echo "$as_me: error: sources are in $srcdir, but \`cd $srcdir' does not work" >&2
    { (exit 1); exit 1; }; }
-	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
+srcdir=`echo "$srcdir" | sed 's%\([^\\/]\)[\\/]*$%\1%'`
+ac_env_build_alias_set=${build_alias+set}
+ac_env_build_alias_value=$build_alias
+ac_cv_env_build_alias_set=${build_alias+set}
+ac_cv_env_build_alias_value=$build_alias
+ac_env_host_alias_set=${host_alias+set}
+ac_env_host_alias_value=$host_alias
+ac_cv_env_host_alias_set=${host_alias+set}
+ac_cv_env_host_alias_value=$host_alias
+ac_env_target_alias_set=${target_alias+set}
+ac_env_target_alias_value=$target_alias
+ac_cv_env_target_alias_set=${target_alias+set}
+ac_cv_env_target_alias_value=$target_alias
+ac_env_CC_set=${CC+set}
+ac_env_CC_value=$CC
+ac_cv_env_CC_set=${CC+set}
+ac_cv_env_CC_value=$CC
+ac_env_CFLAGS_set=${CFLAGS+set}
+ac_env_CFLAGS_value=$CFLAGS
+ac_cv_env_CFLAGS_set=${CFLAGS+set}
+ac_cv_env_CFLAGS_value=$CFLAGS
+ac_env_LDFLAGS_set=${LDFLAGS+set}
+ac_env_LDFLAGS_value=$LDFLAGS
+ac_cv_env_LDFLAGS_set=${LDFLAGS+set}
+ac_cv_env_LDFLAGS_value=$LDFLAGS
+ac_env_CPPFLAGS_set=${CPPFLAGS+set}
+ac_env_CPPFLAGS_value=$CPPFLAGS
+ac_cv_env_CPPFLAGS_set=${CPPFLAGS+set}
+ac_cv_env_CPPFLAGS_value=$CPPFLAGS
+ac_env_CPP_set=${CPP+set}
+ac_env_CPP_value=$CPP
+ac_cv_env_CPP_set=${CPP+set}
+ac_cv_env_CPP_value=$CPP
+ac_env_CXX_set=${CXX+set}
+ac_env_CXX_value=$CXX
+ac_cv_env_CXX_set=${CXX+set}
+ac_cv_env_CXX_value=$CXX
+ac_env_CXXFLAGS_set=${CXXFLAGS+set}
+ac_env_CXXFLAGS_value=$CXXFLAGS
+ac_cv_env_CXXFLAGS_set=${CXXFLAGS+set}
+ac_cv_env_CXXFLAGS_value=$CXXFLAGS
+ac_env_CXXCPP_set=${CXXCPP+set}
+ac_env_CXXCPP_value=$CXXCPP
+ac_cv_env_CXXCPP_set=${CXXCPP+set}
+ac_cv_env_CXXCPP_value=$CXXCPP
+ac_env_F77_set=${F77+set}
+ac_env_F77_value=$F77
+ac_cv_env_F77_set=${F77+set}
+ac_cv_env_F77_value=$F77
+ac_env_FFLAGS_set=${FFLAGS+set}
+ac_env_FFLAGS_value=$FFLAGS
+ac_cv_env_FFLAGS_set=${FFLAGS+set}
+ac_cv_env_FFLAGS_value=$FFLAGS
+ac_env_PKG_CONFIG_set=${PKG_CONFIG+set}
+ac_env_PKG_CONFIG_value=$PKG_CONFIG
+ac_cv_env_PKG_CONFIG_set=${PKG_CONFIG+set}
+ac_cv_env_PKG_CONFIG_value=$PKG_CONFIG
+ac_env_JACK_CFLAGS_set=${JACK_CFLAGS+set}
+ac_env_JACK_CFLAGS_value=$JACK_CFLAGS
+ac_cv_env_JACK_CFLAGS_set=${JACK_CFLAGS+set}
+ac_cv_env_JACK_CFLAGS_value=$JACK_CFLAGS
+ac_env_JACK_LIBS_set=${JACK_LIBS+set}
+ac_env_JACK_LIBS_value=$JACK_LIBS
+ac_cv_env_JACK_LIBS_set=${JACK_LIBS+set}
+ac_cv_env_JACK_LIBS_value=$JACK_LIBS
 
 #
 # Report the --help message.
@@ -1400,6 +985,9 @@
   -n, --no-create         do not create output files
       --srcdir=DIR        find the sources in DIR [configure dir or \`..']
 
+_ACEOF
+
+  cat <<_ACEOF
 Installation directories:
   --prefix=PREFIX         install architecture-independent files in PREFIX
 			  [$ac_default_prefix]
@@ -1417,22 +1005,15 @@
   --bindir=DIR           user executables [EPREFIX/bin]
   --sbindir=DIR          system admin executables [EPREFIX/sbin]
   --libexecdir=DIR       program executables [EPREFIX/libexec]
+  --datadir=DIR          read-only architecture-independent data [PREFIX/share]
   --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]
+  --infodir=DIR          info documentation [PREFIX/info]
+  --mandir=DIR           man documentation [PREFIX/man]
 _ACEOF
 
   cat <<\_ACEOF
@@ -1452,8 +1033,10 @@
   --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
   --enable-debug-output
   --enable-cxx (default=no)
-  --enable-shared[=PKGS]  build shared libraries [default=yes]
-  --enable-static[=PKGS]  build static libraries [default=yes]
+  --enable-shared[=PKGS]
+                          build shared libraries [default=yes]
+  --enable-static[=PKGS]
+                          build static libraries [default=yes]
   --enable-fast-install[=PKGS]
                           optimize for fast installation [default=yes]
   --disable-libtool-lock  avoid locking (might break parallel builds)
@@ -1473,16 +1056,16 @@
   --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
   --with-pic              try to use only PIC/non-PIC objects [default=use
                           both]
-  --with-tags[=TAGS]      include additional configurations [automatic]
+  --with-tags[=TAGS]
+                          include additional configurations [automatic]
 
 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>
+  CPPFLAGS    C/C++ preprocessor flags, e.g. -I<include dir> if you have
+              headers in a nonstandard directory <include dir>
   CPP         C preprocessor
   CXX         C++ compiler command
   CXXFLAGS    C++ compiler flags
@@ -1497,86 +1080,118 @@
 it to find libraries and programs with nonstandard names/locations.
 
 _ACEOF
-ac_status=$?
 fi
 
 if test "$ac_init_help" = "recursive"; then
   # If there are subdirs, report their specific --help.
+  ac_popdir=`pwd`
   for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
-    test -d "$ac_dir" || continue
+    test -d $ac_dir || continue
     ac_builddir=.
 
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
+if test "$ac_dir" != .; then
   ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`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
+  # A "../" for each directory in $ac_dir_suffix.
+  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
+else
+  ac_dir_suffix= ac_top_builddir=
+fi
 
 case $srcdir in
-  .)  # We are building in place.
+  .)  # No --srcdir option.  We are building in place.
     ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
+    if test -z "$ac_top_builddir"; then
+       ac_top_srcdir=.
+    else
+       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
+    fi ;;
+  [\\/]* | ?:[\\/]* )  # Absolute path.
     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 ;;
+    ac_top_srcdir=$srcdir ;;
+  *) # Relative path.
+    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_builddir$srcdir ;;
+esac
+
+# Do not use `cd foo && pwd` to compute absolute paths, because
+# the directories may not exist.
+case `pwd` in
+.) ac_abs_builddir="$ac_dir";;
+*)
+  case "$ac_dir" in
+  .) ac_abs_builddir=`pwd`;;
+  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
+  *) ac_abs_builddir=`pwd`/"$ac_dir";;
+  esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_builddir=${ac_top_builddir}.;;
+*)
+  case ${ac_top_builddir}. in
+  .) ac_abs_top_builddir=$ac_abs_builddir;;
+  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
+  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
+  esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_srcdir=$ac_srcdir;;
+*)
+  case $ac_srcdir in
+  .) ac_abs_srcdir=$ac_abs_builddir;;
+  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
+  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
+  esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_srcdir=$ac_top_srcdir;;
+*)
+  case $ac_top_srcdir in
+  .) ac_abs_top_srcdir=$ac_abs_builddir;;
+  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
+  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
+  esac;;
 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
+    cd $ac_dir
+    # Check for guested configure; otherwise get Cygnus style 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
+    elif test -f $ac_srcdir/configure.ac ||
+	   test -f $ac_srcdir/configure.in; then
+      echo
+      $ac_configure --help
     else
       echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
-    fi || ac_status=$?
-    cd "$ac_pwd" || { ac_status=$?; break; }
+    fi
+    cd $ac_popdir
   done
 fi
 
-test -n "$ac_init_help" && exit $ac_status
+test -n "$ac_init_help" && exit 0
 if $ac_init_version; then
   cat <<\_ACEOF
-configure
-generated by GNU Autoconf 2.61
 
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
-2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+Copyright (C) 2003 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
+  exit 0
 fi
-cat >config.log <<_ACEOF
+exec 5>config.log
+cat >&5 <<_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.61.  Invocation command line was
+generated by GNU Autoconf 2.59.  Invocation command line was
 
   $ $0 $@
 
 _ACEOF
-exec 5>>config.log
 {
 cat <<_ASUNAME
 ## --------- ##
@@ -1595,7 +1210,7 @@
 /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`
+hostinfo               = `(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`
@@ -1609,7 +1224,6 @@
   test -z "$as_dir" && as_dir=.
   echo "PATH: $as_dir"
 done
-IFS=$as_save_IFS
 
 } >&5
 
@@ -1631,6 +1245,7 @@
 ac_configure_args=
 ac_configure_args0=
 ac_configure_args1=
+ac_sep=
 ac_must_keep_next=false
 for ac_pass in 1 2
 do
@@ -1641,7 +1256,7 @@
     -q | -quiet | --quiet | --quie | --qui | --qu | --q \
     | -silent | --silent | --silen | --sile | --sil)
       continue ;;
-    *\'*)
+    *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
       ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
     esac
     case $ac_pass in
@@ -1663,7 +1278,9 @@
 	  -* ) ac_must_keep_next=true ;;
 	esac
       fi
-      ac_configure_args="$ac_configure_args '$ac_arg'"
+      ac_configure_args="$ac_configure_args$ac_sep'$ac_arg'"
+      # Get rid of the leading space.
+      ac_sep=" "
       ;;
     esac
   done
@@ -1674,8 +1291,8 @@
 # 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.
+# WARNING: Be sure not to use single quotes in there, as some shells,
+# such as our DU 5.0 friend, will then `close' the trap.
 trap 'exit_status=$?
   # Save into config.log some information that might help in debugging.
   {
@@ -1688,34 +1305,20 @@
 _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_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
-echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      *) $as_unset $ac_var ;;
-      esac ;;
-    esac
-  done
+{
   (set) 2>&1 |
-    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
+    case `(ac_space='"'"' '"'"'; set | grep ac_space) 2>&1` in
+    *ac_space=\ *)
       sed -n \
-	"s/'\''/'\''\\\\'\'''\''/g;
-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
-      ;; #(
+	"s/'"'"'/'"'"'\\\\'"'"''"'"'/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='"'"'\\2'"'"'/p"
+      ;;
     *)
-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      sed -n \
+	"s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
       ;;
-    esac |
-    sort
-)
+    esac;
+}
     echo
 
     cat <<\_ASBOX
@@ -1726,28 +1329,22 @@
     echo
     for ac_var in $ac_subst_vars
     do
-      eval ac_val=\$$ac_var
-      case $ac_val in
-      *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-      esac
-      echo "$ac_var='\''$ac_val'\''"
+      eval ac_val=$`echo $ac_var`
+      echo "$ac_var='"'"'$ac_val'"'"'"
     done | sort
     echo
 
     if test -n "$ac_subst_files"; then
       cat <<\_ASBOX
-## ------------------- ##
-## File substitutions. ##
-## ------------------- ##
+## ------------- ##
+## Output files. ##
+## ------------- ##
 _ASBOX
       echo
       for ac_var in $ac_subst_files
       do
-	eval ac_val=\$$ac_var
-	case $ac_val in
-	*\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-	esac
-	echo "$ac_var='\''$ac_val'\''"
+	eval ac_val=$`echo $ac_var`
+	echo "$ac_var='"'"'$ac_val'"'"'"
       done | sort
       echo
     fi
@@ -1759,24 +1356,26 @@
 ## ----------- ##
 _ASBOX
       echo
-      cat confdefs.h
+      sed "/^$/d" confdefs.h | sort
       echo
     fi
     test "$ac_signal" != 0 &&
       echo "$as_me: caught signal $ac_signal"
     echo "$as_me: exit $exit_status"
   } >&5
-  rm -f core *.core core.conftest.* &&
-    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+  rm -f core *.core &&
+  rm -rf conftest* confdefs* conf$$* $ac_clean_files &&
     exit $exit_status
-' 0
+     ' 0
 for ac_signal in 1 2 13 15; do
   trap 'ac_signal='$ac_signal'; { (exit 1); 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
+rm -rf conftest* confdefs.h
+# AIX cpp loses on an empty file, so make sure it contains at least a newline.
+echo >confdefs.h
 
 # Predefined preprocessor variables.
 
@@ -1807,17 +1406,14 @@
 
 # Let the site file select an alternate cache file if it wants to.
 # Prefer explicitly selected file to automatically selected ones.
-if test -n "$CONFIG_SITE"; then
-  set x "$CONFIG_SITE"
-elif test "x$prefix" != xNONE; then
-  set x "$prefix/share/config.site" "$prefix/etc/config.site"
-else
-  set x "$ac_default_prefix/share/config.site" \
-	"$ac_default_prefix/etc/config.site"
+if test -z "$CONFIG_SITE"; then
+  if test "x$prefix" != xNONE; then
+    CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
+  else
+    CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
+  fi
 fi
-shift
-for ac_site_file
-do
+for ac_site_file in $CONFIG_SITE; do
   if test -r "$ac_site_file"; then
     { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
 echo "$as_me: loading site script $ac_site_file" >&6;}
@@ -1833,8 +1429,8 @@
     { echo "$as_me:$LINENO: loading cache $cache_file" >&5
 echo "$as_me: loading cache $cache_file" >&6;}
     case $cache_file in
-      [\\/]* | ?:[\\/]* ) . "$cache_file";;
-      *)                      . "./$cache_file";;
+      [\\/]* | ?:[\\/]* ) . $cache_file;;
+      *)                      . ./$cache_file;;
     esac
   fi
 else
@@ -1846,11 +1442,12 @@
 # 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
+for ac_var in `(set) 2>&1 |
+	       sed -n 's/^ac_env_\([a-zA-Z_0-9]*\)_set=.*/\1/p'`; 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
+  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,)
       { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
@@ -1875,7 +1472,8 @@
   # Pass precious variables to config.status.
   if test "$ac_new_set" = set; then
     case $ac_new_val in
-    *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *" "*|*"	"*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
+      ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
     *) ac_arg=$ac_var=$ac_new_val ;;
     esac
     case " $ac_configure_args " in
@@ -1892,6 +1490,11 @@
    { (exit 1); exit 1; }; }
 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
 
 
 
@@ -1908,97 +1511,94 @@
 
 
 
-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
 
 
 
 
 
-# Check whether --with-alsa was given.
+
+# Check whether --with-alsa or --without-alsa was given.
 if test "${with_alsa+set}" = set; then
-  withval=$with_alsa; with_alsa=$withval
+  withval="$with_alsa"
+  with_alsa=$withval
 else
   with_alsa="yes"
-fi
+fi;
 
 
-
-# Check whether --with-jack was given.
+# Check whether --with-jack or --without-jack was given.
 if test "${with_jack+set}" = set; then
-  withval=$with_jack; with_jack=$withval
+  withval="$with_jack"
+  with_jack=$withval
 else
   with_jack="yes"
-fi
+fi;
 
 
-
-# Check whether --with-oss was given.
+# Check whether --with-oss or --without-oss was given.
 if test "${with_oss+set}" = set; then
-  withval=$with_oss; with_oss=$withval
+  withval="$with_oss"
+  with_oss=$withval
 else
   with_oss="yes"
-fi
+fi;
 
 
-
-# Check whether --with-asihpi was given.
+# Check whether --with-asihpi or --without-asihpi was given.
 if test "${with_asihpi+set}" = set; then
-  withval=$with_asihpi; with_asihpi=$withval
+  withval="$with_asihpi"
+  with_asihpi=$withval
 else
   with_asihpi="yes"
-fi
+fi;
 
 
-
-# Check whether --with-host_os was given.
+# Check whether --with-host_os or --without-host_os was given.
 if test "${with_host_os+set}" = set; then
-  withval=$with_host_os; host_os=$withval
-fi
+  withval="$with_host_os"
+  host_os=$withval
+fi;
 
 
-
-# Check whether --with-winapi was given.
+# Check whether --with-winapi or --without-winapi was given.
 if test "${with_winapi+set}" = set; then
-  withval=$with_winapi; with_winapi=$withval
+  withval="$with_winapi"
+  with_winapi=$withval
 else
   with_winapi="wmme"
-fi
+fi;
 
 
-
-# Check whether --with-macapi was given.
+# Check whether --with-macapi or --without-macapi was given.
 if test "${with_macapi+set}" = set; then
-  withval=$with_macapi; with_macapi=$withval
+  withval="$with_macapi"
+  with_macapi=$withval
 else
   with_macapi="core"
-fi
+fi;
 
 
-
-# Check whether --with-asiodir was given.
+# Check whether --with-asiodir or --without-asiodir was given.
 if test "${with_asiodir+set}" = set; then
-  withval=$with_asiodir; with_asiodir=$withval
+  withval="$with_asiodir"
+  with_asiodir=$withval
 else
   with_asiodir="/usr/local/asiosdk2"
-fi
+fi;
 
 
-
-# Check whether --with-dxdir was given.
+# Check whether --with-dxdir or --without-dxdir was given.
 if test "${with_dxdir+set}" = set; then
-  withval=$with_dxdir; with_dxdir=$withval
+  withval="$with_dxdir"
+  with_dxdir=$withval
 else
   with_dxdir="/usr/local/dx7sdk"
-fi
+fi;
 
-
-# Check whether --enable-debug-output was given.
+# Check whether --enable-debug-output or --disable-debug-output was given.
 if test "${enable_debug_output+set}" = set; then
-  enableval=$enable_debug_output; if test x$enableval != xno ; then
+  enableval="$enable_debug_output"
+  if test x$enableval != xno ; then
 
 cat >>confdefs.h <<\_ACEOF
 #define PA_ENABLE_DEBUG_OUTPUT
@@ -2006,16 +1606,15 @@
 
           fi
 
-fi
-
+fi;
 
-# Check whether --enable-cxx was given.
+# Check whether --enable-cxx or --disable-cxx was given.
 if test "${enable_cxx+set}" = set; then
-  enableval=$enable_cxx; enable_cxx=$enableval
+  enableval="$enable_cxx"
+  enable_cxx=$enableval
 else
   enable_cxx="no"
-fi
-
+fi;
 
 
 ac_ext=c
@@ -2026,8 +1625,8 @@
 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
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2040,34 +1639,32 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="${ac_tool_prefix}gcc"
     echo "$as_me:$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
-  { echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6; }
+  echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}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
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2080,51 +1677,36 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_CC="gcc"
     echo "$as_me:$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
-  { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-  if test "x$ac_ct_CC" = x; then
-    CC=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    CC=$ac_ct_CC
-  fi
+  CC=$ac_ct_CC
 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.
+  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
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2137,34 +1719,74 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="${ac_tool_prefix}cc"
     echo "$as_me:$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
-  { echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6; }
+  echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="cc"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
   fi
+done
+done
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6
+else
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+  CC=$ac_ct_CC
+else
+  CC="$ac_cv_prog_CC"
+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
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2178,7 +1800,7 @@
   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 $as_executable_p "$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
@@ -2189,7 +1811,6 @@
   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.
@@ -2207,23 +1828,22 @@
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  { echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6; }
+  echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
 fi
 if test -z "$CC"; then
   if test -n "$ac_tool_prefix"; then
-  for ac_prog in cl.exe
+  for ac_prog in cl
   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
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2236,38 +1856,36 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
     echo "$as_me:$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
-  { echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6; }
+  echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
     test -n "$CC" && break
   done
 fi
 if test -z "$CC"; then
   ac_ct_CC=$CC
-  for ac_prog in cl.exe
+  for ac_prog in cl
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
 set dummy $ac_prog; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2280,45 +1898,29 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_CC="$ac_prog"
     echo "$as_me:$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
-  { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}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:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    CC=$ac_ct_CC
-  fi
+  CC=$ac_ct_CC
 fi
 
 fi
@@ -2331,35 +1933,21 @@
    { (exit 1); exit 1; }; }
 
 # Provide some information about the compiler.
-echo "$as_me:$LINENO: checking for C compiler version" >&5
+echo "$as_me:$LINENO:" \
+     "checking for C compiler version" >&5
 ac_compiler=`set X $ac_compile; echo $2`
-{ (ac_try="$ac_compiler --version >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler --version >&5") 2>&5
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
+  (eval $ac_compiler --version </dev/null >&5) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (ac_try="$ac_compiler -v >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -v >&5") 2>&5
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
+  (eval $ac_compiler -v </dev/null >&5) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (ac_try="$ac_compiler -V >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -V >&5") 2>&5
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
+  (eval $ac_compiler -V </dev/null >&5) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
@@ -2384,77 +1972,47 @@
 # 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.
-{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
-echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
+echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6
 ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-#
-# List of possible output files, starting from the most likely.
-# The algorithm is not robust to junk in `.', hence go to wildcards (a.*)
-# only as a last resort.  b.out is created by i960 compilers.
-ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out'
-#
-# The IRIX 6 linker writes into existing files which may not be
-# executable, retaining their permissions.  Remove them first so a
-# subsequent execution test works.
-ac_rmfiles=
-for ac_file in $ac_files
-do
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link_default") 2>&5
+if { (eval echo "$as_me:$LINENO: \"$ac_link_default\"") >&5
+  (eval $ac_link_default) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; 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 ''
+  # Find the output, starting from the most likely.  This scheme is
+# not robust to junk in `.', hence go to wildcards (a.*) only as a last
+# resort.
+
+# Be careful to initialize this variable, since it used to be cached.
+# Otherwise an old cache value of `no' led to `EXEEXT = no' in a Makefile.
+ac_cv_exeext=
+# b.out is created by i960 compilers.
+for ac_file in a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out
 do
   test -f "$ac_file" || continue
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj )
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj )
+	;;
+    conftest.$ac_ext )
+	# This is the source file.
 	;;
     [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.
+	ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	# FIXME: I believe we export ac_cv_exeext for Libtool,
+	# but it would be cool to find out if it's true.  Does anybody
+	# maintain Libtool? --akim.
+	export ac_cv_exeext
 	break;;
     * )
 	break;;
   esac
 done
-test "$ac_cv_exeext" = no && ac_cv_exeext=
-
 else
-  ac_file=''
-fi
-
-{ echo "$as_me:$LINENO: result: $ac_file" >&5
-echo "${ECHO_T}$ac_file" >&6; }
-if test -z "$ac_file"; then
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
@@ -2466,21 +2024,19 @@
 fi
 
 ac_exeext=$ac_cv_exeext
+echo "$as_me:$LINENO: result: $ac_file" >&5
+echo "${ECHO_T}$ac_file" >&6
 
-# Check that the compiler produces executables we can run.  If not, either
+# Check the compiler produces executables we can run.  If not, either
 # the compiler is broken, or we cross compile.
-{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5
-echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether the C compiler works" >&5
+echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6
 # FIXME: These cross compiler hacks should be removed for Autoconf 3.0
 # 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; }; then
@@ -2499,27 +2055,22 @@
     fi
   fi
 fi
-{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
 
 rm -f a.out a.exe conftest$ac_cv_exeext b.out
 ac_clean_files=$ac_clean_files_save
-# Check that the compiler produces executables we can run.  If not, either
+# Check the compiler produces executables we can run.  If not, either
 # the compiler is broken, or we cross compile.
-{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
-echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; }
-{ echo "$as_me:$LINENO: result: $cross_compiling" >&5
-echo "${ECHO_T}$cross_compiling" >&6; }
-
-{ echo "$as_me:$LINENO: checking for suffix of executables" >&5
-echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; }
-if { (ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
+echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
+echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6
+echo "$as_me:$LINENO: result: $cross_compiling" >&5
+echo "${ECHO_T}$cross_compiling" >&6
+
+echo "$as_me:$LINENO: checking for suffix of executables" >&5
+echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; then
@@ -2530,8 +2081,9 @@
 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 | *.o | *.obj ) ;;
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) ;;
     *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	  export ac_cv_exeext
 	  break;;
     * ) break;;
   esac
@@ -2545,14 +2097,14 @@
 fi
 
 rm -f conftest$ac_cv_exeext
-{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
-echo "${ECHO_T}$ac_cv_exeext" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
+echo "${ECHO_T}$ac_cv_exeext" >&6
 
 rm -f conftest.$ac_ext
 EXEEXT=$ac_cv_exeext
 ac_exeext=$EXEEXT
-{ echo "$as_me:$LINENO: checking for suffix of object files" >&5
-echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for suffix of object files" >&5
+echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6
 if test "${ac_cv_objext+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2572,20 +2124,14 @@
 }
 _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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>&5
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; then
-  for ac_file in conftest.o conftest.obj conftest.*; do
-  test -f "$ac_file" || continue;
+  for ac_file in `(ls conftest.o conftest.obj; ls conftest.*) 2>/dev/null`; do
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;;
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg ) ;;
     *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
        break;;
   esac
@@ -2603,12 +2149,12 @@
 
 rm -f conftest.$ac_cv_objext conftest.$ac_ext
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
-echo "${ECHO_T}$ac_cv_objext" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
+echo "${ECHO_T}$ac_cv_objext" >&6
 OBJEXT=$ac_cv_objext
 ac_objext=$OBJEXT
-{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
-echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6
 if test "${ac_cv_c_compiler_gnu+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2631,49 +2177,50 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_compiler_gnu=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_compiler_gnu=no
+ac_compiler_gnu=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 ac_cv_c_compiler_gnu=$ac_compiler_gnu
 
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6
 GCC=`test $ac_compiler_gnu = yes && echo yes`
 ac_test_CFLAGS=${CFLAGS+set}
 ac_save_CFLAGS=$CFLAGS
-{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
-echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; }
+CFLAGS="-g"
+echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
+echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6
 if test "${ac_cv_prog_cc_g+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&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 >conftest.$ac_ext <<_ACEOF
+  cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
@@ -2689,118 +2236,38 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_prog_cc_g=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	CFLAGS=""
-      cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
   ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_c_werror_flag=$ac_save_c_werror_flag
-	 CFLAGS="-g"
-	 cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
   ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); }; }; then
   ac_cv_prog_cc_g=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
-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_cv_prog_cc_g=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-   ac_c_werror_flag=$ac_save_c_werror_flag
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
+echo "${ECHO_T}$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
@@ -2816,12 +2283,12 @@
     CFLAGS=
   fi
 fi
-{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5
-echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; }
-if test "${ac_cv_prog_cc_c89+set}" = set; then
+echo "$as_me:$LINENO: checking for $CC option to accept ANSI C" >&5
+echo $ECHO_N "checking for $CC option to accept ANSI C... $ECHO_C" >&6
+if test "${ac_cv_prog_cc_stdc+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_cv_prog_cc_c89=no
+  ac_cv_prog_cc_stdc=no
 ac_save_CC=$CC
 cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -2855,17 +2322,12 @@
 /* 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
+   as 'x'.  The following induces an error, until -std1 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.  */
+   that's true only with -std1.  */
 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);};
@@ -2880,92 +2342,241 @@
   return 0;
 }
 _ACEOF
-for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
-	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+# Don't try gcc -ansi; that turns off useful extensions and
+# breaks some systems' header files.
+# AIX			-qlanglvl=ansi
+# Ultrix and OSF/1	-std1
+# HP-UX 10.20 and later	-Ae
+# HP-UX older versions	-Aa -D_HPUX_SOURCE
+# SVR4			-Xc -D__EXTENSIONS__
+for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
 do
   CC="$ac_save_CC $ac_arg"
   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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_prog_cc_c89=$ac_arg
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_prog_cc_stdc=$ac_arg
+break
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext
-  test "x$ac_cv_prog_cc_c89" != "xno" && break
+rm -f conftest.err conftest.$ac_objext
 done
-rm -f conftest.$ac_ext
+rm -f conftest.$ac_ext conftest.$ac_objext
 CC=$ac_save_CC
 
 fi
-# AC_CACHE_VAL
-case "x$ac_cv_prog_cc_c89" in
-  x)
-    { echo "$as_me:$LINENO: result: none needed" >&5
-echo "${ECHO_T}none needed" >&6; } ;;
-  xno)
-    { echo "$as_me:$LINENO: result: unsupported" >&5
-echo "${ECHO_T}unsupported" >&6; } ;;
+
+case "x$ac_cv_prog_cc_stdc" in
+  x|xno)
+    echo "$as_me:$LINENO: result: none needed" >&5
+echo "${ECHO_T}none needed" >&6 ;;
   *)
-    CC="$CC $ac_cv_prog_cc_c89"
-    { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;;
+    echo "$as_me:$LINENO: result: $ac_cv_prog_cc_stdc" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_stdc" >&6
+    CC="$CC $ac_cv_prog_cc_stdc" ;;
 esac
 
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-
-# Check whether --enable-shared was given.
-if test "${enable_shared+set}" = set; then
-  enableval=$enable_shared; p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_shared=yes ;;
-    no) enable_shared=no ;;
-    *)
-      enable_shared=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_shared=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac
+# Some people use a C++ compiler to compile C.  Since we use `exit',
+# in C++ we need to declare it.  In case someone uses the same compiler
+# for both compiling C and C++ we need to have the C++ compiler decide
+# the declaration of exit, since it's the most demanding environment.
+cat >conftest.$ac_ext <<_ACEOF
+#ifndef __cplusplus
+  choke me
+#endif
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  for ac_declaration in \
+   '' \
+   'extern "C" void std::exit (int) throw (); using std::exit;' \
+   'extern "C" void std::exit (int); using std::exit;' \
+   'extern "C" void exit (int) throw ();' \
+   'extern "C" void exit (int);' \
+   'void exit (int);'
+do
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_declaration
+#include <stdlib.h>
+int
+main ()
+{
+exit (42);
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  :
 else
-  enable_shared=yes
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+continue
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_declaration
+int
+main ()
+{
+exit (42);
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  break
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+done
+rm -f conftest*
+if test -n "$ac_declaration"; then
+  echo '#ifdef __cplusplus' >>confdefs.h
+  echo $ac_declaration      >>confdefs.h
+  echo '#endif'             >>confdefs.h
+fi
+
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
 fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+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
+
 
 
-# Check whether --enable-static was given.
+# Check whether --enable-shared or --disable-shared was given.
+if test "${enable_shared+set}" = set; then
+  enableval="$enable_shared"
+  p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_shared=yes ;;
+    no) enable_shared=no ;;
+    *)
+      enable_shared=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_shared=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac
+else
+  enable_shared=yes
+fi;
+
+# Check whether --enable-static or --disable-static was given.
 if test "${enable_static+set}" = set; then
-  enableval=$enable_static; p=${PACKAGE-default}
+  enableval="$enable_static"
+  p=${PACKAGE-default}
     case $enableval in
     yes) enable_static=yes ;;
     no) enable_static=no ;;
@@ -2984,12 +2595,12 @@
     esac
 else
   enable_static=yes
-fi
-
+fi;
 
-# Check whether --enable-fast-install was given.
+# Check whether --enable-fast-install or --disable-fast-install was given.
 if test "${enable_fast_install+set}" = set; then
-  enableval=$enable_fast_install; p=${PACKAGE-default}
+  enableval="$enable_fast_install"
+  p=${PACKAGE-default}
     case $enableval in
     yes) enable_fast_install=yes ;;
     no) enable_fast_install=no ;;
@@ -3008,125 +2619,89 @@
     esac
 else
   enable_fast_install=yes
-fi
-
+fi;
 
 ac_aux_dir=
-for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do
-  if test -f "$ac_dir/install-sh"; then
+for ac_dir in $srcdir $srcdir/.. $srcdir/../..; do
+  if test -f $ac_dir/install-sh; then
     ac_aux_dir=$ac_dir
     ac_install_sh="$ac_aux_dir/install-sh -c"
     break
-  elif test -f "$ac_dir/install.sh"; then
+  elif test -f $ac_dir/install.sh; then
     ac_aux_dir=$ac_dir
     ac_install_sh="$ac_aux_dir/install.sh -c"
     break
-  elif test -f "$ac_dir/shtool"; then
+  elif test -f $ac_dir/shtool; then
     ac_aux_dir=$ac_dir
     ac_install_sh="$ac_aux_dir/shtool install -c"
     break
   fi
 done
 if test -z "$ac_aux_dir"; then
-  { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5
-echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;}
+  { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." >&5
+echo "$as_me: error: cannot find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." >&2;}
    { (exit 1); exit 1; }; }
 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.
-
+ac_config_guess="$SHELL $ac_aux_dir/config.guess"
+ac_config_sub="$SHELL $ac_aux_dir/config.sub"
+ac_configure="$SHELL $ac_aux_dir/configure" # This should be Cygnus configure.
 
 # Make sure we can run config.sub.
-$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
-  { { echo "$as_me:$LINENO: error: cannot run $SHELL $ac_aux_dir/config.sub" >&5
-echo "$as_me: error: cannot run $SHELL $ac_aux_dir/config.sub" >&2;}
+$ac_config_sub sun4 >/dev/null 2>&1 ||
+  { { echo "$as_me:$LINENO: error: cannot run $ac_config_sub" >&5
+echo "$as_me: error: cannot run $ac_config_sub" >&2;}
    { (exit 1); exit 1; }; }
 
-{ echo "$as_me:$LINENO: checking build system type" >&5
-echo $ECHO_N "checking build system type... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking build system type" >&5
+echo $ECHO_N "checking build system type... $ECHO_C" >&6
 if test "${ac_cv_build+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_build_alias=$build_alias
-test "x$ac_build_alias" = x &&
-  ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`
-test "x$ac_build_alias" = x &&
+  ac_cv_build_alias=$build_alias
+test -z "$ac_cv_build_alias" &&
+  ac_cv_build_alias=`$ac_config_guess`
+test -z "$ac_cv_build_alias" &&
   { { echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5
 echo "$as_me: error: cannot guess build type; you must specify one" >&2;}
    { (exit 1); exit 1; }; }
-ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||
-  { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&5
-echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&2;}
+ac_cv_build=`$ac_config_sub $ac_cv_build_alias` ||
+  { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_build_alias failed" >&5
+echo "$as_me: error: $ac_config_sub $ac_cv_build_alias failed" >&2;}
    { (exit 1); exit 1; }; }
 
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_build" >&5
-echo "${ECHO_T}$ac_cv_build" >&6; }
-case $ac_cv_build in
-*-*-*) ;;
-*) { { echo "$as_me:$LINENO: error: invalid value of canonical build" >&5
-echo "$as_me: error: invalid value of canonical build" >&2;}
-   { (exit 1); exit 1; }; };;
-esac
+echo "$as_me:$LINENO: result: $ac_cv_build" >&5
+echo "${ECHO_T}$ac_cv_build" >&6
 build=$ac_cv_build
-ac_save_IFS=$IFS; IFS='-'
-set x $ac_cv_build
-shift
-build_cpu=$1
-build_vendor=$2
-shift; shift
-# Remember, the first character of IFS is used to create $*,
-# except with old shells:
-build_os=$*
-IFS=$ac_save_IFS
-case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac
+build_cpu=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
+build_vendor=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
+build_os=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
 
 
-{ echo "$as_me:$LINENO: checking host system type" >&5
-echo $ECHO_N "checking host system type... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking host system type" >&5
+echo $ECHO_N "checking host system type... $ECHO_C" >&6
 if test "${ac_cv_host+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  if test "x$host_alias" = x; then
-  ac_cv_host=$ac_cv_build
-else
-  ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
-    { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&5
-echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&2;}
+  ac_cv_host_alias=$host_alias
+test -z "$ac_cv_host_alias" &&
+  ac_cv_host_alias=$ac_cv_build_alias
+ac_cv_host=`$ac_config_sub $ac_cv_host_alias` ||
+  { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_host_alias failed" >&5
+echo "$as_me: error: $ac_config_sub $ac_cv_host_alias failed" >&2;}
    { (exit 1); exit 1; }; }
-fi
 
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_host" >&5
-echo "${ECHO_T}$ac_cv_host" >&6; }
-case $ac_cv_host in
-*-*-*) ;;
-*) { { echo "$as_me:$LINENO: error: invalid value of canonical host" >&5
-echo "$as_me: error: invalid value of canonical host" >&2;}
-   { (exit 1); exit 1; }; };;
-esac
+echo "$as_me:$LINENO: result: $ac_cv_host" >&5
+echo "${ECHO_T}$ac_cv_host" >&6
 host=$ac_cv_host
-ac_save_IFS=$IFS; IFS='-'
-set x $ac_cv_host
-shift
-host_cpu=$1
-host_vendor=$2
-shift; shift
-# Remember, the first character of IFS is used to create $*,
-# except with old shells:
-host_os=$*
-IFS=$ac_save_IFS
-case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac
+host_cpu=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
+host_vendor=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
+host_os=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
 
 
-{ echo "$as_me:$LINENO: checking for a sed that does not truncate output" >&5
-echo $ECHO_N "checking for a sed that does not truncate output... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for a sed that does not truncate output" >&5
+echo $ECHO_N "checking for a sed that does not truncate output... $ECHO_C" >&6
 if test "${lt_cv_path_SED+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3179,184 +2754,37 @@
 fi
 
 SED=$lt_cv_path_SED
-{ echo "$as_me:$LINENO: result: $SED" >&5
-echo "${ECHO_T}$SED" >&6; }
-
-{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5
-echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; }
-if test "${ac_cv_path_GREP+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  # Extract the first word of "grep ggrep" to use in msg output
-if test -z "$GREP"; then
-set dummy grep ggrep; ac_prog_name=$2
-if test "${ac_cv_path_GREP+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  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
-  echo $ECHO_N "0123456789$ECHO_C" >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    echo 'GREP' >> "conftest.nl"
-    "$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
-    ac_count=`expr $ac_count + 1`
-    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
-
-
-fi
-
-GREP="$ac_cv_path_GREP"
-if test -z "$GREP"; then
-  { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5
-echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-else
-  ac_cv_path_GREP=$GREP
-fi
-
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5
-echo "${ECHO_T}$ac_cv_path_GREP" >&6; }
- GREP="$ac_cv_path_GREP"
-
+echo "$as_me:$LINENO: result: $SED" >&5
+echo "${ECHO_T}$SED" >&6
 
-{ echo "$as_me:$LINENO: checking for egrep" >&5
-echo $ECHO_N "checking for egrep... $ECHO_C" >&6; }
-if test "${ac_cv_path_EGREP+set}" = set; then
+echo "$as_me:$LINENO: checking for egrep" >&5
+echo $ECHO_N "checking for egrep... $ECHO_C" >&6
+if test "${ac_cv_prog_egrep+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
-   then ac_cv_path_EGREP="$GREP -E"
-   else
-     # Extract the first word of "egrep" to use in msg output
-if test -z "$EGREP"; then
-set dummy egrep; ac_prog_name=$2
-if test "${ac_cv_path_EGREP+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  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
-  echo $ECHO_N "0123456789$ECHO_C" >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    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
-    ac_count=`expr $ac_count + 1`
-    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
+  if echo a | (grep -E '(a|b)') >/dev/null 2>&1
+    then ac_cv_prog_egrep='grep -E'
+    else ac_cv_prog_egrep='egrep'
     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
-
-
-fi
-
-EGREP="$ac_cv_path_EGREP"
-if test -z "$EGREP"; then
-  { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5
-echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-else
-  ac_cv_path_EGREP=$EGREP
-fi
-
-
-   fi
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5
-echo "${ECHO_T}$ac_cv_path_EGREP" >&6; }
- EGREP="$ac_cv_path_EGREP"
+echo "$as_me:$LINENO: result: $ac_cv_prog_egrep" >&5
+echo "${ECHO_T}$ac_cv_prog_egrep" >&6
+ EGREP=$ac_cv_prog_egrep
 
 
 
-# Check whether --with-gnu-ld was given.
+# Check whether --with-gnu-ld or --without-gnu-ld was given.
 if test "${with_gnu_ld+set}" = set; then
-  withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes
+  withval="$with_gnu_ld"
+  test "$withval" = no || with_gnu_ld=yes
 else
   with_gnu_ld=no
-fi
-
+fi;
 ac_prog=ld
 if test "$GCC" = yes; then
   # Check if gcc -print-prog-name=ld gives a path.
-  { echo "$as_me:$LINENO: checking for ld used by $CC" >&5
-echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for ld used by $CC" >&5
+echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6
   case $host in
   *-*-mingw*)
     # gcc leaves a trailing carriage return which upsets mingw
@@ -3385,11 +2813,11 @@
     ;;
   esac
 elif test "$with_gnu_ld" = yes; then
-  { echo "$as_me:$LINENO: checking for GNU ld" >&5
-echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for GNU ld" >&5
+echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6
 else
-  { echo "$as_me:$LINENO: checking for non-GNU ld" >&5
-echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for non-GNU ld" >&5
+echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6
 fi
 if test "${lt_cv_path_LD+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
@@ -3422,17 +2850,17 @@
 
 LD="$lt_cv_path_LD"
 if test -n "$LD"; then
-  { echo "$as_me:$LINENO: result: $LD" >&5
-echo "${ECHO_T}$LD" >&6; }
+  echo "$as_me:$LINENO: result: $LD" >&5
+echo "${ECHO_T}$LD" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found in \$PATH" >&5
 echo "$as_me: error: no acceptable ld found in \$PATH" >&2;}
    { (exit 1); exit 1; }; }
-{ echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5
-echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5
+echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6
 if test "${lt_cv_prog_gnu_ld+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3446,20 +2874,20 @@
   ;;
 esac
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_gnu_ld" >&5
-echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_prog_gnu_ld" >&5
+echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6
 with_gnu_ld=$lt_cv_prog_gnu_ld
 
 
-{ echo "$as_me:$LINENO: checking for $LD option to reload object files" >&5
-echo $ECHO_N "checking for $LD option to reload object files... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $LD option to reload object files" >&5
+echo $ECHO_N "checking for $LD option to reload object files... $ECHO_C" >&6
 if test "${lt_cv_ld_reload_flag+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   lt_cv_ld_reload_flag='-r'
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_ld_reload_flag" >&5
-echo "${ECHO_T}$lt_cv_ld_reload_flag" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_ld_reload_flag" >&5
+echo "${ECHO_T}$lt_cv_ld_reload_flag" >&6
 reload_flag=$lt_cv_ld_reload_flag
 case $reload_flag in
 "" | " "*) ;;
@@ -3476,8 +2904,8 @@
     ;;
 esac
 
-{ echo "$as_me:$LINENO: checking for BSD-compatible nm" >&5
-echo $ECHO_N "checking for BSD-compatible nm... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for BSD-compatible nm" >&5
+echo $ECHO_N "checking for BSD-compatible nm... $ECHO_C" >&6
 if test "${lt_cv_path_NM+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3525,23 +2953,23 @@
   test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm
 fi
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_path_NM" >&5
-echo "${ECHO_T}$lt_cv_path_NM" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_path_NM" >&5
+echo "${ECHO_T}$lt_cv_path_NM" >&6
 NM="$lt_cv_path_NM"
 
-{ echo "$as_me:$LINENO: checking whether ln -s works" >&5
-echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether ln -s works" >&5
+echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6
 LN_S=$as_ln_s
 if test "$LN_S" = "ln -s"; then
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+  echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
 else
-  { echo "$as_me:$LINENO: result: no, using $LN_S" >&5
-echo "${ECHO_T}no, using $LN_S" >&6; }
+  echo "$as_me:$LINENO: result: no, using $LN_S" >&5
+echo "${ECHO_T}no, using $LN_S" >&6
 fi
 
-{ echo "$as_me:$LINENO: checking how to recognise dependent libraries" >&5
-echo $ECHO_N "checking how to recognise dependent libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking how to recognise dependent libraries" >&5
+echo $ECHO_N "checking how to recognise dependent libraries... $ECHO_C" >&6
 if test "${lt_cv_deplibs_check_method+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3716,8 +3144,8 @@
 esac
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_deplibs_check_method" >&5
-echo "${ECHO_T}$lt_cv_deplibs_check_method" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_deplibs_check_method" >&5
+echo "${ECHO_T}$lt_cv_deplibs_check_method" >&6
 file_magic_cmd=$lt_cv_file_magic_cmd
 deplibs_check_method=$lt_cv_deplibs_check_method
 test -z "$deplibs_check_method" && deplibs_check_method=unknown
@@ -3735,11 +3163,11 @@
 compiler=$CC
 
 
-# Check whether --enable-libtool-lock was given.
+# Check whether --enable-libtool-lock or --disable-libtool-lock was given.
 if test "${enable_libtool_lock+set}" = set; then
-  enableval=$enable_libtool_lock;
-fi
+  enableval="$enable_libtool_lock"
 
+fi;
 test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
 
 # Some flags need to be propagated to the compiler or linker for good
@@ -3766,7 +3194,7 @@
   ;;
 *-*-irix6*)
   # Find out which ABI we are using.
-  echo '#line 3769 "configure"' > conftest.$ac_ext
+  echo '#line 3197 "configure"' > conftest.$ac_ext
   if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
   (eval $ac_compile) 2>&5
   ac_status=$?
@@ -3851,8 +3279,8 @@
   # On SCO OpenServer 5, we need -belf to get full-featured binaries.
   SAVE_CFLAGS="$CFLAGS"
   CFLAGS="$CFLAGS -belf"
-  { echo "$as_me:$LINENO: checking whether the C compiler needs -belf" >&5
-echo $ECHO_N "checking whether the C compiler needs -belf... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking whether the C compiler needs -belf" >&5
+echo $ECHO_N "checking whether the C compiler needs -belf... $ECHO_C" >&6
 if test "${lt_cv_cc_needs_belf+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3878,32 +3306,35 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   lt_cv_cc_needs_belf=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	lt_cv_cc_needs_belf=no
+lt_cv_cc_needs_belf=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
      ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
@@ -3912,8 +3343,8 @@
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_cc_needs_belf" >&5
-echo "${ECHO_T}$lt_cv_cc_needs_belf" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_cc_needs_belf" >&5
+echo "${ECHO_T}$lt_cv_cc_needs_belf" >&6
   if test x"$lt_cv_cc_needs_belf" != x"yes"; then
     # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
     CFLAGS="$SAVE_CFLAGS"
@@ -3943,8 +3374,8 @@
   if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args.
 set dummy ${ac_tool_prefix}dlltool; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_DLLTOOL+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3957,34 +3388,32 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 DLLTOOL=$ac_cv_prog_DLLTOOL
 if test -n "$DLLTOOL"; then
-  { echo "$as_me:$LINENO: result: $DLLTOOL" >&5
-echo "${ECHO_T}$DLLTOOL" >&6; }
+  echo "$as_me:$LINENO: result: $DLLTOOL" >&5
+echo "${ECHO_T}$DLLTOOL" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
 fi
 if test -z "$ac_cv_prog_DLLTOOL"; then
   ac_ct_DLLTOOL=$DLLTOOL
   # Extract the first word of "dlltool", so it can be a program name with args.
 set dummy dlltool; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_DLLTOOL+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3997,41 +3426,27 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_DLLTOOL="dlltool"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
+  test -z "$ac_cv_prog_ac_ct_DLLTOOL" && ac_cv_prog_ac_ct_DLLTOOL="false"
 fi
 fi
 ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL
 if test -n "$ac_ct_DLLTOOL"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_DLLTOOL" >&5
-echo "${ECHO_T}$ac_ct_DLLTOOL" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_DLLTOOL" >&5
+echo "${ECHO_T}$ac_ct_DLLTOOL" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-  if test "x$ac_ct_DLLTOOL" = x; then
-    DLLTOOL="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    DLLTOOL=$ac_ct_DLLTOOL
-  fi
+  DLLTOOL=$ac_ct_DLLTOOL
 else
   DLLTOOL="$ac_cv_prog_DLLTOOL"
 fi
@@ -4039,8 +3454,8 @@
   if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}as", so it can be a program name with args.
 set dummy ${ac_tool_prefix}as; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_AS+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -4053,34 +3468,32 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_AS="${ac_tool_prefix}as"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 AS=$ac_cv_prog_AS
 if test -n "$AS"; then
-  { echo "$as_me:$LINENO: result: $AS" >&5
-echo "${ECHO_T}$AS" >&6; }
+  echo "$as_me:$LINENO: result: $AS" >&5
+echo "${ECHO_T}$AS" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
 fi
 if test -z "$ac_cv_prog_AS"; then
   ac_ct_AS=$AS
   # Extract the first word of "as", so it can be a program name with args.
 set dummy as; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_AS+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -4093,41 +3506,27 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_AS="as"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
+  test -z "$ac_cv_prog_ac_ct_AS" && ac_cv_prog_ac_ct_AS="false"
 fi
 fi
 ac_ct_AS=$ac_cv_prog_ac_ct_AS
 if test -n "$ac_ct_AS"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_AS" >&5
-echo "${ECHO_T}$ac_ct_AS" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_AS" >&5
+echo "${ECHO_T}$ac_ct_AS" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-  if test "x$ac_ct_AS" = x; then
-    AS="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    AS=$ac_ct_AS
-  fi
+  AS=$ac_ct_AS
 else
   AS="$ac_cv_prog_AS"
 fi
@@ -4135,8 +3534,8 @@
   if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args.
 set dummy ${ac_tool_prefix}objdump; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_OBJDUMP+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -4149,34 +3548,32 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 OBJDUMP=$ac_cv_prog_OBJDUMP
 if test -n "$OBJDUMP"; then
-  { echo "$as_me:$LINENO: result: $OBJDUMP" >&5
-echo "${ECHO_T}$OBJDUMP" >&6; }
+  echo "$as_me:$LINENO: result: $OBJDUMP" >&5
+echo "${ECHO_T}$OBJDUMP" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
 fi
 if test -z "$ac_cv_prog_OBJDUMP"; then
   ac_ct_OBJDUMP=$OBJDUMP
   # Extract the first word of "objdump", so it can be a program name with args.
 set dummy objdump; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_OBJDUMP+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -4189,41 +3586,27 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_OBJDUMP="objdump"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
+  test -z "$ac_cv_prog_ac_ct_OBJDUMP" && ac_cv_prog_ac_ct_OBJDUMP="false"
 fi
 fi
 ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP
 if test -n "$ac_ct_OBJDUMP"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_OBJDUMP" >&5
-echo "${ECHO_T}$ac_ct_OBJDUMP" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_OBJDUMP" >&5
+echo "${ECHO_T}$ac_ct_OBJDUMP" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-  if test "x$ac_ct_OBJDUMP" = x; then
-    OBJDUMP="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    OBJDUMP=$ac_ct_OBJDUMP
-  fi
+  OBJDUMP=$ac_ct_OBJDUMP
 else
   OBJDUMP="$ac_cv_prog_OBJDUMP"
 fi
@@ -4240,8 +3623,8 @@
 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
-{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5
-echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5
+echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6
 # On Suns, sometimes $CPP names a directory.
 if test -n "$CPP" && test -d "$CPP"; then
   CPP=
@@ -4275,22 +3658,24 @@
 #endif
 		     Syntax error
 _ACEOF
-if { (ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_c_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
   :
 else
   echo "$as_me: failed program was:" >&5
@@ -4299,10 +3684,9 @@
   # Broken: fails on valid input.
 continue
 fi
-
 rm -f conftest.err conftest.$ac_ext
 
-  # OK, works on sane cases.  Now check whether nonexistent headers
+  # OK, works on sane cases.  Now check whether non-existent headers
   # can be detected and how.
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -4312,22 +3696,24 @@
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if { (ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_c_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
   # Broken: success on invalid input.
 continue
 else
@@ -4338,7 +3724,6 @@
 ac_preproc_ok=:
 break
 fi
-
 rm -f conftest.err conftest.$ac_ext
 
 done
@@ -4356,8 +3741,8 @@
 else
   ac_cv_prog_CPP=$CPP
 fi
-{ echo "$as_me:$LINENO: result: $CPP" >&5
-echo "${ECHO_T}$CPP" >&6; }
+echo "$as_me:$LINENO: result: $CPP" >&5
+echo "${ECHO_T}$CPP" >&6
 ac_preproc_ok=false
 for ac_c_preproc_warn_flag in '' yes
 do
@@ -4380,22 +3765,24 @@
 #endif
 		     Syntax error
 _ACEOF
-if { (ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_c_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
   :
 else
   echo "$as_me: failed program was:" >&5
@@ -4404,10 +3791,9 @@
   # Broken: fails on valid input.
 continue
 fi
-
 rm -f conftest.err conftest.$ac_ext
 
-  # OK, works on sane cases.  Now check whether nonexistent headers
+  # OK, works on sane cases.  Now check whether non-existent headers
   # can be detected and how.
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -4417,22 +3803,24 @@
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if { (ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_c_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
   # Broken: success on invalid input.
 continue
 else
@@ -4443,7 +3831,6 @@
 ac_preproc_ok=:
 break
 fi
-
 rm -f conftest.err conftest.$ac_ext
 
 done
@@ -4466,8 +3853,8 @@
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5
-echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for ANSI C header files" >&5
+echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6
 if test "${ac_cv_header_stdc+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -4491,31 +3878,35 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_header_stdc=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_header_stdc=no
+ac_cv_header_stdc=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f 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.
@@ -4571,7 +3962,6 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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))
@@ -4591,27 +3981,18 @@
   for (i = 0; i < 256; i++)
     if (XOR (islower (i), ISLOWER (i))
 	|| toupper (i) != TOUPPER (i))
-      return 2;
-  return 0;
+      exit(2);
+  exit (0);
 }
 _ACEOF
 rm -f conftest$ac_exeext
-if { (ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; }; then
@@ -4624,14 +4005,12 @@
 ( exit $ac_status )
 ac_cv_header_stdc=no
 fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
-
-
 fi
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
-echo "${ECHO_T}$ac_cv_header_stdc" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
+echo "${ECHO_T}$ac_cv_header_stdc" >&6
 if test $ac_cv_header_stdc = yes; then
 
 cat >>confdefs.h <<\_ACEOF
@@ -4654,9 +4033,9 @@
 		  inttypes.h stdint.h unistd.h
 do
 as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   cat >conftest.$ac_ext <<_ACEOF
@@ -4670,35 +4049,38 @@
 #include <$ac_header>
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   eval "$as_ac_Header=yes"
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	eval "$as_ac_Header=no"
+eval "$as_ac_Header=no"
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-ac_res=`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
 if test `eval echo '${'$as_ac_Header'}'` = yes; then
   cat >>confdefs.h <<_ACEOF
 #define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
@@ -4713,19 +4095,18 @@
 for ac_header in dlfcn.h
 do
 as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+  echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 fi
-ac_res=`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
 else
   # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6
 cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
@@ -4736,37 +4117,41 @@
 #include <$ac_header>
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_header_compiler=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_header_compiler=no
+ac_header_compiler=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6
 
 # Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6
 cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
@@ -4775,22 +4160,24 @@
 /* end confdefs.h.  */
 #include <$ac_header>
 _ACEOF
-if { (ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_c_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
   ac_header_preproc=yes
 else
   echo "$as_me: failed program was:" >&5
@@ -4798,10 +4185,9 @@
 
   ac_header_preproc=no
 fi
-
 rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
+echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6
 
 # So?  What about this header?
 case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
@@ -4825,19 +4211,25 @@
 echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
     { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
 echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
-
+    (
+      cat <<\_ASBOX
+## ------------------------------------------ ##
+## Report this to the AC_PACKAGE_NAME lists.  ##
+## ------------------------------------------ ##
+_ASBOX
+    ) |
+      sed "s/^/$as_me: WARNING:     /" >&2
     ;;
 esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   eval "$as_ac_Header=\$ac_header_preproc"
 fi
-ac_res=`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
 
 fi
 if test `eval echo '${'$as_ac_Header'}'` = yes; then
@@ -4849,22 +4241,18 @@
 
 done
 
-ac_ext=cpp
+ac_ext=cc
 ac_cpp='$CXXCPP $CPPFLAGS'
 ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-if test -z "$CXX"; then
-  if test -n "$CCC"; then
-    CXX=$CCC
-  else
-    if test -n "$ac_tool_prefix"; then
-  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+if test -n "$ac_tool_prefix"; then
+  for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC
   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
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_CXX+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -4877,38 +4265,36 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 CXX=$ac_cv_prog_CXX
 if test -n "$CXX"; then
-  { echo "$as_me:$LINENO: result: $CXX" >&5
-echo "${ECHO_T}$CXX" >&6; }
+  echo "$as_me:$LINENO: result: $CXX" >&5
+echo "${ECHO_T}$CXX" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
     test -n "$CXX" && break
   done
 fi
 if test -z "$CXX"; then
   ac_ct_CXX=$CXX
-  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+  for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
 set dummy $ac_prog; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -4921,85 +4307,55 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_CXX="$ac_prog"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 ac_ct_CXX=$ac_cv_prog_ac_ct_CXX
 if test -n "$ac_ct_CXX"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
-echo "${ECHO_T}$ac_ct_CXX" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
+echo "${ECHO_T}$ac_ct_CXX" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
   test -n "$ac_ct_CXX" && break
 done
+test -n "$ac_ct_CXX" || ac_ct_CXX="g++"
 
-  if test "x$ac_ct_CXX" = x; then
-    CXX="g++"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    CXX=$ac_ct_CXX
-  fi
+  CXX=$ac_ct_CXX
 fi
 
-  fi
-fi
+
 # Provide some information about the compiler.
-echo "$as_me:$LINENO: checking for C++ compiler version" >&5
+echo "$as_me:$LINENO:" \
+     "checking for C++ compiler version" >&5
 ac_compiler=`set X $ac_compile; echo $2`
-{ (ac_try="$ac_compiler --version >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler --version >&5") 2>&5
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
+  (eval $ac_compiler --version </dev/null >&5) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (ac_try="$ac_compiler -v >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -v >&5") 2>&5
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
+  (eval $ac_compiler -v </dev/null >&5) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (ac_try="$ac_compiler -V >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -V >&5") 2>&5
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
+  (eval $ac_compiler -V </dev/null >&5) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
 
-{ echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5
-echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6
 if test "${ac_cv_cxx_compiler_gnu+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -5022,49 +4378,50 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_compiler_gnu=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_compiler_gnu=no
+ac_compiler_gnu=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 ac_cv_cxx_compiler_gnu=$ac_compiler_gnu
 
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6
 GXX=`test $ac_compiler_gnu = yes && echo yes`
 ac_test_CXXFLAGS=${CXXFLAGS+set}
 ac_save_CXXFLAGS=$CXXFLAGS
-{ echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
-echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6; }
+CXXFLAGS="-g"
+echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
+echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6
 if test "${ac_cv_prog_cxx_g+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_save_cxx_werror_flag=$ac_cxx_werror_flag
-   ac_cxx_werror_flag=yes
-   ac_cv_prog_cxx_g=no
-   CXXFLAGS="-g"
-   cat >conftest.$ac_ext <<_ACEOF
+  cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
@@ -5080,134 +4437,160 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_prog_cxx_g=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	CXXFLAGS=""
-      cat >conftest.$ac_ext <<_ACEOF
+ac_cv_prog_cxx_g=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6
+if test "$ac_test_CXXFLAGS" = set; then
+  CXXFLAGS=$ac_save_CXXFLAGS
+elif test $ac_cv_prog_cxx_g = yes; then
+  if test "$GXX" = yes; then
+    CXXFLAGS="-g -O2"
+  else
+    CXXFLAGS="-g"
+  fi
+else
+  if test "$GXX" = yes; then
+    CXXFLAGS="-O2"
+  else
+    CXXFLAGS=
+  fi
+fi
+for ac_declaration in \
+   '' \
+   'extern "C" void std::exit (int) throw (); using std::exit;' \
+   'extern "C" void std::exit (int); using std::exit;' \
+   'extern "C" void exit (int) throw ();' \
+   'extern "C" void exit (int);' \
+   'void exit (int);'
+do
+  cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-
+$ac_declaration
+#include <stdlib.h>
 int
 main ()
 {
-
+exit (42);
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   :
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cxx_werror_flag=$ac_save_cxx_werror_flag
-	 CXXFLAGS="-g"
-	 cat >conftest.$ac_ext <<_ACEOF
+continue
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+  cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-
+$ac_declaration
 int
 main ()
 {
-
+exit (42);
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_prog_cxx_g=yes
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  break
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+done
+rm -f conftest*
+if test -n "$ac_declaration"; then
+  echo '#ifdef __cplusplus' >>confdefs.h
+  echo $ac_declaration      >>confdefs.h
+  echo '#endif'             >>confdefs.h
 fi
 
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-   ac_cxx_werror_flag=$ac_save_cxx_werror_flag
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
-echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6; }
-if test "$ac_test_CXXFLAGS" = set; then
-  CXXFLAGS=$ac_save_CXXFLAGS
-elif test $ac_cv_prog_cxx_g = yes; then
-  if test "$GXX" = yes; then
-    CXXFLAGS="-g -O2"
-  else
-    CXXFLAGS="-g"
-  fi
-else
-  if test "$GXX" = yes; then
-    CXXFLAGS="-O2"
-  else
-    CXXFLAGS=
-  fi
-fi
-ac_ext=cpp
+ac_ext=cc
 ac_cpp='$CXXCPP $CPPFLAGS'
 ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
@@ -5218,13 +4601,13 @@
 if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
     ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
     (test "X$CXX" != "Xg++"))) ; then
-  ac_ext=cpp
+  ac_ext=cc
 ac_cpp='$CXXCPP $CPPFLAGS'
 ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-{ echo "$as_me:$LINENO: checking how to run the C++ preprocessor" >&5
-echo $ECHO_N "checking how to run the C++ preprocessor... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking how to run the C++ preprocessor" >&5
+echo $ECHO_N "checking how to run the C++ preprocessor... $ECHO_C" >&6
 if test -z "$CXXCPP"; then
   if test "${ac_cv_prog_CXXCPP+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
@@ -5254,22 +4637,24 @@
 #endif
 		     Syntax error
 _ACEOF
-if { (ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_cxx_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
   :
 else
   echo "$as_me: failed program was:" >&5
@@ -5278,10 +4663,9 @@
   # Broken: fails on valid input.
 continue
 fi
-
 rm -f conftest.err conftest.$ac_ext
 
-  # OK, works on sane cases.  Now check whether nonexistent headers
+  # OK, works on sane cases.  Now check whether non-existent headers
   # can be detected and how.
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -5291,22 +4675,24 @@
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if { (ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_cxx_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
   # Broken: success on invalid input.
 continue
 else
@@ -5317,7 +4703,6 @@
 ac_preproc_ok=:
 break
 fi
-
 rm -f conftest.err conftest.$ac_ext
 
 done
@@ -5335,8 +4720,8 @@
 else
   ac_cv_prog_CXXCPP=$CXXCPP
 fi
-{ echo "$as_me:$LINENO: result: $CXXCPP" >&5
-echo "${ECHO_T}$CXXCPP" >&6; }
+echo "$as_me:$LINENO: result: $CXXCPP" >&5
+echo "${ECHO_T}$CXXCPP" >&6
 ac_preproc_ok=false
 for ac_cxx_preproc_warn_flag in '' yes
 do
@@ -5359,22 +4744,24 @@
 #endif
 		     Syntax error
 _ACEOF
-if { (ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_cxx_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
   :
 else
   echo "$as_me: failed program was:" >&5
@@ -5383,10 +4770,9 @@
   # Broken: fails on valid input.
 continue
 fi
-
 rm -f conftest.err conftest.$ac_ext
 
-  # OK, works on sane cases.  Now check whether nonexistent headers
+  # OK, works on sane cases.  Now check whether non-existent headers
   # can be detected and how.
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -5396,22 +4782,24 @@
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if { (ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_cxx_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
   # Broken: success on invalid input.
 continue
 else
@@ -5422,7 +4810,6 @@
 ac_preproc_ok=:
 break
 fi
-
 rm -f conftest.err conftest.$ac_ext
 
 done
@@ -5438,7 +4825,7 @@
    { (exit 1); exit 1; }; }
 fi
 
-ac_ext=cpp
+ac_ext=cc
 ac_cpp='$CXXCPP $CPPFLAGS'
 ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
@@ -5452,12 +4839,12 @@
 ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_f77_compiler_gnu
 if test -n "$ac_tool_prefix"; then
-  for ac_prog in g77 xlf f77 frt pgf77 cf77 fort77 fl32 af77 xlf90 f90 pgf90 pghpf epcf90 gfortran g95 xlf95 f95 fort ifort ifc efc pgf95 lf95 ftn
+  for ac_prog in g77 f77 xlf frt pgf77 fort77 fl32 af77 f90 xlf90 pgf90 epcf90 f95 fort xlf95 ifc efc pgf95 lf95 gfortran
   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
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_F77+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -5470,38 +4857,36 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_F77="$ac_tool_prefix$ac_prog"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 F77=$ac_cv_prog_F77
 if test -n "$F77"; then
-  { echo "$as_me:$LINENO: result: $F77" >&5
-echo "${ECHO_T}$F77" >&6; }
+  echo "$as_me:$LINENO: result: $F77" >&5
+echo "${ECHO_T}$F77" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
     test -n "$F77" && break
   done
 fi
 if test -z "$F77"; then
   ac_ct_F77=$F77
-  for ac_prog in g77 xlf f77 frt pgf77 cf77 fort77 fl32 af77 xlf90 f90 pgf90 pghpf epcf90 gfortran g95 xlf95 f95 fort ifort ifc efc pgf95 lf95 ftn
+  for ac_prog in g77 f77 xlf frt pgf77 fort77 fl32 af77 f90 xlf90 pgf90 epcf90 f95 fort xlf95 ifc efc pgf95 lf95 gfortran
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
 set dummy $ac_prog; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_F77+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -5514,78 +4899,48 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_F77="$ac_prog"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 ac_ct_F77=$ac_cv_prog_ac_ct_F77
 if test -n "$ac_ct_F77"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_F77" >&5
-echo "${ECHO_T}$ac_ct_F77" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_F77" >&5
+echo "${ECHO_T}$ac_ct_F77" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
   test -n "$ac_ct_F77" && break
 done
 
-  if test "x$ac_ct_F77" = x; then
-    F77=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    F77=$ac_ct_F77
-  fi
+  F77=$ac_ct_F77
 fi
 
 
 # Provide some information about the compiler.
-echo "$as_me:$LINENO: checking for Fortran 77 compiler version" >&5
+echo "$as_me:4929:" \
+     "checking for Fortran 77 compiler version" >&5
 ac_compiler=`set X $ac_compile; echo $2`
-{ (ac_try="$ac_compiler --version >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler --version >&5") 2>&5
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
+  (eval $ac_compiler --version </dev/null >&5) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (ac_try="$ac_compiler -v >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -v >&5") 2>&5
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
+  (eval $ac_compiler -v </dev/null >&5) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (ac_try="$ac_compiler -V >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -V >&5") 2>&5
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
+  (eval $ac_compiler -V </dev/null >&5) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
@@ -5595,8 +4950,8 @@
 # input file.  (Note that this only needs to work for GNU compilers.)
 ac_save_ext=$ac_ext
 ac_ext=F
-{ echo "$as_me:$LINENO: checking whether we are using the GNU Fortran 77 compiler" >&5
-echo $ECHO_N "checking whether we are using the GNU Fortran 77 compiler... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether we are using the GNU Fortran 77 compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU Fortran 77 compiler... $ECHO_C" >&6
 if test "${ac_cv_f77_compiler_gnu+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -5609,42 +4964,46 @@
       end
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_f77_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_f77_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_compiler_gnu=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_compiler_gnu=no
+ac_compiler_gnu=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 ac_cv_f77_compiler_gnu=$ac_compiler_gnu
 
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_f77_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_f77_compiler_gnu" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_f77_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_f77_compiler_gnu" >&6
 ac_ext=$ac_save_ext
 ac_test_FFLAGS=${FFLAGS+set}
 ac_save_FFLAGS=$FFLAGS
 FFLAGS=
-{ echo "$as_me:$LINENO: checking whether $F77 accepts -g" >&5
-echo $ECHO_N "checking whether $F77 accepts -g... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether $F77 accepts -g" >&5
+echo $ECHO_N "checking whether $F77 accepts -g... $ECHO_C" >&6
 if test "${ac_cv_prog_f77_g+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -5655,35 +5014,39 @@
       end
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_f77_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_f77_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_prog_f77_g=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_prog_f77_g=no
+ac_cv_prog_f77_g=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_prog_f77_g" >&5
-echo "${ECHO_T}$ac_cv_prog_f77_g" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_prog_f77_g" >&5
+echo "${ECHO_T}$ac_cv_prog_f77_g" >&6
 if test "$ac_test_FFLAGS" = set; then
   FFLAGS=$ac_save_FFLAGS
 elif test $ac_cv_prog_f77_g = yes; then
@@ -5712,8 +5075,8 @@
 # Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compilers!
 
 # find the maximum length of command line arguments
-{ echo "$as_me:$LINENO: checking the maximum length of command line arguments" >&5
-echo $ECHO_N "checking the maximum length of command line arguments... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking the maximum length of command line arguments" >&5
+echo $ECHO_N "checking the maximum length of command line arguments... $ECHO_C" >&6
 if test "${lt_cv_sys_max_cmd_len+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -5821,19 +5184,19 @@
 fi
 
 if test -n $lt_cv_sys_max_cmd_len ; then
-  { echo "$as_me:$LINENO: result: $lt_cv_sys_max_cmd_len" >&5
-echo "${ECHO_T}$lt_cv_sys_max_cmd_len" >&6; }
+  echo "$as_me:$LINENO: result: $lt_cv_sys_max_cmd_len" >&5
+echo "${ECHO_T}$lt_cv_sys_max_cmd_len" >&6
 else
-  { echo "$as_me:$LINENO: result: none" >&5
-echo "${ECHO_T}none" >&6; }
+  echo "$as_me:$LINENO: result: none" >&5
+echo "${ECHO_T}none" >&6
 fi
 
 
 
 
 # Check for command to grab the raw symbol name followed by C symbol from nm.
-{ echo "$as_me:$LINENO: checking command to parse $NM output from $compiler object" >&5
-echo $ECHO_N "checking command to parse $NM output from $compiler object... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking command to parse $NM output from $compiler object" >&5
+echo $ECHO_N "checking command to parse $NM output from $compiler object... $ECHO_C" >&6
 if test "${lt_cv_sys_global_symbol_pipe+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6037,15 +5400,15 @@
   lt_cv_sys_global_symbol_to_cdecl=
 fi
 if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
-  { echo "$as_me:$LINENO: result: failed" >&5
-echo "${ECHO_T}failed" >&6; }
+  echo "$as_me:$LINENO: result: failed" >&5
+echo "${ECHO_T}failed" >&6
 else
-  { echo "$as_me:$LINENO: result: ok" >&5
-echo "${ECHO_T}ok" >&6; }
+  echo "$as_me:$LINENO: result: ok" >&5
+echo "${ECHO_T}ok" >&6
 fi
 
-{ echo "$as_me:$LINENO: checking for objdir" >&5
-echo $ECHO_N "checking for objdir... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for objdir" >&5
+echo $ECHO_N "checking for objdir... $ECHO_C" >&6
 if test "${lt_cv_objdir+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6059,8 +5422,8 @@
 fi
 rmdir .libs 2>/dev/null
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_objdir" >&5
-echo "${ECHO_T}$lt_cv_objdir" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_objdir" >&5
+echo "${ECHO_T}$lt_cv_objdir" >&6
 objdir=$lt_cv_objdir
 
 
@@ -6111,8 +5474,8 @@
 if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args.
 set dummy ${ac_tool_prefix}ar; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_AR+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6125,34 +5488,32 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_AR="${ac_tool_prefix}ar"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 AR=$ac_cv_prog_AR
 if test -n "$AR"; then
-  { echo "$as_me:$LINENO: result: $AR" >&5
-echo "${ECHO_T}$AR" >&6; }
+  echo "$as_me:$LINENO: result: $AR" >&5
+echo "${ECHO_T}$AR" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
 fi
 if test -z "$ac_cv_prog_AR"; then
   ac_ct_AR=$AR
   # Extract the first word of "ar", so it can be a program name with args.
 set dummy ar; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_AR+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6165,41 +5526,27 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_AR="ar"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
+  test -z "$ac_cv_prog_ac_ct_AR" && ac_cv_prog_ac_ct_AR="false"
 fi
 fi
 ac_ct_AR=$ac_cv_prog_ac_ct_AR
 if test -n "$ac_ct_AR"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_AR" >&5
-echo "${ECHO_T}$ac_ct_AR" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_AR" >&5
+echo "${ECHO_T}$ac_ct_AR" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-  if test "x$ac_ct_AR" = x; then
-    AR="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    AR=$ac_ct_AR
-  fi
+  AR=$ac_ct_AR
 else
   AR="$ac_cv_prog_AR"
 fi
@@ -6207,8 +5554,8 @@
 if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
 set dummy ${ac_tool_prefix}ranlib; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_RANLIB+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6221,34 +5568,32 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 RANLIB=$ac_cv_prog_RANLIB
 if test -n "$RANLIB"; then
-  { echo "$as_me:$LINENO: result: $RANLIB" >&5
-echo "${ECHO_T}$RANLIB" >&6; }
+  echo "$as_me:$LINENO: result: $RANLIB" >&5
+echo "${ECHO_T}$RANLIB" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
 fi
 if test -z "$ac_cv_prog_RANLIB"; then
   ac_ct_RANLIB=$RANLIB
   # Extract the first word of "ranlib", so it can be a program name with args.
 set dummy ranlib; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6261,41 +5606,27 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_RANLIB="ranlib"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
+  test -z "$ac_cv_prog_ac_ct_RANLIB" && ac_cv_prog_ac_ct_RANLIB=":"
 fi
 fi
 ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
 if test -n "$ac_ct_RANLIB"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5
-echo "${ECHO_T}$ac_ct_RANLIB" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5
+echo "${ECHO_T}$ac_ct_RANLIB" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-  if test "x$ac_ct_RANLIB" = x; then
-    RANLIB=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    RANLIB=$ac_ct_RANLIB
-  fi
+  RANLIB=$ac_ct_RANLIB
 else
   RANLIB="$ac_cv_prog_RANLIB"
 fi
@@ -6303,8 +5634,8 @@
 if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
 set dummy ${ac_tool_prefix}strip; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_STRIP+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6317,34 +5648,32 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_STRIP="${ac_tool_prefix}strip"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
 fi
 fi
 STRIP=$ac_cv_prog_STRIP
 if test -n "$STRIP"; then
-  { echo "$as_me:$LINENO: result: $STRIP" >&5
-echo "${ECHO_T}$STRIP" >&6; }
+  echo "$as_me:$LINENO: result: $STRIP" >&5
+echo "${ECHO_T}$STRIP" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
 fi
 if test -z "$ac_cv_prog_STRIP"; then
   ac_ct_STRIP=$STRIP
   # Extract the first word of "strip", so it can be a program name with args.
 set dummy strip; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6357,41 +5686,27 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_STRIP="strip"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
+  test -z "$ac_cv_prog_ac_ct_STRIP" && ac_cv_prog_ac_ct_STRIP=":"
 fi
 fi
 ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP
 if test -n "$ac_ct_STRIP"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5
-echo "${ECHO_T}$ac_ct_STRIP" >&6; }
+  echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5
+echo "${ECHO_T}$ac_ct_STRIP" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-  if test "x$ac_ct_STRIP" = x; then
-    STRIP=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    STRIP=$ac_ct_STRIP
-  fi
+  STRIP=$ac_ct_STRIP
 else
   STRIP="$ac_cv_prog_STRIP"
 fi
@@ -6450,8 +5765,8 @@
 case $deplibs_check_method in
 file_magic*)
   if test "$file_magic_cmd" = '$MAGIC_CMD'; then
-    { echo "$as_me:$LINENO: checking for ${ac_tool_prefix}file" >&5
-echo $ECHO_N "checking for ${ac_tool_prefix}file... $ECHO_C" >&6; }
+    echo "$as_me:$LINENO: checking for ${ac_tool_prefix}file" >&5
+echo $ECHO_N "checking for ${ac_tool_prefix}file... $ECHO_C" >&6
 if test "${lt_cv_path_MAGIC_CMD+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6503,17 +5818,17 @@
 
 MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
 if test -n "$MAGIC_CMD"; then
-  { echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5
-echo "${ECHO_T}$MAGIC_CMD" >&6; }
+  echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5
+echo "${ECHO_T}$MAGIC_CMD" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
 if test -z "$lt_cv_path_MAGIC_CMD"; then
   if test -n "$ac_tool_prefix"; then
-    { echo "$as_me:$LINENO: checking for file" >&5
-echo $ECHO_N "checking for file... $ECHO_C" >&6; }
+    echo "$as_me:$LINENO: checking for file" >&5
+echo $ECHO_N "checking for file... $ECHO_C" >&6
 if test "${lt_cv_path_MAGIC_CMD+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6565,11 +5880,11 @@
 
 MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
 if test -n "$MAGIC_CMD"; then
-  { echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5
-echo "${ECHO_T}$MAGIC_CMD" >&6; }
+  echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5
+echo "${ECHO_T}$MAGIC_CMD" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
   else
@@ -6584,21 +5899,21 @@
 enable_dlopen=no
 enable_win32_dll=yes
 
-# Check whether --enable-libtool-lock was given.
+# Check whether --enable-libtool-lock or --disable-libtool-lock was given.
 if test "${enable_libtool_lock+set}" = set; then
-  enableval=$enable_libtool_lock;
-fi
+  enableval="$enable_libtool_lock"
 
+fi;
 test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
 
 
-# Check whether --with-pic was given.
+# Check whether --with-pic or --without-pic was given.
 if test "${with_pic+set}" = set; then
-  withval=$with_pic; pic_mode="$withval"
+  withval="$with_pic"
+  pic_mode="$withval"
 else
   pic_mode=default
-fi
-
+fi;
 test -z "$pic_mode" && pic_mode=default
 
 # Check if we have a version mismatch between libtool.m4 and ltmain.sh.
@@ -6607,11 +5922,11 @@
 #        We also should do it _before_ AC_LIBTOOL_LANG_C_CONFIG that actually
 #        calls AC_LIBTOOL_CONFIG and creates libtool.
 #
-{ echo "$as_me:$LINENO: checking for correct ltmain.sh version" >&5
-echo $ECHO_N "checking for correct ltmain.sh version... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for correct ltmain.sh version" >&5
+echo $ECHO_N "checking for correct ltmain.sh version... $ECHO_C" >&6
 if test "x$ltmain" = "x" ; then
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
   { { echo "$as_me:$LINENO: error:
 
 *** [Gentoo] sanity check failed! ***
@@ -6627,8 +5942,8 @@
 gentoo_lt_version="1.5.22"
 gentoo_ltmain_version=`sed -n '/^[ 	]*VERSION=/{s/^[ 	]*VERSION=//;p;q;}' "$ltmain"`
 if test "x$gentoo_lt_version" != "x$gentoo_ltmain_version" ; then
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
   { { echo "$as_me:$LINENO: error:
 
 *** [Gentoo] sanity check failed! ***
@@ -6657,8 +5972,8 @@
 " >&2;}
    { (exit 1); exit 1; }; }
 else
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+  echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
 fi
 
 
@@ -6717,8 +6032,8 @@
   lt_prog_compiler_no_builtin_flag=' -fno-builtin'
 
 
-{ echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5
-echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5
+echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6
 if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -6735,11 +6050,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:6738: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:6053: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:6742: \$? = $ac_status" >&5
+   echo "$as_me:6057: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings other than the usual output.
@@ -6752,8 +6067,8 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6
 
 if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then
     lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions"
@@ -6767,8 +6082,8 @@
 lt_prog_compiler_pic=
 lt_prog_compiler_static=
 
-{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
-echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
+echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
 
   if test "$GCC" = yes; then
     lt_prog_compiler_wl='-Wl,'
@@ -6977,16 +6292,16 @@
     esac
   fi
 
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic" >&6
 
 #
 # Check to make sure the PIC flag actually works.
 #
 if test -n "$lt_prog_compiler_pic"; then
 
-{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5
-echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5
+echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic works... $ECHO_C" >&6
 if test "${lt_prog_compiler_pic_works+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -7003,11 +6318,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:7006: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:6321: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:7010: \$? = $ac_status" >&5
+   echo "$as_me:6325: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings other than the usual output.
@@ -7020,8 +6335,8 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_works" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_works" >&6
 
 if test x"$lt_prog_compiler_pic_works" = xyes; then
     case $lt_prog_compiler_pic in
@@ -7048,8 +6363,8 @@
 # Check to make sure the static flag actually works.
 #
 wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\"
-{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
 if test "${lt_prog_compiler_static_works+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -7076,8 +6391,8 @@
    LDFLAGS="$save_LDFLAGS"
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works" >&5
+echo "${ECHO_T}$lt_prog_compiler_static_works" >&6
 
 if test x"$lt_prog_compiler_static_works" = xyes; then
     :
@@ -7086,8 +6401,8 @@
 fi
 
 
-{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
-echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
+echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
 if test "${lt_cv_prog_compiler_c_o+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -7107,11 +6422,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:7110: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:6425: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>out/conftest.err)
    ac_status=$?
    cat out/conftest.err >&5
-   echo "$as_me:7114: \$? = $ac_status" >&5
+   echo "$as_me:6429: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s out/conftest2.$ac_objext
    then
      # The compiler can only warn and ignore the option if not recognized
@@ -7133,23 +6448,23 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_c_o" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_c_o" >&6
 
 
 hard_links="nottested"
 if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then
   # do not overwrite the value of need_locks provided by the user
-  { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
-echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
+echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
   hard_links=yes
   $rm conftest*
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
   touch conftest.a
   ln conftest.a conftest.b 2>&5 || hard_links=no
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  { echo "$as_me:$LINENO: result: $hard_links" >&5
-echo "${ECHO_T}$hard_links" >&6; }
+  echo "$as_me:$LINENO: result: $hard_links" >&5
+echo "${ECHO_T}$hard_links" >&6
   if test "$hard_links" = no; then
     { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
 echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
@@ -7159,8 +6474,8 @@
   need_locks=no
 fi
 
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
 
   runpath_var=
   allow_undefined_flag=
@@ -7575,23 +6890,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
 
 aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
 }'`
@@ -7602,10 +6921,8 @@
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
@@ -7634,23 +6951,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
 
 aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
 }'`
@@ -7661,10 +6982,8 @@
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
@@ -8113,8 +7432,8 @@
     esac
   fi
 
-{ echo "$as_me:$LINENO: result: $ld_shlibs" >&5
-echo "${ECHO_T}$ld_shlibs" >&6; }
+echo "$as_me:$LINENO: result: $ld_shlibs" >&5
+echo "${ECHO_T}$ld_shlibs" >&6
 test "$ld_shlibs" = no && can_build_shared=no
 
 #
@@ -8134,8 +7453,8 @@
       # Test whether the compiler implicitly links with -lc since on some
       # systems, -lgcc has to come before -lc. If gcc already passes -lc
       # to ld, don't add -lc before -lgcc.
-      { echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
-echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6; }
+      echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
+echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
       $rm conftest*
       printf "$lt_simple_compile_test_code" > conftest.$ac_ext
 
@@ -8172,16 +7491,16 @@
         cat conftest.err 1>&5
       fi
       $rm conftest*
-      { echo "$as_me:$LINENO: result: $archive_cmds_need_lc" >&5
-echo "${ECHO_T}$archive_cmds_need_lc" >&6; }
+      echo "$as_me:$LINENO: result: $archive_cmds_need_lc" >&5
+echo "${ECHO_T}$archive_cmds_need_lc" >&6
       ;;
     esac
   fi
   ;;
 esac
 
-{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
-echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
 library_names_spec=
 libname_spec='lib$name'
 soname_spec=
@@ -8805,8 +8124,8 @@
   dynamic_linker=no
   ;;
 esac
-{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6; }
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
 test "$dynamic_linker" = no && can_build_shared=no
 
 variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
@@ -8814,8 +8133,8 @@
   variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
 fi
 
-{ echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
 hardcode_action=
 if test -n "$hardcode_libdir_flag_spec" || \
    test -n "$runpath_var" || \
@@ -8839,8 +8158,8 @@
   # directories.
   hardcode_action=unsupported
 fi
-{ echo "$as_me:$LINENO: result: $hardcode_action" >&5
-echo "${ECHO_T}$hardcode_action" >&6; }
+echo "$as_me:$LINENO: result: $hardcode_action" >&5
+echo "${ECHO_T}$hardcode_action" >&6
 
 if test "$hardcode_action" = relink; then
   # Fast installation is not supported
@@ -8853,29 +8172,29 @@
 
 striplib=
 old_striplib=
-{ echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5
-echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5
+echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6
 if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then
   test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
   test -z "$striplib" && striplib="$STRIP --strip-unneeded"
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+  echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
 else
 # FIXME - insert some real tests, host_os isn't really good enough
   case $host_os in
    darwin*)
        if test -n "$STRIP" ; then
          striplib="$STRIP -x"
-         { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+         echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
        else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
        ;;
    *)
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
     ;;
   esac
 fi
@@ -8907,8 +8226,8 @@
 
   darwin*)
   # if libdl is installed we need to link against it
-    { echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
-echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; }
+    echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
+echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6
 if test "${ac_cv_lib_dl_dlopen+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -8921,53 +8240,56 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char dlopen ();
 int
 main ()
 {
-return dlopen ();
+dlopen ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_dl_dlopen=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_dl_dlopen=no
+ac_cv_lib_dl_dlopen=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
-echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6
 if test $ac_cv_lib_dl_dlopen = yes; then
   lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
 else
@@ -8981,8 +8303,8 @@
    ;;
 
   *)
-    { echo "$as_me:$LINENO: checking for shl_load" >&5
-echo $ECHO_N "checking for shl_load... $ECHO_C" >&6; }
+    echo "$as_me:$LINENO: checking for shl_load" >&5
+echo $ECHO_N "checking for shl_load... $ECHO_C" >&6
 if test "${ac_cv_func_shl_load+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -9009,64 +8331,73 @@
 
 #undef shl_load
 
-/* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
+{
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char shl_load ();
 /* 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_shl_load || defined __stub___shl_load
+#if defined (__stub_shl_load) || defined (__stub___shl_load)
 choke me
+#else
+char (*f) () = shl_load;
+#endif
+#ifdef __cplusplus
+}
 #endif
 
 int
 main ()
 {
-return shl_load ();
+return f != shl_load;
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_func_shl_load=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_func_shl_load=no
+ac_cv_func_shl_load=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5
-echo "${ECHO_T}$ac_cv_func_shl_load" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5
+echo "${ECHO_T}$ac_cv_func_shl_load" >&6
 if test $ac_cv_func_shl_load = yes; then
   lt_cv_dlopen="shl_load"
 else
-  { echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5
-echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5
+echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6
 if test "${ac_cv_lib_dld_shl_load+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -9079,58 +8410,61 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char shl_load ();
 int
 main ()
 {
-return shl_load ();
+shl_load ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_dld_shl_load=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_dld_shl_load=no
+ac_cv_lib_dld_shl_load=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5
-echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6
 if test $ac_cv_lib_dld_shl_load = yes; then
   lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld"
 else
-  { echo "$as_me:$LINENO: checking for dlopen" >&5
-echo $ECHO_N "checking for dlopen... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for dlopen" >&5
+echo $ECHO_N "checking for dlopen... $ECHO_C" >&6
 if test "${ac_cv_func_dlopen+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -9157,64 +8491,73 @@
 
 #undef dlopen
 
-/* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
+{
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char dlopen ();
 /* 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_dlopen || defined __stub___dlopen
+#if defined (__stub_dlopen) || defined (__stub___dlopen)
 choke me
+#else
+char (*f) () = dlopen;
+#endif
+#ifdef __cplusplus
+}
 #endif
 
 int
 main ()
 {
-return dlopen ();
+return f != dlopen;
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_func_dlopen=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_func_dlopen=no
+ac_cv_func_dlopen=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5
-echo "${ECHO_T}$ac_cv_func_dlopen" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5
+echo "${ECHO_T}$ac_cv_func_dlopen" >&6
 if test $ac_cv_func_dlopen = yes; then
   lt_cv_dlopen="dlopen"
 else
-  { echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
-echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
+echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6
 if test "${ac_cv_lib_dl_dlopen+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -9227,58 +8570,61 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char dlopen ();
 int
 main ()
 {
-return dlopen ();
+dlopen ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_dl_dlopen=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_dl_dlopen=no
+ac_cv_lib_dl_dlopen=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
-echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6
 if test $ac_cv_lib_dl_dlopen = yes; then
   lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
 else
-  { echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5
-echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5
+echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6
 if test "${ac_cv_lib_svld_dlopen+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -9291,58 +8637,61 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char dlopen ();
 int
 main ()
 {
-return dlopen ();
+dlopen ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_svld_dlopen=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_lib_svld_dlopen=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_svld_dlopen=no
+ac_cv_lib_svld_dlopen=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5
-echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6
 if test $ac_cv_lib_svld_dlopen = yes; then
   lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
 else
-  { echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5
-echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5
+echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6
 if test "${ac_cv_lib_dld_dld_link+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -9355,53 +8704,56 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char dld_link ();
 int
 main ()
 {
-return dld_link ();
+dld_link ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_dld_dld_link=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_dld_dld_link=no
+ac_cv_lib_dld_dld_link=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5
-echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6
 if test $ac_cv_lib_dld_dld_link = yes; then
   lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld"
 fi
@@ -9441,8 +8793,8 @@
     save_LIBS="$LIBS"
     LIBS="$lt_cv_dlopen_libs $LIBS"
 
-    { echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5
-echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6; }
+    echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5
+echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6
 if test "${lt_cv_dlopen_self+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -9452,7 +8804,7 @@
   lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
   lt_status=$lt_dlunknown
   cat > conftest.$ac_ext <<EOF
-#line 9455 "configure"
+#line 8807 "configure"
 #include "confdefs.h"
 
 #if HAVE_DLFCN_H
@@ -9536,13 +8888,13 @@
 
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5
-echo "${ECHO_T}$lt_cv_dlopen_self" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5
+echo "${ECHO_T}$lt_cv_dlopen_self" >&6
 
     if test "x$lt_cv_dlopen_self" = xyes; then
       wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
-      { echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5
-echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6; }
+      echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5
+echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6
 if test "${lt_cv_dlopen_self_static+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -9552,7 +8904,7 @@
   lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
   lt_status=$lt_dlunknown
   cat > conftest.$ac_ext <<EOF
-#line 9555 "configure"
+#line 8907 "configure"
 #include "confdefs.h"
 
 #if HAVE_DLFCN_H
@@ -9636,8 +8988,8 @@
 
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5
-echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5
+echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6
     fi
 
     CPPFLAGS="$save_CPPFLAGS"
@@ -9659,13 +9011,13 @@
 
 
 # Report which library types will actually be built
-{ echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
-echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6; }
-{ echo "$as_me:$LINENO: result: $can_build_shared" >&5
-echo "${ECHO_T}$can_build_shared" >&6; }
+echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
+echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6
+echo "$as_me:$LINENO: result: $can_build_shared" >&5
+echo "${ECHO_T}$can_build_shared" >&6
 
-{ echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
-echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
+echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6
 test "$can_build_shared" = "no" && enable_shared=no
 
 # On AIX, shared libraries and static libraries use the same namespace, and
@@ -9685,15 +9037,15 @@
   fi
     ;;
 esac
-{ echo "$as_me:$LINENO: result: $enable_shared" >&5
-echo "${ECHO_T}$enable_shared" >&6; }
+echo "$as_me:$LINENO: result: $enable_shared" >&5
+echo "${ECHO_T}$enable_shared" >&6
 
-{ echo "$as_me:$LINENO: checking whether to build static libraries" >&5
-echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether to build static libraries" >&5
+echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6
 # Make sure either enable_shared or enable_static is yes.
 test "$enable_shared" = yes || enable_static=yes
-{ echo "$as_me:$LINENO: result: $enable_static" >&5
-echo "${ECHO_T}$enable_static" >&6; }
+echo "$as_me:$LINENO: result: $enable_static" >&5
+echo "${ECHO_T}$enable_static" >&6
 
 # The else clause should only fire when bootstrapping the
 # libtool distribution, otherwise you forgot to ship ltmain.sh
@@ -10185,11 +9537,11 @@
 CC="$lt_save_CC"
 
 
-# Check whether --with-tags was given.
+# Check whether --with-tags or --without-tags was given.
 if test "${with_tags+set}" = set; then
-  withval=$with_tags; tagnames="$withval"
-fi
-
+  withval="$with_tags"
+  tagnames="$withval"
+fi;
 
 if test -f "$ltmain" && test -n "$tagnames"; then
   if test ! -f "${ofile}"; then
@@ -10243,7 +9595,7 @@
 	if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
 	    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
 	    (test "X$CXX" != "Xg++"))) ; then
-	  ac_ext=cpp
+	  ac_ext=cc
 ac_cpp='$CXXCPP $CPPFLAGS'
 ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
@@ -10362,18 +9714,18 @@
   # Set up default GNU C++ configuration
 
 
-# Check whether --with-gnu-ld was given.
+# Check whether --with-gnu-ld or --without-gnu-ld was given.
 if test "${with_gnu_ld+set}" = set; then
-  withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes
+  withval="$with_gnu_ld"
+  test "$withval" = no || with_gnu_ld=yes
 else
   with_gnu_ld=no
-fi
-
+fi;
 ac_prog=ld
 if test "$GCC" = yes; then
   # Check if gcc -print-prog-name=ld gives a path.
-  { echo "$as_me:$LINENO: checking for ld used by $CC" >&5
-echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for ld used by $CC" >&5
+echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6
   case $host in
   *-*-mingw*)
     # gcc leaves a trailing carriage return which upsets mingw
@@ -10402,11 +9754,11 @@
     ;;
   esac
 elif test "$with_gnu_ld" = yes; then
-  { echo "$as_me:$LINENO: checking for GNU ld" >&5
-echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for GNU ld" >&5
+echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6
 else
-  { echo "$as_me:$LINENO: checking for non-GNU ld" >&5
-echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking for non-GNU ld" >&5
+echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6
 fi
 if test "${lt_cv_path_LD+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
@@ -10439,17 +9791,17 @@
 
 LD="$lt_cv_path_LD"
 if test -n "$LD"; then
-  { echo "$as_me:$LINENO: result: $LD" >&5
-echo "${ECHO_T}$LD" >&6; }
+  echo "$as_me:$LINENO: result: $LD" >&5
+echo "${ECHO_T}$LD" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found in \$PATH" >&5
 echo "$as_me: error: no acceptable ld found in \$PATH" >&2;}
    { (exit 1); exit 1; }; }
-{ echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5
-echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5
+echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6
 if test "${lt_cv_prog_gnu_ld+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -10463,8 +9815,8 @@
   ;;
 esac
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_gnu_ld" >&5
-echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_prog_gnu_ld" >&5
+echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6
 with_gnu_ld=$lt_cv_prog_gnu_ld
 
 
@@ -10514,8 +9866,8 @@
 fi
 
 # PORTME: fill in a description of your system's C++ link characteristics
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
 ld_shlibs_CXX=yes
 case $host_os in
   aix3*)
@@ -10627,23 +9979,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
 
 aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
 }'`
@@ -10654,10 +10010,8 @@
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
@@ -10687,23 +10041,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_cxx_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
 
 aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
 }'`
@@ -10714,10 +10072,8 @@
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
@@ -11448,8 +10804,8 @@
     ld_shlibs_CXX=no
     ;;
 esac
-{ echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5
-echo "${ECHO_T}$ld_shlibs_CXX" >&6; }
+echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5
+echo "${ECHO_T}$ld_shlibs_CXX" >&6
 test "$ld_shlibs_CXX" = no && can_build_shared=no
 
 GCC_CXX="$GXX"
@@ -11588,8 +10944,8 @@
 lt_prog_compiler_pic_CXX=
 lt_prog_compiler_static_CXX=
 
-{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
-echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
+echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
 
   # C++ specific cases for pic, static, wl, etc.
   if test "$GXX" = yes; then
@@ -11862,16 +11218,16 @@
     esac
   fi
 
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_CXX" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_CXX" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_CXX" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_CXX" >&6
 
 #
 # Check to make sure the PIC flag actually works.
 #
 if test -n "$lt_prog_compiler_pic_CXX"; then
 
-{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5
-echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5
+echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... $ECHO_C" >&6
 if test "${lt_prog_compiler_pic_works_CXX+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -11888,11 +11244,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:11891: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:11247: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:11895: \$? = $ac_status" >&5
+   echo "$as_me:11251: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings other than the usual output.
@@ -11905,8 +11261,8 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_CXX" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_works_CXX" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_CXX" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_works_CXX" >&6
 
 if test x"$lt_prog_compiler_pic_works_CXX" = xyes; then
     case $lt_prog_compiler_pic_CXX in
@@ -11933,8 +11289,8 @@
 # Check to make sure the static flag actually works.
 #
 wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\"
-{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
 if test "${lt_prog_compiler_static_works_CXX+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -11961,8 +11317,8 @@
    LDFLAGS="$save_LDFLAGS"
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_CXX" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works_CXX" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_CXX" >&5
+echo "${ECHO_T}$lt_prog_compiler_static_works_CXX" >&6
 
 if test x"$lt_prog_compiler_static_works_CXX" = xyes; then
     :
@@ -11971,8 +11327,8 @@
 fi
 
 
-{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
-echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
+echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
 if test "${lt_cv_prog_compiler_c_o_CXX+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -11992,11 +11348,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:11995: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:11351: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>out/conftest.err)
    ac_status=$?
    cat out/conftest.err >&5
-   echo "$as_me:11999: \$? = $ac_status" >&5
+   echo "$as_me:11355: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s out/conftest2.$ac_objext
    then
      # The compiler can only warn and ignore the option if not recognized
@@ -12018,23 +11374,23 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_CXX" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_c_o_CXX" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_CXX" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_c_o_CXX" >&6
 
 
 hard_links="nottested"
 if test "$lt_cv_prog_compiler_c_o_CXX" = no && test "$need_locks" != no; then
   # do not overwrite the value of need_locks provided by the user
-  { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
-echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
+echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
   hard_links=yes
   $rm conftest*
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
   touch conftest.a
   ln conftest.a conftest.b 2>&5 || hard_links=no
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  { echo "$as_me:$LINENO: result: $hard_links" >&5
-echo "${ECHO_T}$hard_links" >&6; }
+  echo "$as_me:$LINENO: result: $hard_links" >&5
+echo "${ECHO_T}$hard_links" >&6
   if test "$hard_links" = no; then
     { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
 echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
@@ -12044,8 +11400,8 @@
   need_locks=no
 fi
 
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
 
   export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
   case $host_os in
@@ -12069,8 +11425,8 @@
   ;;
   esac
 
-{ echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5
-echo "${ECHO_T}$ld_shlibs_CXX" >&6; }
+echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5
+echo "${ECHO_T}$ld_shlibs_CXX" >&6
 test "$ld_shlibs_CXX" = no && can_build_shared=no
 
 #
@@ -12090,8 +11446,8 @@
       # Test whether the compiler implicitly links with -lc since on some
       # systems, -lgcc has to come before -lc. If gcc already passes -lc
       # to ld, don't add -lc before -lgcc.
-      { echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
-echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6; }
+      echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
+echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
       $rm conftest*
       printf "$lt_simple_compile_test_code" > conftest.$ac_ext
 
@@ -12128,16 +11484,16 @@
         cat conftest.err 1>&5
       fi
       $rm conftest*
-      { echo "$as_me:$LINENO: result: $archive_cmds_need_lc_CXX" >&5
-echo "${ECHO_T}$archive_cmds_need_lc_CXX" >&6; }
+      echo "$as_me:$LINENO: result: $archive_cmds_need_lc_CXX" >&5
+echo "${ECHO_T}$archive_cmds_need_lc_CXX" >&6
       ;;
     esac
   fi
   ;;
 esac
 
-{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
-echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
 library_names_spec=
 libname_spec='lib$name'
 soname_spec=
@@ -12761,8 +12117,8 @@
   dynamic_linker=no
   ;;
 esac
-{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6; }
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
 test "$dynamic_linker" = no && can_build_shared=no
 
 variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
@@ -12770,8 +12126,8 @@
   variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
 fi
 
-{ echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
 hardcode_action_CXX=
 if test -n "$hardcode_libdir_flag_spec_CXX" || \
    test -n "$runpath_var_CXX" || \
@@ -12795,8 +12151,8 @@
   # directories.
   hardcode_action_CXX=unsupported
 fi
-{ echo "$as_me:$LINENO: result: $hardcode_action_CXX" >&5
-echo "${ECHO_T}$hardcode_action_CXX" >&6; }
+echo "$as_me:$LINENO: result: $hardcode_action_CXX" >&5
+echo "${ECHO_T}$hardcode_action_CXX" >&6
 
 if test "$hardcode_action_CXX" = relink; then
   # Fast installation is not supported
@@ -13321,13 +12677,13 @@
 cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
 
 
-{ echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
-echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6; }
-{ echo "$as_me:$LINENO: result: $can_build_shared" >&5
-echo "${ECHO_T}$can_build_shared" >&6; }
+echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
+echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6
+echo "$as_me:$LINENO: result: $can_build_shared" >&5
+echo "${ECHO_T}$can_build_shared" >&6
 
-{ echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
-echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
+echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6
 test "$can_build_shared" = "no" && enable_shared=no
 
 # On AIX, shared libraries and static libraries use the same namespace, and
@@ -13346,15 +12702,15 @@
   fi
   ;;
 esac
-{ echo "$as_me:$LINENO: result: $enable_shared" >&5
-echo "${ECHO_T}$enable_shared" >&6; }
+echo "$as_me:$LINENO: result: $enable_shared" >&5
+echo "${ECHO_T}$enable_shared" >&6
 
-{ echo "$as_me:$LINENO: checking whether to build static libraries" >&5
-echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether to build static libraries" >&5
+echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6
 # Make sure either enable_shared or enable_static is yes.
 test "$enable_shared" = yes || enable_static=yes
-{ echo "$as_me:$LINENO: result: $enable_static" >&5
-echo "${ECHO_T}$enable_static" >&6; }
+echo "$as_me:$LINENO: result: $enable_static" >&5
+echo "${ECHO_T}$enable_static" >&6
 
 GCC_F77="$G77"
 LD_F77="$LD"
@@ -13363,8 +12719,8 @@
 lt_prog_compiler_pic_F77=
 lt_prog_compiler_static_F77=
 
-{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
-echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
+echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
 
   if test "$GCC" = yes; then
     lt_prog_compiler_wl_F77='-Wl,'
@@ -13573,16 +12929,16 @@
     esac
   fi
 
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_F77" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_F77" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_F77" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_F77" >&6
 
 #
 # Check to make sure the PIC flag actually works.
 #
 if test -n "$lt_prog_compiler_pic_F77"; then
 
-{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works" >&5
-echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works" >&5
+echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works... $ECHO_C" >&6
 if test "${lt_prog_compiler_pic_works_F77+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -13599,11 +12955,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:13602: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:12958: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:13606: \$? = $ac_status" >&5
+   echo "$as_me:12962: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings other than the usual output.
@@ -13616,8 +12972,8 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_F77" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_works_F77" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_F77" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_works_F77" >&6
 
 if test x"$lt_prog_compiler_pic_works_F77" = xyes; then
     case $lt_prog_compiler_pic_F77 in
@@ -13644,8 +13000,8 @@
 # Check to make sure the static flag actually works.
 #
 wl=$lt_prog_compiler_wl_F77 eval lt_tmp_static_flag=\"$lt_prog_compiler_static_F77\"
-{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
 if test "${lt_prog_compiler_static_works_F77+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -13672,8 +13028,8 @@
    LDFLAGS="$save_LDFLAGS"
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_F77" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works_F77" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_F77" >&5
+echo "${ECHO_T}$lt_prog_compiler_static_works_F77" >&6
 
 if test x"$lt_prog_compiler_static_works_F77" = xyes; then
     :
@@ -13682,8 +13038,8 @@
 fi
 
 
-{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
-echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
+echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
 if test "${lt_cv_prog_compiler_c_o_F77+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -13703,11 +13059,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:13706: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:13062: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>out/conftest.err)
    ac_status=$?
    cat out/conftest.err >&5
-   echo "$as_me:13710: \$? = $ac_status" >&5
+   echo "$as_me:13066: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s out/conftest2.$ac_objext
    then
      # The compiler can only warn and ignore the option if not recognized
@@ -13729,23 +13085,23 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_F77" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_c_o_F77" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_F77" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_c_o_F77" >&6
 
 
 hard_links="nottested"
 if test "$lt_cv_prog_compiler_c_o_F77" = no && test "$need_locks" != no; then
   # do not overwrite the value of need_locks provided by the user
-  { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
-echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
+echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
   hard_links=yes
   $rm conftest*
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
   touch conftest.a
   ln conftest.a conftest.b 2>&5 || hard_links=no
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  { echo "$as_me:$LINENO: result: $hard_links" >&5
-echo "${ECHO_T}$hard_links" >&6; }
+  echo "$as_me:$LINENO: result: $hard_links" >&5
+echo "${ECHO_T}$hard_links" >&6
   if test "$hard_links" = no; then
     { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
 echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
@@ -13755,8 +13111,8 @@
   need_locks=no
 fi
 
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
 
   runpath_var=
   allow_undefined_flag_F77=
@@ -14161,23 +13517,27 @@
       end
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_f77_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_f77_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
 
 aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
 }'`
@@ -14188,10 +13548,8 @@
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
@@ -14210,23 +13568,27 @@
       end
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_f77_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_f77_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
 
 aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
 }'`
@@ -14237,10 +13599,8 @@
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
@@ -14689,8 +14049,8 @@
     esac
   fi
 
-{ echo "$as_me:$LINENO: result: $ld_shlibs_F77" >&5
-echo "${ECHO_T}$ld_shlibs_F77" >&6; }
+echo "$as_me:$LINENO: result: $ld_shlibs_F77" >&5
+echo "${ECHO_T}$ld_shlibs_F77" >&6
 test "$ld_shlibs_F77" = no && can_build_shared=no
 
 #
@@ -14710,8 +14070,8 @@
       # Test whether the compiler implicitly links with -lc since on some
       # systems, -lgcc has to come before -lc. If gcc already passes -lc
       # to ld, don't add -lc before -lgcc.
-      { echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
-echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6; }
+      echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
+echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
       $rm conftest*
       printf "$lt_simple_compile_test_code" > conftest.$ac_ext
 
@@ -14748,16 +14108,16 @@
         cat conftest.err 1>&5
       fi
       $rm conftest*
-      { echo "$as_me:$LINENO: result: $archive_cmds_need_lc_F77" >&5
-echo "${ECHO_T}$archive_cmds_need_lc_F77" >&6; }
+      echo "$as_me:$LINENO: result: $archive_cmds_need_lc_F77" >&5
+echo "${ECHO_T}$archive_cmds_need_lc_F77" >&6
       ;;
     esac
   fi
   ;;
 esac
 
-{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
-echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
 library_names_spec=
 libname_spec='lib$name'
 soname_spec=
@@ -15381,8 +14741,8 @@
   dynamic_linker=no
   ;;
 esac
-{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6; }
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
 test "$dynamic_linker" = no && can_build_shared=no
 
 variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
@@ -15390,8 +14750,8 @@
   variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
 fi
 
-{ echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
 hardcode_action_F77=
 if test -n "$hardcode_libdir_flag_spec_F77" || \
    test -n "$runpath_var_F77" || \
@@ -15415,8 +14775,8 @@
   # directories.
   hardcode_action_F77=unsupported
 fi
-{ echo "$as_me:$LINENO: result: $hardcode_action_F77" >&5
-echo "${ECHO_T}$hardcode_action_F77" >&6; }
+echo "$as_me:$LINENO: result: $hardcode_action_F77" >&5
+echo "${ECHO_T}$hardcode_action_F77" >&6
 
 if test "$hardcode_action_F77" = relink; then
   # Fast installation is not supported
@@ -15853,6 +15213,7 @@
 	if test -n "$GCJ" && test "X$GCJ" != "Xno"; then
 
 
+
 # Source file extension for Java test sources.
 ac_ext=java
 
@@ -15920,8 +15281,8 @@
   lt_prog_compiler_no_builtin_flag_GCJ=' -fno-builtin'
 
 
-{ echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5
-echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5
+echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6
 if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -15938,11 +15299,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:15941: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:15302: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:15945: \$? = $ac_status" >&5
+   echo "$as_me:15306: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings other than the usual output.
@@ -15955,8 +15316,8 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6
 
 if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then
     lt_prog_compiler_no_builtin_flag_GCJ="$lt_prog_compiler_no_builtin_flag_GCJ -fno-rtti -fno-exceptions"
@@ -15970,8 +15331,8 @@
 lt_prog_compiler_pic_GCJ=
 lt_prog_compiler_static_GCJ=
 
-{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
-echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
+echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
 
   if test "$GCC" = yes; then
     lt_prog_compiler_wl_GCJ='-Wl,'
@@ -16180,16 +15541,16 @@
     esac
   fi
 
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_GCJ" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_GCJ" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_GCJ" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_GCJ" >&6
 
 #
 # Check to make sure the PIC flag actually works.
 #
 if test -n "$lt_prog_compiler_pic_GCJ"; then
 
-{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works" >&5
-echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works" >&5
+echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works... $ECHO_C" >&6
 if test "${lt_prog_compiler_pic_works_GCJ+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -16206,11 +15567,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:16209: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:15570: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&5
-   echo "$as_me:16213: \$? = $ac_status" >&5
+   echo "$as_me:15574: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings other than the usual output.
@@ -16223,8 +15584,8 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_GCJ" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_works_GCJ" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_GCJ" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_works_GCJ" >&6
 
 if test x"$lt_prog_compiler_pic_works_GCJ" = xyes; then
     case $lt_prog_compiler_pic_GCJ in
@@ -16251,8 +15612,8 @@
 # Check to make sure the static flag actually works.
 #
 wl=$lt_prog_compiler_wl_GCJ eval lt_tmp_static_flag=\"$lt_prog_compiler_static_GCJ\"
-{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
 if test "${lt_prog_compiler_static_works_GCJ+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -16279,8 +15640,8 @@
    LDFLAGS="$save_LDFLAGS"
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_GCJ" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works_GCJ" >&6; }
+echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_GCJ" >&5
+echo "${ECHO_T}$lt_prog_compiler_static_works_GCJ" >&6
 
 if test x"$lt_prog_compiler_static_works_GCJ" = xyes; then
     :
@@ -16289,8 +15650,8 @@
 fi
 
 
-{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
-echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
+echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
 if test "${lt_cv_prog_compiler_c_o_GCJ+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -16310,11 +15671,11 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:16313: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:15674: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>out/conftest.err)
    ac_status=$?
    cat out/conftest.err >&5
-   echo "$as_me:16317: \$? = $ac_status" >&5
+   echo "$as_me:15678: \$? = $ac_status" >&5
    if (exit $ac_status) && test -s out/conftest2.$ac_objext
    then
      # The compiler can only warn and ignore the option if not recognized
@@ -16336,23 +15697,23 @@
    $rm conftest*
 
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_GCJ" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_c_o_GCJ" >&6; }
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_GCJ" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_c_o_GCJ" >&6
 
 
 hard_links="nottested"
 if test "$lt_cv_prog_compiler_c_o_GCJ" = no && test "$need_locks" != no; then
   # do not overwrite the value of need_locks provided by the user
-  { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
-echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; }
+  echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
+echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
   hard_links=yes
   $rm conftest*
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
   touch conftest.a
   ln conftest.a conftest.b 2>&5 || hard_links=no
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  { echo "$as_me:$LINENO: result: $hard_links" >&5
-echo "${ECHO_T}$hard_links" >&6; }
+  echo "$as_me:$LINENO: result: $hard_links" >&5
+echo "${ECHO_T}$hard_links" >&6
   if test "$hard_links" = no; then
     { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
 echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
@@ -16362,8 +15723,8 @@
   need_locks=no
 fi
 
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
 
   runpath_var=
   allow_undefined_flag_GCJ=
@@ -16778,23 +16139,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
 
 aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
 }'`
@@ -16805,10 +16170,8 @@
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
@@ -16837,23 +16200,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
 
 aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
 }'`
@@ -16864,10 +16231,8 @@
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
 
@@ -17316,8 +16681,8 @@
     esac
   fi
 
-{ echo "$as_me:$LINENO: result: $ld_shlibs_GCJ" >&5
-echo "${ECHO_T}$ld_shlibs_GCJ" >&6; }
+echo "$as_me:$LINENO: result: $ld_shlibs_GCJ" >&5
+echo "${ECHO_T}$ld_shlibs_GCJ" >&6
 test "$ld_shlibs_GCJ" = no && can_build_shared=no
 
 #
@@ -17337,8 +16702,8 @@
       # Test whether the compiler implicitly links with -lc since on some
       # systems, -lgcc has to come before -lc. If gcc already passes -lc
       # to ld, don't add -lc before -lgcc.
-      { echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
-echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6; }
+      echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
+echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
       $rm conftest*
       printf "$lt_simple_compile_test_code" > conftest.$ac_ext
 
@@ -17375,16 +16740,16 @@
         cat conftest.err 1>&5
       fi
       $rm conftest*
-      { echo "$as_me:$LINENO: result: $archive_cmds_need_lc_GCJ" >&5
-echo "${ECHO_T}$archive_cmds_need_lc_GCJ" >&6; }
+      echo "$as_me:$LINENO: result: $archive_cmds_need_lc_GCJ" >&5
+echo "${ECHO_T}$archive_cmds_need_lc_GCJ" >&6
       ;;
     esac
   fi
   ;;
 esac
 
-{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
-echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
 library_names_spec=
 libname_spec='lib$name'
 soname_spec=
@@ -18008,8 +17373,8 @@
   dynamic_linker=no
   ;;
 esac
-{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6; }
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
 test "$dynamic_linker" = no && can_build_shared=no
 
 variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
@@ -18017,8 +17382,8 @@
   variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
 fi
 
-{ echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
 hardcode_action_GCJ=
 if test -n "$hardcode_libdir_flag_spec_GCJ" || \
    test -n "$runpath_var_GCJ" || \
@@ -18042,8 +17407,8 @@
   # directories.
   hardcode_action_GCJ=unsupported
 fi
-{ echo "$as_me:$LINENO: result: $hardcode_action_GCJ" >&5
-echo "${ECHO_T}$hardcode_action_GCJ" >&6; }
+echo "$as_me:$LINENO: result: $hardcode_action_GCJ" >&5
+echo "${ECHO_T}$hardcode_action_GCJ" >&6
 
 if test "$hardcode_action_GCJ" = relink; then
   # Fast installation is not supported
@@ -18479,6 +17844,7 @@
       RC)
 
 
+
 # Source file extension for RC test sources.
 ac_ext=rc
 
@@ -19022,8 +18388,8 @@
 # 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.
-{ echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5
-echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5
+echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6
 if test -z "$INSTALL"; then
 if test "${ac_cv_path_install+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
@@ -19045,7 +18411,7 @@
     # 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 $as_executable_p "$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.
@@ -19064,22 +18430,21 @@
     ;;
 esac
 done
-IFS=$as_save_IFS
 
 
 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
+    # As a last resort, use the slow shell script.  We don't cache a
+    # path 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.
+    # removed, or if the path is relative.
     INSTALL=$ac_install_sh
   fi
 fi
-{ echo "$as_me:$LINENO: result: $INSTALL" >&5
-echo "${ECHO_T}$INSTALL" >&6; }
+echo "$as_me:$LINENO: result: $INSTALL" >&5
+echo "${ECHO_T}$INSTALL" >&6
 
 # Use test -z because SunOS4 sh mishandles braces in ${var-val}.
 # It thinks the first close brace ends the variable substitution.
@@ -19089,21 +18454,21 @@
 
 test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
 
-{ echo "$as_me:$LINENO: checking whether ln -s works" >&5
-echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether ln -s works" >&5
+echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6
 LN_S=$as_ln_s
 if test "$LN_S" = "ln -s"; then
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+  echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
 else
-  { echo "$as_me:$LINENO: result: no, using $LN_S" >&5
-echo "${ECHO_T}no, using $LN_S" >&6; }
+  echo "$as_me:$LINENO: result: no, using $LN_S" >&5
+echo "${ECHO_T}no, using $LN_S" >&6
 fi
 
 # Extract the first word of "ar", so it can be a program name with args.
 set dummy ar; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_path_AR+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -19118,37 +18483,36 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_path_AR="$as_dir/$ac_word$ac_exec_ext"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
   test -z "$ac_cv_path_AR" && ac_cv_path_AR="no"
   ;;
 esac
 fi
 AR=$ac_cv_path_AR
+
 if test -n "$AR"; then
-  { echo "$as_me:$LINENO: result: $AR" >&5
-echo "${ECHO_T}$AR" >&6; }
+  echo "$as_me:$LINENO: result: $AR" >&5
+echo "${ECHO_T}$AR" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
 if [ $AR = "no" ] ; then
     { { echo "$as_me:$LINENO: error: \"Could not find ar - needed to create a library\"" >&5
 echo "$as_me: error: \"Could not find ar - needed to create a library\"" >&2;}
    { (exit 1); exit 1; }; };
 fi
 
-{ echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5
-echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5
+echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6
 if test "${ac_cv_c_bigendian+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -19165,8 +18529,7 @@
 int
 main ()
 {
-#if  ! (defined BYTE_ORDER && defined BIG_ENDIAN && defined LITTLE_ENDIAN \
-	&& BYTE_ORDER && BIG_ENDIAN && LITTLE_ENDIAN)
+#if !BYTE_ORDER || !BIG_ENDIAN || !LITTLE_ENDIAN
  bogus endian macros
 #endif
 
@@ -19175,22 +18538,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   # It does; now see whether it defined to BIG_ENDIAN or not.
 cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -19213,36 +18581,40 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_c_bigendian=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_c_bigendian=no
+ac_cv_c_bigendian=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	# It does not; compile a test program.
+# It does not; compile a test program.
 if test "$cross_compiling" = yes; then
   # try to guess the endianness by grepping values into an object file
   ac_cv_c_bigendian=unknown
@@ -19252,11 +18624,11 @@
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
-short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
+short ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
+short ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
 void _ascii () { char *s = (char *) ascii_mm; s = (char *) ascii_ii; }
-short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
-short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
+short ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
+short ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
 void _ebcdic () { char *s = (char *) ebcdic_mm; s = (char *) ebcdic_ii; }
 int
 main ()
@@ -19267,22 +18639,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   if grep BIGenDianSyS conftest.$ac_objext >/dev/null ; then
   ac_cv_c_bigendian=yes
 fi
@@ -19298,10 +18675,8 @@
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 else
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -19309,41 +18684,27 @@
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-$ac_includes_default
 int
 main ()
 {
-
   /* Are we little or big endian?  From Harbison&Steele.  */
   union
   {
-    long int l;
-    char c[sizeof (long int)];
+    long l;
+    char c[sizeof (long)];
   } u;
   u.l = 1;
-  return u.c[sizeof (long int) - 1] == 1;
-
-  ;
-  return 0;
+  exit (u.c[sizeof (long) - 1] == 1);
 }
 _ACEOF
 rm -f conftest$ac_exeext
-if { (ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; }; then
@@ -19356,16 +18717,13 @@
 ( exit $ac_status )
 ac_cv_c_bigendian=yes
 fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
-
-
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5
-echo "${ECHO_T}$ac_cv_c_bigendian" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5
+echo "${ECHO_T}$ac_cv_c_bigendian" >&6
 case $ac_cv_c_bigendian in
   yes)
 
@@ -19385,8 +18743,8 @@
 
 
 
-{ echo "$as_me:$LINENO: checking for snd_pcm_open in -lasound" >&5
-echo $ECHO_N "checking for snd_pcm_open in -lasound... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for snd_pcm_open in -lasound" >&5
+echo $ECHO_N "checking for snd_pcm_open in -lasound... $ECHO_C" >&6
 if test "${ac_cv_lib_asound_snd_pcm_open+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -19399,61 +18757,64 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char snd_pcm_open ();
 int
 main ()
 {
-return snd_pcm_open ();
+snd_pcm_open ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_asound_snd_pcm_open=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_asound_snd_pcm_open=no
+ac_cv_lib_asound_snd_pcm_open=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_asound_snd_pcm_open" >&5
-echo "${ECHO_T}$ac_cv_lib_asound_snd_pcm_open" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_asound_snd_pcm_open" >&5
+echo "${ECHO_T}$ac_cv_lib_asound_snd_pcm_open" >&6
 if test $ac_cv_lib_asound_snd_pcm_open = yes; then
   have_alsa=yes
 else
   have_alsa=no
 fi
 
-{ echo "$as_me:$LINENO: checking for HPI_SubSysCreate in -lhpi" >&5
-echo $ECHO_N "checking for HPI_SubSysCreate in -lhpi... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for HPI_SubSysCreate in -lhpi" >&5
+echo $ECHO_N "checking for HPI_SubSysCreate in -lhpi... $ECHO_C" >&6
 if test "${ac_cv_lib_hpi_HPI_SubSysCreate+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -19466,53 +18827,56 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char HPI_SubSysCreate ();
 int
 main ()
 {
-return HPI_SubSysCreate ();
+HPI_SubSysCreate ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_hpi_HPI_SubSysCreate=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_hpi_HPI_SubSysCreate=no
+ac_cv_lib_hpi_HPI_SubSysCreate=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_hpi_HPI_SubSysCreate" >&5
-echo "${ECHO_T}$ac_cv_lib_hpi_HPI_SubSysCreate" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_hpi_HPI_SubSysCreate" >&5
+echo "${ECHO_T}$ac_cv_lib_hpi_HPI_SubSysCreate" >&6
 if test $ac_cv_lib_hpi_HPI_SubSysCreate = yes; then
   have_asihpi=yes
 else
@@ -19527,8 +18891,8 @@
 	if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args.
 set dummy ${ac_tool_prefix}pkg-config; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_path_PKG_CONFIG+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -19543,35 +18907,34 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
   ;;
 esac
 fi
 PKG_CONFIG=$ac_cv_path_PKG_CONFIG
+
 if test -n "$PKG_CONFIG"; then
-  { echo "$as_me:$LINENO: result: $PKG_CONFIG" >&5
-echo "${ECHO_T}$PKG_CONFIG" >&6; }
+  echo "$as_me:$LINENO: result: $PKG_CONFIG" >&5
+echo "${ECHO_T}$PKG_CONFIG" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-
 fi
 if test -z "$ac_cv_path_PKG_CONFIG"; then
   ac_pt_PKG_CONFIG=$PKG_CONFIG
   # Extract the first word of "pkg-config", so it can be a program name with args.
 set dummy pkg-config; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
 if test "${ac_cv_path_ac_pt_PKG_CONFIG+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -19586,42 +18949,28 @@
   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 $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
-IFS=$as_save_IFS
 
   ;;
 esac
 fi
 ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG
+
 if test -n "$ac_pt_PKG_CONFIG"; then
-  { echo "$as_me:$LINENO: result: $ac_pt_PKG_CONFIG" >&5
-echo "${ECHO_T}$ac_pt_PKG_CONFIG" >&6; }
+  echo "$as_me:$LINENO: result: $ac_pt_PKG_CONFIG" >&5
+echo "${ECHO_T}$ac_pt_PKG_CONFIG" >&6
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 fi
 
-  if test "x$ac_pt_PKG_CONFIG" = x; then
-    PKG_CONFIG=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=yes ;;
-esac
-    PKG_CONFIG=$ac_pt_PKG_CONFIG
-  fi
+  PKG_CONFIG=$ac_pt_PKG_CONFIG
 else
   PKG_CONFIG="$ac_cv_path_PKG_CONFIG"
 fi
@@ -19629,22 +18978,22 @@
 fi
 if test -n "$PKG_CONFIG"; then
 	_pkg_min_version=0.9.0
-	{ echo "$as_me:$LINENO: checking pkg-config is at least version $_pkg_min_version" >&5
-echo $ECHO_N "checking pkg-config is at least version $_pkg_min_version... $ECHO_C" >&6; }
+	echo "$as_me:$LINENO: checking pkg-config is at least version $_pkg_min_version" >&5
+echo $ECHO_N "checking pkg-config is at least version $_pkg_min_version... $ECHO_C" >&6
 	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
-		{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+		echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
 	else
-		{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+		echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
 		PKG_CONFIG=""
 	fi
 
 fi
 
 pkg_failed=no
-{ echo "$as_me:$LINENO: checking for JACK" >&5
-echo $ECHO_N "checking for JACK... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for JACK" >&5
+echo $ECHO_N "checking for JACK... $ECHO_C" >&6
 
 if test -n "$PKG_CONFIG"; then
     if test -n "$JACK_CFLAGS"; then
@@ -19706,14 +19055,14 @@
 else
 	JACK_CFLAGS=$pkg_cv_JACK_CFLAGS
 	JACK_LIBS=$pkg_cv_JACK_LIBS
-        { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+        echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
 	have_jack=yes
 fi
 
 
-{ echo "$as_me:$LINENO: checking for short" >&5
-echo $ECHO_N "checking for short... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for short" >&5
+echo $ECHO_N "checking for short... $ECHO_C" >&6
 if test "${ac_cv_type_short+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -19724,57 +19073,61 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-typedef short ac__type_new_;
 int
 main ()
 {
-if ((ac__type_new_ *) 0)
+if ((short *) 0)
   return 0;
-if (sizeof (ac__type_new_))
+if (sizeof (short))
   return 0;
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_type_short=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_type_short=no
+ac_cv_type_short=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_short" >&5
-echo "${ECHO_T}$ac_cv_type_short" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_type_short" >&5
+echo "${ECHO_T}$ac_cv_type_short" >&6
 
-# The cast to long int works around a bug in the HP C Compiler
-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
-# This bug is HP SR number 8606223364.
-{ echo "$as_me:$LINENO: checking size of short" >&5
-echo $ECHO_N "checking size of short... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking size of short" >&5
+echo $ECHO_N "checking size of short... $ECHO_C" >&6
 if test "${ac_cv_sizeof_short+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
+  if test "$ac_cv_type_short" = yes; then
+  # The cast to unsigned long works around a bug in the HP C Compiler
+  # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
+  # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
+  # This bug is HP SR number 8606223364.
   if test "$cross_compiling" = yes; then
   # Depending upon the size, compute the lo and hi bounds.
 cat >conftest.$ac_ext <<_ACEOF
@@ -19784,11 +19137,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef short ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)];
+static int test_array [1 - 2 * !(((long) (sizeof (short))) >= 0)];
 test_array [0] = 0
 
   ;
@@ -19796,22 +19148,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_lo=0 ac_mid=0
   while :; do
     cat >conftest.$ac_ext <<_ACEOF
@@ -19821,11 +19178,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef short ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)];
+static int test_array [1 - 2 * !(((long) (sizeof (short))) <= $ac_mid)];
 test_array [0] = 0
 
   ;
@@ -19833,53 +19189,56 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_hi=$ac_mid; break
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_lo=`expr $ac_mid + 1`
-			if test $ac_lo -le $ac_mid; then
-			  ac_lo= ac_hi=
-			  break
-			fi
-			ac_mid=`expr 2 '*' $ac_mid + 1`
+ac_lo=`expr $ac_mid + 1`
+		    if test $ac_lo -le $ac_mid; then
+		      ac_lo= ac_hi=
+		      break
+		    fi
+		    ac_mid=`expr 2 '*' $ac_mid + 1`
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
   done
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	cat >conftest.$ac_ext <<_ACEOF
+cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef short ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)];
+static int test_array [1 - 2 * !(((long) (sizeof (short))) < 0)];
 test_array [0] = 0
 
   ;
@@ -19887,22 +19246,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_hi=-1 ac_mid=-1
   while :; do
     cat >conftest.$ac_ext <<_ACEOF
@@ -19912,11 +19276,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef short ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)];
+static int test_array [1 - 2 * !(((long) (sizeof (short))) >= $ac_mid)];
 test_array [0] = 0
 
   ;
@@ -19924,48 +19287,50 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_lo=$ac_mid; break
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_hi=`expr '(' $ac_mid ')' - 1`
-			if test $ac_mid -le $ac_hi; then
-			  ac_lo= ac_hi=
-			  break
-			fi
-			ac_mid=`expr 2 '*' $ac_mid`
+ac_hi=`expr '(' $ac_mid ')' - 1`
+		       if test $ac_mid -le $ac_hi; then
+			 ac_lo= ac_hi=
+			 break
+		       fi
+		       ac_mid=`expr 2 '*' $ac_mid`
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
   done
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_lo= ac_hi=
+ac_lo= ac_hi=
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 # Binary search between lo and hi bounds.
 while test "x$ac_lo" != "x$ac_hi"; do
   ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo`
@@ -19976,11 +19341,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef short ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)];
+static int test_array [1 - 2 * !(((long) (sizeof (short))) <= $ac_mid)];
 test_array [0] = 0
 
   ;
@@ -19988,45 +19352,52 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_hi=$ac_mid
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_lo=`expr '(' $ac_mid ')' + 1`
+ac_lo=`expr '(' $ac_mid ')' + 1`
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 done
 case $ac_lo in
 ?*) ac_cv_sizeof_short=$ac_lo;;
-'') if test "$ac_cv_type_short" = yes; then
-     { { echo "$as_me:$LINENO: error: cannot compute sizeof (short)
+'') { { echo "$as_me:$LINENO: error: cannot compute sizeof (short), 77
 See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute sizeof (short)
+echo "$as_me: error: cannot compute sizeof (short), 77
 See \`config.log' for more details." >&2;}
-   { (exit 77); exit 77; }; }
-   else
-     ac_cv_sizeof_short=0
-   fi ;;
+   { (exit 1); exit 1; }; } ;;
 esac
 else
+  if test "$cross_compiling" = yes; then
+  { { echo "$as_me:$LINENO: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
+else
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
@@ -20034,9 +19405,8 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef short ac__type_sizeof_;
-static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); }
-static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); }
+long longval () { return (long) (sizeof (short)); }
+unsigned long ulongval () { return (long) (sizeof (short)); }
 #include <stdio.h>
 #include <stdlib.h>
 int
@@ -20045,44 +19415,35 @@
 
   FILE *f = fopen ("conftest.val", "w");
   if (! f)
-    return 1;
-  if (((long int) (sizeof (ac__type_sizeof_))) < 0)
+    exit (1);
+  if (((long) (sizeof (short))) < 0)
     {
-      long int i = longval ();
-      if (i != ((long int) (sizeof (ac__type_sizeof_))))
-	return 1;
+      long i = longval ();
+      if (i != ((long) (sizeof (short))))
+	exit (1);
       fprintf (f, "%ld\n", i);
     }
   else
     {
-      unsigned long int i = ulongval ();
-      if (i != ((long int) (sizeof (ac__type_sizeof_))))
-	return 1;
+      unsigned long i = ulongval ();
+      if (i != ((long) (sizeof (short))))
+	exit (1);
       fprintf (f, "%lu\n", i);
     }
-  return ferror (f) || fclose (f) != 0;
+  exit (ferror (f) || fclose (f) != 0);
 
   ;
   return 0;
 }
 _ACEOF
 rm -f conftest$ac_exeext
-if { (ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; }; then
@@ -20093,32 +19454,29 @@
 sed 's/^/| /' conftest.$ac_ext >&5
 
 ( exit $ac_status )
-if test "$ac_cv_type_short" = yes; then
-     { { echo "$as_me:$LINENO: error: cannot compute sizeof (short)
+{ { echo "$as_me:$LINENO: error: cannot compute sizeof (short), 77
 See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute sizeof (short)
+echo "$as_me: error: cannot compute sizeof (short), 77
 See \`config.log' for more details." >&2;}
-   { (exit 77); exit 77; }; }
-   else
-     ac_cv_sizeof_short=0
-   fi
+   { (exit 1); exit 1; }; }
+fi
+rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
 rm -f conftest.val
+else
+  ac_cv_sizeof_short=0
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_short" >&5
-echo "${ECHO_T}$ac_cv_sizeof_short" >&6; }
-
-
-
+fi
+echo "$as_me:$LINENO: result: $ac_cv_sizeof_short" >&5
+echo "${ECHO_T}$ac_cv_sizeof_short" >&6
 cat >>confdefs.h <<_ACEOF
 #define SIZEOF_SHORT $ac_cv_sizeof_short
 _ACEOF
 
 
-{ echo "$as_me:$LINENO: checking for int" >&5
-echo $ECHO_N "checking for int... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for int" >&5
+echo $ECHO_N "checking for int... $ECHO_C" >&6
 if test "${ac_cv_type_int+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -20129,57 +19487,61 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-typedef int ac__type_new_;
 int
 main ()
 {
-if ((ac__type_new_ *) 0)
+if ((int *) 0)
   return 0;
-if (sizeof (ac__type_new_))
+if (sizeof (int))
   return 0;
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_type_int=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_type_int=no
+ac_cv_type_int=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_int" >&5
-echo "${ECHO_T}$ac_cv_type_int" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_type_int" >&5
+echo "${ECHO_T}$ac_cv_type_int" >&6
 
-# The cast to long int works around a bug in the HP C Compiler
-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
-# This bug is HP SR number 8606223364.
-{ echo "$as_me:$LINENO: checking size of int" >&5
-echo $ECHO_N "checking size of int... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking size of int" >&5
+echo $ECHO_N "checking size of int... $ECHO_C" >&6
 if test "${ac_cv_sizeof_int+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
+  if test "$ac_cv_type_int" = yes; then
+  # The cast to unsigned long works around a bug in the HP C Compiler
+  # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
+  # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
+  # This bug is HP SR number 8606223364.
   if test "$cross_compiling" = yes; then
   # Depending upon the size, compute the lo and hi bounds.
 cat >conftest.$ac_ext <<_ACEOF
@@ -20189,11 +19551,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef int ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)];
+static int test_array [1 - 2 * !(((long) (sizeof (int))) >= 0)];
 test_array [0] = 0
 
   ;
@@ -20201,22 +19562,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_lo=0 ac_mid=0
   while :; do
     cat >conftest.$ac_ext <<_ACEOF
@@ -20226,11 +19592,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef int ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)];
+static int test_array [1 - 2 * !(((long) (sizeof (int))) <= $ac_mid)];
 test_array [0] = 0
 
   ;
@@ -20238,53 +19603,56 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_hi=$ac_mid; break
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_lo=`expr $ac_mid + 1`
-			if test $ac_lo -le $ac_mid; then
-			  ac_lo= ac_hi=
-			  break
-			fi
-			ac_mid=`expr 2 '*' $ac_mid + 1`
+ac_lo=`expr $ac_mid + 1`
+		    if test $ac_lo -le $ac_mid; then
+		      ac_lo= ac_hi=
+		      break
+		    fi
+		    ac_mid=`expr 2 '*' $ac_mid + 1`
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
   done
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	cat >conftest.$ac_ext <<_ACEOF
+cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef int ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)];
+static int test_array [1 - 2 * !(((long) (sizeof (int))) < 0)];
 test_array [0] = 0
 
   ;
@@ -20292,22 +19660,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_hi=-1 ac_mid=-1
   while :; do
     cat >conftest.$ac_ext <<_ACEOF
@@ -20317,11 +19690,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef int ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)];
+static int test_array [1 - 2 * !(((long) (sizeof (int))) >= $ac_mid)];
 test_array [0] = 0
 
   ;
@@ -20329,48 +19701,50 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_lo=$ac_mid; break
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_hi=`expr '(' $ac_mid ')' - 1`
-			if test $ac_mid -le $ac_hi; then
-			  ac_lo= ac_hi=
-			  break
-			fi
-			ac_mid=`expr 2 '*' $ac_mid`
+ac_hi=`expr '(' $ac_mid ')' - 1`
+		       if test $ac_mid -le $ac_hi; then
+			 ac_lo= ac_hi=
+			 break
+		       fi
+		       ac_mid=`expr 2 '*' $ac_mid`
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
   done
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_lo= ac_hi=
+ac_lo= ac_hi=
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 # Binary search between lo and hi bounds.
 while test "x$ac_lo" != "x$ac_hi"; do
   ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo`
@@ -20381,11 +19755,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef int ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)];
+static int test_array [1 - 2 * !(((long) (sizeof (int))) <= $ac_mid)];
 test_array [0] = 0
 
   ;
@@ -20393,45 +19766,52 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_hi=$ac_mid
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_lo=`expr '(' $ac_mid ')' + 1`
+ac_lo=`expr '(' $ac_mid ')' + 1`
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 done
 case $ac_lo in
 ?*) ac_cv_sizeof_int=$ac_lo;;
-'') if test "$ac_cv_type_int" = yes; then
-     { { echo "$as_me:$LINENO: error: cannot compute sizeof (int)
+'') { { echo "$as_me:$LINENO: error: cannot compute sizeof (int), 77
 See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute sizeof (int)
+echo "$as_me: error: cannot compute sizeof (int), 77
 See \`config.log' for more details." >&2;}
-   { (exit 77); exit 77; }; }
-   else
-     ac_cv_sizeof_int=0
-   fi ;;
+   { (exit 1); exit 1; }; } ;;
 esac
 else
+  if test "$cross_compiling" = yes; then
+  { { echo "$as_me:$LINENO: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
+else
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
@@ -20439,9 +19819,8 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef int ac__type_sizeof_;
-static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); }
-static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); }
+long longval () { return (long) (sizeof (int)); }
+unsigned long ulongval () { return (long) (sizeof (int)); }
 #include <stdio.h>
 #include <stdlib.h>
 int
@@ -20450,44 +19829,35 @@
 
   FILE *f = fopen ("conftest.val", "w");
   if (! f)
-    return 1;
-  if (((long int) (sizeof (ac__type_sizeof_))) < 0)
+    exit (1);
+  if (((long) (sizeof (int))) < 0)
     {
-      long int i = longval ();
-      if (i != ((long int) (sizeof (ac__type_sizeof_))))
-	return 1;
+      long i = longval ();
+      if (i != ((long) (sizeof (int))))
+	exit (1);
       fprintf (f, "%ld\n", i);
     }
   else
     {
-      unsigned long int i = ulongval ();
-      if (i != ((long int) (sizeof (ac__type_sizeof_))))
-	return 1;
+      unsigned long i = ulongval ();
+      if (i != ((long) (sizeof (int))))
+	exit (1);
       fprintf (f, "%lu\n", i);
     }
-  return ferror (f) || fclose (f) != 0;
+  exit (ferror (f) || fclose (f) != 0);
 
   ;
   return 0;
 }
 _ACEOF
 rm -f conftest$ac_exeext
-if { (ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; }; then
@@ -20498,32 +19868,29 @@
 sed 's/^/| /' conftest.$ac_ext >&5
 
 ( exit $ac_status )
-if test "$ac_cv_type_int" = yes; then
-     { { echo "$as_me:$LINENO: error: cannot compute sizeof (int)
+{ { echo "$as_me:$LINENO: error: cannot compute sizeof (int), 77
 See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute sizeof (int)
+echo "$as_me: error: cannot compute sizeof (int), 77
 See \`config.log' for more details." >&2;}
-   { (exit 77); exit 77; }; }
-   else
-     ac_cv_sizeof_int=0
-   fi
+   { (exit 1); exit 1; }; }
+fi
+rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
 rm -f conftest.val
+else
+  ac_cv_sizeof_int=0
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_int" >&5
-echo "${ECHO_T}$ac_cv_sizeof_int" >&6; }
-
-
-
+fi
+echo "$as_me:$LINENO: result: $ac_cv_sizeof_int" >&5
+echo "${ECHO_T}$ac_cv_sizeof_int" >&6
 cat >>confdefs.h <<_ACEOF
 #define SIZEOF_INT $ac_cv_sizeof_int
 _ACEOF
 
 
-{ echo "$as_me:$LINENO: checking for long" >&5
-echo $ECHO_N "checking for long... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for long" >&5
+echo $ECHO_N "checking for long... $ECHO_C" >&6
 if test "${ac_cv_type_long+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -20534,57 +19901,61 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-typedef long ac__type_new_;
 int
 main ()
 {
-if ((ac__type_new_ *) 0)
+if ((long *) 0)
   return 0;
-if (sizeof (ac__type_new_))
+if (sizeof (long))
   return 0;
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_type_long=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_type_long=no
+ac_cv_type_long=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_long" >&5
-echo "${ECHO_T}$ac_cv_type_long" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_type_long" >&5
+echo "${ECHO_T}$ac_cv_type_long" >&6
 
-# The cast to long int works around a bug in the HP C Compiler
-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
-# This bug is HP SR number 8606223364.
-{ echo "$as_me:$LINENO: checking size of long" >&5
-echo $ECHO_N "checking size of long... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking size of long" >&5
+echo $ECHO_N "checking size of long... $ECHO_C" >&6
 if test "${ac_cv_sizeof_long+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
+  if test "$ac_cv_type_long" = yes; then
+  # The cast to unsigned long works around a bug in the HP C Compiler
+  # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
+  # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
+  # This bug is HP SR number 8606223364.
   if test "$cross_compiling" = yes; then
   # Depending upon the size, compute the lo and hi bounds.
 cat >conftest.$ac_ext <<_ACEOF
@@ -20594,11 +19965,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef long ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)];
+static int test_array [1 - 2 * !(((long) (sizeof (long))) >= 0)];
 test_array [0] = 0
 
   ;
@@ -20606,22 +19976,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_lo=0 ac_mid=0
   while :; do
     cat >conftest.$ac_ext <<_ACEOF
@@ -20631,11 +20006,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef long ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)];
+static int test_array [1 - 2 * !(((long) (sizeof (long))) <= $ac_mid)];
 test_array [0] = 0
 
   ;
@@ -20643,53 +20017,56 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_hi=$ac_mid; break
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_lo=`expr $ac_mid + 1`
-			if test $ac_lo -le $ac_mid; then
-			  ac_lo= ac_hi=
-			  break
-			fi
-			ac_mid=`expr 2 '*' $ac_mid + 1`
+ac_lo=`expr $ac_mid + 1`
+		    if test $ac_lo -le $ac_mid; then
+		      ac_lo= ac_hi=
+		      break
+		    fi
+		    ac_mid=`expr 2 '*' $ac_mid + 1`
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
   done
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	cat >conftest.$ac_ext <<_ACEOF
+cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef long ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)];
+static int test_array [1 - 2 * !(((long) (sizeof (long))) < 0)];
 test_array [0] = 0
 
   ;
@@ -20697,22 +20074,27 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_hi=-1 ac_mid=-1
   while :; do
     cat >conftest.$ac_ext <<_ACEOF
@@ -20722,11 +20104,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef long ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)];
+static int test_array [1 - 2 * !(((long) (sizeof (long))) >= $ac_mid)];
 test_array [0] = 0
 
   ;
@@ -20734,48 +20115,50 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_lo=$ac_mid; break
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_hi=`expr '(' $ac_mid ')' - 1`
-			if test $ac_mid -le $ac_hi; then
-			  ac_lo= ac_hi=
-			  break
-			fi
-			ac_mid=`expr 2 '*' $ac_mid`
+ac_hi=`expr '(' $ac_mid ')' - 1`
+		       if test $ac_mid -le $ac_hi; then
+			 ac_lo= ac_hi=
+			 break
+		       fi
+		       ac_mid=`expr 2 '*' $ac_mid`
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
   done
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_lo= ac_hi=
+ac_lo= ac_hi=
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 # Binary search between lo and hi bounds.
 while test "x$ac_lo" != "x$ac_hi"; do
   ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo`
@@ -20786,11 +20169,10 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef long ac__type_sizeof_;
 int
 main ()
 {
-static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)];
+static int test_array [1 - 2 * !(((long) (sizeof (long))) <= $ac_mid)];
 test_array [0] = 0
 
   ;
@@ -20798,45 +20180,52 @@
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_hi=$ac_mid
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_lo=`expr '(' $ac_mid ')' + 1`
+ac_lo=`expr '(' $ac_mid ')' + 1`
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 done
 case $ac_lo in
 ?*) ac_cv_sizeof_long=$ac_lo;;
-'') if test "$ac_cv_type_long" = yes; then
-     { { echo "$as_me:$LINENO: error: cannot compute sizeof (long)
+'') { { echo "$as_me:$LINENO: error: cannot compute sizeof (long), 77
 See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute sizeof (long)
+echo "$as_me: error: cannot compute sizeof (long), 77
 See \`config.log' for more details." >&2;}
-   { (exit 77); exit 77; }; }
-   else
-     ac_cv_sizeof_long=0
-   fi ;;
+   { (exit 1); exit 1; }; } ;;
 esac
 else
+  if test "$cross_compiling" = yes; then
+  { { echo "$as_me:$LINENO: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
+else
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
@@ -20844,9 +20233,8 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-   typedef long ac__type_sizeof_;
-static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); }
-static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); }
+long longval () { return (long) (sizeof (long)); }
+unsigned long ulongval () { return (long) (sizeof (long)); }
 #include <stdio.h>
 #include <stdlib.h>
 int
@@ -20855,44 +20243,35 @@
 
   FILE *f = fopen ("conftest.val", "w");
   if (! f)
-    return 1;
-  if (((long int) (sizeof (ac__type_sizeof_))) < 0)
+    exit (1);
+  if (((long) (sizeof (long))) < 0)
     {
-      long int i = longval ();
-      if (i != ((long int) (sizeof (ac__type_sizeof_))))
-	return 1;
+      long i = longval ();
+      if (i != ((long) (sizeof (long))))
+	exit (1);
       fprintf (f, "%ld\n", i);
     }
   else
     {
-      unsigned long int i = ulongval ();
-      if (i != ((long int) (sizeof (ac__type_sizeof_))))
-	return 1;
+      unsigned long i = ulongval ();
+      if (i != ((long) (sizeof (long))))
+	exit (1);
       fprintf (f, "%lu\n", i);
     }
-  return ferror (f) || fclose (f) != 0;
+  exit (ferror (f) || fclose (f) != 0);
 
   ;
   return 0;
 }
 _ACEOF
 rm -f conftest$ac_exeext
-if { (ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; }; then
@@ -20903,25 +20282,22 @@
 sed 's/^/| /' conftest.$ac_ext >&5
 
 ( exit $ac_status )
-if test "$ac_cv_type_long" = yes; then
-     { { echo "$as_me:$LINENO: error: cannot compute sizeof (long)
+{ { echo "$as_me:$LINENO: error: cannot compute sizeof (long), 77
 See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute sizeof (long)
+echo "$as_me: error: cannot compute sizeof (long), 77
 See \`config.log' for more details." >&2;}
-   { (exit 77); exit 77; }; }
-   else
-     ac_cv_sizeof_long=0
-   fi
+   { (exit 1); exit 1; }; }
+fi
+rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
 rm -f conftest.val
+else
+  ac_cv_sizeof_long=0
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long" >&5
-echo "${ECHO_T}$ac_cv_sizeof_long" >&6; }
-
-
-
+fi
+echo "$as_me:$LINENO: result: $ac_cv_sizeof_long" >&5
+echo "${ECHO_T}$ac_cv_sizeof_long" >&6
 cat >>confdefs.h <<_ACEOF
 #define SIZEOF_LONG $ac_cv_sizeof_long
 _ACEOF
@@ -20929,8 +20305,8 @@
 
 
 save_LIBS="${LIBS}"
-{ echo "$as_me:$LINENO: checking for clock_gettime in -lrt" >&5
-echo $ECHO_N "checking for clock_gettime in -lrt... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for clock_gettime in -lrt" >&5
+echo $ECHO_N "checking for clock_gettime in -lrt... $ECHO_C" >&6
 if test "${ac_cv_lib_rt_clock_gettime+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -20943,53 +20319,56 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char clock_gettime ();
 int
 main ()
 {
-return clock_gettime ();
+clock_gettime ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_rt_clock_gettime=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_rt_clock_gettime=no
+ac_cv_lib_rt_clock_gettime=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_rt_clock_gettime" >&5
-echo "${ECHO_T}$ac_cv_lib_rt_clock_gettime" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_rt_clock_gettime" >&5
+echo "${ECHO_T}$ac_cv_lib_rt_clock_gettime" >&6
 if test $ac_cv_lib_rt_clock_gettime = yes; then
   rt_libs=" -lrt"
 fi
@@ -21001,9 +20380,9 @@
 for ac_func in clock_gettime nanosleep
 do
 as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6
+if eval "test \"\${$as_ac_var+set}\" = set"; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   cat >conftest.$ac_ext <<_ACEOF
@@ -21029,60 +20408,68 @@
 
 #undef $ac_func
 
-/* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
+{
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char $ac_func ();
 /* 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_$ac_func || defined __stub___$ac_func
+#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
 choke me
+#else
+char (*f) () = $ac_func;
+#endif
+#ifdef __cplusplus
+}
 #endif
 
 int
 main ()
 {
-return $ac_func ();
+return f != $ac_func;
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   eval "$as_ac_var=yes"
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	eval "$as_ac_var=no"
+eval "$as_ac_var=no"
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 fi
-ac_res=`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6
 if test `eval echo '${'$as_ac_var'}'` = yes; then
   cat >>confdefs.h <<_ACEOF
 #define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
@@ -21218,8 +20605,8 @@
 
   irix* )
 
-{ echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5
-echo $ECHO_N "checking for pthread_create in -lpthread... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5
+echo $ECHO_N "checking for pthread_create in -lpthread... $ECHO_C" >&6
 if test "${ac_cv_lib_pthread_pthread_create+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -21232,53 +20619,56 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char pthread_create ();
 int
 main ()
 {
-return pthread_create ();
+pthread_create ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_pthread_pthread_create=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_pthread_pthread_create=no
+ac_cv_lib_pthread_pthread_create=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthread_pthread_create" >&5
-echo "${ECHO_T}$ac_cv_lib_pthread_pthread_create" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_pthread_pthread_create" >&5
+echo "${ECHO_T}$ac_cv_lib_pthread_pthread_create" >&6
 if test $ac_cv_lib_pthread_pthread_create = yes; then
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LIBPTHREAD 1
@@ -21293,8 +20683,8 @@
 fi
 
 
-{ echo "$as_me:$LINENO: checking for alOpenPort in -laudio" >&5
-echo $ECHO_N "checking for alOpenPort in -laudio... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for alOpenPort in -laudio" >&5
+echo $ECHO_N "checking for alOpenPort in -laudio... $ECHO_C" >&6
 if test "${ac_cv_lib_audio_alOpenPort+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -21307,53 +20697,56 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char alOpenPort ();
 int
 main ()
 {
-return alOpenPort ();
+alOpenPort ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_audio_alOpenPort=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_audio_alOpenPort=no
+ac_cv_lib_audio_alOpenPort=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_audio_alOpenPort" >&5
-echo "${ECHO_T}$ac_cv_lib_audio_alOpenPort" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_audio_alOpenPort" >&5
+echo "${ECHO_T}$ac_cv_lib_audio_alOpenPort" >&6
 if test $ac_cv_lib_audio_alOpenPort = yes; then
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LIBAUDIO 1
@@ -21368,8 +20761,8 @@
 fi
 
 
-{ echo "$as_me:$LINENO: checking for dmGetUST in -ldmedia" >&5
-echo $ECHO_N "checking for dmGetUST in -ldmedia... $ECHO_C" >&6; }
+echo "$as_me:$LINENO: checking for dmGetUST in -ldmedia" >&5
+echo $ECHO_N "checking for dmGetUST in -ldmedia... $ECHO_C" >&6
 if test "${ac_cv_lib_dmedia_dmGetUST+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -21382,53 +20775,56 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char dmGetUST ();
 int
 main ()
 {
-return dmGetUST ();
+dmGetUST ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_dmedia_dmGetUST=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_dmedia_dmGetUST=no
+ac_cv_lib_dmedia_dmGetUST=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dmedia_dmGetUST" >&5
-echo "${ECHO_T}$ac_cv_lib_dmedia_dmGetUST" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_dmedia_dmGetUST" >&5
+echo "${ECHO_T}$ac_cv_lib_dmedia_dmGetUST" >&6
 if test $ac_cv_lib_dmedia_dmGetUST = yes; then
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LIBDMEDIA 1
@@ -21459,8 +20855,8 @@
 
   *)
 
-   { echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5
-echo $ECHO_N "checking for pthread_create in -lpthread... $ECHO_C" >&6; }
+   echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5
+echo $ECHO_N "checking for pthread_create in -lpthread... $ECHO_C" >&6
 if test "${ac_cv_lib_pthread_pthread_create+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -21473,53 +20869,56 @@
 cat >>conftest.$ac_ext <<_ACEOF
 /* 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.  */
+/* Override any gcc2 internal prototype to avoid an error.  */
 #ifdef __cplusplus
 extern "C"
 #endif
+/* We use char because int might match the return type of a gcc2
+   builtin and then its argument prototype would still apply.  */
 char pthread_create ();
 int
 main ()
 {
-return pthread_create ();
+pthread_create ();
   ;
   return 0;
 }
 _ACEOF
 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 "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
   ac_cv_lib_pthread_pthread_create=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	ac_cv_lib_pthread_pthread_create=no
+ac_cv_lib_pthread_pthread_create=no
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+rm -f conftest.err conftest.$ac_objext \
       conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthread_pthread_create" >&5
-echo "${ECHO_T}$ac_cv_lib_pthread_pthread_create" >&6; }
+echo "$as_me:$LINENO: result: $ac_cv_lib_pthread_pthread_create" >&5
+echo "${ECHO_T}$ac_cv_lib_pthread_pthread_create" >&6
 if test $ac_cv_lib_pthread_pthread_create = yes; then
   have_pthread="yes"
 
@@ -21578,7 +20977,9 @@
 CFLAGS="$CFLAGS $THREAD_CFLAGS"
 
 if test "$enable_cxx" = "yes"; then
-   subdirs="$subdirs bindings/cpp"
+
+
+subdirs="$subdirs bindings/cpp"
 
    ENABLE_CXX_TRUE=""
    ENABLE_CXX_FALE="#"
@@ -21589,8 +20990,160 @@
 
 
 
-ac_config_files="$ac_config_files Makefile portaudio-2.0.pc"
+#check for some headers
+
+
+for ac_header in libkern/OSAtomic.h sys/stat.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+  echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+else
+  # Is the header compilable?
+echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_header_compiler=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_header_compiler=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6
+
+# Is the header present?
+echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <$ac_header>
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null; then
+  if test -s conftest.err; then
+    ac_cpp_err=$ac_c_preproc_warn_flag
+    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+  else
+    ac_cpp_err=
+  fi
+else
+  ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+  ac_header_preproc=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  ac_header_preproc=no
+fi
+rm -f conftest.err conftest.$ac_ext
+echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6
+
+# So?  What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+  yes:no: )
+    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+    ac_header_preproc=yes
+    ;;
+  no:yes:* )
+    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header:     check for missing prerequisite headers?" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+    (
+      cat <<\_ASBOX
+## ------------------------------------------ ##
+## Report this to the AC_PACKAGE_NAME lists.  ##
+## ------------------------------------------ ##
+_ASBOX
+    ) |
+      sed "s/^/$as_me: WARNING:     /" >&2
+    ;;
+esac
+echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  eval "$as_ac_Header=\$ac_header_preproc"
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+  cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
 
+                    ac_config_files="$ac_config_files Makefile portaudio-2.0.pc"
 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
@@ -21609,58 +21162,39 @@
 
 # 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.
+# So, don't put newlines in cache variables' values.
 # 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_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
-echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      *) $as_unset $ac_var ;;
-      esac ;;
-    esac
-  done
-
+{
   (set) 2>&1 |
-    case $as_nl`(ac_space=' '; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
+    case `(ac_space=' '; set | grep ac_space) 2>&1` in
+    *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"
+      sed -n \
+	"s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
       ;;
-    esac |
-    sort
-) |
+    esac;
+} |
   sed '
-     /^ac_cv_env_/b end
      t clear
-     :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" &&
-      { echo "$as_me:$LINENO: updating cache $cache_file" >&5
-echo "$as_me: updating cache $cache_file" >&6;}
+     /^ac_cv_env/!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" && echo "updating cache $cache_file"
     cat confcache >$cache_file
   else
-    { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5
-echo "$as_me: not updating unwritable cache $cache_file" >&6;}
+    echo "not updating unwritable cache $cache_file"
   fi
 fi
 rm -f confcache
@@ -21669,48 +21203,63 @@
 # Let make expand exec_prefix.
 test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
 
+# 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
+
 # Transform confdefs.h into DEFS.
 # Protect against shell expansion while executing Makefile rules.
 # Protect against Makefile macro expansion.
 #
 # If the first sed substitution is executed (which looks for macros that
-# take arguments), then branch to the quote section.  Otherwise,
+# take arguments), then we branch to the quote section.  Otherwise,
 # look for a macro that doesn't take arguments.
-ac_script='
+cat >confdef2opt.sed <<\_ACEOF
 t clear
-:clear
-s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\)/-D\1=\2/g
+: clear
+s,^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\),-D\1=\2,g
 t quote
-s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\)/-D\1=\2/g
+s,^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\),-D\1=\2,g
 t quote
-b any
-:quote
-s/[	 `~#$^&*(){}\\|;'\''"<>?]/\\&/g
-s/\[/\\&/g
-s/\]/\\&/g
-s/\$/$$/g
-H
-:any
-${
-	g
-	s/^\n//
-	s/\n/ /g
-	p
-}
-'
-DEFS=`sed -n "$ac_script" confdefs.h`
+d
+: quote
+s,[	 `~#$^&*(){}\\|;'"<>?],\\&,g
+s,\[,\\&,g
+s,\],\\&,g
+s,\$,$$,g
+p
+_ACEOF
+# We use echo to avoid assuming a particular line-breaking character.
+# The extra dot is to prevent the shell from consuming trailing
+# line-breaks from the sub-command output.  A line-break within
+# single-quotes doesn't work because, if this script is created in a
+# platform that uses two characters for line-breaks (e.g., DOS), tr
+# would break.
+ac_LF_and_DOT=`echo; echo .`
+DEFS=`sed -n -f confdef2opt.sed confdefs.h | tr "$ac_LF_and_DOT" ' .'`
+rm -f confdef2opt.sed
 
 
 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=`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.
-  ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext"
-  ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo'
+  ac_i=`echo "$ac_i" |
+	 sed 's/\$U\././;s/\.o$//;s/\.obj$//'`
+  # 2. Add them.
+  ac_libobjs="$ac_libobjs $ac_i\$U.$ac_objext"
+  ac_ltlibobjs="$ac_ltlibobjs $ac_i"'$U.lo'
 done
 LIBOBJS=$ac_libobjs
 
@@ -21741,45 +21290,17 @@
 ## M4sh Initialization.  ##
 ## --------------------- ##
 
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
+# Be Bourne compatible
 if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
   emulate sh
   NULLCMD=:
   # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
   # 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
-
-
-
-
-# PATH needs CR
-# 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
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
+elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
+  set -o posix
 fi
+DUALCASE=1; export DUALCASE # for MKS sh
 
 # Support unset when possible.
 if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
@@ -21789,43 +21310,8 @@
 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.)
-as_nl='
-'
-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
-  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  { (exit 1); exit 1; }
-fi
-
 # Work around bugs in pre-3.0 UWIN ksh.
-for as_var in ENV MAIL MAILPATH
-do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-done
+$as_unset ENV MAIL MAILPATH
 PS1='$ '
 PS2='> '
 PS4='+ '
@@ -21839,19 +21325,18 @@
   if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
     eval $as_var=C; export $as_var
   else
-    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+    $as_unset $as_var
   fi
 done
 
 # Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+if expr a : '\(a\)' >/dev/null 2>&1; then
   as_expr=expr
 else
   as_expr=false
 fi
 
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
   as_basename=basename
 else
   as_basename=false
@@ -21859,120 +21344,159 @@
 
 
 # Name of the executable.
-as_me=`$as_basename -- "$0" ||
+as_me=`$as_basename "$0" ||
 $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
 	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+	 X"$0" : 'X\(/\)$' \| \
+	 .     : '\(.\)' 2>/dev/null ||
 echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
+    sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
+  	  /^X\/\(\/\/\)$/{ s//\1/; q; }
+  	  /^X\/\(\/\).*/{ s//\1/; q; }
+  	  s/.*/./; q'`
 
-# CDPATH.
-$as_unset CDPATH
+
+# PATH needs CR, and LINENO needs CR and PATH.
+# 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
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
+fi
 
 
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x$as_lineno_3"  = "x$as_lineno_2"  || {
+  # Find who we are.  Look in the path if we contain no path at all
+  # relative or not.
+  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
 
+       ;;
+  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
+    { { echo "$as_me:$LINENO: error: cannot find myself; rerun with an absolute path" >&5
+echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2;}
+   { (exit 1); exit 1; }; }
+  fi
+  case $CONFIG_SHELL in
+  '')
+    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for as_base in sh bash ksh sh5; do
+	 case $as_dir in
+	 /*)
+	   if ("$as_dir/$as_base" -c '
   as_lineno_1=$LINENO
   as_lineno_2=$LINENO
+  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
   test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+  test "x$as_lineno_3"  = "x$as_lineno_2" ') 2>/dev/null; then
+	     $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
+	     $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
+	     CONFIG_SHELL=$as_dir/$as_base
+	     export CONFIG_SHELL
+	     exec "$CONFIG_SHELL" "$0" ${1+"$@"}
+	   fi;;
+	 esac
+       done
+done
+;;
+  esac
 
   # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
   # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line after each line using $LINENO; the second 'sed'
-  # does the real work.  The second script uses 'N' to pair each
-  # line-number line with the line containing $LINENO, and appends
-  # trailing '-' during substitution so that $LINENO is not a special
-  # case at line end.
+  # line-number line before each line; the second 'sed' does the real
+  # work.  The second script uses 'N' to pair each line-number line
+  # with the numbered line, and appends trailing '-' during
+  # substitution so that $LINENO is not a special case at line end.
   # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # scripts with optimization help from Paolo Bonzini.  Blame Lee
-  # E. McMahon (1931-1989) for sed's syntax.  :-)
-  sed -n '
-    p
-    /[$]LINENO/=
-  ' <$as_myself |
+  # second 'sed' script.  Blame Lee E. McMahon for sed's syntax.  :-)
+  sed '=' <$as_myself |
     sed '
-      s/[$]LINENO.*/&-/
-      t lineno
-      b
-      :lineno
       N
-      :loop
-      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      s,$,-,
+      : loop
+      s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
       t loop
-      s/-\n.*//
+      s,-$,,
+      s,^['$as_cr_digits']*\n,,
     ' >$as_me.lineno &&
-  chmod +x "$as_me.lineno" ||
-    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+  chmod +x $as_me.lineno ||
+    { { echo "$as_me:$LINENO: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&5
+echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2;}
    { (exit 1); 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"
+  # original and so on.  Autoconf is especially sensible to this).
+  . ./$as_me.lineno
   # Exit status is that of the last command.
   exit
 }
 
 
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in
--n*)
-  case `echo 'x\c'` in
-  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
-  *)   ECHO_C='\c';;
-  esac;;
-*)
-  ECHO_N='-n';;
+case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
+  *c*,-n*) ECHO_N= ECHO_C='
+' ECHO_T='	' ;;
+  *c*,*  ) ECHO_N=-n ECHO_C= ECHO_T= ;;
+  *)       ECHO_N= ECHO_C='\c' ECHO_T= ;;
 esac
 
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+if expr a : '\(a\)' >/dev/null 2>&1; then
   as_expr=expr
 else
   as_expr=false
 fi
 
 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
-fi
 echo >conf$$.file
 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 ||
+  # We could just check for DJGPP; but this test a) works b) is more generic
+  # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
+  if test -f conf$$.exe; then
+    # Don't use ln at all; we don't have any links
     as_ln_s='cp -p'
+  else
+    as_ln_s='ln -s'
+  fi
 elif ln conf$$.file conf$$ 2>/dev/null; then
   as_ln_s=ln
 else
   as_ln_s='cp -p'
 fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
+rm -f conf$$ conf$$.exe conf$$.file
 
 if mkdir -p . 2>/dev/null; then
   as_mkdir_p=:
@@ -21981,28 +21505,7 @@
   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
+as_executable_p="test -f"
 
 # 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'"
@@ -22011,14 +21514,31 @@
 as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
 
 
+# IFS
+# We need space, tab and new line, in precisely that order.
+as_nl='
+'
+IFS=" 	$as_nl"
+
+# CDPATH.
+$as_unset CDPATH
+
 exec 6>&1
 
-# Save the log message, to keep $[0] and so on meaningful, and to
+# Open the log real soon, 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="
+# values after options handling.  Logging --version etc. is OK.
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+} >&5
+cat >&5 <<_CSEOF
+
 This file was extended by $as_me, which was
-generated by GNU Autoconf 2.61.  Invocation command line was
+generated by GNU Autoconf 2.59.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
   CONFIG_HEADERS  = $CONFIG_HEADERS
@@ -22026,18 +21546,30 @@
   CONFIG_COMMANDS = $CONFIG_COMMANDS
   $ $0 $@
 
-on `(hostname || uname -n) 2>/dev/null | sed 1q`
-"
-
+_CSEOF
+echo "on `(hostname || uname -n) 2>/dev/null | sed 1q`" >&5
+echo >&5
 _ACEOF
 
-cat >>$CONFIG_STATUS <<_ACEOF
 # Files that config.status was made for.
-config_files="$ac_config_files"
+if test -n "$ac_config_files"; then
+  echo "config_files=\"$ac_config_files\"" >>$CONFIG_STATUS
+fi
 
-_ACEOF
+if test -n "$ac_config_headers"; then
+  echo "config_headers=\"$ac_config_headers\"" >>$CONFIG_STATUS
+fi
+
+if test -n "$ac_config_links"; then
+  echo "config_links=\"$ac_config_links\"" >>$CONFIG_STATUS
+fi
+
+if test -n "$ac_config_commands"; then
+  echo "config_commands=\"$ac_config_commands\"" >>$CONFIG_STATUS
+fi
 
 cat >>$CONFIG_STATUS <<\_ACEOF
+
 ac_cs_usage="\
 \`$as_me' instantiates files from templates according to the
 current configuration.
@@ -22045,7 +21577,7 @@
 Usage: $0 [OPTIONS] [FILE]...
 
   -h, --help       print this help, then exit
-  -V, --version    print version number and configuration settings, then exit
+  -V, --version    print version number, then exit
   -q, --quiet      do not print progress messages
   -d, --debug      don't remove temporary files
       --recheck    update $as_me by reconfiguring in the same conditions
@@ -22056,21 +21588,19 @@
 $config_files
 
 Report bugs to <bug-autoconf at gnu.org>."
-
 _ACEOF
+
 cat >>$CONFIG_STATUS <<_ACEOF
 ac_cs_version="\\
 config.status
-configured by $0, generated by GNU Autoconf 2.61,
-  with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
+configured by $0, generated by GNU Autoconf 2.59,
+  with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\"
 
-Copyright (C) 2006 Free Software Foundation, Inc.
+Copyright (C) 2003 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'
+srcdir=$srcdir
+INSTALL="$INSTALL"
 _ACEOF
 
 cat >>$CONFIG_STATUS <<\_ACEOF
@@ -22081,42 +21611,60 @@
 do
   case $1 in
   --*=*)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_option=`expr "x$1" : 'x\([^=]*\)='`
+    ac_optarg=`expr "x$1" : 'x[^=]*=\(.*\)'`
     ac_shift=:
     ;;
-  *)
+  -*)
     ac_option=$1
     ac_optarg=$2
     ac_shift=shift
     ;;
+  *) # This is not an option, so the user has probably given explicit
+     # arguments.
+     ac_option=$1
+     ac_need_defaults=false;;
   esac
 
   case $ac_option in
   # Handling of the options.
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
   -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
     ac_cs_recheck=: ;;
-  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
-    echo "$ac_cs_version"; exit ;;
-  --debug | --debu | --deb | --de | --d | -d )
+  --version | --vers* | -V )
+    echo "$ac_cs_version"; exit 0 ;;
+  --he | --h)
+    # Conflict between --help and --header
+    { { echo "$as_me:$LINENO: error: ambiguous option: $1
+Try \`$0 --help' for more information." >&5
+echo "$as_me: error: ambiguous option: $1
+Try \`$0 --help' for more information." >&2;}
+   { (exit 1); exit 1; }; };;
+  --help | --hel | -h )
+    echo "$ac_cs_usage"; exit 0 ;;
+  --debug | --d* | -d )
     debug=: ;;
   --file | --fil | --fi | --f )
     $ac_shift
     CONFIG_FILES="$CONFIG_FILES $ac_optarg"
     ac_need_defaults=false;;
-  --he | --h |  --help | --hel | -h )
-    echo "$ac_cs_usage"; exit ;;
+  --header | --heade | --head | --hea )
+    $ac_shift
+    CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg"
+    ac_need_defaults=false;;
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil | --si | --s)
     ac_cs_silent=: ;;
 
   # This is an error.
-  -*) { echo "$as_me: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&2
+  -*) { { echo "$as_me:$LINENO: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&5
+echo "$as_me: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&2;}
    { (exit 1); exit 1; }; } ;;
 
-  *) ac_config_targets="$ac_config_targets $1"
-     ac_need_defaults=false ;;
+  *) ac_config_targets="$ac_config_targets $1" ;;
 
   esac
   shift
@@ -22132,43 +21680,29 @@
 _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF
 if \$ac_cs_recheck; then
-  echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
-  CONFIG_SHELL=$SHELL
-  export CONFIG_SHELL
-  exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+  echo "running $SHELL $0 " $ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
+  exec $SHELL $0 $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
 fi
 
 _ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-exec 5>>config.log
-{
-  echo
-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
-  echo "$ac_log"
-} >&5
 
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-_ACEOF
 
-cat >>$CONFIG_STATUS <<\_ACEOF
 
-# Handling of arguments.
+
+
+cat >>$CONFIG_STATUS <<\_ACEOF
 for ac_config_target in $ac_config_targets
 do
-  case $ac_config_target in
-    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
-    "portaudio-2.0.pc") CONFIG_FILES="$CONFIG_FILES portaudio-2.0.pc" ;;
-
+  case "$ac_config_target" in
+  # Handling of arguments.
+  "Makefile" ) CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+  "portaudio-2.0.pc" ) CONFIG_FILES="$CONFIG_FILES portaudio-2.0.pc" ;;
   *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
 echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
    { (exit 1); exit 1; }; };;
   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
@@ -22178,406 +21712,345 @@
 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,
+# simply because there is no reason to put 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'.
+# Create a temporary directory, and hook for its removal unless debugging.
 $debug ||
 {
-  tmp=
-  trap 'exit_status=$?
-  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
-' 0
+  trap 'exit_status=$?; rm -rf $tmp && exit $exit_status' 0
   trap '{ (exit 1); exit 1; }' 1 2 13 15
 }
+
 # Create a (secure) tmp directory for tmp files.
 
 {
-  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  tmp=`(umask 077 && mktemp -d -q "./confstatXXXXXX") 2>/dev/null` &&
   test -n "$tmp" && test -d "$tmp"
 }  ||
 {
-  tmp=./conf$$-$RANDOM
-  (umask 077 && mkdir "$tmp")
+  tmp=./confstat$$-$RANDOM
+  (umask 077 && mkdir $tmp)
 } ||
 {
    echo "$me: cannot create a temporary directory in ." >&2
    { (exit 1); exit 1; }
 }
 
+_ACEOF
+
+cat >>$CONFIG_STATUS <<_ACEOF
+
 #
-# Set up the sed scripts for CONFIG_FILES section.
+# CONFIG_FILES section.
 #
 
 # No need to generate the scripts if there are no CONFIG_FILES.
 # This happens for instance when ./config.status config.h
-if test -n "$CONFIG_FILES"; then
-
-_ACEOF
-
-
-
-ac_delim='%!_!# '
-for ac_last_try in false false false false false :; do
-  cat >conf$$subs.sed <<_ACEOF
-SHELL!$SHELL$ac_delim
-PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim
-PACKAGE_NAME!$PACKAGE_NAME$ac_delim
-PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim
-PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim
-PACKAGE_STRING!$PACKAGE_STRING$ac_delim
-PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim
-exec_prefix!$exec_prefix$ac_delim
-prefix!$prefix$ac_delim
-program_transform_name!$program_transform_name$ac_delim
-bindir!$bindir$ac_delim
-sbindir!$sbindir$ac_delim
-libexecdir!$libexecdir$ac_delim
-datarootdir!$datarootdir$ac_delim
-datadir!$datadir$ac_delim
-sysconfdir!$sysconfdir$ac_delim
-sharedstatedir!$sharedstatedir$ac_delim
-localstatedir!$localstatedir$ac_delim
-includedir!$includedir$ac_delim
-oldincludedir!$oldincludedir$ac_delim
-docdir!$docdir$ac_delim
-infodir!$infodir$ac_delim
-htmldir!$htmldir$ac_delim
-dvidir!$dvidir$ac_delim
-pdfdir!$pdfdir$ac_delim
-psdir!$psdir$ac_delim
-libdir!$libdir$ac_delim
-localedir!$localedir$ac_delim
-mandir!$mandir$ac_delim
-DEFS!$DEFS$ac_delim
-ECHO_C!$ECHO_C$ac_delim
-ECHO_N!$ECHO_N$ac_delim
-ECHO_T!$ECHO_T$ac_delim
-LIBS!$LIBS$ac_delim
-build_alias!$build_alias$ac_delim
-host_alias!$host_alias$ac_delim
-target_alias!$target_alias$ac_delim
-CC!$CC$ac_delim
-CFLAGS!$CFLAGS$ac_delim
-LDFLAGS!$LDFLAGS$ac_delim
-CPPFLAGS!$CPPFLAGS$ac_delim
-ac_ct_CC!$ac_ct_CC$ac_delim
-EXEEXT!$EXEEXT$ac_delim
-OBJEXT!$OBJEXT$ac_delim
-build!$build$ac_delim
-build_cpu!$build_cpu$ac_delim
-build_vendor!$build_vendor$ac_delim
-build_os!$build_os$ac_delim
-host!$host$ac_delim
-host_cpu!$host_cpu$ac_delim
-host_vendor!$host_vendor$ac_delim
-host_os!$host_os$ac_delim
-GREP!$GREP$ac_delim
-EGREP!$EGREP$ac_delim
-LN_S!$LN_S$ac_delim
-ECHO!$ECHO$ac_delim
-AR!$AR$ac_delim
-RANLIB!$RANLIB$ac_delim
-STRIP!$STRIP$ac_delim
-DLLTOOL!$DLLTOOL$ac_delim
-AS!$AS$ac_delim
-OBJDUMP!$OBJDUMP$ac_delim
-CPP!$CPP$ac_delim
-CXX!$CXX$ac_delim
-CXXFLAGS!$CXXFLAGS$ac_delim
-ac_ct_CXX!$ac_ct_CXX$ac_delim
-CXXCPP!$CXXCPP$ac_delim
-F77!$F77$ac_delim
-FFLAGS!$FFLAGS$ac_delim
-ac_ct_F77!$ac_ct_F77$ac_delim
-LIBTOOL!$LIBTOOL$ac_delim
-INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim
-INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim
-INSTALL_DATA!$INSTALL_DATA$ac_delim
-PKG_CONFIG!$PKG_CONFIG$ac_delim
-JACK_CFLAGS!$JACK_CFLAGS$ac_delim
-JACK_LIBS!$JACK_LIBS$ac_delim
-LT_CURRENT!$LT_CURRENT$ac_delim
-LT_REVISION!$LT_REVISION$ac_delim
-LT_AGE!$LT_AGE$ac_delim
-OTHER_OBJS!$OTHER_OBJS$ac_delim
-PADLL!$PADLL$ac_delim
-SHARED_FLAGS!$SHARED_FLAGS$ac_delim
-THREAD_CFLAGS!$THREAD_CFLAGS$ac_delim
-DLL_LIBS!$DLL_LIBS$ac_delim
-NASM!$NASM$ac_delim
-NASMOPT!$NASMOPT$ac_delim
-subdirs!$subdirs$ac_delim
-ENABLE_CXX_TRUE!$ENABLE_CXX_TRUE$ac_delim
-ENABLE_CXX_FALSE!$ENABLE_CXX_FALSE$ac_delim
-LIBOBJS!$LIBOBJS$ac_delim
-LTLIBOBJS!$LTLIBOBJS$ac_delim
-_ACEOF
-
-  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 92; then
-    break
-  elif $ac_last_try; then
-    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
-echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
-   { (exit 1); exit 1; }; }
-  else
-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+if test -n "\$CONFIG_FILES"; then
+  # Protect against being on the right side of a sed subst in config.status.
+  sed 's/,@/@@/; s/@,/@@/; s/,;t t\$/@;t t/; /@;t t\$/s/[\\\\&,]/\\\\&/g;
+   s/@@/,@/; s/@@/@,/; s/@;t t\$/,;t t/' >\$tmp/subs.sed <<\\CEOF
+s, at SHELL@,$SHELL,;t t
+s, at PATH_SEPARATOR@,$PATH_SEPARATOR,;t t
+s, at PACKAGE_NAME@,$PACKAGE_NAME,;t t
+s, at PACKAGE_TARNAME@,$PACKAGE_TARNAME,;t t
+s, at PACKAGE_VERSION@,$PACKAGE_VERSION,;t t
+s, at PACKAGE_STRING@,$PACKAGE_STRING,;t t
+s, at PACKAGE_BUGREPORT@,$PACKAGE_BUGREPORT,;t t
+s, at exec_prefix@,$exec_prefix,;t t
+s, at prefix@,$prefix,;t t
+s, at program_transform_name@,$program_transform_name,;t t
+s, at bindir@,$bindir,;t t
+s, at sbindir@,$sbindir,;t t
+s, at libexecdir@,$libexecdir,;t t
+s, at datadir@,$datadir,;t t
+s, at sysconfdir@,$sysconfdir,;t t
+s, at sharedstatedir@,$sharedstatedir,;t t
+s, at localstatedir@,$localstatedir,;t t
+s, at libdir@,$libdir,;t t
+s, at includedir@,$includedir,;t t
+s, at oldincludedir@,$oldincludedir,;t t
+s, at infodir@,$infodir,;t t
+s, at mandir@,$mandir,;t t
+s, at build_alias@,$build_alias,;t t
+s, at host_alias@,$host_alias,;t t
+s, at target_alias@,$target_alias,;t t
+s, at DEFS@,$DEFS,;t t
+s, at ECHO_C@,$ECHO_C,;t t
+s, at ECHO_N@,$ECHO_N,;t t
+s, at ECHO_T@,$ECHO_T,;t t
+s, at LIBS@,$LIBS,;t t
+s, at CC@,$CC,;t t
+s, at CFLAGS@,$CFLAGS,;t t
+s, at LDFLAGS@,$LDFLAGS,;t t
+s, at CPPFLAGS@,$CPPFLAGS,;t t
+s, at ac_ct_CC@,$ac_ct_CC,;t t
+s, at EXEEXT@,$EXEEXT,;t t
+s, at OBJEXT@,$OBJEXT,;t t
+s, at build@,$build,;t t
+s, at build_cpu@,$build_cpu,;t t
+s, at build_vendor@,$build_vendor,;t t
+s, at build_os@,$build_os,;t t
+s, at host@,$host,;t t
+s, at host_cpu@,$host_cpu,;t t
+s, at host_vendor@,$host_vendor,;t t
+s, at host_os@,$host_os,;t t
+s, at EGREP@,$EGREP,;t t
+s, at LN_S@,$LN_S,;t t
+s, at ECHO@,$ECHO,;t t
+s, at AR@,$AR,;t t
+s, at ac_ct_AR@,$ac_ct_AR,;t t
+s, at RANLIB@,$RANLIB,;t t
+s, at ac_ct_RANLIB@,$ac_ct_RANLIB,;t t
+s, at STRIP@,$STRIP,;t t
+s, at ac_ct_STRIP@,$ac_ct_STRIP,;t t
+s, at DLLTOOL@,$DLLTOOL,;t t
+s, at ac_ct_DLLTOOL@,$ac_ct_DLLTOOL,;t t
+s, at AS@,$AS,;t t
+s, at ac_ct_AS@,$ac_ct_AS,;t t
+s, at OBJDUMP@,$OBJDUMP,;t t
+s, at ac_ct_OBJDUMP@,$ac_ct_OBJDUMP,;t t
+s, at CPP@,$CPP,;t t
+s, at CXX@,$CXX,;t t
+s, at CXXFLAGS@,$CXXFLAGS,;t t
+s, at ac_ct_CXX@,$ac_ct_CXX,;t t
+s, at CXXCPP@,$CXXCPP,;t t
+s, at F77@,$F77,;t t
+s, at FFLAGS@,$FFLAGS,;t t
+s, at ac_ct_F77@,$ac_ct_F77,;t t
+s, at LIBTOOL@,$LIBTOOL,;t t
+s, at INSTALL_PROGRAM@,$INSTALL_PROGRAM,;t t
+s, at INSTALL_SCRIPT@,$INSTALL_SCRIPT,;t t
+s, at INSTALL_DATA@,$INSTALL_DATA,;t t
+s, at PKG_CONFIG@,$PKG_CONFIG,;t t
+s, at ac_pt_PKG_CONFIG@,$ac_pt_PKG_CONFIG,;t t
+s, at JACK_CFLAGS@,$JACK_CFLAGS,;t t
+s, at JACK_LIBS@,$JACK_LIBS,;t t
+s, at LT_CURRENT@,$LT_CURRENT,;t t
+s, at LT_REVISION@,$LT_REVISION,;t t
+s, at LT_AGE@,$LT_AGE,;t t
+s, at OTHER_OBJS@,$OTHER_OBJS,;t t
+s, at PADLL@,$PADLL,;t t
+s, at SHARED_FLAGS@,$SHARED_FLAGS,;t t
+s, at THREAD_CFLAGS@,$THREAD_CFLAGS,;t t
+s, at DLL_LIBS@,$DLL_LIBS,;t t
+s, at NASM@,$NASM,;t t
+s, at NASMOPT@,$NASMOPT,;t t
+s, at subdirs@,$subdirs,;t t
+s, at ENABLE_CXX_TRUE@,$ENABLE_CXX_TRUE,;t t
+s, at ENABLE_CXX_FALSE@,$ENABLE_CXX_FALSE,;t t
+s, at LIBOBJS@,$LIBOBJS,;t t
+s, at LTLIBOBJS@,$LTLIBOBJS,;t t
+CEOF
+
+_ACEOF
+
+  cat >>$CONFIG_STATUS <<\_ACEOF
+  # Split the substitutions into bite-sized pieces for seds with
+  # small command number limits, like on Digital OSF/1 and HP-UX.
+  ac_max_sed_lines=48
+  ac_sed_frag=1 # Number of current file.
+  ac_beg=1 # First line for current file.
+  ac_end=$ac_max_sed_lines # Line after last line for current file.
+  ac_more_lines=:
+  ac_sed_cmds=
+  while $ac_more_lines; do
+    if test $ac_beg -gt 1; then
+      sed "1,${ac_beg}d; ${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
+    else
+      sed "${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
+    fi
+    if test ! -s $tmp/subs.frag; then
+      ac_more_lines=false
+    else
+      # The purpose of the label and of the branching condition is to
+      # speed up the sed processing (if there are no `@' at all, there
+      # is no need to browse any of the substitutions).
+      # These are the two extra sed commands mentioned above.
+      (echo ':t
+  /@[a-zA-Z_][a-zA-Z_0-9]*@/!b' && cat $tmp/subs.frag) >$tmp/subs-$ac_sed_frag.sed
+      if test -z "$ac_sed_cmds"; then
+	ac_sed_cmds="sed -f $tmp/subs-$ac_sed_frag.sed"
+      else
+	ac_sed_cmds="$ac_sed_cmds | sed -f $tmp/subs-$ac_sed_frag.sed"
+      fi
+      ac_sed_frag=`expr $ac_sed_frag + 1`
+      ac_beg=$ac_end
+      ac_end=`expr $ac_end + $ac_max_sed_lines`
+    fi
+  done
+  if test -z "$ac_sed_cmds"; then
+    ac_sed_cmds=cat
   fi
-done
-
-ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
-if test -n "$ac_eof"; then
-  ac_eof=`echo "$ac_eof" | sort -nru | sed 1q`
-  ac_eof=`expr $ac_eof + 1`
-fi
+fi # test -n "$CONFIG_FILES"
 
-cat >>$CONFIG_STATUS <<_ACEOF
-cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
-_ACEOF
-sed '
-s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
-s/^/s,@/; s/!/@,|#_!!_#|/
-:n
-t n
-s/'"$ac_delim"'$/,g/; t
-s/$/\\/; p
-N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
-' >>$CONFIG_STATUS <conf$$subs.sed
-rm -f conf$$subs.sed
-cat >>$CONFIG_STATUS <<_ACEOF
-:end
-s/|#_!!_#|//g
-CEOF$ac_eof
 _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
-fi # test -n "$CONFIG_FILES"
-
-
-for ac_tag in  :F $CONFIG_FILES
-do
-  case $ac_tag in
-  :[FHLC]) ac_mode=$ac_tag; continue;;
-  esac
-  case $ac_mode$ac_tag in
-  :[FHL]*:*);;
-  :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
-echo "$as_me: error: Invalid tag $ac_tag." >&2;}
-   { (exit 1); exit 1; }; };;
-  :[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 ||
-	   { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
-echo "$as_me: error: cannot find input file: $ac_f" >&2;}
-   { (exit 1); exit 1; }; };;
-      esac
-      ac_file_inputs="$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 "`IFS=:
-	  echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
-    if test x"$ac_file" != x-; then
-      configure_input="$ac_file.  $configure_input"
-      { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
-    fi
-
-    case $ac_tag in
-    *:-:* | *:-) cat >"$tmp/stdin";;
-    esac
-    ;;
+for ac_file in : $CONFIG_FILES; do test "x$ac_file" = x: && continue
+  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
+  case $ac_file in
+  - | *:- | *:-:* ) # input from stdin
+	cat >$tmp/stdin
+	ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
+	ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
+  *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
+	ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
+  * )   ac_file_in=$ac_file.in ;;
   esac
 
-  ac_dir=`$as_dirname -- "$ac_file" ||
+  # Compute @srcdir@, @top_srcdir@, and @INSTALL@ for subdirectories.
+  ac_dir=`(dirname "$ac_file") 2>/dev/null ||
 $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
 	 X"$ac_file" : 'X\(//\)[^/]' \| \
 	 X"$ac_file" : 'X\(//\)$' \| \
-	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+	 X"$ac_file" : 'X\(/\)' \| \
+	 .     : '\(.\)' 2>/dev/null ||
 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"
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+  	  /^X\(\/\/\)$/{ s//\1/; q; }
+  	  /^X\(\/\).*/{ s//\1/; q; }
+  	  s/.*/./; q'`
+  { if $as_mkdir_p; then
+    mkdir -p "$ac_dir"
+  else
+    as_dir="$ac_dir"
     as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
+    while test ! -d "$as_dir"; do
+      as_dirs="$as_dir $as_dirs"
+      as_dir=`(dirname "$as_dir") 2>/dev/null ||
 $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
 	 X"$as_dir" : 'X\(//\)[^/]' \| \
 	 X"$as_dir" : 'X\(//\)$' \| \
-	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+	 X"$as_dir" : 'X\(/\)' \| \
+	 .     : '\(.\)' 2>/dev/null ||
 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
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+  	  /^X\(\/\/\)$/{ s//\1/; q; }
+  	  /^X\(\/\).*/{ s//\1/; q; }
+  	  s/.*/./; q'`
     done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
-echo "$as_me: error: cannot create directory $as_dir" >&2;}
+    test ! -n "$as_dirs" || mkdir $as_dirs
+  fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
+echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
    { (exit 1); exit 1; }; }; }
+
   ac_builddir=.
 
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
+if test "$ac_dir" != .; then
   ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`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
+  # A "../" for each directory in $ac_dir_suffix.
+  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
+else
+  ac_dir_suffix= ac_top_builddir=
+fi
 
 case $srcdir in
-  .)  # We are building in place.
+  .)  # No --srcdir option.  We are building in place.
     ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
+    if test -z "$ac_top_builddir"; then
+       ac_top_srcdir=.
+    else
+       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
+    fi ;;
+  [\\/]* | ?:[\\/]* )  # Absolute path.
     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 ;;
+    ac_top_srcdir=$srcdir ;;
+  *) # Relative path.
+    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_builddir$srcdir ;;
 esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
 
+# Do not use `cd foo && pwd` to compute absolute paths, because
+# the directories may not exist.
+case `pwd` in
+.) ac_abs_builddir="$ac_dir";;
+*)
+  case "$ac_dir" in
+  .) ac_abs_builddir=`pwd`;;
+  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
+  *) ac_abs_builddir=`pwd`/"$ac_dir";;
+  esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_builddir=${ac_top_builddir}.;;
+*)
+  case ${ac_top_builddir}. in
+  .) ac_abs_top_builddir=$ac_abs_builddir;;
+  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
+  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
+  esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_srcdir=$ac_srcdir;;
+*)
+  case $ac_srcdir in
+  .) ac_abs_srcdir=$ac_abs_builddir;;
+  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
+  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
+  esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_srcdir=$ac_top_srcdir;;
+*)
+  case $ac_top_srcdir in
+  .) ac_abs_top_srcdir=$ac_abs_builddir;;
+  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
+  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
+  esac;;
+esac
 
-  case $ac_mode in
-  :F)
-  #
-  # CONFIG_FILE
-  #
 
   case $INSTALL in
   [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
-  *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;;
+  *) ac_INSTALL=$ac_top_builddir$INSTALL ;;
   esac
-_ACEOF
 
-cat >>$CONFIG_STATUS <<\_ACEOF
-# 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=
-
-case `sed -n '/datarootdir/ {
-  p
-  q
-}
-/@datadir@/p
-/@docdir@/p
-/@infodir@/p
-/@localedir@/p
-/@mandir@/p
-' $ac_file_inputs` in
-*datarootdir*) ac_datarootdir_seen=yes;;
-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
-  { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-  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
+  if test x"$ac_file" != x-; then
+    { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+    rm -f "$ac_file"
+  fi
+  # 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.  */
+  if test x"$ac_file" = x-; then
+    configure_input=
+  else
+    configure_input="$ac_file.  "
+  fi
+  configure_input=$configure_input"Generated from `echo $ac_file_in |
+				     sed 's,.*/,,'` by configure."
+
+  # First look for the input files in the build tree, otherwise in the
+  # src tree.
+  ac_file_inputs=`IFS=:
+    for f in $ac_file_in; do
+      case $f in
+      -) echo $tmp/stdin ;;
+      [\\/$]*)
+	 # Absolute (can't be DOS-style, as IFS=:)
+	 test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
+echo "$as_me: error: cannot find input file: $f" >&2;}
+   { (exit 1); exit 1; }; }
+	 echo "$f";;
+      *) # Relative
+	 if test -f "$f"; then
+	   # Build tree
+	   echo "$f"
+	 elif test -f "$srcdir/$f"; then
+	   # Source tree
+	   echo "$srcdir/$f"
+	 else
+	   # /dev/null tree
+	   { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
+echo "$as_me: error: cannot find input file: $f" >&2;}
+   { (exit 1); exit 1; }; }
+	 fi;;
+      esac
+    done` || { (exit 1); exit 1; }
 _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
   sed "$ac_vpsub
 $extrasub
@@ -22585,40 +22058,29 @@
 cat >>$CONFIG_STATUS <<\_ACEOF
 :t
 /@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s&@configure_input@&$configure_input&;t t
-s&@top_builddir@&$ac_top_builddir_sub&;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
-" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out
-
-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"; } &&
-  { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined." >&5
-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
- ;;
-
-
-
-  esac
+s, at configure_input@,$configure_input,;t t
+s, at srcdir@,$ac_srcdir,;t t
+s, at abs_srcdir@,$ac_abs_srcdir,;t t
+s, at top_srcdir@,$ac_top_srcdir,;t t
+s, at abs_top_srcdir@,$ac_abs_top_srcdir,;t t
+s, at builddir@,$ac_builddir,;t t
+s, at abs_builddir@,$ac_abs_builddir,;t t
+s, at top_builddir@,$ac_top_builddir,;t t
+s, at abs_top_builddir@,$ac_abs_top_builddir,;t t
+s, at INSTALL@,$ac_INSTALL,;t t
+" $ac_file_inputs | (eval "$ac_sed_cmds") >$tmp/out
+  rm -f $tmp/stdin
+  if test x"$ac_file" != x-; then
+    mv $tmp/out $ac_file
+  else
+    cat $tmp/out
+    rm -f $tmp/out
+  fi
 
-done # for ac_tag
+done
+_ACEOF
 
+cat >>$CONFIG_STATUS <<\_ACEOF
 
 { (exit 0); exit 0; }
 _ACEOF
@@ -22655,10 +22117,7 @@
   # Remove --cache-file and --srcdir arguments so they do not pile up.
   ac_sub_configure_args=
   ac_prev=
-  eval "set x $ac_configure_args"
-  shift
-  for ac_arg
-  do
+  for ac_arg in $ac_configure_args; do
     if test -n "$ac_prev"; then
       ac_prev=
       continue
@@ -22681,123 +22140,123 @@
       ac_prev=prefix ;;
     -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
       ;;
-    *)
-      case $ac_arg in
-      *\'*) ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
-      esac
-      ac_sub_configure_args="$ac_sub_configure_args '$ac_arg'" ;;
+    *) ac_sub_configure_args="$ac_sub_configure_args $ac_arg" ;;
     esac
   done
 
   # Always prepend --prefix to ensure using the same prefix
   # in subdir configurations.
-  ac_arg="--prefix=$prefix"
-  case $ac_arg in
-  *\'*) ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
-  esac
-  ac_sub_configure_args="'$ac_arg' $ac_sub_configure_args"
-
-  # Pass --silent
-  if test "$silent" = yes; then
-    ac_sub_configure_args="--silent $ac_sub_configure_args"
-  fi
+  ac_sub_configure_args="--prefix=$prefix $ac_sub_configure_args"
 
   ac_popdir=`pwd`
   for ac_dir in : $subdirs; do test "x$ac_dir" = x: && continue
 
     # Do not complain, so a configure script can configure whichever
     # parts of a large source tree are present.
-    test -d "$srcdir/$ac_dir" || continue
+    test -d $srcdir/$ac_dir || continue
 
-    ac_msg="=== configuring in $ac_dir (`pwd`/$ac_dir)"
-    echo "$as_me:$LINENO: $ac_msg" >&5
-    echo "$ac_msg" >&6
-    { as_dir="$ac_dir"
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+    { echo "$as_me:$LINENO: configuring in $ac_dir" >&5
+echo "$as_me: configuring in $ac_dir" >&6;}
+    { if $as_mkdir_p; then
+    mkdir -p "$ac_dir"
+  else
+    as_dir="$ac_dir"
     as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
+    while test ! -d "$as_dir"; do
+      as_dirs="$as_dir $as_dirs"
+      as_dir=`(dirname "$as_dir") 2>/dev/null ||
 $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
 	 X"$as_dir" : 'X\(//\)[^/]' \| \
 	 X"$as_dir" : 'X\(//\)$' \| \
-	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+	 X"$as_dir" : 'X\(/\)' \| \
+	 .     : '\(.\)' 2>/dev/null ||
 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
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+  	  /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+  	  /^X\(\/\/\)$/{ s//\1/; q; }
+  	  /^X\(\/\).*/{ s//\1/; q; }
+  	  s/.*/./; q'`
     done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
-echo "$as_me: error: cannot create directory $as_dir" >&2;}
+    test ! -n "$as_dirs" || mkdir $as_dirs
+  fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
+echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
    { (exit 1); exit 1; }; }; }
+
     ac_builddir=.
 
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
+if test "$ac_dir" != .; then
   ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`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
+  # A "../" for each directory in $ac_dir_suffix.
+  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
+else
+  ac_dir_suffix= ac_top_builddir=
+fi
 
 case $srcdir in
-  .)  # We are building in place.
+  .)  # No --srcdir option.  We are building in place.
     ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
+    if test -z "$ac_top_builddir"; then
+       ac_top_srcdir=.
+    else
+       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
+    fi ;;
+  [\\/]* | ?:[\\/]* )  # Absolute path.
     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 ;;
+    ac_top_srcdir=$srcdir ;;
+  *) # Relative path.
+    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_builddir$srcdir ;;
+esac
+
+# Do not use `cd foo && pwd` to compute absolute paths, because
+# the directories may not exist.
+case `pwd` in
+.) ac_abs_builddir="$ac_dir";;
+*)
+  case "$ac_dir" in
+  .) ac_abs_builddir=`pwd`;;
+  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
+  *) ac_abs_builddir=`pwd`/"$ac_dir";;
+  esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_builddir=${ac_top_builddir}.;;
+*)
+  case ${ac_top_builddir}. in
+  .) ac_abs_top_builddir=$ac_abs_builddir;;
+  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
+  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
+  esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_srcdir=$ac_srcdir;;
+*)
+  case $ac_srcdir in
+  .) ac_abs_srcdir=$ac_abs_builddir;;
+  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
+  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
+  esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_srcdir=$ac_top_srcdir;;
+*)
+  case $ac_top_srcdir in
+  .) ac_abs_top_srcdir=$ac_abs_builddir;;
+  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
+  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
+  esac;;
 esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
 
 
-    cd "$ac_dir"
+    cd $ac_dir
 
     # Check for guested configure; otherwise get Cygnus style configure.
-    if test -f "$ac_srcdir/configure.gnu"; then
-      ac_sub_configure=$ac_srcdir/configure.gnu
-    elif test -f "$ac_srcdir/configure"; then
-      ac_sub_configure=$ac_srcdir/configure
-    elif test -f "$ac_srcdir/configure.in"; then
-      # This should be Cygnus configure.
-      ac_sub_configure=$ac_aux_dir/configure
+    if test -f $ac_srcdir/configure.gnu; then
+      ac_sub_configure="$SHELL '$ac_srcdir/configure.gnu'"
+    elif test -f $ac_srcdir/configure; then
+      ac_sub_configure="$SHELL '$ac_srcdir/configure'"
+    elif test -f $ac_srcdir/configure.in; then
+      ac_sub_configure=$ac_configure
     else
       { echo "$as_me:$LINENO: WARNING: no configuration information is in $ac_dir" >&5
 echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2;}
@@ -22809,21 +22268,21 @@
       # Make the cache file name correct relative to the subdirectory.
       case $cache_file in
       [\\/]* | ?:[\\/]* ) ac_sub_cache_file=$cache_file ;;
-      *) # Relative name.
-	ac_sub_cache_file=$ac_top_build_prefix$cache_file ;;
+      *) # Relative path.
+	ac_sub_cache_file=$ac_top_builddir$cache_file ;;
       esac
 
-      { echo "$as_me:$LINENO: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&5
-echo "$as_me: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&6;}
+      { echo "$as_me:$LINENO: running $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&5
+echo "$as_me: running $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&6;}
       # The eval makes quoting arguments work.
-      eval "\$SHELL \"\$ac_sub_configure\" $ac_sub_configure_args \
-	   --cache-file=\"\$ac_sub_cache_file\" --srcdir=\"\$ac_srcdir\"" ||
+      eval $ac_sub_configure $ac_sub_configure_args \
+	   --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir ||
 	{ { echo "$as_me:$LINENO: error: $ac_sub_configure failed for $ac_dir" >&5
 echo "$as_me: error: $ac_sub_configure failed for $ac_dir" >&2;}
    { (exit 1); exit 1; }; }
     fi
 
-    cd "$ac_popdir"
+    cd $ac_popdir
   done
 fi
 

Modified: freeswitch/branches/cparker/libs/portaudio/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/portaudio/configure.in	(original)
+++ freeswitch/branches/cparker/libs/portaudio/configure.in	Tue Apr 24 10:14:28 2007
@@ -308,4 +308,7 @@
 AC_SUBST(ENABLE_CXX_TRUE)
 AC_SUBST(ENABLE_CXX_FALSE)
 
+#check for some headers
+AC_CHECK_HEADERS([libkern/OSAtomic.h])
+
 AC_OUTPUT([Makefile portaudio-2.0.pc])

Modified: freeswitch/branches/cparker/libs/portaudio/src/common/pa_ringbuffer.c
==============================================================================
--- freeswitch/branches/cparker/libs/portaudio/src/common/pa_ringbuffer.c	(original)
+++ freeswitch/branches/cparker/libs/portaudio/src/common/pa_ringbuffer.c	Tue Apr 24 10:14:28 2007
@@ -71,7 +71,7 @@
  *
  ****************/
 
-#if defined(__APPLE__) || defined(__FreeBSD__)
+#if defined(HAVE_LIBKERN_OSATOMIC_H) && (defined(__APPLE__) || defined(__FreeBSD__))
 #   include <libkern/OSAtomic.h>
     /* Here are the memory barrier functions. Mac OS X and FreeBSD only provide
        full memory barriers, so the three types of barriers are the same. */

Modified: freeswitch/branches/cparker/libs/sofia-sip/.update
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/.update	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/.update	Tue Apr 24 10:14:28 2007
@@ -1 +1 @@
-Sat Feb 17 01:18:56 EST 2007
+Sat Apr 21 16:48:55 EDT 2007

Modified: freeswitch/branches/cparker/libs/sofia-sip/AUTHORS
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/AUTHORS	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/AUTHORS	Tue Apr 24 10:14:28 2007
@@ -10,6 +10,8 @@
 
 Chan, Tat <first.surname at nokia.com>
 Ciarkowski, Andrzej <wp-voigtkampff -at users -dot sourceforge -dot net>
+Denis-Courmont, Remi <first.surname at nokia.com>
+Filonenko Roman <shkoder -at ua -dot fm>
 Haataja, Mikko <first.surname at nokia.com>
 Jacobs, Remeres <first.surname at nokia.com>
 Jalava, Teemu <first.surname at nokia.com>
@@ -26,9 +28,7 @@
 Whittaker, Colin <colinw -at occamnetworks -dot com>
 Zabaluev, Mikhail <first.surname at nokia.com>
 
-
 Note: for details on who did what, see the version control 
       system change history, and release notes for past releases at
       http://sofia-sip.sourceforge.net/relnotes/
-
-      
\ No newline at end of file
+ 
\ No newline at end of file

Modified: freeswitch/branches/cparker/libs/sofia-sip/COPYRIGHTS
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/COPYRIGHTS	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/COPYRIGHTS	Tue Apr 24 10:14:28 2007
@@ -221,3 +221,31 @@
 been advised of the possibility of such damages.
 
 ----------------------------------------------------------------------------
+
+libsofia-sip-ua/su/poll.c
+
+The package also contains files from GNU C Library by Free Software
+Foundation.
+
+These files are distributed with the following copyright notice:
+
+Copyright (C) 1994,1996,1997,1998,1999,2001,2002
+Free Software Foundation, Inc.
+This file is part of the GNU C Library.
+
+The GNU C Library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+The GNU C Library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with the GNU C Library; if not, write to the Free
+Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+----------------------------------------------------------------------------

Modified: freeswitch/branches/cparker/libs/sofia-sip/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -27,6 +27,10 @@
 EXTRA_DIST += 	m4/sac-general.m4 m4/sac-su.m4 \
 		m4/sac-su2.m4 m4/sac-tport.m4 m4/sac-openssl.m4
 
+EXTRA_DIST +=   docs/build_system.txt \
+		docs/devel_platform_notes.txt \
+		docs/release_management.txt
+
 dist_man_MANS = man/man1/sip-date.1 man/man1/sip-options.1 \
 		man/man1/localinfo.1 man/man1/addrinfo.1 \
 		man/man1/stunc.1 man/man1/sip-dig.1
@@ -36,7 +40,10 @@
 manpages: built-sources
 	-mkdir -p man man/man1 2> /dev/null
 if HAVE_DOXYGEN
-	cd utils && $(DOXYGEN) Doxyfile.build
+	@echo 'cd utils && $(DOXYGEN)'
+	@cd utils && \
+	{ exec 3>&1 1>&2; { $(DOXYGEN) 2>&1; echo $$? >& 3 ;} | \
+	  fgrep -v 'Warning:' ;} | { read x; exit $$x ;}
 	@rm -f man/man1/_*.1
 else
 	-touch $(dist_man_MANS)
@@ -44,7 +51,12 @@
 
 CLEANFILES = $(dist_man_MANS)
 
-coverage built-sources clean-built-sources doxygen:
-	for i in libsofia-sip-ua $(GLIB_SUBDIRS) ; do $(MAKE) $(AM_MAKEFLAGS) -C $$i $@ ; done
+coverage built-sources clean-built-sources valcheck doxygen:
+	@failcom='exit 1'; for f in x $$MAKEFLAGS; do \
+	case $$f in *=* | --[!k]*);; *k*) failcom='fail=yes';; esac; done; \
+	for i in libsofia-sip-ua $(GLIB_SUBDIRS) ; do \
+	  (cd $$i && $(MAKE) $(AM_MAKEFLAGS) $@) || eval $$failcom; \
+	done ; \
+	test -z "$$fail"
 
-.PHONY: coverage built-sources clean-built-sources doxygen manpages
+.PHONY: coverage built-sources clean-built-sources valcheck doxygen manpages

Modified: freeswitch/branches/cparker/libs/sofia-sip/README
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/README	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/README	Tue Apr 24 10:14:28 2007
@@ -46,7 +46,6 @@
 - localinfo (libsofia-sip-ua/su), prints information about
   local network interfaces 
 
-
 References
 ----------
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/RELEASE
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/RELEASE	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/RELEASE	Tue Apr 24 10:14:28 2007
@@ -5,98 +5,112 @@
 Changes since last release
 --------------------------
 
-<changes since last written in freshmeat.net "Changes:" style;
- and in less than 10 lines />
-
-Bugs in blaa and foo have been fixed. The stack now supports
-use of foobar...
+Numerous nua bugs introduced in the release 1.12.5 have been fixed. Support
+for nextnonce in Authentication-Info header has been added. The nua engine
+now fully supports application-driven SDP.
 
 API/ABI changes and versioning
 ------------------------------
 
-<see previous release notes at
- http://sofia-sip.sourceforge.net/relnotes/ for examples ;
- - should include all changes to public headers, and 
-   other important information to developers; 
- - and should be updated _continuously_! />
-
-**template**: New features in API are marked with Doxytag macro @VERSION_1_XX_X.
-
 libsofia-sip-ua:
-- **template**: Added foobar() function (sofia-sip/foobar.h).
-- Added sip_is_allowed() function and k_bitmap field to the 
-  sip_allow_t structure 
-- Added SIP header Refer-Sub and related functions
-- Added <sofia-sip/sip_extra.h> include file
-- Added auc_info() function (sofia-sip/auth_client.h)
+- Use calling/received callstate in nua_i_state event sent because of UPDATE
+  while call is ready
+- Added tag define NUTAG_WITH_CURRENT() as an alias to NUTAG_WITH_THIS()
+- Added tag NUTAG_DIALOG() controlling whether nua_method() creates a dialog.
+- Added tag NUTAG_AUTH_CACHE() <sofia-sip/nua_tag.h> determining when to 
+  include credentials in the request
+- Added kqueue and /dev/poll interfaces (su_devpoll_port_create(),
+  su_devpoll_clone_start(), su_kqueue_port_create(), su_kqueue_clone_start()
+  in <sofia-sip/su_wait.h>)
+- Added SIP_IS_ALLOWED() macro to <sofia-sip/sip_util.h>
+- Fixed NUTAG_APPL_METHOD() implementation for UPDATE and PRACK as documented
+  ("100rel" and "precondition" extensions now require explicit calls to
+  nua_update() and nua_prack() if those methods are included in
+  NUTAG_APPL_METHOD())
+- Added auc_clear field and member to authentication client plugin interface
+  in <sofia-sip/auth_client_plugin.h>
+- Added nua_event_is_incoming_request() to <sofia-sip/nua.h>
 - This release is ABI/API compatible with applications linked against 
   any 1.12.x release. However, applications built against this release won't 
   work against an older library. The ABI has been tested with the nua module 
   unit test (test_nua) built against original 1.12.0 release.
 
 libsofia-sip-ua-glib:
-- The 'nua-glib' module has been removed from the library and moved
-  to a separate package 'sofia-nua-glib'. The remaining library (su-glib) 
-  is now considered stable and will be API/ABI compatible with later 
-  releases in the 1.12.x series.
-- ABI has been modified and applications built against 1.12.4 and earlier 
-  releases need to be rebuilt.
+- No ABI/API changes, compatible with 1.12.0. Note, libsofia-sip-ua-glib
+  interface is not considered stable and may change in a future 1.12.x
+  release.
 
 Contributors to this release
 ----------------------------
 
-<list of people who contributed to _this_ release
- - update as people's patches are added, or when you commit stuff
- - current development team members (see AUTHORS) may be omitted
- - name of the contributor should be enough (email addresses in AUTHORS),
-   plus a brief description of what was contributed
- - roughly sorted by number of patches accepted
-/> 
-
-- **template**: First Surname (patch to nua/soa/msg)
-- Petteri Puolakka (patch to stun)
-- Mikhail Zabluev (patch to su-glib mainloop integration)
+- Pekka Pessi (/dev/poll interface to Solaris, kqueue)
+- Martti Mela (kqueue interface to Max OS X and FreeBSD)
+- Michael Jerris (Solaris patches)
+- Colin Whittaker (sresolv patch)
 
 See the AUTHORS file in the distribution package.
 
 Notes on new features
 ---------------------
 
-RFC 4488 defines the Refer-Sub header. Its datatypes, related functions and
-methods declared in <sofia-sip/sip_extra.h> include file. The Refer-Sub
-header structure can be accessed from sip_t structure with sip_refer_sub()
-method, e.g.,
-
-  if (sip_refer_sub(sip) && 
-      strcasecmp("false", sip_refer_sub(sip)->rs_value) == 0) {
-     /* Do not create implicit subscription */ 
-  }
-
-<information about major new features
- - new/changed/removed functionality
- - links to further documentation
- - section may be omitted for minor releases
-/> 
+The Sofia-SIP has been compiled and tested on Solaris. The /dev/poll
+interface (in su_devpoll_port.c) has been added for Solaris. Likewise, the
+kqueue interface (in su_kqueue_port.c) has been added for FreeBSD and Mac OS
+X. There is also select-based reactor for systems without poll().
+
+The client authentication in nua has been updated. The nextnonce in
+Authentication-Info or Proxy-Authentication-Info headers is now used during
+the next . The NUTAG_AUTH_CACHE() policy determines how the cached
+credentials are used. By default, the credentials are included in each
+request within the dialog, however, with the
+NUTAG_AUTH_CACHE(nua_auth_cache_challenged) the client authenticates
+requests only after they have been challenged.
+
+The application can now fully control the SDP negotiation (when soa is
+disabled with NUTAG_MEDIA_ENABLE(0)). The application can send UPDATE and
+PRACK requests and respond to them. The callstate sent in nua_i_state after
+UPDATE while the call has already been completed has been also changed.
 
 Bugs fixed in this release
 --------------------------
 
-< notable bugs fixed in this release
- - check the sf.net bug tracker; see closed bugs,
-   sorted by closing date
- - other bugs as fixed in CVS/darcs
-/>
-
-- **template**: #9499652 sf.net bug item title
-
-- Fixed crash when nua_bye() was called while a NOTIFY client transaction
-  was in progress. Problem reported by Anthony Minnessale.
-- Not using close() with sockets in sres.c. Problem reported by
-  Roman Filonenko.
-- Bug in zero-padding STUN messages with a message integrity 
-  attribute. Patch by Petteri Puolakka.
-- Fixed a severe problem with timer accuracy, when sofia-sip timers 
-  where used under glib's mainloop.
-- Improved glib mainloop integration to avoid warnings about already
-  active mainloop context, and potentially other issue. Patch by 
-  Mikhail Zabaluev. Closes sf.net item #1606786.
+- Fixed nua failing to refresh publication with re-PUBLISH.
+  Problem reported by Jan van den Bosch.
+- Fixed encoding of c= lines without IN address.
+  Problem reported by Saurav Sahu.
+- Fixed status code sent to network and returned to the client if there was
+  an internal error while responding to a request. 
+  The problem was reported by Michael Jerris and Joshua Engelbrecht.
+- Fixed #1685249, unclear termination of call in absense of credentials by
+  nua_authenticate(). Problem reported by Mikhail Zabaluev.
+- Fixed status code reported to application when REGISTER transaction was
+  restarted by nua stack. Problem reported by Mikhail Zabaluev.
+- An invalid Contact was used if STUN was disabled but there was no STUN
+  server. Problem reported by Miguel Freitas.
+- Fixed problem logging long lines from with TPORT_LOG.
+  Problem reported by Mike Murdock and Michael Jerris.
+- Nua now includes the SDP capabilities in the response to the OPTIONS
+- Fixed assertion failure because BYE destroyed a session twice.
+  Problem reported by Michael Jerris.
+- Fixed crash caused by a 0-length UDP datagram.
+  Problem reported by Michael Jerris.
+- Fixed the 305 response handling by nua stack.
+  Bug #1676445 reported by Fabio Margarido.
+- Fixed authentication-related bugs #1685245 and #1570746.
+  #1685245 reported by Mikhail Zabaluev.
+- Fixed problems resuming DNS after server or link downtime.
+  Bug #1631198 reported and initial patch submitted by Colin Whittaker.
+- Fixed NUTAG_APPL_METHOD() implementation for UPDATE and PRACK as documented
+- Fixed crashes in nua state engines:
+  - when nua_invite() was called second time before receiving
+    final response to first INVITE
+  - when UAS expected PRACK but received CANCEL
+  - when UAC received error response to PRACK, it tried to send BYE and crashed
+  - when UAS rejected initial request, the subsequent request with same 
+    dialog id (Call-ID, From-tag) crashed (dialog cleanup code left dialog
+    dangling)
+  Problems reported by Michael Jerris
+- Fixed crash in nta state engine:
+  - DNS resolver failure in non-invite transctions crashed
+- Fixed sdp handling when soa is disabled (NUTAG_MEDIA_ENABLE(0)).
+  Problem reported by Marcin Michalak

Modified: freeswitch/branches/cparker/libs/sofia-sip/RELEASE.template
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/RELEASE.template	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/RELEASE.template	Tue Apr 24 10:14:28 2007
@@ -6,7 +6,8 @@
 --------------------------
 
 <changes since last written in freshmeat.net "Changes:" style;
- and in less than 10 lines />
+ and in less than 10 lines, written in 3rd person English, with
+ complete sentences />
 
 Bugs in blaa and foo have been fixed. The stack now supports
 use of foobar...
@@ -39,9 +40,11 @@
 
 <list of people who contributed to _this_ release
  - update as people's patches are added, or when you commit stuff
- - current development team members (see AUTHORS) may be omitted
+ - current development team members (see AUTHORS) may be omitted,
+   or listed at the end of the contribur list (depending on the scope 
+   of the work done since the last release)
  - name of the contributor should be enough (email addresses in AUTHORS),
-   plus a brief description of what was contributed
+   plus a _brief_ description of what was contributed
  - roughly sorted by number of patches accepted
 /> 
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/configure.ac
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/configure.ac	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/configure.ac	Tue Apr 24 10:14:28 2007
@@ -11,14 +11,14 @@
 dnl ---------------------------
 
 dnl update both the version for AC_INIT and the LIBSOFIA_SIP_UA_MAJOR_MINOR
-AC_INIT([sofia-sip], [1.12.4work])
+AC_INIT([sofia-sip], [1.12.5work6])
 AC_CONFIG_SRCDIR([libsofia-sip-ua/sip/sofia-sip/sip.h])
 AC_SUBST(VER_LIBSOFIA_SIP_UA_MAJOR_MINOR, [1.12])
 dnl Includedir specific to this sofia version
 AC_SUBST(include_sofiadir, '${includedir}/sofia-sip-1.12')
-AC_SUBST(LIBVER_SOFIA_SIP_UA_CUR, [3])
+AC_SUBST(LIBVER_SOFIA_SIP_UA_CUR, [5])
 AC_SUBST(LIBVER_SOFIA_SIP_UA_REV, [0])
-AC_SUBST(LIBVER_SOFIA_SIP_UA_AGE, [3])
+AC_SUBST(LIBVER_SOFIA_SIP_UA_AGE, [5])
 AC_SUBST(LIBVER_SOFIA_SIP_UA_SOVER, [0]) # CUR-AGE
 AC_SUBST(LIBVER_SOFIA_SIP_UA_GLIB_CUR, [3])
 AC_SUBST(LIBVER_SOFIA_SIP_UA_GLIB_REV, [0])
@@ -29,7 +29,7 @@
 SAC_CANONICAL_SYSTEM_CACHE_CHECK
 
 AM_INIT_AUTOMAKE
-AM_MAINTAINER_MODE
+
 AC_CONFIG_HEADERS([config.h])
 
 AC_GNU_SOURCE
@@ -53,8 +53,15 @@
 dnl Add parameters for aclocal
 AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
 
-AC_CHECK_PROG([DOXYGEN], [doxygen], [doxygen], [echo])
-AM_CONDITIONAL([HAVE_DOXYGEN], [test $DOXYGEN = doxygen])
+AC_ARG_WITH(doxygen,
+[  --with-doxygen[[=CMD]]    use doxygen command CMD [[doxygen]]],[
+case $enable_doxygen in 
+yes ) doxygen=doxygen ;;
+no ) doxygen=echo ;;
+esac], doxygen=doxygen)
+
+AC_CHECK_PROG([DOXYGEN], [doxygen], [$doxygen], [echo])
+AM_CONDITIONAL([HAVE_DOXYGEN], [test $DOXYGEN != echo])
 
 ### checks for libraries
 ### --------------------
@@ -71,7 +78,7 @@
 AC_DEFINE([HAVE_SOFIA_SMIME], 0, [Define to 1 if we use S/MIME library])
 
 AC_ARG_ENABLE(stun,
-[  --disable-stun              disable stun module (enabled)],
+[  --disable-stun          disable stun module (enabled)],
  , enable_stun=yes)
 
 if test x$enable_stun = xno ; then
@@ -83,10 +90,19 @@
 else
   AC_DEFINE([HAVE_SOFIA_STUN], 1, [Define to 1 if we use STUN library])
 fi
+AM_CONDITIONAL([HAVE_STUN], [test "x$enable_stun" = xyes])
+
+AC_ARG_ENABLE(nth,
+[  --disable-nth           disable nth and http modules (enabled)],
+ , enable_nth=yes)
+AM_CONDITIONAL([HAVE_NTH], [test "x$enable_nth" = xyes])
+if test x$enable_nth = xyes ; then
+  AC_DEFINE([HAVE_SOFIA_NTH], 1, [Define to 1 if we use NTH library])
+fi
 
 dnl Disable NTLM support by default
 AC_ARG_ENABLE(ntlm,
-[  --enable-ntlm               enable NTLM support (disabled)],
+[  --enable-ntlm           enable NTLM support [[disabled]]],
  , enable_ntlm=no)
 
 if test x$enable_ntlm = xyes ; then
@@ -104,22 +120,97 @@
 
 ### checks for declarations
 ### -----------------------
-AC_CHECK_DECL([SIGPIPE], [
-AC_DEFINE([HAVE_SIGPIPE], 1, [Define to 1 if you have SIGPIPE])],,[
-#include <signal.h>
-])
 
 ### checks for types
 ### ----------------
 
 AC_TYPE_SIGNAL
-AC_TYPE_LONGLONG([
-AC_DEFINE([LLU], ["%llu"], [Define to format (%llu) for unsigned long long])dnl
-AC_DEFINE([LLI], ["%lli"], [Define to format (%lli) for long long])dnl
-AC_DEFINE([LLX], ["%llx"], [Define to format (%llx) for long long hex])dnl
+AC_TYPE_LONGLONG
+
+dnl
+dnl Define HAVE_C99_FORMAT to 1 if the formatted IO functions (printf/scanf
+dnl et.al.) support the C99 'size specifiers', namely ll, hh, j, z, t
+dnl (representing long long int, char, intmax_t, size_t, ptrdiff_t). Some C
+dnl compilers supported these specifiers prior to C99 as an extension.
+dnl
+AC_CACHE_CHECK([whether IO functions support C99 size specifiers],
+[ac_cv_c_c99_format],[
+
+ac_cv_c_c99_format=yes
+
+AC_RUN_IFELSE([AC_LANG_PROGRAM([AC_INCLUDES_DEFAULT],
+[[char buf[64];
+ if (sprintf(buf, "%lld%hhd%jd%zd%td", (long long int)1, (char)2, (intmax_t)3, (size_t)4, (ptrdiff_t)5) != 5)
+  exit(1);
+ else if (strcmp(buf, "12345"))
+  exit(2);]])],
+ [ac_cv_c_c99_format=yes],
+ [ac_cv_c_c99_format=no],
+ [ac_cv_c_c99_format=yes])
+])
+
+if test $ac_cv_c_c99_format = yes; then
+  AC_DEFINE([HAVE_C99_FORMAT], [1], [Define to 1 if printf supports C99 size specifiers])dnl
+
+  AC_DEFINE([LLU], ["%llu"], [Format (%llu) for unsigned long long])dnl
+  AC_DEFINE([LLI], ["%lli"], [Format (%lli) for long long])dnl
+  AC_DEFINE([LLX], ["%llx"], [Format (%llx) for long long hex])dnl
+  AC_DEFINE([MOD_ZD], ["%zd"], [Define printf() modifier for ssize_t])dnl
+  AC_DEFINE([MOD_ZU], ["%zu"], [Define printf() modifier for size_t])dnl
+
+else
+
+AC_CACHE_CHECK([whether IO functions support size specifier for long long],
+[ac_cv_c_ll_format],[
+
+ac_cv_c_ll_format=yes
+
+AC_RUN_IFELSE([AC_LANG_PROGRAM([AC_INCLUDES_DEFAULT],
+[[char buf[64];
+ if (sprintf(buf, "%lld", (long long int)1) != 1)
+  exit(1);
+ else if (strcmp(buf, "1"))
+  exit(2);]])],
+ [ac_cv_c_ll_format=yes],
+ [ac_cv_c_ll_format=no],
+ [ac_cv_c_ll_format=yes])
+])
+
+if test $ac_cv_c_ll_format = yes; then
+  AC_DEFINE([LLU], ["%llu"], [Format (%llu) for unsigned long long])dnl
+  AC_DEFINE([LLI], ["%lli"], [Format (%lli) for long long])dnl
+  AC_DEFINE([LLX], ["%llx"], [Format (%llx) for long long hex])dnl
+else
+  AC_MSG_ERROR("printf cannot handle 64-bit integers")
+fi
+
+AC_CACHE_CHECK([whether IO functions support size specifier for size_t],
+[ac_cv_c_z_format],[
+
+ac_cv_c_z_format=yes
+
+AC_RUN_IFELSE([AC_LANG_PROGRAM([AC_INCLUDES_DEFAULT],
+[[char buf[64];
+ if (sprintf(buf, "%zd", (size_t)1) != 1)
+  exit(1);
+ else if (strcmp(buf, "1"))
+  exit(2);]])],
+ [ac_cv_c_z_format=yes],
+ [ac_cv_c_z_format=no],
+ [ac_cv_c_z_format=yes])
 ])
-AC_DEFINE([MOD_ZD], ["%zd"], [Define printf() modifier for ssize_t])
-AC_DEFINE([MOD_ZU], ["%zu"], [Define printf() modifier for size_t])
+
+if test $ac_cv_c_z_format = yes; then
+  AC_DEFINE([MOD_ZD], ["%ld"], [Define printf() modifier for ssize_t])dnl
+  AC_DEFINE([MOD_ZU], ["%lu"], [Define printf() modifier for size_t])dnl
+else 
+  dnl Cross fingers
+  AC_MSG_WARN("printf cannot handle size_t, using long instead")
+  AC_DEFINE([MOD_ZD], ["%ld"], [Define printf() modifier for ssize_t])dnl
+  AC_DEFINE([MOD_ZU], ["%lu"], [Define printf() modifier for size_t])dnl
+fi 
+
+fi
 
 ### checks for structures
 ### ---------------------
@@ -138,7 +229,6 @@
 AC_HEADER_TIME
 AC_TYPE_SIZE_T
 
-AC_STRUCT_SIN6
 AC_SYS_SA_LEN
 
 ### checks for library functions
@@ -159,31 +249,51 @@
 packages/sofia-sip-ua-glib.pc
 libsofia-sip-ua/Makefile
 libsofia-sip-ua/bnf/Makefile
+libsofia-sip-ua/bnf/Doxyfile
 libsofia-sip-ua/docs/Makefile
+libsofia-sip-ua/docs/Doxyfile
 libsofia-sip-ua/docs/Doxyfile.version
 libsofia-sip-ua/docs/sofia-footer.html
+libsofia-sip-ua/features/Doxyfile
 libsofia-sip-ua/features/Makefile
+libsofia-sip-ua/http/Doxyfile
 libsofia-sip-ua/http/Makefile
+libsofia-sip-ua/ipt/Doxyfile
 libsofia-sip-ua/ipt/Makefile
+libsofia-sip-ua/iptsec/Doxyfile
 libsofia-sip-ua/iptsec/Makefile
+libsofia-sip-ua/msg/Doxyfile
 libsofia-sip-ua/msg/Makefile
+libsofia-sip-ua/nea/Doxyfile
 libsofia-sip-ua/nea/Makefile
+libsofia-sip-ua/nta/Doxyfile
 libsofia-sip-ua/nta/Makefile
+libsofia-sip-ua/nth/Doxyfile
 libsofia-sip-ua/nth/Makefile
+libsofia-sip-ua/nua/Doxyfile
 libsofia-sip-ua/nua/Makefile
+libsofia-sip-ua/sdp/Doxyfile
 libsofia-sip-ua/sdp/Makefile
+libsofia-sip-ua/sip/Doxyfile
 libsofia-sip-ua/sip/Makefile
+libsofia-sip-ua/soa/Doxyfile
 libsofia-sip-ua/soa/Makefile
+libsofia-sip-ua/sresolv/Doxyfile
 libsofia-sip-ua/sresolv/Makefile 
+libsofia-sip-ua/stun/Doxyfile
 libsofia-sip-ua/stun/Makefile
+libsofia-sip-ua/su/Doxyfile
 libsofia-sip-ua/su/Makefile
+libsofia-sip-ua/tport/Doxyfile
 libsofia-sip-ua/tport/Makefile
+libsofia-sip-ua/url/Doxyfile
 libsofia-sip-ua/url/Makefile
 libsofia-sip-ua/features/sofia-sip/sofia_features.h
 libsofia-sip-ua-glib/Makefile
 libsofia-sip-ua-glib/su-glib/Makefile
+libsofia-sip-ua-glib/su-glib/Doxyfile
 utils/Makefile
-utils/Doxyfile.build
+utils/Doxyfile
 win32/Makefile
 win32/config.h
 ])

Modified: freeswitch/branches/cparker/libs/sofia-sip/configure.gnu
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/configure.gnu	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/configure.gnu	Tue Apr 24 10:14:28 2007
@@ -1,2 +1,3 @@
 #! /bin/sh
-./configure $@ --with-pic --with-glib=no
+./configure "$@" --with-pic --with-glib=no --disable-shared
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/docs/build_system.txt
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/docs/build_system.txt	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/docs/build_system.txt	Tue Apr 24 10:14:28 2007
@@ -38,6 +38,11 @@
   separately in ``DIST_SOURCES`` variable (otherwise ``make dist``
   will fail)
 
+Makefile fragments
+------------------
+
+Some common makefile rules are in 'rules' subdirectory.
+
 Maintainer mode
 ---------------
 
@@ -54,13 +59,16 @@
 Running tests
 =============
 
-Sofia-SIP has quite complete suite of test cases. It is prudent to
-run them while making changes and before committing them to revision
-control system. However, running certain tests takes quite a long
-time. Therefore, they are run only if the environment variable
+Sofia-SIP has quite complete suite of test cases. It is prudent to run
+them while making changes and before committing them to revision control
+system. However, running certain tests takes quite a long time to
+execture. Therefore, they are run only if the environment variable
 EXPENSIVE_CHECKS has been set. EXPENSIVE_CHECKS is also set by the build
 system if configure option '--enable-expensive-checks' has been used.
 
+On hosts with i386 architecture, it is possible to run tests under
+valgrind. Use the make target 'valcheck' for that purpose.
+
 Code-tree layout
 ================
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/docs/devel_platform_notes.txt
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/docs/devel_platform_notes.txt	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/docs/devel_platform_notes.txt	Tue Apr 24 10:14:28 2007
@@ -11,14 +11,30 @@
 be at least 1.7. You can avoid running autoreconf explicitly if you use
 ./configure option --enable-maintainer-mode.
 
+Notes to distributors
+----------------------
+
+Build options such as "--disable-stun" (HAVE_SOFIA_STUN) and 
+"--disable-nth" (HAVE_SOFIA_NTH) modify the public library API/ABI,
+by omitting certain interfaces from the resulting library and installed
+header files.
+
+Options such as '--disable-size-compat' modify the library
+ABI by changing the types used in public library function 
+signatures.
+
 Generic POSIX (GNU/Linux, BSD, ...) 
 -----------------------------------
 
 Sofia-SIP should compile out-of-the-box on generic POSIX
 machines. Use the standard GNU autotool 'configure+make'
-procedure to build the software. See top-level INSTALL
+procedure to build the software. See top-level README file
 for more information.
 
+The configure script accepts various options. See "./configure --help"
+for the full list.
+
+
 Mac OS X 
 --------
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/docs/release_management.txt
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/docs/release_management.txt	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/docs/release_management.txt	Tue Apr 24 10:14:28 2007
@@ -61,7 +61,8 @@
     sh> cvs tag rel-sofia-sip-x_y_z
 - take a fresh checkout of the release using the release tag
     sh> darcs get http://sofia-sip.org/repos/sofia-sip --tag=rel-sofia-sip-1_yy_z
-- create the release tarball with "make distcheck"
+- create the release tarball with "make distcheck" (make sure depcomp et
+  al libtool scripts are correctly created)
 - calculate md5 and sha1 hashes using md5sum and sha1sum utilities,
   and copy the values to the release-notes (see below)
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -31,19 +31,8 @@
 	     docs/Doxyfile.conf \
 	     docs/Doxyfile.version
 
-built-sources: built-sources-recursive 
-clean-built-sources: clean-built-sources-recursive
-
-built-sources-recursive clean-built-sources-recursive:
-	target=`echo $@ | sed s/-recursive//`; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  echo "Making $@ in $$subdir"; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$target) \
-	done;
-
 doxygen: built-sources
-	@cd ${srcdir} ;\
-	mkdir -p docs docs/html &&\
+	@mkdir -p docs docs/html &&\
 	for d in $(DIST_SUBDIRS) $(DIST_SUBDIRS); do \
 	  test -r $$d/Doxyfile \
 	  && pushd $$d > /dev/null \
@@ -51,6 +40,8 @@
           && ${DOXYGEN} \
           && popd > /dev/null ; \
 	done
-	cd ${srcdir}/docs/html && ../../${top_srcdir}/libsofia-sip-ua/docs/hide_emails.sh
+	${top_srcdir}/libsofia-sip-ua/docs/hide_emails.sh docs/html 
+
+include $(top_srcdir)/rules/recursive.am
 
 .PHONY: built-sources built-sources-am doxygen 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -58,4 +58,4 @@
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../../libsofia-sip-ua/sofia.am
+include $(top_srcdir)/rules/sofia.am

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/sofia-sip/su_glib.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/sofia-sip/su_glib.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/sofia-sip/su_glib.h	Tue Apr 24 10:14:28 2007
@@ -43,6 +43,7 @@
 
 SOFIAPUBFUN su_root_t *su_glib_root_create(su_root_magic_t *) __attribute__((__malloc__));
 SOFIAPUBFUN GSource *su_glib_root_gsource(su_root_t *);
+SOFIAPUBFUN void su_glib_prefer_gsource(void);
 
 SOFIA_END_DECLS
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/su_source.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/su_source.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua-glib/su-glib/su_source.c	Tue Apr 24 10:14:28 2007
@@ -25,7 +25,11 @@
 /**
  * @file su_source.c
  * @brief Wrapper for glib GSource.
- * *  
+ *  
+ * Refs: 
+ *  - http://sofia-sip.sourceforge.net/refdocs/su/group__su__wait.html
+ *  - http://developer.gnome.org/doc/API/glib/glib-the-main-event-loop.html
+ *
  * @author Pekka Pessi <Pekka.Pessi at nokia.com>.
  * 
  * @date Created: Thu Mar  4 15:15:15 2004 ppessi
@@ -36,12 +40,6 @@
 #include "config.h"
 #endif
 
-#include <stdlib.h>
-#include <assert.h>
-#include <stdio.h>
-#include <string.h>
-#include <limits.h>
-
 #include <glib.h>
 
 #define SU_PORT_IMPLEMENTATION 1
@@ -57,16 +55,26 @@
 #include "su_port.h"
 #include "sofia-sip/su_alloc.h"
 
-static su_port_t *su_source_create(void) __attribute__((__malloc__));
+#include <stdlib.h>
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <limits.h>
+
+#if 1
+#define PORT_LOCK_DEBUG(x)  ((void)0)
+#else
+#define PORT_LOCK_DEBUG(x)  printf x
+#endif
+
+static su_port_t *su_source_port_create(void) __attribute__((__malloc__));
 static gboolean su_source_prepare(GSource *gs, gint *return_tout);
 static gboolean su_source_check(GSource *gs);
 static gboolean su_source_dispatch(GSource *gs,
-			    GSourceFunc callback,
-			    gpointer user_data);
+				   GSourceFunc callback,
+				   gpointer user_data);
 static void su_source_finalize(GSource *source);
 
-static int su_source_getmsgs(su_port_t *self);
-
 static
 GSourceFuncs su_source_funcs[1] = {{
     su_source_prepare,
@@ -106,21 +114,22 @@
 static su_duration_t su_source_step(su_port_t *self, su_duration_t tout);
 static int su_source_own_thread(su_port_t const *port);
 static int su_source_add_prepoll(su_port_t *port,
-			       su_root_t *root, 
-			       su_prepoll_f *, 
-			       su_prepoll_magic_t *);
+				 su_root_t *root, 
+				 su_prepoll_f *, 
+				 su_prepoll_magic_t *);
 static int su_source_remove_prepoll(su_port_t *port,
 				  su_root_t *root);
-static su_timer_t **su_source_timers(su_port_t *port);
 static int su_source_multishot(su_port_t *self, int multishot);
-static int su_source_threadsafe(su_port_t *port);
 
-static
-su_port_vtable_t const su_source_vtable[1] =
+static char const *su_source_name(su_port_t const *self);
+
+static 
+su_port_vtable_t const su_source_port_vtable[1] =
   {{
-      /* su_vtable_size: */ sizeof su_source_vtable,
+      /* su_vtable_size: */ sizeof su_source_port_vtable,
       su_source_lock,
       su_source_unlock,
+
       su_source_incref,
       su_source_decref,
 
@@ -138,32 +147,38 @@
       su_source_own_thread,
       su_source_add_prepoll,
       su_source_remove_prepoll,
-      su_source_timers,
+      su_base_port_timers,
       su_source_multishot,
-      su_source_threadsafe
-
+      su_base_port_threadsafe,
+      /*su_source_yield*/ NULL,
+      /*su_source_wait_events*/ NULL,
+      su_base_port_getmsgs,
+      su_base_port_getmsgs_from,
+      su_source_name,
+      su_base_port_start_shared,
+      su_base_port_wait,
+      NULL,
     }};
 
+static char const *su_source_name(su_port_t const *self)
+{
+  return "GSource";
+}
+
 /** 
  * Port is a per-thread reactor.  
  *
  * Multiple root objects executed by single thread share a su_port_t object. 
  */
 struct su_source_s {
-  su_home_t        sup_home[1];
-  su_port_vtable_t const *sup_vtable;
+  su_base_port_t   sup_base[1];
   
   GThread         *sup_tid;
   GStaticMutex     sup_mutex[1];
-  GStaticRWLock    sup_ref[1];
 
-  GSource         *sup_source;
-  GMainLoop       *sup_main_loop;
+  GSource         *sup_source;	/**< Backpointer to source */
+  GMainLoop       *sup_main_loop; /**< Reference to mainloop while running */
   
-  /* Message list - this is protected by lock  */
-  su_msg_t        *sup_head;
-  su_msg_t       **sup_tail;
-
   /* Waits */
   unsigned         sup_registers; /** Counter incremented by 
 				      su_port_register() or 
@@ -177,9 +192,6 @@
   su_wakeup_f     *sup_wait_cbs; 
   su_wakeup_arg_t**sup_wait_args; 
   su_root_t      **sup_wait_roots; 
-
-  /* Timer list */
-  su_timer_t      *sup_timers;
 };
 
 typedef struct _SuSource
@@ -194,10 +206,6 @@
 #define SU_SOURCE_INCREF(p, f)    (g_source_ref(p->sup_source))
 #define SU_SOURCE_DECREF(p, f)    (g_source_unref(p->sup_source))
 
-#define SU_SOURCE_INITLOCK(p)     (g_static_mutex_init((p)->sup_mutex))
-#define SU_SOURCE_LOCK(p, f)      (g_static_mutex_lock((p)->sup_mutex))
-#define SU_SOURCE_UNLOCK(p, f)    (g_static_mutex_unlock((p)->sup_mutex))
-
 #else
 
 /* Debugging versions */
@@ -205,15 +213,6 @@
 #define SU_SOURCE_DECREF(p, f)    do { printf("decref(%p) by %s\n", (p), f), \
   g_source_unref(p->sup_source); } while(0)
 
-#define SU_SOURCE_INITLOCK(p) \
-   (g_static_mutex_init((p)->sup_mutex), printf("init_lock(%p)\n", p))
-
-#define SU_SOURCE_LOCK(p, f)    \
-   (printf("%ld at %s locking(%p)...", g_thread_self(), f, p), g_static_mutex_lock((p)->sup_mutex), printf(" ...%ld at %s locked(%p)...", g_thread_self(), f, p))
-
-#define SU_SOURCE_UNLOCK(p, f)  \
-  (g_static_mutex_unlock((p)->sup_mutex), printf(" ...%ld at %s unlocked(%p)\n", g_thread_self(), f, p))
-
 #endif
 
 #if HAVE_FUNC
@@ -229,7 +228,7 @@
 /** Create a root that uses GSource as reactor */
 su_root_t *su_glib_root_create(su_root_magic_t *magic)
 {
-  return su_root_create_with_port(magic, su_source_create());
+  return su_root_create_with_port(magic, su_source_port_create());
 }
 
 /** Deprecated */
@@ -238,6 +237,15 @@
   return su_glib_root_create(magic);
 }
 
+/** 
+ * Returns a GSource object for the root 
+ *
+ * Note that you need to unref the GSource with g_source_unref() 
+ * before destroying the root object.
+ *
+ * @return NULL on error (for instance if root was not created with 
+ *         su_glib_root_create())
+ */
 GSource *su_glib_root_gsource(su_root_t *root)
 {
   g_assert(root);
@@ -246,41 +254,20 @@
 
 /*=============== Private function definitions ===============*/
 
-/**@internal
- *
- * Allocates and initializes a reactor and message port object.
- *
- * @return
- *   If successful a pointer to the new message port is returned, otherwise
- *   NULL is returned.  
- */
-su_port_t *su_source_create(void)
+/** Initialize source port */
+int su_source_port_init(su_port_t *self,
+			GSource *gs,
+			su_port_vtable_t const *vtable)
 {
-  SuSource *ss;
-
-  SU_DEBUG_9(("su_source_create() called\n"));
-
-  ss = (SuSource *)g_source_new(su_source_funcs, (sizeof *ss));
-
-  if (ss) {
-    su_port_t *self = ss->ss_port;
-
-    self->sup_vtable = su_source_vtable;
-    self->sup_source = ss->ss_source;
-    
-    SU_SOURCE_INITLOCK(self);
-
-    self->sup_tail = &self->sup_head;
-    self->sup_tid = g_thread_self();
+  if (su_base_port_init(self, vtable) < 0)
+    return -1;
 
-    SU_DEBUG_9(("su_source_with_main_context() returns %p\n", self));
+  self->sup_source = gs;
+  self->sup_tid = g_thread_self();
 
-    return self;
-  } else {
-    su_perror("su_source_with_main_context(): su_home_clone");
-    SU_DEBUG_9(("su_source_with_main_context() fails\n"));
-    return NULL;
-  }
+  g_static_mutex_init(self->sup_mutex);
+  
+  return 0;
 }
 
 /** @internal Destroy a port. */
@@ -294,23 +281,70 @@
 
   SU_DEBUG_9(("su_source_finalize() called\n"));
 
-  if (self->sup_waits) 
-    free(self->sup_waits), self->sup_waits = NULL;
-  if (self->sup_wait_cbs)
-    free(self->sup_wait_cbs), self->sup_wait_cbs = NULL;
-  if (self->sup_wait_args)
-    free(self->sup_wait_args), self->sup_wait_args = NULL;
-  if (self->sup_wait_roots)
-    free(self->sup_wait_roots), self->sup_wait_roots = NULL;
-  if (self->sup_indices)
-    free(self->sup_indices), self->sup_indices = NULL;
+  g_static_mutex_free(self->sup_mutex);
+
+  su_base_port_deinit(self);
+
+  su_home_deinit(self->sup_base->sup_home);
+}
+
+void su_source_port_lock(su_port_t *self, char const *who)
+{
+  PORT_LOCK_DEBUG(("%p at %s locking(%p)...",
+		   (void *)g_thread_self(), who, self));
+
+  g_static_mutex_lock(self->sup_mutex);
+
+  PORT_LOCK_DEBUG((" ...%p at %s locked(%p)...", 
+		   (void *)g_thread_self(), who, self));
+}
+
+void su_source_port_unlock(su_port_t *self, char const *who)
+{
+  g_static_mutex_unlock(self->sup_mutex);
+
+  PORT_LOCK_DEBUG((" ...%p at %s unlocked(%p)\n", 
+		   (void *)g_thread_self(), who, self));
+}
+
+/** @internal Send a message to the port. */
+int su_source_send(su_port_t *self, su_msg_r rmsg)
+{
+  int wakeup = su_base_port_send(self, rmsg);
+  GMainContext *gmc;
+
+  if (wakeup < 0)
+    return -1;
+  if (wakeup == 0)
+    return 0;
+
+  gmc = g_source_get_context(self->sup_source);
+
+  if (gmc)
+    g_main_context_wakeup(gmc);
 
-  su_home_deinit(self->sup_home);
+  return 0;
 }
 
+/** @internal
+ * Checks if the calling thread owns the port object.
+ *
+ * @param self pointer to a port object
+ *
+ * @retval true (nonzero) if the calling thread owns the port,
+ * @retval false (zero) otherwise.
+ */
+int su_source_own_thread(su_port_t const *self)
+{
+  return self == NULL || SU_SOURCE_OWN_THREAD(self);
+}
+
+/* -- Registering and unregistering ------------------------------------- */
+
 /* Seconds from 1.1.1900 to 1.1.1970 */
 #define NTP_EPOCH 2208988800UL 
 
+/** Prepare to wait - calculate time to next timer */
 static
 gboolean su_source_prepare(GSource *gs, gint *return_tout)
 {
@@ -319,12 +353,12 @@
 
   enter;
   
-  if (self->sup_head) {
+  if (self->sup_base->sup_head) {
     *return_tout = 0;
     return TRUE;
   }
 
-  if (self->sup_timers) {
+  if (self->sup_base->sup_timers) {
     su_time_t now;
     GTimeVal  gtimeval;
     su_duration_t tout;
@@ -333,7 +367,7 @@
     now.tv_sec = gtimeval.tv_sec + 2208988800UL;
     now.tv_usec = gtimeval.tv_usec;
 
-    tout = su_timer_next_expires(self->sup_timers, now);
+    tout = su_timer_next_expires(self->sup_base->sup_timers, now);
 
     *return_tout = (tout < 0 || tout > (su_duration_t)G_MAXINT)?
 	-1 : (gint)tout;
@@ -376,10 +410,10 @@
 
   enter;
 
-  if (self->sup_head)
-    su_source_getmsgs(self);
+  if (self->sup_base->sup_head)
+    su_base_port_getmsgs(self);
 
-  if (self->sup_timers) {
+  if (self->sup_base->sup_timers) {
     su_time_t now;
     GTimeVal  gtimeval;
     su_duration_t tout;
@@ -392,7 +426,7 @@
     now.tv_sec = gtimeval.tv_sec + 2208988800UL;
     now.tv_usec = gtimeval.tv_usec;
 
-    timers = su_timer_expire(&self->sup_timers, &tout, now);
+    timers = su_timer_expire(&self->sup_base->sup_timers, &tout, now);
   }
 
 #if SU_HAVE_POLL
@@ -424,12 +458,20 @@
 
 static void su_source_lock(su_port_t *self, char const *who)
 {
-  SU_SOURCE_LOCK(self, who);
+  PORT_LOCK_DEBUG(("%p at %s locking(%p)...",
+		   (void *)g_thread_self(), who, self));
+  g_static_mutex_lock(self->sup_mutex);
+
+  PORT_LOCK_DEBUG((" ...%p at %s locked(%p)...", 
+		   (void *)g_thread_self(), who, self));
 }
 
 static void su_source_unlock(su_port_t *self, char const *who)
 {
-  SU_SOURCE_UNLOCK(self, who);
+  g_static_mutex_unlock(self->sup_mutex);
+
+  PORT_LOCK_DEBUG((" ...%p at %s unlocked(%p)\n", 
+		   (void *)g_thread_self(), who, self));
 }
 
 static void su_source_incref(su_port_t *self, char const *who)
@@ -448,81 +490,6 @@
   return self->sup_source;
 }
 
-/** @internal Send a message to the port. */
-int su_source_send(su_port_t *self, su_msg_r rmsg)
-{
-  enter;
-  
-  if (self) {
-    su_msg_t *msg;
-    GMainContext *gmc;
-
-    SU_SOURCE_LOCK(self, "su_source_send");
-    
-    msg = rmsg[0]; rmsg[0] = NULL;
-    *self->sup_tail = msg;
-    self->sup_tail = &msg->sum_next;
-
-    SU_SOURCE_UNLOCK(self, "su_source_send");
-
-    gmc = g_source_get_context(self->sup_source);
-
-    if (gmc)
-      g_main_context_wakeup(gmc);
-
-    return 0;
-  }
-  else {
-    su_msg_destroy(rmsg);
-    return -1;
-  }
-}
-
-/** @internal
- * Execute the messages in the incoming queue until the queue is empty..
- *
- * @param self - pointer to a port object
- *
- * @retval 0 if there was a signal to handle, 
- * @retval -1 otherwise.
- */
-static
-int su_source_getmsgs(su_port_t *self)
-{
-  enter;
-  
-  if (self && self->sup_head) {
-    su_root_t *root;
-    su_msg_f f;
-
-    SU_SOURCE_INCREF(self, "su_source_getmsgs");
-    SU_SOURCE_LOCK(self, "su_source_getmsgs");
-
-    while (self->sup_head) {
-      su_msg_t *msg = self->sup_head;
-      self->sup_head = msg->sum_next;
-      if (!self->sup_head) {
-	assert(self->sup_tail == &msg->sum_next);
-	self->sup_tail = &self->sup_head;
-      }
-      root = msg->sum_to->sut_root;
-      f = msg->sum_func;
-      SU_SOURCE_UNLOCK(self, "su_source_getmsgs");
-      if (f) 
-	f(su_root_magic(root), &msg, msg->sum_data);
-      su_msg_delivery_report(&msg);
-      SU_SOURCE_LOCK(self, "su_source_getmsgs");
-    }
-
-    SU_SOURCE_UNLOCK(self, "su_source_getmsgs");
-    SU_SOURCE_DECREF(self, "su_source_getmsgs");
-
-    return 0;
-  }
-  else
-    return -1;
-}
-
 /** @internal
  *
  *  Register a @c su_wait_t object. The wait object, a callback function and
@@ -914,13 +881,6 @@
     return (errno = EINVAL), -1;
 }
 
-/** @internal Enable threadsafe operation. */
-static
-int su_source_threadsafe(su_port_t *port)
-{
-  return su_home_threadsafe(port->sup_home);
-}
-
 
 /** @internal Main loop.
  * 
@@ -1019,18 +979,19 @@
   return 0;
 }
 
+static int su_source_add_prepoll(su_port_t *port,
+				 su_root_t *root, 
+				 su_prepoll_f *prepoll, 
+				 su_prepoll_magic_t *magic)
+{
+  /* We could call prepoll in su_source_prepare()?? */
+  return -1;
+}
 
-/** @internal
- * Checks if the calling thread owns the port object.
- *
- * @param self pointer to a port object
- *
- * @retval true (nonzero) if the calling thread owns the port,
- * @retval false (zero) otherwise.
- */
-int su_source_own_thread(su_port_t const *self)
+static int su_source_remove_prepoll(su_port_t *port,
+				  su_root_t *root)
 {
-  return self == NULL || SU_SOURCE_OWN_THREAD(self);
+  return -1;
 }
 
 #if 0
@@ -1061,52 +1022,44 @@
 
 #endif
 
-/* =========================================================================
- * Pre-poll() callback
+/**@internal
+ *
+ * Allocates and initializes a reactor and message port object.
+ *
+ * @return
+ *   If successful a pointer to the new message port is returned, otherwise
+ *   NULL is returned.  
  */
-
-int su_source_add_prepoll(su_port_t *port,
-			su_root_t *root, 
-			su_prepoll_f *callback, 
-			su_prepoll_magic_t *magic)
+static su_port_t *su_source_port_create(void)
 {
-#if 0
-  if (port->sup_prepoll)
-    return -1;
+  SuSource *ss;
+  su_port_t *self = NULL;
 
-  port->sup_prepoll = callback;
-  port->sup_pp_magic = magic;
-  port->sup_pp_root = root;
+  SU_DEBUG_9(("su_source_port_create() called\n"));
 
-  return 0;
-#else
-  return -1;
-#endif
-}
+  ss = (SuSource *)g_source_new(su_source_funcs, (sizeof *ss));
 
-int su_source_remove_prepoll(su_port_t *port,
-			   su_root_t *root)
-{
-#if 0
-  if (port->sup_pp_root != root)
-    return -1;
+  if (ss) {
+    self = ss->ss_port;
+    if (su_source_port_init(self, ss->ss_source, su_source_port_vtable) < 0)
+      g_source_unref(ss->ss_source), self = NULL;
+  } else {
+    su_perror("su_source_port_create(): g_source_new");
+  }
 
-  port->sup_prepoll = NULL;
-  port->sup_pp_magic = NULL;
-  port->sup_pp_root = NULL;
+  SU_DEBUG_1(("su_source_port_create() returns %p\n", (void *)self));
 
-  return 0;
-#else
-  return -1;
-#endif
+  return self;
 }
 
-/* =========================================================================
- * Timers
- */
+/* No su_source_port_start */
 
-static
-su_timer_t **su_source_timers(su_port_t *self)
+/** Use su_source implementation when su_root_create() is called.
+ *
+ * @NEW_1_12_5
+ */
+void su_glib_prefer_gsource(void)
 {
-  return &self->sup_timers;
+  su_port_prefer(su_source_port_create, NULL);
 }
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ChangeLog
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ChangeLog	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ChangeLog	Tue Apr 24 10:14:28 2007
@@ -1,3 +1,11 @@
+2007-02-09  Kai Vehmanen  <kai.vehmanen at nokia.com>
+
+	* libsofia-sip-ua interface v4 frozen (4:0:4) for the 1.12.5 release
+
+2006-10-12  Kai Vehmanen  <kai.vehmanen at nokia.com>
+
+	* libsofia-sip-ua interface v3 frozen (3:0:3) for the 1.12.3 release
+	
 2006-09-26  Kai Vehmanen  <kai.vehmanen at nokia.com>
 
 	* libsofia-sip-ua interface v2 frozen (2:0:2) for the 1.12.2 release

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -9,12 +9,25 @@
 
 AUTOMAKE_OPTIONS = foreign
 
+# select whicn optional sofia-sip modules have been enabled
+# in the build
+OPT_LIBADD =
+OPT_SUBDIRS_STUN =
+OPT_SUBDIRS_NTH =
+if HAVE_STUN
+OPT_LIBADD += stun/libstun.la 
+OPT_SUBDIRS_STUN += stun
+endif
+if HAVE_NTH
+OPT_LIBADD += nth/libnth.la http/libhttp.la
+OPT_SUBDIRS_NTH += nth http
+endif
+
 # note: order does matter in the subdir list
-SUBDIRS = su features bnf sresolv sdp url msg sip stun ipt soa \
-	  tport http nta nea iptsec nth nua
+SUBDIRS = su features bnf sresolv sdp url msg sip $(OPT_SUBDIRS_STUN) ipt soa \
+	  tport nta nea iptsec $(OPT_SUBDIRS_NTH) nua
 DIST_SUBDIRS = $(SUBDIRS) docs
 
-EXTRA_DIST = sofia.am
 DOXYGEN = doxygen
 
 lib_LTLIBRARIES = libsofia-sip-ua.la
@@ -27,41 +40,25 @@
 				msg/libmsg.la \
 				nea/libnea.la \
 				nta/libnta.la \
-				nth/libnth.la \
 				nua/libnua.la \
-				http/libhttp.la \
 				sdp/libsdp.la \
 				sip/libsip.la \
 				soa/libsoa.la \
 				sresolv/libsresolv.la \
 				su/libsu.la \
-				stun/libstun.la \
 				tport/libtport.la \
-				url/liburl.la
+				url/liburl.la \
+				$(OPT_LIBADD)
+
 # set the libtool version info version:revision:age for libsofia-sip-ua
 # - soname to 'libsofia-sip-ua.so.(CUR-AGE)'
 libsofia_sip_ua_la_LDFLAGS = \
 	-version-info $(LIBVER_SOFIA_SIP_UA_CUR):$(LIBVER_SOFIA_SIP_UA_REV):$(LIBVER_SOFIA_SIP_UA_AGE)
 
-if ENABLE_COVERAGE
-COVERAGE_RECURSIVE = coverage-recursive
-coverage: $(COVERAGE_RECURSIVE)
-endif
-
-all-recursive: built-sources-recursive
-built-sources: built-sources-recursive 
-clean-built-sources: clean-built-sources-recursive
-
-built-sources-recursive clean-built-sources-recursive $(COVERAGE_RECURSIVE):
-	target=`echo $@ | sed s/-recursive//`; \
-	list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  echo "Making $@ in $$subdir"; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$target) \
-	done;
+include $(top_srcdir)/rules/recursive.am
 
 doxygen: built-sources
 	@echo Generating empty doxytags
-	cd ${srcdir}; \
 	mkdir -p docs/html ; \
 	for d in $(DIST_SUBDIRS); do \
 	  test -r $$d/Doxyfile || continue ; \
@@ -73,20 +70,18 @@
 	    mv -f docs/$$d.doxytags.tmp docs/$$d.doxytags ; \
           fi ; \
 	done
-	@cd ${srcdir} ;\
 	for d in $(DIST_SUBDIRS); do \
 	  test -r $$d/Doxyfile \
 	  && pushd $$d > /dev/null \
 	  && echo running ${DOXYGEN} first time in $$d \
           && ${DOXYGEN} 2>&1 \
-	  | egrep -v -i -e 'Warning: (unsupported (xml/)?html tag|unable to resolve reference|could not be resolved)' \
+	  | egrep -v -i -e 'Warning: (unsupported (xml/)?html tag|unable to resolve reference|explicit link.*could not be resolved)' \
           ; popd > /dev/null ; \
 	  test -r docs/$$d.doxytags && \
 	  sed '2,10s!<name>index</name>!<name>'$$d'_index</name>!' \
 	    docs/$$d.doxytags > docs/$$d.doxytags.tmp && \
 	  mv -f docs/$$d.doxytags.tmp docs/$$d.doxytags ; \
 	done 
-	@cd ${srcdir} ;\
 	for d in $(DIST_SUBDIRS); do \
 	  test -r $$d/Doxyfile \
 	  && pushd $$d > /dev/null \
@@ -99,6 +94,6 @@
 	    docs/$$d.doxytags > docs/$$d.doxytags.tmp && \
 	  mv -f docs/$$d.doxytags.tmp docs/$$d.doxytags ; \
 	done 
-	cd ${srcdir}/docs/html && ../hide_emails.sh
+	${srcdir}/docs/hide_emails.sh docs/html
 
 .PHONY: built-sources built-sources-am empty-doxytags doxygen 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -33,7 +33,7 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile bnf.docs
+EXTRA_DIST =		bnf.docs
 
 # ----------------------------------------------------------------------
 # Tests
@@ -43,4 +43,5 @@
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/bnf.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/bnf.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/bnf.c	Tue Apr 24 10:14:28 2007
@@ -377,7 +377,7 @@
 
     if (i == maxparts + 1) {
       /* There is an extra doublecolon */
-      for (j = doublecolon; j <= i; j++)
+      for (j = doublecolon; j + 1 < i; j++)
 	hexparts[j] = hexparts[j + 1];
       i--;
     }
@@ -825,9 +825,9 @@
 {
   size_t len;
   int canonize = 0;
+  char buf[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"];
 
 #if SU_HAVE_IN6
-  char buf[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"];
 
   len = span_ip6_reference(s);
   if (len) {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/torture_bnf.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/torture_bnf.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/bnf/torture_bnf.c	Tue Apr 24 10:14:28 2007
@@ -340,9 +340,10 @@
   END();
 }
 
-void usage(void)
+void usage(int exitcode)
 {
-  fprintf(stderr, "usage: %s [-v]\n", name);
+  fprintf(stderr, "usage: %s [-v] [-a]\n", name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -353,8 +354,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       test_flags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      test_flags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= bnf_test(); fflush(stdout);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.aliases
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.aliases	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.aliases	Tue Apr 24 10:14:28 2007
@@ -45,4 +45,8 @@
  "VERSION_1_12_4=<a href=\"http://sofia-sip.sf.net/relnotes/relnotes-sofia-sip-1.12.4.txt\">1.12.4</a>" \
  "VERSION_1_12_5=<a href=\"http://sofia-sip.sf.net/relnotes/relnotes-sofia-sip-1.12.5.txt\">1.12.5</a>" \
  "NEW_1_12_5=@since New in <a href=\"http://sofia-sip.sf.net/relnotes/relnotes-sofia-sip-1.12.5.txt\">1.12.5</a>" \
+ "EXP_1_12_5=@since Experimental in <a href=\"http://sofia-sip.sf.net/relnotes/relnotes-sofia-sip-1.12.5.txt\">1.12.5</a>, available if --enable-experimental configuration option is given" \
+ "VERSION_1_12_6=<a href=\"http://sofia-sip.sf.net/relnotes/relnotes-sofia-sip-1.12.6.txt\">1.12.6</a>" \
+ "NEW_1_12_6=@since New in <a href=\"http://sofia-sip.sf.net/relnotes/relnotes-sofia-sip-1.12.6.txt\">1.12.6</a>" \
+ "EXP_1_12_6=@since Experimental in <a href=\"http://sofia-sip.sf.net/relnotes/relnotes-sofia-sip-1.12.6.txt\">1.12.6</a>, available if --enable-experimental configuration option is given" \
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.conf
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.conf	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.conf	Tue Apr 24 10:14:28 2007
@@ -62,5 +62,3 @@
 EXCLUDE_PATTERNS     = acconfig.h config.h confdefs.h \
 			test*.h test*.c torture*.c *test.c *torture.c \
 			*_tag_dll.c *_tag_ref.c
-
-IMAGE_PATH           = ../../libsofia-sip-ua/docs/pictures

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.version.in
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.version.in	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Doxyfile.version.in	Tue Apr 24 10:14:28 2007
@@ -1 +1,3 @@
 PROJECT_NUMBER = @VERSION@
+
+IMAGE_PATH = @top_srcdir@/libsofia-sip-ua/docs/pictures

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -1,9 +1,7 @@
-EXTRA_DIST = 	Doxyfile Doxyfile.aliases Doxyfile.conf \
+EXTRA_DIST = 	Doxyfile.aliases Doxyfile.conf \
 		docguide.docs \
 		mainpage.docs \
 		conformance.docs \
-		Doxyfile.version.in \
-		sofia-footer.html.in \
 		hide_emails.sh \
 		ChangeLog \
 	pictures/SIP_basic_incoming_operation.eps \
@@ -47,4 +45,4 @@
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
\ No newline at end of file
+include $(top_srcdir)/rules/sofia.am

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/conformance.docs
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/conformance.docs	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/conformance.docs	Tue Apr 24 10:14:28 2007
@@ -43,6 +43,7 @@
 <a href="#3892">RFC 3892</a> <br>
 <a href="#3903">RFC 3903</a> <br>
 <a href="#4028">RFC 4028</a> <br>
+<a href="#4320">RFC 4320</a> <br>
 <a href="#4566">RFC 4566</a> <br>
 </td><td>
 <a href="#2327">RFC 2327</a> <br>
@@ -849,9 +850,11 @@
         The session-expires value and refreshing party is negotiated in
 	<a href="nua/index.html">user-agent engine</a>. When user-agent
 	engine is responsible for refreshes, it will initiate re-INVITE or
-	UPDATE transaction at regular intervals. If there has been no SIP
-	activity in session during the refresh period, it will try to
-	automatically terminate the call by sending a @b BYE request.
+	UPDATE transaction at regular intervals.
+
+	If there has been no SIP activity in session during the refresh
+	period, it will try to automatically terminate the call by sending a
+	@b BYE request.
 
         The SIP headers explicitly supported (generating, parsing and
 	syntax checking) are @ref sip_session_expires "Session-Expires" ("x") and
@@ -861,6 +864,29 @@
 	&nbsp;
     </td>
 </tr>
+
+<tr valign=top>
+    <th align="left">
+	<a name="4320"></a>
+	@RFC4320: Actions Addressing Identified Issues with SIP's Non-INVITE Transaction
+    </th>
+    <td>
+	The action 1 (make the best use of provisional responses) is
+	supported when NTATAG_EXTRA_100(1) is used with nua_create() or
+	nta_agent_create(). The 100 Trying provisional response is sent
+	after T2 is expired or when a retransmission is received after T2/2
+        after the initial request.
+
+	The action 2 (remove the useless late-response storm) is supported
+	by default. The 408 timeout response is not forwarded by default (it's
+	forwarding can be enabled with NTATAG_PASS_408(1), however).
+    </td>
+    <td>
+        Application must include NTATAG_EXTRA_100(1) with nua_create() or
+	nta_agent_create() tags.
+    </td>
+</tr>
+
 </table>
 
 <table border=1 cellpadding=4 cellspacing=0>

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/hide_emails.sh
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/hide_emails.sh	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/docs/hide_emails.sh	Tue Apr 24 10:14:28 2007
@@ -29,9 +29,9 @@
 #
 # --------------------------------------------------------------------
 
-find . -name '*.html' -print | while read i ; do 
-  (
-    echo "Hiding email addresses in ${i}."
-    sed -r -i 's/([:>;][a-z][-a-z.]*)(@[a-z][a-z]*)\.[a-z][a-z]*(["<\&])/\1\2-email.address.hidden\3/gi' $i
- )
-done
+echo "Hiding email addresses in ${1:-.}"
+
+find ${1:-.} -name '*.html' -print0 | 
+xargs -0 \
+sed -r -i 's/([:>;][a-z][-a-z.]*)(@[a-z][a-z]*)\.[a-z][a-z]*(["<\&])/\1\2-email.address.hidden\3/gi'
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/features/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/features/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/features/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -26,9 +26,10 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile features.docs
+EXTRA_DIST =		features.docs
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -30,17 +30,17 @@
 			sofia-sip/http_status.h sofia-sip/http_hclasses.h
 
 BUILT_H = 		sofia-sip/http_protos.h sofia-sip/http_tag.h 
-BUILT_C = 		http_tag.c http_tag_ref.c http_parser_table.c
+BUILT_C = 		http_tag.c http_parser_table.c
 
-BUILT_SOURCES = 	$(BUILT_H) $(BUILT_C)
+BUILT_SOURCES = 	$(BUILT_H) $(BUILT_C) http_tag_ref.c
 
 nobase_include_sofia_HEADERS = $(BUILT_H) $(PUBLIC_H) 
 
 libhttp_la_SOURCES = 	$(INTERNAL_H) \
 			http_parser.c http_header.c \
-			http_basic.c http_extra.c \
+			http_basic.c http_extra.c http_inlined.c \
 			http_status.c http_tag_class.c \
-			$(BUILT_C)
+			$(BUILT_SOURCES)
 
 COVERAGE_INPUT = 	$(libhttp_la_SOURCES) $(include_sofia_HEADERS)
 
@@ -48,6 +48,7 @@
 			../bnf/libbnf.la \
 			../msg/libmsg.la \
 			../url/liburl.la \
+			../ipt/libipt.la \
 			../su/libsu.la
 
 test_http_LDFLAGS = 	-static
@@ -55,7 +56,7 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile http.docs \
+EXTRA_DIST =		http.docs \
 			sofia-sip/http_protos.h.in \
 			sofia-sip/http_tag.h.in \
 			http_parser_table.c.in \
@@ -64,30 +65,29 @@
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
 
 TAG_DLL_FLAGS = DLLREF=1
 
-MSG_PARSER_AWK = $(srcdir)/../msg/msg_parser.awk
+MSG_PARSER_AWK = ${srcdir}/../msg/msg_parser.awk
 
-AWK_HTTP_AWK = $(AWK) -f $(MSG_PARSER_AWK) module=http
+AWK_HTTP_AWK = LC_ALL=C ${AWK} -f ${MSG_PARSER_AWK} module=http
 
-sofia-sip/http_tag.h: sofia-sip/http_tag.h.in $(MSG_PARSER_AWK)
-sofia-sip/http_protos.h: sofia-sip/http_protos.h.in $(MSG_PARSER_AWK)
-http_tag.c: http_tag.c.in $(MSG_PARSER_AWK)
-http_parser_table.c: http_parser_table.c.in $(MSG_PARSER_AWK)
+SS_HTTP_H = ${srcdir}/sofia-sip/http.h
 
-sofia-sip/http_protos.h: sofia-sip/http.h
+${BUILT_H} ${BUILT_C}: ${srcdir}/sofia-sip/http.h ${MSG_PARSER_AWK}
+
+sofia-sip/http_protos.h: ${srcdir}/sofia-sip/http_protos.h.in 
 	@-mkdir sofia-sip 2>/dev/null || true
-	$(AWK_HTTP_AWK) PR=$@ TEMPLATE=$(srcdir)/sofia-sip/http_protos.h.in $<
+	${AWK_HTTP_AWK} PR=$@ TEMPLATE=${srcdir}/sofia-sip/http_protos.h.in ${SS_HTTP_H}
 
-sofia-sip/http_tag.h: sofia-sip/http.h
+sofia-sip/http_tag.h: ${srcdir}/sofia-sip/http_tag.h.in
 	@-mkdir sofia-sip 2>/dev/null || true
-	$(AWK_HTTP_AWK) PR=$@ TEMPLATE=$(srcdir)/sofia-sip/http_tag.h.in $<
+	${AWK_HTTP_AWK} PR=$@ TEMPLATE=${srcdir}/sofia-sip/http_tag.h.in ${SS_HTTP_H}
 
-http_tag.c: sofia-sip/http.h
-	$(AWK_HTTP_AWK) PR=$@ TEMPLATE=$(srcdir)/http_tag.c.in $<
+http_tag.c: ${srcdir}/http_tag.c.in
+	${AWK_HTTP_AWK} PR=$@ TEMPLATE=${srcdir}/http_tag.c.in ${SS_HTTP_H}
 
-http_parser_table.c: sofia-sip/http.h
-	$(AWK_HTTP_AWK) PT=$@ TEMPLATE=$(srcdir)/http_parser_table.c.in \
-		MC_HASH_SIZE=127 $<
+http_parser_table.c: ${srcdir}/http_parser_table.c.in
+	${AWK_HTTP_AWK} PT=$@ TEMPLATE=${srcdir}/http_parser_table.c.in \
+		MC_HASH_SIZE=127 ${SS_HTTP_H}

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/http_basic.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/http_basic.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/http_basic.c	Tue Apr 24 10:14:28 2007
@@ -55,6 +55,7 @@
 #include <string.h>
 #include <assert.h>
 #include <stdio.h>
+#include <limits.h>
 
 /* ====================================================================== */
 
@@ -1196,7 +1197,7 @@
   http_range_t const *o = (http_range_t const *)src;
   char *end = b + xtra;
 
-  b = msg_params_dup((char const * const **)&rng->rng_specs,
+  b = msg_params_dup((msg_param_t const **)&rng->rng_specs,
 		     o->rng_specs, b, xtra);
   MSG_STRING_DUP(b, rng->rng_unit, o->rng_unit);
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/http_parser.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/http_parser.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/http_parser.c	Tue Apr 24 10:14:28 2007
@@ -61,9 +61,9 @@
 /** HTTP version 0.9 is an empty string. */
 char const http_version_0_9[] = "";
 
-msg_mclass_t *http_default_mclass(void)
+msg_mclass_t const *http_default_mclass(void)
 {
-  extern msg_mclass_t http_mclass[];
+  extern msg_mclass_t const http_mclass[];
 
   return http_mclass;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/sofia-sip/http_header.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/sofia-sip/http_header.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/sofia-sip/http_header.h	Tue Apr 24 10:14:28 2007
@@ -95,7 +95,7 @@
  */
 
 /** HTTP parser description. */
-SOFIAPUBFUN msg_mclass_t *http_default_mclass(void);
+SOFIAPUBFUN msg_mclass_t const *http_default_mclass(void);
 
 /** Complete a HTTP request. */
 SOFIAPUBFUN int http_request_complete(msg_t *msg);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/test_http.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/test_http.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/http/test_http.c	Tue Apr 24 10:14:28 2007
@@ -76,14 +76,7 @@
 static int test_query_parser(void);
 
 static msg_t *read_message(char const string[]);
-msg_mclass_t *test_mclass = NULL;
-
-void usage(void)
-{
-  fprintf(stderr,
-	  "usage: %s [-v]\n",
-	  name);
-}
+msg_mclass_t const *test_mclass = NULL;
 
 char *lastpart(char *path)
 {
@@ -95,6 +88,14 @@
 
 int tstflags;
 
+void usage(int exitcode)
+{
+  fprintf(stderr,
+	  "usage: %s [-v] [-a]\n",
+	  name);
+  exit(exitcode);
+}
+
 int main(int argc, char *argv[])
 {
   int retval = 0;
@@ -105,8 +106,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   if (!test_mclass)

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -46,9 +46,10 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST +=		Doxyfile ipt.docs
+EXTRA_DIST +=		ipt.docs
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/sofia-sip/base64.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/sofia-sip/base64.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/sofia-sip/base64.h	Tue Apr 24 10:14:28 2007
@@ -57,6 +57,9 @@
 /** Calculate size of n bytes encoded in base64 */
 #define BASE64_SIZE(n) ((((n) + 2) / 3) * 4)
 
+/** Calculate size of n bytes encoded in base64 sans trailing =. @NEW_1_12_5 */
+#define BASE64_MINSIZE(n) ((n * 4 + 2) / 3)
+
 SOFIA_END_DECLS
 
 #endif /* !BASE_64 */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/sofia-sip/string0.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/sofia-sip/string0.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/sofia-sip/string0.h	Tue Apr 24 10:14:28 2007
@@ -28,11 +28,11 @@
 
 /**@file sofia-sip/string0.h
  *
- * @brief String comparison functions accepting NULL pointers
- *
- * This module contains string comparison functions that can be called
- * with NULL pointer as argument.
+ * @brief Extra string function.
  *
+ * String comparison functions accepting NULL pointers: str0cmp(),
+ * str0ncmp(), str0casecmp(), str0ncasecmp(). Also includes span functions
+ * testing at most @a n bytes: strncspn(), strnspn().
  */
 
 #ifndef SU_CONFIG_H
@@ -43,56 +43,39 @@
 
 SOFIA_BEGIN_DECLS
 
-#if SU_HAVE_INLINE
-su_inline
-#else
-SOFIAPUBFUN
-#endif
-int 
-  str0cmp(char const *a, char const *b),
-  str0ncmp(char const *a, char const *b, size_t n),
-  str0casecmp(char const *a, char const *b),
-  str0ncasecmp(char const *a, char const *b, size_t n);
-
-#if SU_HAVE_INLINE
-su_inline
-#else
-SOFIAPUBFUN
-#endif
-size_t
-strnspn(char const *s, size_t size, char const *term),
-  strncspn(char const *s, size_t ssize, char const *reject);
-
-#if SU_HAVE_INLINE
-int str0cmp(char const *a, char const *b)
+su_inline int str0cmp(char const *a, char const *b)
 {
   if (a == NULL) a = "";
   if (b == NULL) b = "";
   return strcmp(a, b);
 }
 
-int str0ncmp(char const *a, char const *b, size_t n)
+su_inline int str0ncmp(char const *a, char const *b, size_t n)
 {
   if (a == NULL) a = "";
   if (b == NULL) b = "";
   return strncmp(a, b, n);
 }
 
-int str0casecmp(char const *a, char const *b)
+su_inline int str0casecmp(char const *a, char const *b)
 {
   if (a == NULL) a = "";
   if (b == NULL) b = "";
   return strcasecmp(a, b);
 }
 
-int str0ncasecmp(char const *a, char const *b, size_t n)
+su_inline int str0ncasecmp(char const *a, char const *b, size_t n)
 {
   if (a == NULL) a = "";
   if (b == NULL) b = "";
   return strncasecmp(a, b, n);
 }
 
-size_t strnspn(char const *s, size_t ssize, char const *term)
+#if !SU_HAVE_INLINE
+SOFIAPUBFUN size_t strnspn(char const *s, size_t size, char const *term);
+SOFIAPUBFUN size_t strncspn(char const *s, size_t ssize, char const *reject);
+#else
+su_inline size_t strnspn(char const *s, size_t ssize, char const *term)
 {
   size_t n;
   size_t tsize = strlen(term);
@@ -123,7 +106,7 @@
   return n;
 }
 
-size_t strncspn(char const *s, size_t ssize, char const *reject)
+su_inline size_t strncspn(char const *s, size_t ssize, char const *reject)
 {
   size_t n;
   size_t rsize = strlen(reject);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/torture_base64.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/torture_base64.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/ipt/torture_base64.c	Tue Apr 24 10:14:28 2007
@@ -161,11 +161,12 @@
 }
 
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr,
-	  "usage: %s [-v]\n",
+	  "usage: %s [-v] [-a]\n",
 	  name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -176,8 +177,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= test_encoding(); fflush(stdout);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -35,29 +35,18 @@
 			sofia-sip/auth_common.h \
 			sofia-sip/auth_client.h sofia-sip/auth_digest.h \
 			sofia-sip/auth_module.h sofia-sip/auth_plugin.h \
-			sofia-sip/auth_client_plugin.h \
-			$(NTLM_HEADER)
+			sofia-sip/auth_client_plugin.h
 
 libiptsec_la_SOURCES = 	iptsec_debug.h \
 			auth_client.c auth_common.c auth_digest.c \
 			auth_module.c auth_tag.c auth_tag_ref.c \
 			auth_plugin.c auth_plugin_delayed.c \
-			auth_module_http.c auth_module_sip.c \
-			$(NTLM_SOURCE) \
+			auth_module_sip.c \
 			iptsec_debug.c
 
-NTLM_HEADER = 		sofia-sip/auth_ntlm.h
-if HAVE_NTLM
-NTLM_SOURCE = 		auth_ntlm.c auth_client_ntlm.c auth_plugin_ntlm.c
-endif
-
-EXTRA_libiptsec_la_SOURCES = \
-			auth_ntlm.c auth_client_ntlm.c auth_plugin_ntlm.c
-
 COVERAGE_INPUT = 	$(libiptsec_la_SOURCES) $(include_sofia_HEADERS)
 
 LDADD = 		libiptsec.la \
-			../http/libhttp.la \
 			../nta/libnta.la \
 			../sip/libsip.la \
 			../msg/libmsg.la \
@@ -68,13 +57,31 @@
 
 test_auth_digest_LDFLAGS = -static
 
+if HAVE_NTLM
+nobase_include_sofia_HEADERS += $(NTLM_HEADER)
+libiptsec_la_SOURCES += $(NTLM_SOURCE)
+endif
+
+if HAVE_NTH
+libiptsec_la_SOURCES += $(HTTP_SOURCE)
+LDADD +=		../http/libhttp.la
+endif
+
+HTTP_SOURCE =		auth_module_http.c
+
+NTLM_HEADER = 		sofia-sip/auth_ntlm.h
+NTLM_SOURCE = 		auth_ntlm.c auth_client_ntlm.c auth_plugin_ntlm.c
+
+EXTRA_libiptsec_la_SOURCES = \
+			$(NTLM_HEADER) $(NTLM_SOURCE) $(HTTP_SOURCE)
+
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST = 		Doxyfile iptsec.docs testpasswd \
-			auth_module_sip.c auth_module_http.c $(BUILT_SOURCES)
+EXTRA_DIST = 		iptsec.docs testpasswd $(BUILT_SOURCES)
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_client.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_client.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_client.c	Tue Apr 24 10:14:28 2007
@@ -31,6 +31,8 @@
 
 #include "config.h"
 
+#define SOFIA_EXTEND_AUTH_CLIENT 1
+
 #include <sofia-sip/su.h>
 #include <sofia-sip/su_md5.h>
 
@@ -77,9 +79,7 @@
 			  char const *user,
 			  char const *pass);
 
-static int ca_clear_credentials(auth_client_t *ca, 
-				char const *scheme,
-				char const *realm);
+static int ca_clear_credentials(auth_client_t *ca);
 
 
 /** Initialize authenticators.
@@ -178,29 +178,31 @@
     return -1;
 
   if (!ca->ca_credential_class)
-    stale = 1, ca->ca_credential_class = credential_class;
+    stale = 2, ca->ca_credential_class = credential_class;
 
-  return stale ? 2 : 1;
+  return stale > 1 ? 2 : 1;
 }
 
 /** Store authentication info to authenticators.
  *
- * The function auc_info() feeds the authentication data from the
- * authentication info @a info to the list of authenticators @a auc_list.
+ * The function auc_info() feeds the authentication data from the @b
+ * Authentication-Info header @a info to the list of authenticators @a
+ * auc_list.
  *
  * @param[in,out] auc_list  list of authenticators to be updated
- * @param[in] info      info to be processed
- * @param[in] crcl      corresponding credential class
+ * @param[in] info        info header to be processed
+ * @param[in] credential_class      corresponding credential class
  *
- * The authentication info can be in either Authentication-Info or in
- * Proxy-Authentication-Info headers.
- * If the header is Authentication-Info, the @a crcl should be
- * #sip_authorization_class or #http_authorization_class.
- * Likewise, If the header is Proxy-Authentication-Info, the @a crcl should
- * be #sip_proxy_authorization_class or #http_proxy_authorization_class.
-
- * The authentication into usually contains next nonce or mutual
- * authentication information. We handle only nextnonce parameter. 
+ * The authentication info can be in either @AuthenticationInfo or in
+ * @ProxyAuthenticationInfo headers. If the header is @AuthenticationInfo,
+ * the @a credential_class should be #sip_authorization_class or
+ * #http_authorization_class. Likewise, If the header is
+ * @ProxyAuthenticationInfo, the @a credential_class should be
+ * #sip_proxy_authorization_class or #http_proxy_authorization_class.
+
+ * The authentication into header usually contains next nonce or mutual
+ * authentication information. Currently, only the nextnonce parameter is
+ * processed.
  *
  * @bug
  * The result can be quite unexpected if there are more than one
@@ -210,9 +212,11 @@
  * @retval number of challenges to updated
  * @retval 0 when there was no challenge to update
  * @retval -1 upon an error
+ *
+ * @NEW_1_12_5
  */
 int auc_info(auth_client_t **auc_list,
-	     msg_auth_info_t const *ai,
+	     msg_auth_info_t const *info,
 	     msg_hclass_t *credential_class)
 {
   auth_client_t *ca;
@@ -222,7 +226,7 @@
 
   /* Update matching authenticator */
   for (ca = *auc_list; ca; ca = ca->ca_next) {
-    int updated = ca_info(ca, ai, credential_class);
+    int updated = ca_info(ca, info, credential_class);
     if (updated < 0)
       return -1;
     if (updated >= 1)
@@ -241,12 +245,12 @@
  */
 static
 int ca_info(auth_client_t *ca, 
-	    msg_auth_info_t const *ai,
+	    msg_auth_info_t const *info,
 	    msg_hclass_t *credential_class)
 {
-  assert(ca); assert(ai);
+  assert(ca); assert(info);
 
-  if (!ca || !ai)
+  if (!ca || !info)
     return -1;
 
   if (!ca->ca_credential_class)
@@ -261,7 +265,7 @@
       || !ca->ca_auc->auc_info)
     return 0;
 
-  return ca->ca_auc->auc_info(ca, ai);
+  return ca->ca_auc->auc_info(ca, info);
 }
 
 
@@ -336,8 +340,8 @@
  * @param[in] user          username 
  * @param[in] pass          password
  * 
- * @retval number of matching clients
- * @retval 0 when no matching client was found
+ * @retval number of updated clients
+ * @retval 0 when no client was updated
  * @retval -1 upon an error
  */
 int auc_all_credentials(auth_client_t **auc_list, 
@@ -371,6 +375,9 @@
 		   char const *user,
 		   char const *pass)
 {
+  char *new_user, *new_pass;
+  char *old_user, *old_pass;
+
   assert(ca);
 
   if (!ca || !ca->ca_scheme || !ca->ca_realm)
@@ -380,12 +387,24 @@
       (realm != NULL && strcmp(realm, ca->ca_realm)))
     return -1;
 
-  ca->ca_user = su_strdup(ca->ca_home, user);
-  ca->ca_pass = su_strdup(ca->ca_home, pass);
+  old_user = ca->ca_user, old_pass = ca->ca_pass;
+
+  if (str0cmp(user, old_user) == 0 && str0cmp(pass, old_pass) == 0)
+    return 0;
+
+  new_user = su_strdup(ca->ca_home, user);
+  new_pass = su_strdup(ca->ca_home, pass);
 
-  if (!ca->ca_user || !ca->ca_pass)
+  if (!new_user || !new_pass)
     return -1;
 
+  ca->ca_user = new_user, ca->ca_pass = new_pass;
+  if (AUTH_CLIENT_IS_EXTENDED(ca))
+    ca->ca_clear = 0;
+
+  su_free(ca->ca_home, old_user);
+  su_free(ca->ca_home, old_pass);
+
   return 1;
 }
 
@@ -412,12 +431,15 @@
       char *u, *p;
       if (!ca->ca_user || !ca->ca_pass)
 	continue;
+      if (AUTH_CLIENT_IS_EXTENDED(ca) && ca->ca_clear)
+	continue;
       if (!ca->ca_scheme[0] || strcmp(ca->ca_scheme, d->ca_scheme))
 	continue;
       if (!ca->ca_realm[0] || strcmp(ca->ca_realm, d->ca_realm))
 	continue;
 
-      if (d->ca_user && strcmp(d->ca_user, ca->ca_user) == 0 &&
+      if (!(AUTH_CLIENT_IS_EXTENDED(d) && d->ca_clear) &&
+	  d->ca_user && strcmp(d->ca_user, ca->ca_user) == 0 &&
 	  d->ca_pass && strcmp(d->ca_pass, ca->ca_pass) == 0) {
 	retval++;
 	break;
@@ -431,6 +453,9 @@
       if (d->ca_user) su_free(d->ca_home, (void *)d->ca_user);
       if (d->ca_pass) su_free(d->ca_home, (void *)d->ca_pass);
       d->ca_user = u, d->ca_pass = p;
+      if (AUTH_CLIENT_IS_EXTENDED(d))
+	d->ca_clear = 0;
+
       retval++;
       break;
     }
@@ -453,13 +478,24 @@
  * @retval -1 upon an error
  */
 int auc_clear_credentials(auth_client_t **auc_list, 
-			 char const *scheme,
-			 char const *realm)
+			  char const *scheme,
+			  char const *realm)
 {
   int retval = 0;
+  int match;
 
   for (; *auc_list; auc_list = &(*auc_list)->ca_next) {
-    int match = ca_clear_credentials(*auc_list, scheme, realm);
+    auth_client_t *ca = *auc_list;
+
+    if (!AUTH_CLIENT_IS_EXTENDED(ca))
+      continue;
+
+    if ((scheme != NULL && strcasecmp(scheme, ca->ca_scheme)) ||
+	(realm != NULL && strcmp(realm, ca->ca_realm)))
+      continue;
+
+    match = ca->ca_auc->auc_clear(*auc_list);
+
     if (match < 0) {
       retval = -1;
       break;
@@ -472,21 +508,14 @@
 }
 
 static
-int ca_clear_credentials(auth_client_t *ca, 
-			 char const *scheme,
-			 char const *realm)
+int ca_clear_credentials(auth_client_t *ca)
 {
-  assert(ca);
-
-  if (!ca || !ca->ca_scheme || !ca->ca_realm)
-    return -1;
+  assert(ca); assert(ca->ca_home->suh_size >= (int)(sizeof *ca));
 
-  if ((scheme != NULL && strcasecmp(scheme, ca->ca_scheme)) ||
-      (realm != NULL && strcmp(realm, ca->ca_realm)))
+  if (!ca)
     return -1;
 
-  su_free(ca->ca_home, (void *)ca->ca_user), ca->ca_user = NULL;
-  su_free(ca->ca_home, (void *)ca->ca_pass), ca->ca_pass = NULL;
+  ca->ca_clear = 1;
 
   return 1;
 }
@@ -495,6 +524,8 @@
  * 
  * @retval 1 when authorization can proceed
  * @retval 0 when there is not enough credentials
+ *
+ * @NEW_1_12_5
  */
 int auc_has_authorization(auth_client_t **auc_list)
 {
@@ -507,6 +538,8 @@
   for (ca = *auc_list; ca; ca = ca->ca_next) {
     if (!ca->ca_user || !ca->ca_pass || !ca->ca_credential_class)
       return 0;
+    if (AUTH_CLIENT_IS_EXTENDED(ca) && ca->ca_clear)
+      return 0;
   }
 
   return 1;
@@ -564,8 +597,11 @@
     if (!ca->ca_auc)
       continue;
 
-    if (ca->ca_auc->auc_authorize(ca, home, method, url, body, &h) < 0
-	|| msg_header_insert(msg, pub, h) < 0)
+    if (ca->ca_auc->auc_authorize(ca, home, method, url, body, &h) < 0)
+      return -1;
+    if (h == NULL)
+      continue;
+    if (msg_header_insert(msg, pub, h) < 0)
       return -1;
   }
 
@@ -633,14 +669,15 @@
 				   msg_payload_t const *body,
 				   msg_header_t **);
 
-const auth_client_plugin_t ca_basic_plugin = 
+static const auth_client_plugin_t ca_basic_plugin = 
 { 
   /* auc_plugin_size: */ sizeof ca_basic_plugin,
   /* auc_size: */        sizeof (auth_client_t),
   /* auc_name: */       "Basic",
   /* auc_challenge: */   NULL,
   /* auc_authorize: */   auc_basic_authorization,
-  /* auc_info: */        NULL
+  /* auc_info: */        NULL,
+  /* auc_clear: */       ca_clear_credentials
 };
 
 /**Create a basic authorization header.
@@ -677,6 +714,9 @@
   if (user == NULL || pass == NULL)
     return -1;
 
+  if (AUTH_CLIENT_IS_EXTENDED(ca) && ca->ca_clear)
+    return 0;
+
   ulen = strlen(user), plen = strlen(pass), uplen = ulen + 1 + plen;
   b64len = BASE64_SIZE(uplen);
   basiclen = strlen("Basic ") + b64len;
@@ -731,7 +771,7 @@
 				    msg_payload_t const *body,
 				    msg_header_t **);
 static int auc_digest_info(auth_client_t *ca, 
-			   msg_auth_info_t const *ai);
+			   msg_auth_info_t const *info);
 
 static const auth_client_plugin_t ca_digest_plugin = 
 { 
@@ -740,10 +780,15 @@
   /* auc_name: */       "Digest", 
   /* auc_challenge: */   auc_digest_challenge,
   /* auc_authorize: */   auc_digest_authorization,
-  /* auc_info: */        auc_digest_info
+  /* auc_info: */        auc_digest_info,
+  /* auc_clear: */       ca_clear_credentials
 };
 
 /** Store a digest authorization challenge.
+ *
+ * @retval 2 if credentials need to be (re)sent
+ * @retval 1 if challenge was updated
+ * @retval -1 upon an error
  */
 static int auc_digest_challenge(auth_client_t *ca, msg_auth_t const *ch)
 {
@@ -761,27 +806,18 @@
   if (ac->ac_qop && !ac->ac_auth && !ac->ac_auth_int)
     goto error;
 
-  stale = ac->ac_stale || str0cmp(ac->ac_nonce, cda->cda_ac->ac_nonce);
+  stale = ac->ac_stale || cda->cda_ac->ac_nonce == NULL;
 
   if (ac->ac_qop && (cda->cda_cnonce == NULL || ac->ac_stale)) {
     su_guid_t guid[1];
     char *cnonce;
-    char *e;
-
+    size_t b64len = BASE64_MINSIZE(sizeof(guid)) + 1;
     if (cda->cda_cnonce != NULL)
       /* Free the old one if we are updating after stale=true */
       su_free(home, (void *)cda->cda_cnonce);
     su_guid_generate(guid);
-    cda->cda_cnonce = cnonce = su_alloc(home, BASE64_SIZE(sizeof(guid)) + 1);
-    base64_e(cnonce, BASE64_SIZE(sizeof(guid)) + 1, guid, sizeof(guid));
-    /* somewhere else in the code the '=' chars are stripped in the header 
-       we need to strip it now before the digest is created or we're in trouble
-       cos they won't match.....
-    */
-    e = cnonce + strlen(cnonce) - 1;
-    while(*e == '=') {
-       *e-- = '\0';
-    }
+    cda->cda_cnonce = cnonce = su_alloc(home, b64len);
+    base64_e(cnonce, b64len, guid, sizeof(guid));
     cda->cda_ncount = 0;
   }
 
@@ -797,14 +833,14 @@
 }
 
 static int auc_digest_info(auth_client_t *ca,
-			   msg_auth_info_t const *ai)
+			   msg_auth_info_t const *info)
 {
   auth_digest_client_t *cda = (auth_digest_client_t *)ca;
   su_home_t *home = ca->ca_home;
   char const *nextnonce = NULL;
   issize_t n;
 
-  n = auth_get_params(home, ai->ai_params,
+  n = auth_get_params(home, info->ai_params,
 		      "nextnonce=", &nextnonce,
 		      NULL);
 
@@ -825,9 +861,9 @@
  * sip_authorization_class or sip_proxy_authorization_class, as well as
  * http_authorization_class or http_proxy_authorization_class.
  *
- * @return
- * Returns a pointer to newly created authorization header, or NULL upon an
- * error.
+ * @retval 1 when authorization headers has been created  
+ * @retval 0 when there is no credentials
+ * @retval -1 upon an error
  */
 static
 int auc_digest_authorization(auth_client_t *ca, 
@@ -853,6 +889,9 @@
   auth_response_t ar[1] = {{ 0 }};
   char ncount[17];
 
+  if (!user || !pass || (AUTH_CLIENT_IS_EXTENDED(ca) && ca->ca_clear))
+    return 0;
+
   ar->ar_size = sizeof(ar);
   ar->ar_username = user;
   ar->ar_realm = ac->ac_realm;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_module.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_module.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_module.c	Tue Apr 24 10:14:28 2007
@@ -76,6 +76,7 @@
 
 char const auth_internal_server_error[] = "Internal server error";
 
+static void auth_call_scheme_destructor(void *);
 static void auth_md5_hmac_key(auth_mod_t *am);
 
 HTABLE_PROTOS_WITH(auth_htable, aht, auth_passwd_t, usize_t, unsigned);
@@ -94,7 +95,7 @@
 
   if ((am = su_home_new(scheme->asch_size))) {
     am->am_scheme = scheme;
-    am->am_refcount = 1;
+    su_home_destructor(am->am_home, auth_call_scheme_destructor);
   }
 
   return am;
@@ -246,10 +247,14 @@
 /** Destroy (a reference to) an authentication module. */
 void auth_mod_destroy(auth_mod_t *am)
 {
-  if (am && am->am_refcount != 0 && --am->am_refcount == 0) {
-    am->am_scheme->asch_destroy(am);
-    su_home_zap(am->am_home);
-  }
+  su_home_unref(am->am_home);
+}
+
+/** Call scheme-specific destructor function. */
+static void auth_call_scheme_destructor(void *arg)
+{
+  auth_mod_t *am = arg;
+  am->am_scheme->asch_destroy(am);
 }
 
 /** Do-nothing destroy function.
@@ -264,18 +269,13 @@
 /** Create a new reference to authentication module. */
 auth_mod_t *auth_mod_ref(auth_mod_t *am)
 {
-  if (!am || am->am_refcount == 0)
-    return NULL;
-
-  am->am_refcount++;
-
-  return am;
+  return (auth_mod_t *)su_home_ref(am->am_home);
 }
 
 /** Destroy a reference to an authentication module. */
 void auth_mod_unref(auth_mod_t *am)
 {
-  auth_mod_destroy(am);
+  su_home_unref(am->am_home);
 }
 
 /** Get authenticatin module name. @NEW_1_12_4. */
@@ -608,7 +608,7 @@
   uint8_t    digest[6];
 };
 
-#define AUTH_DIGEST_NONCE_LEN (BASE64_SIZE(sizeof (struct nonce)) + 1)
+#define AUTH_DIGEST_NONCE_LEN (BASE64_MINSIZE(sizeof (struct nonce)) + 1)
 
 /** Authenticate a request with @b Digest authentication scheme.
  *
@@ -950,7 +950,8 @@
 #include <sys/file.h>
 #endif
 
-#define auth_apw_local auth_readdb_internal
+/* This is just a magic value */
+#define auth_apw_local ((void *)(intptr_t)auth_readdb_internal)
 
 /** Read authentication database */
 static

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_plugin_delayed.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_plugin_delayed.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/auth_plugin_delayed.c	Tue Apr 24 10:14:28 2007
@@ -126,7 +126,7 @@
 
 struct auth_splugin_t 
 {
-  void const      *asp_tag;
+  void const      *asp_cookie;
   auth_splugin_t  *asp_next;
   auth_splugin_t **asp_prev;
   auth_mod_t      *asp_am;
@@ -136,6 +136,8 @@
   int              asp_canceled;
 };
 
+/* This is unique identifier */
+#define delayed_asp_cookie ((void const *)(intptr_t)delayed_auth_cancel)
 
 static void delayed_auth_method_recv(su_root_magic_t *rm,
 				     su_msg_r msg,
@@ -162,7 +164,7 @@
 
   asp = su_msg_data(mamc); assert(asp);
 
-  asp->asp_tag = delayed_auth_cancel;
+  asp->asp_cookie = delayed_asp_cookie;
   asp->asp_am = am;
   asp->asp_as = as;
   asp->asp_header = auth;
@@ -216,7 +218,7 @@
 
   (void)ap;			/* xyzzy */
   
-  if (as->as_plugin && as->as_plugin->asp_tag == delayed_auth_cancel)
+  if (as->as_plugin && as->as_plugin->asp_cookie == delayed_asp_cookie)
     as->as_plugin->asp_canceled = 1;
 
   as->as_status = 500, as->as_phrase = "Authentication canceled";

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/sofia-sip/auth_client_plugin.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/sofia-sip/auth_client_plugin.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/sofia-sip/auth_client_plugin.h	Tue Apr 24 10:14:28 2007
@@ -29,6 +29,10 @@
 /**@file sofia-sip/auth_client_plugin.h
  * @brief Client-side plugin interface for authentication
  * 
+ * @note For extensions in 1.12.6 or later, 
+ * you have to define SOFIA_EXTEND_AUTH_CLIENT to 1
+ * before including this file.
+ *
  * @author Pekka Pessi <Pekka.Pessi at nokia.com>
  * 
  * @date Created: Fri May 19 16:18:21 EEST 2006
@@ -58,6 +62,10 @@
   char         *ca_pass;
 
   msg_hclass_t *ca_credential_class;
+
+#if SOFIA_EXTEND_AUTH_CLIENT
+  int           ca_clear;
+#endif
 };
 
 struct auth_client_plugin
@@ -81,8 +89,19 @@
 
   /** Store nextnonce from Authentication-Info or Proxy-Authentication-Info. */
   int (*auc_info)(auth_client_t *ca, msg_auth_info_t const *ai);
+
+#if SOFIA_EXTEND_AUTH_CLIENT
+  /** Clear credentials (user/pass). @NEW_1_12_6 */
+  int (*auc_clear)(auth_client_t *ca);
+#endif
 };
 
+/** Check if authentication client has been extended. @NEW_1_12_6 */
+#define AUTH_CLIENT_IS_EXTENDED(ca)					\
+  ((ca)->ca_auc->auc_plugin_size >					\
+   (int)offsetof(auth_client_plugin_t, auc_clear)			\
+   && (ca)->ca_auc->auc_clear != NULL)
+
 SOFIA_END_DECLS
 
 #endif /* !defined AUTH_CLIENT_PLUGIN_H */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/sofia-sip/auth_plugin.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/sofia-sip/auth_plugin.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/sofia-sip/auth_plugin.h	Tue Apr 24 10:14:28 2007
@@ -105,7 +105,7 @@
 typedef struct
 {
   unsigned        apw_index;	/**< Key to hash table */
-  void const     *apw_type;	/**< Magic pointer */
+  void const     *apw_type;	/**< Magic identifier */
 
   char const   	 *apw_user;	/**< Username */
   char const     *apw_realm;	/**< Realm */
@@ -124,7 +124,7 @@
 struct auth_mod_t
 {
   su_home_t      am_home[1];
-  unsigned       am_refcount;	/**< Number of references to this module */
+  unsigned       _am_refcount;	/**< Not used */
 
   /* User database / cache */
   char const    *am_db;		/**< User database file name */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/test_auth_digest.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/test_auth_digest.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/iptsec/test_auth_digest.c	Tue Apr 24 10:14:28 2007
@@ -769,8 +769,6 @@
     {
       char const *nonce1, *nextnonce, *nonce2;
 
-      reinit_as(as); auth_mod_destroy(am); aucs = NULL;
-
       TEST_1(am = auth_mod_create(NULL, 
 				  AUTHTAG_METHOD("Digest"),
 				  AUTHTAG_REALM("ims3.so.noklab.net"),
@@ -1164,9 +1162,10 @@
 extern su_log_t iptsec_log[];
 
 static
-void usage(void)
+void usage(int exitcode)
 {
-  fprintf(stderr, "usage: %s [-v] [-l n]\n", name);
+  fprintf(stderr, "usage: %s [-v] [-a] [-l n]\n", name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -1179,8 +1178,10 @@
   su_init();
 
   for (i = 1; argv[i]; i++) {
-    if (argv[i] && strcmp(argv[i], "-v") == 0)
+    if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else if (strncmp(argv[i], "-l", 2) == 0) {
       int level = 3;
       char *rest = NULL;
@@ -1193,11 +1194,11 @@
 	level = 3, rest = "";
 
       if (rest == NULL || *rest)
-	usage();
+	usage(1);
       
       su_log_set_level(iptsec_log, level);
     } else {
-      usage();
+      usage(1);
     }
   }
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -35,10 +35,12 @@
 nobase_include_sofia_HEADERS = \
 			$(GENERATED_H) $(PUBLIC_H) 
 
-BUILT_SOURCES = $(GENERATED_H) msg_mime_table.c test_table.c test_protos.h
+GENERATED_HC = $(GENERATED_H) msg_mime_table.c test_table.c test_protos.h
 
-libmsg_la_SOURCES = $(INTERNAL_H) \
-	msg.c msg_tag.c \
+BUILT_SOURCES = $(GENERATED_HC)
+
+libmsg_la_SOURCES = msg_internal.h \
+	msg.c msg_tag.c msg_inlined.c \
 	msg_mime.c msg_mime_table.c \
 	msg_header_copy.c msg_header_make.c \
 	msg_parser.c msg_mclass.c msg_parser_util.c \
@@ -46,11 +48,13 @@
 
 COVERAGE_INPUT = 	$(libmsg_la_SOURCES) $(include_sofia_HEADERS)
 
-libtest_msg_a_SOURCES = test_class.c test_table.c test_protos.h
+libtest_msg_a_SOURCES = test_class.c test_class.h \
+			test_table.c test_inlined.c test_protos.h
 
 LDADD = 		libtest_msg.a libmsg.la \
 			../bnf/libbnf.la \
 			../url/liburl.la \
+			../ipt/libipt.la \
 			../su/libsu.la 
 
 test_msg_LDFLAGS = 	-static
@@ -62,7 +66,7 @@
 
 dist_pkgdata_SCRIPTS = 	msg_parser.awk
 
-EXTRA_DIST =		Doxyfile msg.docs \
+EXTRA_DIST =		msg.docs \
 			sofia-sip/msg_mime_protos.h.in \
 			sofia-sip/msg_protos.h.in \
 			msg_mime_table.c.in \
@@ -77,41 +81,46 @@
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
 
 MSG_PARSER_AWK = $(srcdir)/msg_parser.awk
 
-AWK_MSG_AWK = $(AWK) -f $(MSG_PARSER_AWK)
+AWK_MSG_AWK = LC_ALL=C $(AWK) -f $(MSG_PARSER_AWK)
 
-test_protos.h: test_protos.h.in $(MSG_PARSER_AWK)
-test_table.c: test_table.c.in $(MSG_PARSER_AWK)
+${GENERATED_HC}: ${MSG_PARSER_AWK}
 
-sofia-sip/msg_mime_protos.h: sofia-sip/msg_mime_protos.h.in
-sofia-sip/msg_protos.h: sofia-sip/msg_protos.h.in
-msg_mime_table.c: msg_mime_table.c.in $(MSG_PARSER_AWK)
+TEST_CLASS_H = ${srcdir}/test_class.h
 
-sofia-sip/msg_mime_protos.h sofia-sip/msg_protos.h: $(MSG_PARSER_AWK)
+test_protos.h test_table.c: ${TEST_CLASS_H}
 
-test_protos.h: test_class.h
+test_protos.h: ${srcdir}/test_protos.h.in
 	$(AWK_MSG_AWK) module=msg_test NO_MIDDLE=1 NO_LAST=1 \
-		PR=$@ TEMPLATE=$(srcdir)/test_protos.h.in $<
+		PR=$@ TEMPLATE=${srcdir}/test_protos.h.in ${TEST_CLASS_H}
 
-test_table.c: test_class.h 
+test_table.c: ${srcdir}/test_table.c.in
 	$(AWK_MSG_AWK) module=msg_test prefix=msg \
 		MC_HASH_SIZE=127 multipart=msg_multipart \
-		PT=$@ TEMPLATE=$(srcdir)/test_table.c.in $<
+		PT=$@ TEMPLATE=${srcdir}/test_table.c.in ${TEST_CLASS_H}
+
+SS_MIME_H = ${srcdir}/sofia-sip/msg_mime.h
+
+sofia-sip/msg_protos.h sofia-sip/msg_mime_protos.h: ${SS_MIME_H}
+msg_mime_table.c: ${SS_MIME_H}
 
-sofia-sip/msg_protos.h: sofia-sip/msg_mime.h
+sofia-sip/msg_protos.h: ${srcdir}/sofia-sip/msg_protos.h.in
 	@-mkdir sofia-sip 2>/dev/null || true
 	$(AWK_MSG_AWK) module=msg NO_FIRST=1 NO_MIDDLE=1 \
-		PR=$@ TEMPLATE=$(srcdir)/sofia-sip/msg_protos.h.in $<
+		PR=$@ TEMPLATE=${srcdir}/sofia-sip/msg_protos.h.in \
+		${SS_MIME_H}
 
-sofia-sip/msg_mime_protos.h: sofia-sip/msg_mime.h
+sofia-sip/msg_mime_protos.h: ${srcdir}/sofia-sip/msg_mime_protos.h.in
 	@-mkdir sofia-sip 2>/dev/null || true
 	$(AWK_MSG_AWK) module=msg NO_FIRST=1 NO_LAST=1 \
-		PR=$@ TEMPLATE=$(srcdir)/sofia-sip/msg_mime_protos.h.in $<
+		PR=$@ TEMPLATE=${srcdir}/sofia-sip/msg_mime_protos.h.in \
+		${SS_MIME_H}
 
-msg_mime_table.c: sofia-sip/msg_mime.h
+msg_mime_table.c: ${srcdir}/msg_mime_table.c.in
 	$(AWK_MSG_AWK) module=msg_multipart \
 		tprefix=msg prefix=mp MC_HASH_SIZE=127 \
-		PT=$@ TEMPLATE=$(srcdir)/msg_mime_table.c.in $<
+		PT=$@ TEMPLATE=${srcdir}/msg_mime_table.c.in \
+		${SS_MIME_H}

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/msg_parser.awk
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/msg_parser.awk	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/msg_parser.awk	Tue Apr 24 10:14:28 2007
@@ -54,11 +54,13 @@
   split("", NAMES);
   split("", Comments);
   split("", COMMENTS);
+  split("", experimental);
 
   # indexed by the C name of the header
   split("", Since);		# Non-NUL if extra
   split("", Extra);		# Offset in extra headers
 
+  without_experimental = 0;
   template="";
   template1="";
   template2="";
@@ -78,13 +80,18 @@
 {
   hash = 0;
 
-  len = split(name, chars, "");
+  len = length(name); 
 
   for (i = 1; i <= len; i++) {
-    c = tolower(chars[i]);
+    c = tolower(substr(name, i, 1));
     hash = (38501 * (hash + index(ascii, c))) % 65536;
   }
 
+  if (hash == 0) {
+    print "*** msg_parser.awk: calculating hash failed\n";
+    exit(5);
+  }
+
   if (0) {
     # Test that hash algorithm above agrees with the C version
     pipe = ("../msg/msg_name_hash " name);
@@ -155,11 +162,24 @@
     Extra[name] = extra++;
   }
 
+  expr = (without_experimental > 0 && do_hash);
+  if (expr) {
+    printf "%s is experimental\n", Comment;
+  }    
+  
+  experimental[N] = expr;
+
   if (PR) {
+    if (expr) {
+      print "#if SU_HAVE_EXPERIMENTAL" > PR;
+    }
     replace(template, hash, name, NAME, comment, Comment, COMMENT, since);
     replace(template1, hash, name, NAME, comment, Comment, COMMENT, since);
     replace(template2, hash, name, NAME, comment, Comment, COMMENT, since);
     replace(template3, hash, name, NAME, comment, Comment, COMMENT, since);
+    if (expr) {
+      print "#endif /* SU_HAVE_EXPERIMENTAL */" > PR;
+    }
   }
 }
 
@@ -181,7 +201,7 @@
     }
     else {
       # Remove line with #version#
-      gsub(/\n[^\n]*#version#[^\n]*\n/, "\n", p);
+      gsub(/\n[^#\n]*#version#[^\n]*/, "", p);
     }
     	    
     print p > PR;
@@ -210,8 +230,19 @@
   for (i = 1; i <= n; i++) {
     l = lines[i];
     if (match(tolower(l), /#(xxxxxx(x_xxxxxxx)?|hash)#/)) {
+      expr = 0;
+
       for (j = 1; j <= N; j++) {
 	l = lines[i];
+	if (expr != experimental[j]) {
+	  expr = experimental[j];
+	  if (expr) {
+	    print "#if SU_HAVE_EXPERIMENTAL" > PR;
+	  }
+	  else {
+	    print "#endif /* SU_HAVE_EXPERIMENTAL */" > PR;
+	  }
+	}
 	gsub(/#hash#/, hashes[j], l);
 	gsub(/#xxxxxxx_xxxxxxx#/, comments[j], l);
 	gsub(/#Xxxxxxx_Xxxxxxx#/, Comments[j], l);
@@ -220,6 +251,10 @@
 	gsub(/#XXXXXX#/, NAMES[j], l);
 	print l > PR;
       }
+
+      if (expr) {
+	print "#endif /* SU_HAVE_EXPERIMENTAL */" > PR;
+      }
     } else {
       print l > PR;
     }
@@ -333,10 +368,11 @@
 }
 
 /^#### EXTRA HEADER LIST STARTS HERE ####$/ { HLIST=1; templates(); }
+HLIST && /^#### EXPERIMENTAL HEADER LIST STARTS HERE ####$/ { 
+  without_experimental=total; }
 HLIST && /^[a-z]/ { protos($1, $0, 0, $2); headers[total++] = $1; }
 /^#### EXTRA HEADER LIST ENDS HERE ####$/ { HLIST=0;  }
 
-
 /^ *\/\* === Headers start here \*\// { in_header_list=1;  templates(); }
 /^ *\/\* === Headers end here \*\// { in_header_list=0; }
 
@@ -366,10 +402,13 @@
 END {
   if (failed) { exit };
 
+  if (without_experimental == 0)
+    without_experimental = total;
+
   if (!NO_LAST) {
     protos("unknown", "/**< Unknown headers */", -3);
     protos("error", "/**< Erroneous headers */", -4);
-    protos("separator", "/**< Separator line between headers and payload */", -5);
+    protos("separator", "/**< Separator line between headers and body */", -5);
     protos("payload", "/**< Message payload */", -6);
     if (multipart)
       protos("multipart", "/**< Multipart payload */", -7);
@@ -397,6 +436,10 @@
     gsub(/#DATE#/, "@date Generated: " date, header);
     print header > PT;
 
+    print "" > PT;
+    print "#define msg_offsetof(s, f) ((unsigned short)offsetof(s ,f))" > PT;
+    print "" > PT;
+
     if (MC_SHORT_SIZE) {
       printf("static msg_href_t const " \
 	     "%s_short_forms[MC_SHORT_SIZE] = \n{\n", 
@@ -408,7 +451,7 @@
 	  n = shorts[i];
         flags = header_flags[n]; if (flags) flags = ",\n      " flags;
 	  
-	  printf("  { /* %s */ %s_%s_class, offsetof(%s_t, %s_%s)%s }%s\n", 
+	  printf("  { /* %s */ %s_%s_class, msg_offsetof(%s_t, %s_%s)%s }%s\n", 
 		 substr(lower_case, i, 1), 
 		 tprefix, n, module, prefix, n, flags, c)	\
 	    > PT;
@@ -426,7 +469,16 @@
     if (extra > 0) {
       printf("struct %s {\n", extra_struct) > PT;
       printf("  %s base;\n", module_struct) > PT;
-      printf("  msg_header_t *extra[%u];\n", extra) > PT;
+      if (total - without_experimental < extra) {
+	printf("  msg_header_t *extra[%u];\n", 
+	       extra - (total - without_experimental)) > PT;
+      }
+      if (total - without_experimental > 0) {
+	print "#if SU_HAVE_EXPERIMENTAL" > PT;
+	printf("  msg_header_t *experimental[%u];\n", 
+	       total - without_experimental) > PT;
+	print "#endif" > PT;
+      }
       printf("};\n\n") > PT;
       module_struct = "struct " extra_struct;
     }
@@ -450,11 +502,11 @@
     len = split("request status separator payload unknown error", unnamed, " ");
 
     for (i = 1; i <= len; i++) {
-      printf("  {{ %s_%s_class, offsetof(%s_t, %s_%s) }},\n", 
+      printf("  {{ %s_%s_class, msg_offsetof(%s_t, %s_%s) }},\n", 
 	     tprefix, unnamed[i], module, prefix, unnamed[i]) > PT;
     }
     if (multipart) {
-      printf("  {{ %s_class, offsetof(%s_t, %s_multipart) }},\n",
+      printf("  {{ %s_class, msg_offsetof(%s_t, %s_multipart) }},\n",
 	     multipart, module, prefix) > PT;
     } else {
       printf("  {{ NULL, 0 }},\n") > PT;
@@ -465,7 +517,13 @@
     else {
       printf("  NULL, \n") > PT;
     }
-    printf("  %d, %d, \n", MC_HASH_SIZE, total) > PT;
+    printf("  %d, \n", MC_HASH_SIZE) > PT;
+    printf ("#if SU_HAVE_EXPERIMENTAL\n" \
+	    "  %d,\n" \
+	    "#else\n" \
+	    "  %d,\n" \
+	    "#endif\n", \
+	    total, without_experimental) > PT;
     printf("  {\n") > PT;
 
     for (i = 0; i < total; i++) {
@@ -484,6 +542,7 @@
       }
 
       header_hash[j] = n;
+      experimental2[j] = (i >= without_experimental);
     }
 
     for (i = 0; i < MC_HASH_SIZE; i++) {
@@ -492,14 +551,23 @@
 	n = header_hash[i];
         flags = header_flags[n]; if (flags) flags = ",\n      " flags;
 
+	if (experimental2[i]) {
+	  print "#if SU_HAVE_EXPERIMENTAL" > PT;
+	}
+
 	if (Since[n]) {
-	  printf("    { %s_%s_class, offsetof(struct %s, extra[%u])%s }%s\n", 
+	  printf("    { %s_%s_class,\n" \
+		 "      msg_offsetof(struct %s, extra[%u])%s }%s\n", 
 		 tprefix, n, extra_struct, Extra[n], flags, c) > PT;
 	}
 	else {
-	  printf("    { %s_%s_class, offsetof(%s_t, %s_%s)%s }%s\n", 
+	  printf("    { %s_%s_class, msg_offsetof(%s_t, %s_%s)%s }%s\n", 
 		 tprefix, n, module, prefix, n, flags, c) > PT;
 	}
+
+	if (experimental2[i]) {
+	  printf("#else\n    { NULL, 0 }%s\n#endif\n", c) > PT;
+	}
       }
       else {
 	printf("    { NULL, 0 }%s\n", c) > PT;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/msg_parser_util.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/msg_parser_util.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/msg_parser_util.c	Tue Apr 24 10:14:28 2007
@@ -1974,6 +1974,8 @@
     return NULL;
 
   msg = msg_create(mc, flags);
+  if (msg == NULL)
+    return NULL;
 
   su_home_preload(msg_home(msg), 1, len + 1024);
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/sofia-sip/msg_parser.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/sofia-sip/msg_parser.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/sofia-sip/msg_parser.h	Tue Apr 24 10:14:28 2007
@@ -56,7 +56,8 @@
  * 1) Header class definitions.
  */
 
-#if HAVE_STRUCT_KEYWORDS
+/* Do not use keywords until you fix msg_kind_foo_critical thing! */ \
+#if HAVE_STRUCT_KEYWORDS && 0
 /** Define a header class */
 #define MSG_HEADER_CLASS(pr, c, l, s, params, kind, dup, upd)	\
   {{								\
@@ -74,6 +75,7 @@
     hc_kind:	msg_kind_##kind,				\
   }}
 #else
+/** Define a header class */
 #define MSG_HEADER_CLASS(pr, c, l, s, params, kind, dup, upd)	\
   {{ \
      pr##c##_hash, \
@@ -198,9 +200,11 @@
 
 /** Duplicate string. @HI */
 #define MSG_STRING_DUP(p, d, s) \
-  (void)((s)?((p)=(char*)memccpy((void *)((d)=(char*)p),(s),0,SIZE_MAX))\
+  (void)((s)?((p)=(char*)memccpy((void *)((d)=(char*)p),(s),0,INT_MAX))\
 	    :((d)=NULL))
 
+/* Solaris has broken memccpy - it considers last argument as signed */
+
 /** Calculate string size. @HI */
 #define MSG_STRING_SIZE(s) ((s) ? (strlen(s) + 1) : 0)
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/test_msg.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/test_msg.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/msg/test_msg.c	Tue Apr 24 10:14:28 2007
@@ -59,11 +59,6 @@
 
 char const name[] = "test_msg";
 
-void usage(void)
-{
-  fprintf(stderr, "usage: %s [-v]\n", name);
-}
-
 static int msg_time_test(void)
 {
   char buf[32];
@@ -138,7 +133,6 @@
   }
 
   END();
-  return 0;
 }
 
 static int addr_test(void)
@@ -1688,6 +1682,12 @@
   END();
 }
 
+void usage(int exitcode)
+{
+  fprintf(stderr, "usage: %s [-v] [-a]\n", name);
+  exit(exitcode);
+}
+
 int main(int argc, char *argv[])
 {
   int retval = 0;
@@ -1696,8 +1696,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       test_flags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      test_flags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= msg_time_test(); fflush(stdout);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -54,9 +54,10 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile nea.docs $(BUILT_SOURCES)
+EXTRA_DIST =		nea.docs $(BUILT_SOURCES)
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/nea_server.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/nea_server.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nea/nea_server.c	Tue Apr 24 10:14:28 2007
@@ -496,14 +496,14 @@
 	nes->nes_eventity_uri &&
 	(nes->nes_leg || leg == NULL) &&
 	nes->nes_timer) {
-      SU_DEBUG_5(("nea_server_create(%p): success\n", nes));
+      SU_DEBUG_5(("nea_server_create(%p): success\n", (void *)nes));
       su_timer_set(nes->nes_timer, nes_event_timer, nes);
 
       nes->nes_callback = callback;
       nes->nes_context = context;
     }
     else {
-      SU_DEBUG_5(("nea_server_create(%p): failed\n", nes));
+      SU_DEBUG_5(("nea_server_create(%p): failed\n", (void *)nes));
       nea_server_destroy(nes), nes = NULL;
     }
   }
@@ -551,11 +551,11 @@
     return 500;
 
   if (nes->nes_in_callback) {
-    SU_DEBUG_5(("nea_server_shutdown(%p) while in callback\n", nes));
+    SU_DEBUG_5(("nea_server_shutdown(%p) while in callback\n", (void *)nes));
     return 100;
   }
   
-  SU_DEBUG_5(("nea_server_shutdown(%p)\n", nes));
+  SU_DEBUG_5(("nea_server_shutdown(%p)\n", (void *)nes));
 
   in_callback = nes->nes_in_callback; nes->nes_in_callback = 1;
 
@@ -585,12 +585,12 @@
     return;
 
   if (nes->nes_in_callback) {
-    SU_DEBUG_5(("nea_server_destroy(%p) while in callback\n", nes));
+    SU_DEBUG_5(("nea_server_destroy(%p) while in callback\n", (void *)nes));
     nes->nes_pending_destroy = 1;
     return;
   }
   
-  SU_DEBUG_5(("nea_server_destroy(%p)\n", nes));
+  SU_DEBUG_5(("nea_server_destroy(%p)\n", (void *)nes));
   
   nta_leg_destroy(nes->nes_leg), nes->nes_leg = NULL;
   
@@ -837,8 +837,8 @@
   if (evq->evq_content_type)
     nea_view_queue(nes, evv, evq);
 
-  SU_DEBUG_7(("nea_server_update(%p): %s (%s)\n", 
-	      nes, ev->ev_event->o_type, evv->evv_content_type->c_type));
+  SU_DEBUG_7(("nea_server_update(%p): %s (%s)\n", (void *)nes,
+	      ev->ev_event->o_type, evv->evv_content_type->c_type));
 
   return 1;
 }
@@ -1019,7 +1019,8 @@
   nea_sub_t *s;
   int notified = 0, throttled = nes->nes_throttled;
 
-  SU_DEBUG_7(("nea_server_notify(%p): %s\n", nes, ev ? ev->ev_event->o_type: ""));
+  SU_DEBUG_7(("nea_server_notify(%p): %s\n", (void *)nes,
+	      ev ? ev->ev_event->o_type: ""));
 
   ++nes->nes_in_list;
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -66,14 +66,14 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile nta.docs sl_utils.docs \
+EXTRA_DIST =		nta.docs sl_utils.docs \
 			agent.pem cafile.pem \
 			invite.msc $(BUILT_SOURCES) 
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
 
 # Generate list of nta tags
 TAG_DLL_FLAGS = 	LIST=nta_tag_list
\ No newline at end of file

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta.c	Tue Apr 24 10:14:28 2007
@@ -29,7 +29,7 @@
  * 1) agent
  * 2) tport handling
  * 3) dispatching messages received from network
- * 4) message creation, message utility
+ * 4) message creation and message utility functions
  * 5) stateless operation
  * 6) dialogs (legs)
  * 7) server transactions (incoming)
@@ -145,7 +145,7 @@
 
 static int complete_response(msg_t *response, 
 			     int status, char const *phrase, 
-			     msg_t const *request);
+			     msg_t *request);
 
 #define IF_SIGCOMP_TPTAG_COMPARTMENT(cc)     TAG_IF(cc, TPTAG_COMPARTMENT(cc)),
 #define IF_SIGCOMP_TPTAG_COMPARTMENT_REF(cc) TPTAG_COMPARTMENT_REF(cc),
@@ -225,7 +225,7 @@
 static inline int incoming_merge(nta_incoming_t *irq, msg_t *msg, sip_t *sip,
 				 tport_t *tport);
 static inline int incoming_timestamp(nta_incoming_t *, msg_t *, sip_t *);
-static inline int incoming_timer(nta_agent_t *, su_duration_t);
+static inline su_duration_t incoming_timer(nta_agent_t *, su_duration_t);
 
 static nta_reliable_t *reliable_mreply(nta_incoming_t *,
 				       nta_prack_f *, nta_reliable_magic_t *,
@@ -259,7 +259,7 @@
 				     sip_via_t const *v);
 static int outgoing_recv(nta_outgoing_t *orq, int status, msg_t *, sip_t *);
 static void outgoing_default_recv(nta_outgoing_t *, int, msg_t *, sip_t *);
-static inline int outgoing_timer(nta_agent_t *, su_duration_t);
+static inline su_duration_t outgoing_timer(nta_agent_t *, su_duration_t);
 static int outgoing_recv_reliable(nta_outgoing_t *orq, msg_t *msg, sip_t *sip);
 
 /* Internal message passing */
@@ -292,7 +292,9 @@
  * 
  * @sa <su_debug.h>, #su_log_global, #SOFIA_DEBUG
  */
-extern char const NTA_DEBUG[];
+#ifdef DOXYGEN
+extern char const NTA_DEBUG[]; /* dummy declaration for Doxygen */
+#endif
 
 #ifndef SU_DEBUG
 #define SU_DEBUG 3
@@ -311,7 +313,7 @@
 /**
  * Create an NTA agent object.
  *
- * The function nta_agent_create() creates an NTA agent object.  The agent
+ * Create an NTA agent object.  The agent
  * object creates and binds a server socket with address specified in @e url.
  * If the @e host portion of the @e url is @c "*", the agent listens to all
  * addresses available on the host.
@@ -327,6 +329,8 @@
  * @note
  * If @e url is @c NULL, the default @e url @c "sip:*" is used.
  * @par
+ * If @e url is @c NONE (iow, (void*)-1), no server sockets are bound.
+ * @par
  * If @p transport parameters are specified in @a url, agent uses only
  * specified transport type.
  *
@@ -369,8 +373,10 @@
     agent->sa_flags = MSG_DO_CANONIC;
 
     agent->sa_maxsize         = 2 * 1024 * 1024; /* 2 MB */
-    agent->sa_bad_req_mask    = (unsigned)(~(sip_mask_response | sip_mask_proxy));
-    agent->sa_bad_resp_mask   = (unsigned)(~(sip_mask_request | sip_mask_proxy));
+    agent->sa_bad_req_mask    = 
+      (unsigned) ~(sip_mask_response | sip_mask_proxy);
+    agent->sa_bad_resp_mask   = 
+      (unsigned) ~(sip_mask_request | sip_mask_proxy);
     agent->sa_t1 	      = NTA_SIP_T1;
     agent->sa_t2 	      = NTA_SIP_T2;
     agent->sa_t4              = NTA_SIP_T4;
@@ -563,14 +569,10 @@
 
 /** Return @Contact header.
  *
- * The function nta_agent_contact() returns a @Contact header, which can be
- * used to reach @a agent.
+ * Get a @Contact header, which can be used to reach @a agent.
  *
  * @param agent NTA agent object
  *
- * @return The function nta_agent_contact() returns a sip_contact_t object
- * corresponding to the @a agent.
- *
  * User agents can insert the @Contact header in the outgoing REGISTER,
  * INVITE, and ACK requests and replies to incoming INVITE and OPTIONS
  * transactions.
@@ -582,6 +584,8 @@
  *	 			 sip->sip_request->rq_url,
  *				 contact->m_url);
  * @endcode
+ *
+ * @return A sip_contact_t object corresponding to the @a agent.
  */
 sip_contact_t *nta_agent_contact(nta_agent_t const *agent)
 {
@@ -590,44 +594,68 @@
 
 /** Return a list of @Via headers.
  *
- * The function nta_agent_via() returns @Via headers for all activated
- * transport.
+ * Get @Via headers for all activated transport.
  *
  * @param agent NTA agent object
  *
- * @return The function nta_agent_via() returns a list of sip_via_t objects
- * used by the @a agent.
+ * @return A list of #sip_via_t objects used by the @a agent.
  */
 sip_via_t *nta_agent_via(nta_agent_t const *agent)
 {
   return agent ? agent->sa_vias : NULL;
 }
 
-
 /** Return a list of public (UPnP, STUN) @Via headers.
  *
- * The function nta_agent_public_via() returns public @Via headers for all activated
- * transports.
+ * Get public @Via headers for all activated transports.
  *
  * @param agent NTA agent object
  *
- * @return The function nta_agent_public_via() returns a list of sip_via_t objects
- * used by the @a agent.
+ * @return A list of #sip_via_t objects used by the @a agent.
  */
 sip_via_t *nta_agent_public_via(nta_agent_t const *agent)
 {
   return agent ? agent->sa_public_vias : NULL;
 }
 
+/** Match a @Via header @a v with @Via headers in @a agent.
+ *
+ */
+static
+sip_via_t *agent_has_via(nta_agent_t const *agent, sip_via_t const *via)
+{
+  sip_via_t const *v;
+
+  for (v = agent->sa_public_vias; v; v = v->v_next) {
+    if (strcasecmp(via->v_host, v->v_host))
+      continue;
+    if (str0cmp(via->v_port, v->v_port))
+      continue;
+    if (strcasecmp(via->v_protocol, v->v_protocol))
+      continue;
+    return (sip_via_t *)v;
+  }
+
+  for (v = agent->sa_vias; v; v = v->v_next) {
+    if (strcasecmp(via->v_host, v->v_host))
+      continue;
+    if (str0cmp(via->v_port, v->v_port))
+      continue;
+    if (strcasecmp(via->v_protocol, v->v_protocol))
+      continue;
+    return (sip_via_t *)v;
+  }
+
+  return NULL;
+}
+
 /** Return @UserAgent header.
  *
- * The function nta_agent_name() returns a @UserAgent information with
- * NTA version.
+ * Get @UserAgent information with NTA version.
  *
  * @param agent NTA agent object (may be NULL)
  *
- * @return The function nta_agent_contact() returns a string containing the
- * @a agent version.
+ * @return A string containing the @a agent version.
  */
 char const *nta_agent_version(nta_agent_t const *agent)
 {
@@ -667,53 +695,108 @@
 static
 int agent_timer_init(nta_agent_t *agent)
 {
-  return su_timer_set(agent->sa_timer =
-		      su_timer_create(su_root_task(agent->sa_root),
-				      NTA_SIP_T1 / 8),
+  agent->sa_timer = su_timer_create(su_root_task(agent->sa_root),
+				    NTA_SIP_T1 / 8);
+#if 0
+  return su_timer_set(agent->sa_timer,
 		      agent_timer,
 		      agent);
+#endif
+  return -(agent->sa_timer == NULL);
 }
 
+#define NEXT_TIMEOUT(next, p, f, now) \
+  (p && p->f - (next) < 0 ? (p->f - (now) > 0 ? p->f : (now)) : (next))
+
 /**
  * Agent timer routine.
  */
 static
 void agent_timer(su_root_magic_t *rm, su_timer_t *timer, nta_agent_t *agent)
 {
-  su_duration_t now = su_time_ms(agent->sa_now = su_now());
-  int again;
+  su_time_t stamp = su_now();
+  su_duration_t now = su_time_ms(stamp), next;
 
   now += now == 0;
 
+  agent->sa_now = stamp;
   agent->sa_millisec = now;
+  agent->sa_next = 0;
+  agent->sa_in_timer = 1;
 
-  again = outgoing_timer(agent, now);
-  again = incoming_timer(agent, now) || again;
+  next = now + SU_DURATION_MAX;
+  next = outgoing_timer(agent, next);
+  next = incoming_timer(agent, next);
 
   agent->sa_millisec = 0;
+  agent->sa_in_timer = 0;
 
-  if (again)
-    su_timer_set_at(timer, agent_timer, agent, su_time_add(su_now(), 1));
-  else
-    su_timer_set(timer, agent_timer, agent);
+  if (agent->sa_next)
+    next = NEXT_TIMEOUT(next, agent, sa_next, now);
+
+  if (next == now + SU_DURATION_MAX) {
+    /* Do not set timer */
+    SU_DEBUG_9(("nta: timer not set\n"));
+    assert(!agent->sa_out.completed->q_head);
+    assert(!agent->sa_out.trying->q_head);
+    assert(!agent->sa_out.inv_calling->q_head);
+    assert(!agent->sa_out.re_list);
+    assert(!agent->sa_in.inv_confirmed->q_head);
+    assert(!agent->sa_in.preliminary->q_head);
+    assert(!agent->sa_in.completed->q_head);
+    assert(!agent->sa_in.inv_completed->q_head);
+    assert(!agent->sa_in.re_list);
+    return;
+  }
+
+  if (next == now) if (++next == 0) ++next;
+
+  SU_DEBUG_9(("nta: timer %s to %ld ms\n", "set next", (long)(next - now)));
+
+  agent->sa_next = next;
+
+  su_timer_set_at(timer, agent_timer, agent, su_time_add(stamp, next - now));
 }
 
-/** Calculate nonzero value for timer */
-static inline
-su_duration_t set_timeout(nta_agent_t const *agent, su_duration_t offset)
+/** Calculate nonzero value for timeout.
+ *
+ * Sets or adjusts agent timer when needed.
+ *
+ * @retval 0 if offset is 0
+ * @retval timeout (millisecond counter) otherwise
+ */
+static
+su_duration_t set_timeout(nta_agent_t *agent, su_duration_t offset)
 {
-  su_duration_t now;
+  su_time_t now;
+  su_duration_t next, ms;
 
-#if 0
-  if (agent->sa_millisec)
-    now = agent->sa_millisec;
+  if (offset == 0)
+    return 0;
+
+  if (agent->sa_millisec) /* Avoid expensive call to su_timer_ms() */
+    now = agent->sa_now, ms = agent->sa_millisec;
   else
-#endif
-    now = (su_duration_t)su_time_ms(su_now());
+    now = su_now(), ms = (su_duration_t)su_time_ms(now);
+  
+  next = ms + offset; if (next == 0) next = 1;
+
+  if (agent->sa_in_timer)
+    return next;
 
-  now += offset;
+  if (agent->sa_next == 0 || agent->sa_next - next - 5L > 0) {
+    /* Set timer */
+    if (agent->sa_next)
+      SU_DEBUG_9(("nta: timer %s to %ld ms\n", "shortened", (long)offset));
+    else
+      SU_DEBUG_9(("nta: timer %s to %ld ms\n", "set", (long)offset));
+      
+    su_timer_set_at(agent->sa_timer, agent_timer, agent, 
+		    su_time_add(now, offset));
+    agent->sa_next = next;
+  }
 
-  return now ? now : 1;
+  return next;
 }
 
 
@@ -721,7 +804,10 @@
 static
 su_time_t agent_now(nta_agent_t const *agent)
 {
-  return agent->sa_millisec ? agent->sa_now : su_now();
+  if (agent && agent->sa_millisec != 0)
+    return agent->sa_now;
+  else 
+    return su_now();
 }
 
 
@@ -833,7 +919,7 @@
   unsigned threadpool      = agent->sa_tport_threadpool;
   char const *sigcomp = agent->sa_sigcomp_options;
   char const *algorithm = NONE;
-  msg_mclass_t *mclass = NONE;
+  msg_mclass_t const *mclass = NONE;
   sip_contact_t const *aliases = NONE;
   url_string_t const *proxy = NONE;
   tport_t *tport;
@@ -929,7 +1015,7 @@
     agent->sa_algorithm = su_strdup(home, algorithm);
 
   if (str0cmp(sigcomp, agent->sa_sigcomp_options)) {
-    char const * const *l = NULL;
+    msg_param_t const *l = NULL;
     char *s = su_strdup(home, sigcomp);
     char *s1 = su_strdup(home, s), *s2 = s1;
 
@@ -1338,7 +1424,7 @@
 
 /** Add a transport to the agent.
  *
- * The function nta_agent_add_tport() creates a new transport and binds it
+ * Creates a new transport and binds it
  * to the port specified by the @a uri. The @a uri must have sip: or sips:
  * scheme or be a wildcard uri ("*"). The @a uri syntax allowed is as
  * follows:
@@ -1475,7 +1561,7 @@
 	(nta_compressor_vtable == NULL || 
 	 strcasecmp(tpn->tpn_comp, nta_compressor_vtable->ncv_name) != 0)) {
       SU_DEBUG_1(("nta(%p): comp=%s not supported for " URL_PRINT_FORMAT "\n",
-		  self, tpn->tpn_comp, URL_PRINT_ARGS(url)));
+		  (void *)self, tpn->tpn_comp, URL_PRINT_ARGS(url)));
     }
   }
 
@@ -1739,10 +1825,20 @@
   if (self->sa_contact)
     return 0;
 
-  if (self->sa_vias)
-    v1 = self->sa_vias;
-  else
-    v1 = self->sa_public_vias;
+  for (v1 = self->sa_vias ? self->sa_vias : self->sa_public_vias;
+       v1;
+       v1 = v1->v_next) {
+    if (host_is_ip_address(v1->v_host)) {
+      if (!host_is_local(v1->v_host))
+	break;
+    }
+    else if (!host_has_domain_invalid(v1->v_host)) {
+      break;
+    }
+  }
+
+  if (v1 == NULL)
+    v1 = self->sa_vias ? self->sa_vias : self->sa_public_vias;
 
   if (!v1)
     return -1;
@@ -1960,7 +2056,8 @@
   }
   else {
     /* XXX - we should do something else? */
-    SU_DEBUG_3(("nta(%p): transport address updated\n", self));
+    SU_DEBUG_3(("%s(%p): %s\n", "nta", (void *)self, 
+		"transport address updated"));
   }
 }
 
@@ -2474,7 +2571,10 @@
 
   if (sip->sip_cseq->cs_method == sip_method_invite
       && 200 <= sip->sip_status->st_status
-      && sip->sip_status->st_status < 300) {
+      && sip->sip_status->st_status < 300
+      /* Exactly one Via header, belonging to us */
+      && sip->sip_via && !sip->sip_via->v_next 
+      && agent_has_via(agent, sip->sip_via)) {
     agent->sa_stats->as_trless_200++;
     /* Orphan 200 Ok to INVITE. ACK and BYE it */
     SU_DEBUG_5(("nta: %03d %s must be ACK&BYE\n", status, phrase));
@@ -2485,6 +2585,7 @@
   SU_DEBUG_5(("nta: %03d %s was discarded\n", status, phrase));
   msg_destroy(msg);
 }
+
 /** @internal Agent receives garbage */
 static
 void agent_recv_garbage(nta_agent_t *agent,
@@ -2800,7 +2901,7 @@
 static
 int complete_response(msg_t *response, 
 		      int status, char const *phrase, 
-		      msg_t const *request)
+		      msg_t *request)
 {
   su_home_t *home = msg_home(response);
   sip_t *response_sip = sip_object(response);
@@ -2951,11 +3052,11 @@
 
 /**Complete a request with values from dialog.
  *
- * The function nta_msg_request_complete() completes a request message @a
- * msg belonging to a dialog associated with @a leg. It increments the local
- * @CSeq value, adds @CallID, @To, @From and @Route headers (if
- * there is such headers present in @a leg), and creates a new request line
- * object from @a method, @a method_name and @a request_uri.
+ * Complete a request message @a msg belonging to a dialog associated with
+ * @a leg. It increments the local @CSeq value, adds @CallID, @To, @From and
+ * @Route headers (if there is such headers present in @a leg), and creates
+ * a new request line object from @a method, @a method_name and @a
+ * request_uri.
  *
  * @param msg          pointer to a request message object
  * @param leg          pointer to a #nta_leg_t object
@@ -3106,7 +3207,7 @@
   method = sip->sip_request->rq_method;
   method_name = sip->sip_request->rq_method_name;
 
-  if (!leg->leg_id && !sip->sip_call_id && sip->sip_cseq)
+  if (!leg->leg_id && sip->sip_cseq)
     seq = sip->sip_cseq->cs_seq; 
   else if (method == sip_method_ack || method == sip_method_cancel)
     /* Dangerous - we may do PRACK/UPDATE meanwhile */
@@ -3179,9 +3280,9 @@
 /**
  * Create a new leg object.
  *
- * The function nta_leg_tcreate() creates a leg object. A leg object is used
- * to represent dialogs, partial dialogs (for example, in case of REGISTER),
- * and destinations within a particular NTA object.
+ * Creates a leg object, which is used to represent dialogs, partial dialogs
+ * (for example, in case of REGISTER), and destinations within a particular
+ * NTA object.
  *
  * When a leg is created, a callback pointer and a application context is
  * provided. All other parameters are optional.
@@ -3421,7 +3522,7 @@
 
   leg_insert(agent, leg);
 
-  SU_DEBUG_9(("nta_leg_create(%p)\n", leg));
+  SU_DEBUG_9(("nta_leg_create(%p)\n", (void *)leg));
 
   return leg;
 
@@ -3471,7 +3572,7 @@
  */
 void nta_leg_destroy(nta_leg_t *leg)
 {
-  SU_DEBUG_9(("nta_leg_destroy(%p)\n", leg));
+  SU_DEBUG_9(("nta_leg_destroy(%p)\n", (void *)leg));
 
   if (leg) {
     leg_htable_t *leg_hash;
@@ -3518,8 +3619,8 @@
 
 /**Bind a callback function and context to a leg object.
  *
- * The function nta_leg_bind() is used to change the callback
- * and context pointer attached to a leg object.
+ * Change the callback function and context pointer attached to a leg
+ * object.
  *
  * @param leg      leg object to be bound
  * @param callback new callback function (or NULL if no callback is desired)
@@ -3566,6 +3667,7 @@
   if (tag) {
     if (sip_to_tag(leg->leg_home, leg->leg_local, tag) < 0)
       return NULL;
+    leg->leg_tagged = 1;
     return leg->leg_local->a_tag;
   }
 
@@ -3574,6 +3676,8 @@
   if (!tag || sip_to_add_param(leg->leg_home, leg->leg_local, tag) < 0)
     return NULL;
 
+  leg->leg_tagged = 1;
+
   return leg->leg_local->a_tag;
 }
 
@@ -3757,7 +3861,7 @@
 
   if (!(irq = incoming_create(agent, msg, sip, tport, tag))) {
     SU_DEBUG_3(("nta: leg_recv(%p): cannot create transaction for %s\n",
-		leg, method_name));
+		(void *)leg, method_name));
     nta_msg_treply(agent, msg,
 		   SIP_500_INTERNAL_SERVER_ERROR,
 		   NTATAG_TPORT(tport),
@@ -3783,12 +3887,12 @@
 
   if (status < 100 || status > 699) {
     SU_DEBUG_3(("nta_leg(%p): invalid status %03d from callback\n",
-		leg, status));
+		(void *)leg, status));
     status = 500;
   }
   else if (method == sip_method_invite && status >= 200 && status < 300) {
     SU_DEBUG_3(("nta_leg(%p): invalid INVITE status %03d from callback\n",
-		leg, status));
+		(void *)leg, status));
     status = 500;
   }
 
@@ -3818,8 +3922,8 @@
 
 /** Get a leg by dialog.
  *
- * The function nta_leg_by_dialog() searches for a dialog leg from agent's
- * hash table. The matching rules based on parameters  are as follows:
+ * Search for a dialog leg from agent's hash table. The matching rules based
+ * on parameters are as follows:
  *
  * @param agent        pointer to agent object
  * @param request_uri  if non-NULL, and there is destination URI
@@ -3922,6 +4026,14 @@
     /* Do not match if the incoming To has tag, but the local does not */
     if (!local_tag && to_tag)
       continue;
+
+    /*
+     * Do not match if incoming To has no tag and we have local tag
+     * and the tag has been there from the beginning.
+     */
+    if (local_tag && !to_tag && !leg->leg_tagged)
+      continue;
+
     /* Do not match if incoming From has no tag but remote has a tag */
     if (remote_tag && !from_tag)
       continue;
@@ -4034,8 +4146,8 @@
 
 /** Set leg route and target URL.
  *
- * The function leg_route() sets the leg route and contact using the
- * @RecordRoute and @Contact headers.
+ * Sets the leg route and contact using the @RecordRoute and @Contact
+ * headers.
  */
 static
 int leg_route(nta_leg_t *leg,
@@ -4153,7 +4265,7 @@
 static inline void incoming_remove(nta_incoming_t *irq);
 static inline void incoming_set_timer(nta_incoming_t *, unsigned interval);
 static inline void incoming_reset_timer(nta_incoming_t *);
-static inline size_t incoming_mass_destroy(nta_agent_t *sa, incoming_queue_t *q);
+static inline size_t incoming_mass_destroy(nta_agent_t *, incoming_queue_t *);
 
 static int incoming_set_params(nta_incoming_t *irq, tagi_t const *tags);
 static inline
@@ -4208,9 +4320,9 @@
 
 /** Create a server transaction. 
  *
- * The function nta_incoming_create() creates a server transaction for a
- * request message. This function is used when an element processing
- * requests statelessly wants to process a particular request statefully.
+ * Create a server transaction for a request message. This function is used
+ * when an element processing requests statelessly wants to process a
+ * particular request statefully.
  *
  * @param agent pointer to agent object
  * @param leg  pointer to leg object (either @a agent or @a leg may be NULL)
@@ -4436,7 +4548,7 @@
 
     if (leg->leg_rseq > sip->sip_cseq->cs_seq) {
       SU_DEBUG_3(("nta_leg(%p): out-of-order %s (%u < %u)\n",
-		  leg, method_name, seq, leg->leg_rseq));
+		  (void *)leg, method_name, seq, leg->leg_rseq));
       return 500;
     }
 
@@ -4514,8 +4626,8 @@
 /** @internal
  * Insert an incoming transaction into a queue. 
  *
- * The function incoming_queue() inserts a server transaction into a queue,
- * and sets the corresponding timeout at the same time.
+ * Insert a server transaction into a queue, and sets the corresponding
+ * timeout at the same time.
  */
 static inline
 void incoming_queue(incoming_queue_t *queue, 
@@ -4531,10 +4643,7 @@
 
   assert(*queue->q_tail == NULL);
 
-  if (queue->q_timeout)
-    irq->irq_timeout = set_timeout(irq->irq_agent, queue->q_timeout);
-  else
-    irq->irq_timeout = 0;
+  irq->irq_timeout = set_timeout(irq->irq_agent, queue->q_timeout);
 
   irq->irq_queue = queue;
   irq->irq_prev = queue->q_tail; 
@@ -4626,7 +4735,7 @@
 static
 void incoming_free(nta_incoming_t *irq)
 {
-  SU_DEBUG_9(("nta: incoming_free(%p)\n", irq));
+  SU_DEBUG_9(("nta: incoming_free(%p)\n", (void *)irq));
 
   incoming_cut_off(irq);
   incoming_reclaim(irq);
@@ -4706,7 +4815,8 @@
   incoming_queue_t *q = u->a_incoming_queue;
   nta_incoming_t *irq, *irq_next;
 
-  SU_DEBUG_9(("incoming_reclaim_all(%p, %p, %p)\n", rm, msg, u));
+  SU_DEBUG_9(("incoming_reclaim_all(%p, %p, %p)\n",
+	      (void *)rm, (void *)msg, (void *)u));
 
   for (irq = q->q_head; irq; irq = irq_next) {
     irq_next = irq->irq_next;
@@ -4716,10 +4826,10 @@
 
 /**Bind a callback and context to an incoming transaction object
  *
- * The function nta_incoming_bind() is used to set the callback and
- * context pointer attached to an incoming request object.  The callback
- * function will be invoked if the incoming request is cancelled, or if the
- * final response to an incoming @b INVITE request has been acknowledged.
+ * Set the callback function and context pointer attached to an incoming
+ * request object. The callback function will be invoked if the incoming
+ * request is cancelled, or if the final response to an incoming @b INVITE
+ * request has been acknowledged.
  *
  * If the callback is NULL, or no callback has been bound, NTA invokes the
  * request callback of the call leg.
@@ -4916,15 +5026,16 @@
 nta_incoming_t *incoming_find(nta_agent_t const *agent,
 			      sip_t const *sip,
 			      sip_via_t const *v,
-			      nta_incoming_t **merge,
-			      nta_incoming_t **ack)
+			      nta_incoming_t **return_merge,
+			      nta_incoming_t **return_ack)
 {
   sip_cseq_t const *cseq = sip->sip_cseq;
   sip_call_id_t const *i = sip->sip_call_id;
   sip_to_t const *to = sip->sip_to;
   sip_from_t const *from = sip->sip_from;
   sip_request_t *rq = sip->sip_request;
-  int is_uas_ack = ack && agent->sa_is_a_uas && rq->rq_method == sip_method_ack;
+  int is_uas_ack = return_ack && 
+    agent->sa_is_a_uas && rq->rq_method == sip_method_ack;
   incoming_htable_t const *iht = agent->sa_incoming;
   hash_value_t hash = NTA_HASH(i, cseq->cs_seq);
 
@@ -4941,6 +5052,30 @@
       continue;
     if (str0casecmp(irq->irq_from->a_tag, from->a_tag))
       continue;
+
+    if (str0casecmp(irq->irq_via->v_branch, v->v_branch) != 0 ||
+	strcasecmp(irq->irq_via->v_host, v->v_host) != 0) {
+      if (!agent->sa_is_a_uas)
+	continue;
+      
+      if (is_uas_ack &&
+	  irq->irq_method == sip_method_invite && 
+	  200 <= irq->irq_status && irq->irq_status < 300 &&
+	  addr_match(irq->irq_to, to))
+	*return_ack = irq;
+      /* RFC3261 - section 8.2.2.2 Merged Requests */
+      else if (return_merge && agent->sa_merge_482 &&
+	       irq->irq_cseq->cs_method == cseq->cs_method &&
+	       (irq->irq_cseq->cs_method != sip_method_unknown ||
+		strcmp(irq->irq_cseq->cs_method_name, 
+		       cseq->cs_method_name) == 0)) {
+	*return_merge = irq;
+	continue;
+      }
+      else
+	continue;
+    }
+
     if (is_uas_ack) {
       if (!addr_match(irq->irq_to, to))
 	continue;
@@ -4953,16 +5088,6 @@
     else if (str0casecmp(irq->irq_to->a_tag, to->a_tag))
       continue;
 
-    if (str0casecmp(irq->irq_via->v_branch, v->v_branch) != 0) {
-      if (!agent->sa_is_a_uas)
-	continue;
-      if (is_uas_ack && irq->irq_status >= 200 && irq->irq_status < 300)
-	*ack = irq;
-      /* RFC3261 - section 8.2.2.2 Merged Requests */
-      else if (merge && !to->a_tag && agent->sa_merge_482)
-	*merge = irq;
-      continue;
-    }
     if (!is_uas_ack && url_cmp(irq->irq_rq->rq_url, rq->rq_url))
       continue;
 
@@ -4974,18 +5099,24 @@
     if (irq->irq_method == rq->rq_method)
       break;		/* found */
 
-    if (ack && rq->rq_method == sip_method_cancel)
-      *ack = irq;
-    else if (ack && rq->rq_method == sip_method_ack && 
-	     irq->irq_method == sip_method_invite)
-      *ack = irq;
+    if (!return_ack)
+      continue;
+
+    if (irq->irq_method == sip_method_invite) {
+      if (rq->rq_method == sip_method_cancel)
+	*return_ack = irq;
+      else if (rq->rq_method == sip_method_ack)
+	*return_ack = irq;
+    }
+    else if (rq->rq_method == sip_method_cancel && !irq->irq_terminated)
+      *return_ack = irq;
   }
 
   if (irq)
     return irq;
 
   /* Check PRACKed requests */
-  if (ack && rq->rq_method == sip_method_prack && sip->sip_rack) {
+  if (return_ack && rq->rq_method == sip_method_prack && sip->sip_rack) {
     sip_rack_t const *rack = sip->sip_rack;
     hash = NTA_HASH(i, rack->ra_cseq);
 
@@ -5005,7 +5136,7 @@
 	continue;
       if (!irq->irq_from->a_tag != !from->a_tag)
 	continue;
-      *ack = irq;
+      *return_ack = irq;
 
       return NULL;
     }
@@ -5097,10 +5228,18 @@
   nta_agent_t *agent = irq->irq_agent;
 
   /* Respond to the CANCEL */
-  nta_msg_treply(agent, msg_ref_create(msg), SIP_200_OK, 
-		 NTATAG_TPORT(tport),
-		 TAG_END());
 
+  if (200 <= irq->irq_status && irq->irq_status < 300) {
+    nta_msg_treply(agent, msg_ref_create(msg), SIP_481_NO_TRANSACTION, 
+		   NTATAG_TPORT(tport),
+		   TAG_END());
+  }
+  else
+    nta_msg_treply(agent, msg_ref_create(msg), SIP_200_OK, 
+		   NTATAG_TPORT(tport),
+		   TAG_END());
+
+  /* We have already sent final response */
   if (irq->irq_completed || irq->irq_method != sip_method_invite) {
     msg_destroy(msg);
     return 0;
@@ -5276,6 +5415,34 @@
   return 0;
 }
 
+/** Add essential headers to the response message */
+static int nta_incoming_response_headers(nta_incoming_t *irq, 
+					 msg_t *msg,
+					 sip_t *sip)
+{
+  int clone = 0;
+  su_home_t *home = msg_home(msg);
+
+  if (!sip->sip_from)
+    clone = 1, sip->sip_from = sip_from_copy(home, irq->irq_from);
+  if (!sip->sip_to)
+    clone = 1, sip->sip_to = sip_to_copy(home, irq->irq_to);
+  if (!sip->sip_call_id)
+    clone = 1, sip->sip_call_id = sip_call_id_copy(home, irq->irq_call_id);
+  if (!sip->sip_cseq)
+    clone = 1, sip->sip_cseq = sip_cseq_copy(home, irq->irq_cseq);
+  if (!sip->sip_via)
+    clone = 1, sip->sip_via = sip_via_copy(home, irq->irq_via);
+
+  if (clone)
+    msg_set_parent(msg, (msg_t *)irq->irq_home);
+
+  if (!sip->sip_from || !sip->sip_to || !sip->sip_call_id || !sip->sip_cseq || !sip->sip_via)
+    return -1;
+
+  return 0;
+}
+
 /** Complete a response message.
  *
  * @param irq     server transaction object
@@ -5297,7 +5464,6 @@
 {
   su_home_t *home = msg_home(msg);
   sip_t *sip = sip_object(msg);
-  int clone = 0;
   int retval;
   ta_list ta;
 
@@ -5307,7 +5473,7 @@
   if (status != 0 && (status < 100 || status > 699))
     return su_seterrno(EINVAL), -1;
 
-  if (!sip->sip_status)
+  if (status != 0 && !sip->sip_status)
     sip->sip_status = sip_status_create(home, status, phrase, NULL);
 
   ta_start(ta, tag, value);
@@ -5320,42 +5486,54 @@
   if (irq->irq_default)
     return sip_complete_message(msg);
 
-  if (!sip->sip_from)
-    clone = 1, sip->sip_from = sip_from_copy(home, irq->irq_from);
   if (status > 100 && !irq->irq_tag) {
     if (sip->sip_to)
       nta_incoming_tag(irq, sip->sip_to->a_tag);
     else
       nta_incoming_tag(irq, NULL);
   }
-  if (!sip->sip_to)
-    clone = 1, sip->sip_to = sip_to_copy(home, irq->irq_to);
+
+  if (nta_incoming_response_headers(irq, msg, sip) < 0)
+    return -1;
+
   if (sip->sip_status && sip->sip_status->st_status > 100 &&
       irq->irq_tag && sip->sip_to && !sip->sip_to->a_tag)
-    sip_to_tag(home, sip->sip_to, irq->irq_tag);
-  if (!sip->sip_call_id)
-    clone = 1, sip->sip_call_id = sip_call_id_copy(home, irq->irq_call_id);
-  if (!sip->sip_cseq)
-    clone = 1, sip->sip_cseq = sip_cseq_copy(home, irq->irq_cseq);
-  if (!sip->sip_via)
-    clone = 1, sip->sip_via = sip_via_copy(home, irq->irq_via);
-  if (status < 300 && 
-      !sip->sip_record_route && irq->irq_record_route)
-    sip_add_dup(msg, sip, (sip_header_t *)irq->irq_record_route);
-
-  if (clone)
-    msg_set_parent(msg, (msg_t *)irq->irq_home);
+    if (sip_to_tag(home, sip->sip_to, irq->irq_tag) < 0)
+      return -1;
 
-  if (retval < 0 || !sip->sip_from || !sip->sip_to || !sip->sip_call_id
-      || !sip->sip_cseq || !sip->sip_via
-      || (status < 300 && irq->irq_record_route && !sip->sip_record_route &&
-	  sip->sip_cseq && sip->sip_cseq->cs_method != sip_method_register))
-    return -1;
+  if (status < 300 && !sip->sip_record_route && irq->irq_record_route)
+    if (sip_add_dup(msg, sip, (sip_header_t *)irq->irq_record_route) < 0)
+      return -1;
 
   return sip_complete_message(msg);
 }
 
 
+/** Create a response message for request.
+ *
+ * @NEW_1_12_5.
+ */
+msg_t *nta_incoming_create_response(nta_incoming_t *irq,
+				    int status, char const *phrase)
+{
+  msg_t *msg = NULL;
+  sip_t *sip;
+
+  if (irq) {
+    msg = nta_msg_create(irq->irq_agent, 0);
+    sip = sip_object(msg);
+
+    if (status != 0)
+      sip->sip_status = sip_status_create(msg_home(msg), status, phrase, NULL);
+
+    if (nta_incoming_response_headers(irq, msg, sip) < 0)
+      msg_destroy(msg), msg = NULL;
+  }
+  
+  return msg;
+}
+
+
 /**Reply to an incoming transaction request.
  *
  * This function creates a response message to an incoming request and sends
@@ -5744,8 +5922,9 @@
 
 /** @internal Timer routine for the incoming request. */
 static inline
-int incoming_timer(nta_agent_t *sa, su_duration_t now)
+su_duration_t incoming_timer(nta_agent_t *sa, su_duration_t next)
 {
+  su_duration_t now = sa->sa_millisec;
   nta_incoming_t *irq, *irq_next;
   size_t retransmitted = 0, timeout = 0, terminated = 0, destroyed = 0;
   size_t unconfirmed = 
@@ -5762,8 +5941,9 @@
 
   /* Handle retry queue */
   while ((irq = sa->sa_in.re_list)) {
-    if ((irq->irq_retry && irq->irq_retry - now > 0) ||
-	retransmitted >= timer_max_retransmit) 
+    if (irq->irq_retry - now > 0)
+      break;
+    if (retransmitted >= timer_max_retransmit)
       break;
 
     if (irq->irq_method == sip_method_invite && irq->irq_status >= 200) {
@@ -5801,7 +5981,8 @@
 	retransmitted++;
 	incoming_retransmit_reply(irq, irq->irq_tport);
       }
-    } else {
+    }
+    else {
       /* Timer N1 */
       SU_DEBUG_5(("nta: timer N1 fired, sending %u %s\n", SIP_100_TRYING));
       incoming_reset_timer(irq);
@@ -5809,6 +5990,8 @@
     }
   }
 
+  next = NEXT_TIMEOUT(next, irq, irq_retry, now);
+
   while ((irq = sa->sa_in.final_failed->q_head)) {
     incoming_remove(irq);
     irq->irq_final_failed = 0;
@@ -5841,8 +6024,9 @@
     assert(irq->irq_status < 200);
     assert(irq->irq_timeout);
 
-    if (irq->irq_timeout - now > 0 
-	|| timeout >= timer_max_timeout)
+    if (irq->irq_timeout - now > 0)
+      break;
+    if (timeout >= timer_max_timeout)
       break;
 
     timeout++;
@@ -5855,6 +6039,8 @@
     reliable_timeout(irq, 1);
   }
 
+  next = NEXT_TIMEOUT(next, irq, irq_timeout, now);
+
   while ((irq = sa->sa_in.inv_completed->q_head)) {
     assert(irq->irq_status >= 200);
     assert(irq->irq_timeout);
@@ -5883,13 +6069,14 @@
     }
   } 
 
+  next = NEXT_TIMEOUT(next, irq, irq_timeout, now);
+
   while ((irq = sa->sa_in.inv_confirmed->q_head)) {
     assert(irq->irq_timeout);
     assert(irq->irq_status >= 200);
     assert(irq->irq_method == sip_method_invite);
 
-    if (irq->irq_timeout - now > 0 || 
-	terminated >= timer_max_terminate)
+    if (irq->irq_timeout - now > 0 || terminated >= timer_max_terminate)
       break;
     
     /* Timer I */
@@ -5905,13 +6092,14 @@
       incoming_free_queue(rq, irq);
   }
 
+  next = NEXT_TIMEOUT(next, irq, irq_timeout, now);
+
   while ((irq = sa->sa_in.completed->q_head)) {
     assert(irq->irq_status >= 200);
     assert(irq->irq_timeout);
     assert(irq->irq_method != sip_method_invite);
 
-    if (irq->irq_timeout - now > 0 || 
-	terminated >= timer_max_terminate)
+    if (irq->irq_timeout - now > 0 || terminated >= timer_max_terminate)
       break;
 
     /* Timer J */
@@ -5928,6 +6116,8 @@
       incoming_free_queue(rq, irq);
   }
 
+  next = NEXT_TIMEOUT(next, irq, irq_timeout, now);
+
   for (irq = sa->sa_in.terminated->q_head; irq; irq = irq_next) {
     irq_next = irq->irq_next;
     if (irq->irq_destroyed)
@@ -5947,10 +6137,7 @@
 		terminated, unterminated, 
 		destroyed, total));
 
-  return 
-    retransmitted >= timer_max_retransmit
-    || timeout >= timer_max_timeout
-    || terminated >= timer_max_terminate;
+  return next;
 }
 
 /** Mass destroy server transactions */
@@ -6018,11 +6205,11 @@
 static inline void outgoing_set_timer(nta_outgoing_t *orq, unsigned interval);
 static inline void outgoing_reset_timer(nta_outgoing_t *orq);
 static size_t outgoing_timer_dk(outgoing_queue_t *q, 
-			     char const *timer, 
-			     su_duration_t now);
+				char const *timer, 
+				su_duration_t now);
 static size_t outgoing_timer_bf(outgoing_queue_t *q, 
-			     char const *timer, 
-			     su_duration_t now);
+				char const *timer, 
+				su_duration_t now);
 
 static void outgoing_ack(nta_outgoing_t *orq, msg_t *msg, sip_t *sip);
 static msg_t *outgoing_ackmsg(nta_outgoing_t *, sip_method_t, char const *,
@@ -6093,12 +6280,11 @@
 
 /**Create an outgoing request and client transaction belonging to the leg.
  *
- * The function nta_outgoing_tcreate() creates a request message and passes
- * the request message to an outgoing client transaction object. The request
- * is sent to the @a route_url (if non-NULL), default proxy (if defined by
- * NTATAG_DEFAULT_PROXY()), or to the address specified by @a request_uri.
- * If no @a request_uri is specified, it is taken from route-set target or
- * from the @To header.
+ * Create a request message and pass the request message to an outgoing
+ * client transaction object. The request is sent to the @a route_url (if
+ * non-NULL), default proxy (if defined by NTATAG_DEFAULT_PROXY()), or to
+ * the address specified by @a request_uri. If no @a request_uri is
+ * specified, it is taken from route-set target or from the @To header.
  *
  * When NTA receives response to the request, it invokes the @a callback
  * function.
@@ -6381,7 +6567,8 @@
     return;
 
   if (orq->orq_destroyed) {
-    SU_DEBUG_1(("nta_outgoing_destroy(%p): already destroyed\n", orq));
+    SU_DEBUG_1(("%s(%p): %s\n", "nta_outgoing_destroy", (void *)orq, 
+		"already destroyed"));
     return;
   }
 
@@ -6474,10 +6661,10 @@
 
 /**Create an outgoing request.
  *
- * The function outgoing_create() creates an outgoing transaction object and
- * sends the request to the network. The request is sent to the @a route_url
- * (if non-NULL), default proxy (if defined by NTATAG_DEFAULT_PROXY()), or
- * to the address specified by @a sip->sip_request->rq_url.
+ * Create an outgoing transaction object and send the request to the
+ * network. The request is sent to the @a route_url (if non-NULL), default
+ * proxy (if defined by NTATAG_DEFAULT_PROXY()), or to the address specified
+ * by @a sip->sip_request->rq_url.
  *
  * When NTA receives response to the request, it invokes the @a callback
  * function.
@@ -7228,8 +7415,8 @@
 /** @internal
  * Insert an outgoing transaction into a queue. 
  *
- * The function outgoing_queue() inserts a client transaction into a queue,
- * and sets the corresponding timeout at the same time.
+ * Insert a client transaction into a queue and set the corresponding
+ * timeout at the same time.
  */
 static inline
 void outgoing_queue(outgoing_queue_t *queue, 
@@ -7246,7 +7433,7 @@
   assert(*queue->q_tail == NULL);
 
   orq->orq_timeout = set_timeout(orq->orq_agent, queue->q_timeout);
-    
+
   orq->orq_queue = queue;
   orq->orq_prev = queue->q_tail; 
   *queue->q_tail = orq;
@@ -7277,8 +7464,7 @@
 
 /** Set retransmit timer (orq_retry).
  *
- * The function outgoing_set_timer() will set the retry timer (B/D) on
- * the outgoing request (client transaction). 
+ * Set the retry timer (B/D) on the outgoing request (client transaction).
  */
 static inline
 void outgoing_set_timer(nta_outgoing_t *orq, unsigned interval)
@@ -7305,6 +7491,7 @@
 
   orq->orq_retry = set_timeout(orq->orq_agent, orq->orq_interval = interval);
 
+  /* Shortcut into queue at SIP T1 */
   rq = orq->orq_agent->sa_out.re_t1;
 
   if (!(*rq) || (*rq)->orq_retry - orq->orq_retry > 0)
@@ -7343,7 +7530,7 @@
 static
 void outgoing_free(nta_outgoing_t *orq)
 {
-  SU_DEBUG_9(("nta: outgoing_free(%p)\n", orq));
+  SU_DEBUG_9(("nta: outgoing_free(%p)\n", (void *)orq));
   outgoing_cut_off(orq);
   outgoing_reclaim(orq);
 }
@@ -7410,7 +7597,8 @@
   outgoing_queue_t *q = u->a_outgoing_queue;
   nta_outgoing_t *orq, *orq_next;
 
-  SU_DEBUG_9(("outgoing_reclaim_all(%p, %p, %p)\n", rm, msg, u));
+  SU_DEBUG_9(("outgoing_reclaim_all(%p, %p, %p)\n",
+	      (void *)rm, (void *)msg, (void *)u));
 
   for (orq = q->q_head; orq; orq = orq_next) {
     orq_next = orq->orq_next;
@@ -7434,6 +7622,14 @@
   if (orq->orq_terminated || orq->orq_default) {
     outgoing_free(orq);
   }
+  /* We have to handle 200 OK statelessly => 
+     kill transaction immediately */
+  else if (orq->orq_method == sip_method_invite && !orq->orq_completed
+	   /* (unless we have to wait to send CANCEL) */
+	   && !orq->orq_cancel) {
+    orq->orq_destroyed = 1;
+    outgoing_terminate(orq);
+  }
   else {
     orq->orq_destroyed = 1;
     orq->orq_callback = outgoing_default_cb;
@@ -7441,24 +7637,29 @@
   }
 }
 
-/** @internal Outgoing transaction timer routine. */
-static
-int outgoing_timer(nta_agent_t *sa, su_duration_t now)
+/** @internal Outgoing transaction timer routine. 
+ *
+ */
+static inline 
+su_duration_t outgoing_timer(nta_agent_t *sa, su_duration_t next)
 {
+  su_duration_t now = sa->sa_millisec;
   nta_outgoing_t *orq;
   outgoing_queue_t rq[1];
   size_t retransmitted = 0, terminated = 0, timeout = 0, destroyed;
   size_t total = sa->sa_outgoing->oht_used;
   size_t trying = sa->sa_out.re_length;
-  size_t pending = sa->sa_out.trying->q_length + sa->sa_out.inv_calling->q_length;
+  size_t pending = sa->sa_out.trying->q_length + 
+    sa->sa_out.inv_calling->q_length;
   size_t completed = sa->sa_out.completed->q_length + 
     sa->sa_out.inv_completed->q_length;
 
   outgoing_queue_init(sa->sa_out.free = rq, 0);
 
   while ((orq = sa->sa_out.re_list)) {
-    if ((orq->orq_retry && orq->orq_retry - now > 0)
-	|| retransmitted >= timer_max_retransmit)
+    if (orq->orq_retry - now > 0)
+      break;
+    if (retransmitted >= timer_max_retransmit)
       break;
 
     if (orq->orq_reliable) {
@@ -7494,14 +7695,22 @@
       su_root_yield(sa->sa_root);	/* Handle received packets */
   }
 
+  next = NEXT_TIMEOUT(next, orq, orq_retry, now);
+
   terminated
     = outgoing_timer_dk(sa->sa_out.inv_completed, "D", now)
     + outgoing_timer_dk(sa->sa_out.completed, "K", now);
 
+  next = NEXT_TIMEOUT(next, sa->sa_out.inv_completed->q_head, orq_timeout, now);
+  next = NEXT_TIMEOUT(next, sa->sa_out.completed->q_head, orq_timeout, now);
+
   timeout
     = outgoing_timer_bf(sa->sa_out.inv_calling, "B", now)
     + outgoing_timer_bf(sa->sa_out.trying, "F", now);
 
+  next = NEXT_TIMEOUT(next, sa->sa_out.inv_calling->q_head, orq_timeout, now);
+  next = NEXT_TIMEOUT(next, sa->sa_out.trying->q_head, orq_timeout, now);
+
   destroyed = outgoing_mass_destroy(sa, rq);
 
   sa->sa_out.free = NULL;
@@ -7518,10 +7727,7 @@
 		destroyed, total));
   }
 
-  return 
-    retransmitted >= timer_max_retransmit || 
-    terminated >= timer_max_terminate || 
-    timeout >= timer_max_timeout;
+  return next;
 }
 
 /** @internal Retransmit the outgoing request. */
@@ -7558,16 +7764,12 @@
 			 char const *timer, 
 			 su_duration_t now)
 {
+  nta_outgoing_t *orq;
   size_t timeout = 0;
 
-  for (;;) {
-    nta_outgoing_t *orq = q->q_head;
-
-    if (!orq 
-	|| !orq->orq_timeout
-	|| orq->orq_timeout - now > 0 
-	|| timeout >= timer_max_timeout)
-      return timeout;
+  while ((orq = q->q_head)) {
+    if (orq->orq_timeout - now > 0 || timeout >= timer_max_timeout)
+      break;
 
     timeout++;
     
@@ -7579,6 +7781,8 @@
 
     assert(q->q_head != orq || orq->orq_timeout - now > 0);
   }
+
+  return timeout;
 }
 
 /** @internal Signal transaction timeout to the application. */
@@ -7587,7 +7791,8 @@
   nta_outgoing_t *cancel;
 
   if (outgoing_other_destinations(orq)) {
-    SU_DEBUG_5(("nta(%p): try next after timeout\n", orq));
+    SU_DEBUG_5(("%s(%p): %s\n", "nta", (void *)orq,
+		"try next after timeout"));
     outgoing_try_another(orq);
     return;
   }
@@ -7634,16 +7839,12 @@
 			 char const *timer, 
 			 su_duration_t now)
 {
+  nta_outgoing_t *orq;
   size_t terminated = 0;
 
-  for (;;) {
-    nta_outgoing_t *orq = q->q_head;
-
-    if (!orq 
-	|| !orq->orq_timeout 
-	|| orq->orq_timeout - now > 0 
-	|| terminated >= timer_max_terminate)
-      return terminated;
+  while ((orq = q->q_head)) {
+    if (orq->orq_timeout - now > 0 || terminated >= timer_max_terminate)
+      break;
 
     terminated++;
 
@@ -7652,6 +7853,8 @@
 
     outgoing_terminate(orq);
   }
+  
+  return terminated;
 }
 
 /** Terminate a client transaction. */
@@ -7815,10 +8018,11 @@
 {
   nta_agent_t *sa = orq->orq_agent;
   short orq_status = orq->orq_status;
+  int internal = sip == NULL || (sip->sip_flags & NTA_INTERNAL_MSG) != 0;
 
   if (status < 100) status = 100;
 
-  if (sip && orq->orq_delay == UINT_MAX)
+  if (!internal && orq->orq_delay == UINT_MAX)
     outgoing_estimate_delay(orq, sip);
 
   if (orq->orq_cc)
@@ -7835,6 +8039,16 @@
       outgoing_send(cancel, 0);
     else
       outgoing_reply(cancel, SIP_481_NO_TRANSACTION, 0);
+
+    if (status < 300 && orq->orq_destroyed && 
+	orq->orq_method == sip_method_invite) {
+      outgoing_terminate(orq);      /* We can now kill transaction */
+      if (status == 100) {
+	msg_destroy(msg);
+	return 0;
+      }
+      return -1;
+    }
   }
 
   if (orq->orq_pending) {
@@ -7866,7 +8080,7 @@
     }
     else {
       /* Final response */
-      if (status >= 300)
+      if (status >= 300 && !internal)
 	outgoing_ack(orq, msg, sip);
 
       if (!orq->orq_completed) {
@@ -7896,7 +8110,8 @@
   }
   else if (orq->orq_method != sip_method_ack) {
     /* Non-INVITE */
-    if (orq->orq_queue == sa->sa_out.trying) {
+    if (orq->orq_queue == sa->sa_out.trying ||
+	orq->orq_queue == sa->sa_out.resolving) {
       assert(orq_status < 200); (void)orq_status;
 
       if (status < 200) {
@@ -7911,7 +8126,8 @@
 	msg_destroy(msg);
 	return 0;
       }
-    } else {
+    }
+    else {
       /* Already completed or terminated */
       assert(orq->orq_queue == sa->sa_out.completed ||
 	     orq->orq_queue == sa->sa_out.terminated);
@@ -8167,7 +8383,8 @@
 
   if (orq->orq_method == sip_method_ack) {
     if (status != delayed)
-      SU_DEBUG_3(("nta(%p): responding %u %s to ACK!\n", orq, status, phrase));
+      SU_DEBUG_3(("nta(%p): responding %u %s to ACK!\n",
+		  (void *)orq, status, phrase));
     orq->orq_status = status;
     if (orq->orq_queue == NULL)
       outgoing_complete(orq);	/* Timer D/K */
@@ -8447,8 +8664,8 @@
 
     /* Nothing found */
     if (!sr->sr_tports[0]) {
-      SU_DEBUG_3(("nta(%p): transport %s is not supported%s%s\n", orq, tpname,
-		  ident ? " by interface " : "", ident ? ident : ""));
+      SU_DEBUG_3(("nta(%p): transport %s is not supported%s%s\n", (void *)orq,
+		  tpname, ident ? " by interface " : "", ident ? ident : ""));
       outgoing_resolving_error(orq, SIPDNS_503_ERROR);
       return;
     }
@@ -9062,10 +9279,10 @@
     inet_ntop(AF_INET6, &aaaa->aaaa_addr, addr, sizeof(addr));
 
     if (j == 0)
-      SU_DEBUG_5(("nta(%p): %s IN AAAA %s\n", orq, 
+      SU_DEBUG_5(("nta(%p): %s IN AAAA %s\n", (void *)orq, 
 		  aaaa->aaaa_record->r_name, addr));
     else
-      SU_DEBUG_5(("nta(%p):  AAAA %s\n", orq, addr));
+      SU_DEBUG_5(("nta(%p):  AAAA %s\n", (void *)orq, addr));
 
     assert(j < found);
     results[j++] = su_strdup(home, addr);
@@ -9147,7 +9364,7 @@
     if (j == 0)
       SU_DEBUG_5(("nta: %s IN A %s\n", a->a_record->r_name, addr));
     else
-      SU_DEBUG_5(("nta(%p):  A %s\n", orq, addr));
+      SU_DEBUG_5(("nta(%p):  A %s\n", (void *)orq, addr));
 
     assert(j < found);
     results[j++] = su_strdup(home, addr);
@@ -9171,7 +9388,7 @@
       sq->sq_type != sr->sr_a_aaaa2) {
     sq->sq_type = sr->sr_a_aaaa2;
 
-    SU_DEBUG_7(("nta(%p): %s %s record still unresolved\n", orq,
+    SU_DEBUG_7(("nta(%p): %s %s record still unresolved\n", (void *)orq,
 		sq->sq_domain, sq->sq_type == sres_type_a ? "A" : "AAAA"));
 
     /*
@@ -9492,8 +9709,9 @@
   status = rel->rel_callback(rel->rel_magic, rel, pr_irq, sip); rel = NULL;
   irq->irq_in_callback = pr_irq->irq_in_callback = 0;
 
-  if (pr_irq->irq_destroyed && pr_irq->irq_terminated) {
-    incoming_free(pr_irq);
+  if (pr_irq->irq_completed) {	/* Already sent final response */
+    if (pr_irq->irq_terminated && pr_irq->irq_destroyed)
+      incoming_free(pr_irq);
   }
   else if (status != 0) {
     if (status < 200 || status > 299) {
@@ -9622,8 +9840,7 @@
 
 /** Destroy a reliable response.
  *
- * The function nta_reliable_destroy() marks a reliable response object for
- * destroyal, and frees it if possible.
+ * Mark a reliable response object for destroyal and free it if possible.
  */
 void nta_reliable_destroy(nta_reliable_t *rel)
 {
@@ -9631,7 +9848,7 @@
     return;
 
   if (rel->rel_callback == nta_reliable_destroyed)
-    SU_DEBUG_1(("%s(%p): already destroyed\n", __func__, rel));
+    SU_DEBUG_1(("%s(%p): %s\n", __func__, (void *)rel, "already destroyed"));
 
   rel->rel_callback = nta_reliable_destroyed;
 
@@ -9658,7 +9875,7 @@
 
   if (!*prev) {
     assert(*prev);
-    SU_DEBUG_1(("%s(%p): not linked\n", __func__, rel));
+    SU_DEBUG_1(("%s(%p): %s\n", __func__, (void *)rel, "not linked"));
     return 200;
   }
 
@@ -9739,7 +9956,8 @@
   if (orq == NULL || to_tag == NULL)
     return NULL;
   if (orq->orq_to->a_tag) {
-    SU_DEBUG_1(("%s: transaction %p already in dialog\n", __func__, orq));
+    SU_DEBUG_1(("%s: transaction %p already in dialog\n", __func__,
+		(void *)orq));
     return NULL;
   }
 
@@ -9755,6 +9973,9 @@
 
   tagged->orq_prev = NULL, tagged->orq_next = NULL, tagged->orq_queue = NULL;
   tagged->orq_rprev = NULL, tagged->orq_rnext = NULL;
+#if HAVE_SOFIA_SRESOLV
+  tagged->orq_resolver = NULL;
+#endif
 
   if (tagged->orq_cc)
     nta_compartment_ref(tagged->orq_cc);
@@ -9784,8 +10005,8 @@
 
 /**PRACK a provisional response.
  *
- * The function nta_outgoing_prack() creates and sends a PRACK request used
- * to acknowledge a provisional response. 
+ * Create and send a PRACK request used to acknowledge a provisional
+ * response.
  *
  * The request is sent using the route of the original request @a oorq.
  *
@@ -9801,9 +10022,8 @@
  * @param tag,value,... optional
  *
  * @return
- * If successful, the function nta_outgoing_prack() returns a pointer
- * to newly created client transaction object for PRACK request, NULL
- * otherwise.
+ * If successful, return a pointer to newly created client transaction
+ * object for PRACK request, NULL otherwise.
  *
  * @sa
  * nta_outgoing_tcreate(), nta_outgoing_tcancel(), nta_outgoing_destroy().
@@ -10147,8 +10367,12 @@
 
   assert(orq); (void)tp;
 
+#if HAVE_SOFIA_STUN
   return tport_keepalive(orq->orq_tport, msg_addrinfo(orq->orq_request),
 			 TAG_END());
+#else
+  return -1;
+#endif
 }
 
 /** Close all transports. @since Experimental in @VERSION_1_12_2. */
@@ -10168,7 +10392,7 @@
       
       orq->orq_pending = 0;
       tport_unref(orq->orq_tport), orq->orq_tport = NULL;
-    }  
+    }
   
   
   for (i = iht->iht_size; i-- > 0;)

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_check.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_check.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_check.c	Tue Apr 24 10:14:28 2007
@@ -343,8 +343,8 @@
 /**Check @SessionExpires header.
  *
  * If the proposed session-expiration time is smaller than @MinSE or our
- * minimal session expiration time, respond with 422 containing our minimal
- * session expiration time in @MinSE header.
+ * minimal session expiration time, respond with 422 containing shortest
+ * acceptable session expiration time in @MinSE header.
  *
  * @param irq 	incoming transaction object (may be NULL).
  * @param sip 	contents of the SIP message
@@ -359,26 +359,28 @@
 			      sip_time_t my_min_se,
 			      tag_type_t tag, tag_value_t value, ...)
 {
-  if ((sip->sip_min_se &&
-       sip->sip_session_expires->x_delta < sip->sip_min_se->min_delta)
-      || sip->sip_session_expires->x_delta < my_min_se) {
-    ta_list ta;
+  unsigned long min_se = my_min_se;
+
+  if (sip->sip_min_se && min_se < sip->sip_min_se->min_delta)
+    min_se = sip->sip_min_se->min_delta;
 
-    sip_min_se_t min_se[1];
+  if (sip->sip_session_expires->x_delta >= min_se)
+    return 0;
+
+  if (irq) {
+    ta_list ta;
+    sip_min_se_t min_se0[1];
 
-    sip_min_se_init(min_se)->min_delta = my_min_se;
+    ta_start(ta, tag, value);
 
-    if (irq) {
-      ta_start(ta, tag, value);
-      nta_incoming_treply(irq,
-			  SIP_422_SESSION_TIMER_TOO_SMALL,
-			  SIPTAG_MIN_SE(min_se),
-			  ta_tags(ta));
-      ta_end(ta);
-    }
+    sip_min_se_init(min_se0)->min_delta = min_se;
 
-    return 422;
+    nta_incoming_treply(irq,
+			SIP_422_SESSION_TIMER_TOO_SMALL,
+			SIPTAG_MIN_SE(min_se0),
+			ta_tags(ta));
+    ta_end(ta);
   }
 
-  return 0;
+  return 422;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_internal.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_internal.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_internal.h	Tue Apr 24 10:14:28 2007
@@ -98,16 +98,17 @@
   nta_agent_magic_t    *sa_magic;
   nta_message_f        *sa_callback;     
 
-  uint32_t              sa_nw_updates; /* Shall we enable network detector? */
-
   nta_update_magic_t   *sa_update_magic;
   nta_update_tport_f   *sa_update_tport;
 
-  su_time_t             sa_now;	/**< Timestamp in microsecond resolution. */
+  su_duration_t         sa_next; /**< Timestamp for next agent_timer. */
+  su_time_t             sa_now;	 /**< Timestamp in microsecond resolution. */
   uint32_t              sa_millisec; /**< Timestamp in milliseconds resolution. */
 
+  uint32_t              sa_nw_updates; /* Shall we enable network detector? */
+
   uint32_t              sa_flags;	/**< Message flags */
-  msg_mclass_t         *sa_mclass;
+  msg_mclass_t const   *sa_mclass;
 
   sip_contact_t        *sa_contact;
   sip_via_t            *sa_vias;   /**< @Via headers for all transports */
@@ -223,6 +224,9 @@
   /** If true, automatically create compartments */
   unsigned              sa_auto_comp:1;
 
+  /** Set when executing timer */
+  unsigned              sa_in_timer:1;
+
   unsigned              :0;
 
   /** Messages memory preload. */
@@ -342,6 +346,11 @@
   unsigned          leg_loose_route : 1; /**< Topmost route in set is LR */
 #endif
   unsigned          leg_local_is_to : 1; /**< Backwards-compatibility. */
+  unsigned          leg_tagged : 1; /**< Tagged after creation.
+				     *
+				     * Request missing To tag matches it
+				     * even after tagging.
+				     */
   unsigned:0;
   nta_request_f    *leg_callback;
   nta_leg_magic_t  *leg_magic;
@@ -463,12 +472,17 @@
 
   sip_method_t        	orq_method;
   char const           *orq_method_name;
+  url_t const          *orq_url;        /**< Original RequestURI */
+
   sip_from_t const     *orq_from;
   sip_to_t const       *orq_to;
+  char const           *orq_tag;        /**< Tag from final response. */
+
   sip_cseq_t const     *orq_cseq;
   sip_call_id_t const  *orq_call_id;
 
-  char const           *orq_tag;        /**< Tag from final response. */
+  msg_t		       *orq_request;
+  msg_t                *orq_response;
 
   su_time_t             orq_sent;       /**< When request was sent? */
   unsigned              orq_delay;      /**< RTT estimate */
@@ -501,11 +515,9 @@
   unsigned orq_sigcomp_new:1;	/**< Create compartment if needed */
   unsigned orq_sigcomp_zap:1;	/**< Reset SigComp after completing */
   unsigned orq_must_100rel : 1;
-  unsigned orq_timestamp : 1;	/**< insert @Timestamp header. */
+  unsigned orq_timestamp : 1;	/**< Insert @Timestamp header. */
   unsigned : 0;	/* pad */
 
-  uint32_t              orq_rseq;       /**< Latest incoming rseq */
-
 #if HAVE_SOFIA_SRESOLV
   sipdns_resolver_t    *orq_resolver;
 #endif
@@ -522,12 +534,10 @@
 
   char const           *orq_branch;	/**< Transaction branch */
   char const           *orq_via_branch;	/**< @Via branch */
-  url_t const          *orq_url;        /**< Original RequestURI */
-
-  msg_t		       *orq_request;
-  msg_t                *orq_response;
 
   nta_outgoing_t       *orq_cancel;     /**< CANCEL transaction */
+
+  uint32_t              orq_rseq;       /**< Latest incoming rseq */
 };
 
 /* Virtual function table for plugging in SigComp */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_tag.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_tag.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/nta_tag.c	Tue Apr 24 10:14:28 2007
@@ -110,38 +110,38 @@
 
 /* Status */
 
-tag_typedef_t ntatag_s_irq_hash =         UINTTAG_TYPEDEF(s_irq_hash);
-tag_typedef_t ntatag_s_orq_hash =         UINTTAG_TYPEDEF(s_orq_hash);
-tag_typedef_t ntatag_s_leg_hash =         UINTTAG_TYPEDEF(s_leg_hash);
-tag_typedef_t ntatag_s_irq_hash_used =    UINTTAG_TYPEDEF(s_irq_hash_used);
-tag_typedef_t ntatag_s_orq_hash_used =    UINTTAG_TYPEDEF(s_orq_hash_used);
-tag_typedef_t ntatag_s_leg_hash_used =    UINTTAG_TYPEDEF(s_leg_hash_used);
-tag_typedef_t ntatag_s_recv_msg =         UINTTAG_TYPEDEF(s_recv_msg);
-tag_typedef_t ntatag_s_recv_request =     UINTTAG_TYPEDEF(s_recv_request);
-tag_typedef_t ntatag_s_recv_response =    UINTTAG_TYPEDEF(s_recv_response);
-tag_typedef_t ntatag_s_bad_message =      UINTTAG_TYPEDEF(s_bad_message);
-tag_typedef_t ntatag_s_bad_request =      UINTTAG_TYPEDEF(s_bad_request);
-tag_typedef_t ntatag_s_bad_response =     UINTTAG_TYPEDEF(s_bad_response);
-tag_typedef_t ntatag_s_drop_request =     UINTTAG_TYPEDEF(s_drop_request);
-tag_typedef_t ntatag_s_drop_response =    UINTTAG_TYPEDEF(s_drop_response);
-tag_typedef_t ntatag_s_client_tr =        UINTTAG_TYPEDEF(s_client_tr);
-tag_typedef_t ntatag_s_server_tr =        UINTTAG_TYPEDEF(s_server_tr);
-tag_typedef_t ntatag_s_dialog_tr =        UINTTAG_TYPEDEF(s_dialog_tr);
-tag_typedef_t ntatag_s_acked_tr =         UINTTAG_TYPEDEF(s_acked_tr);
-tag_typedef_t ntatag_s_canceled_tr =      UINTTAG_TYPEDEF(s_canceled_tr);
-tag_typedef_t ntatag_s_trless_request =   UINTTAG_TYPEDEF(s_trless_request);
-tag_typedef_t ntatag_s_trless_to_tr =     UINTTAG_TYPEDEF(s_trless_to_tr);
-tag_typedef_t ntatag_s_trless_response =  UINTTAG_TYPEDEF(s_trless_response);
-tag_typedef_t ntatag_s_trless_200 =       UINTTAG_TYPEDEF(s_trless_200);
-tag_typedef_t ntatag_s_merged_request =   UINTTAG_TYPEDEF(s_merged_request);
-tag_typedef_t ntatag_s_sent_msg =      	  UINTTAG_TYPEDEF(s_sent_msg);
-tag_typedef_t ntatag_s_sent_request =  	  UINTTAG_TYPEDEF(s_sent_request);
-tag_typedef_t ntatag_s_sent_response = 	  UINTTAG_TYPEDEF(s_sent_response);
-tag_typedef_t ntatag_s_retry_request = 	  UINTTAG_TYPEDEF(s_retry_request);
-tag_typedef_t ntatag_s_retry_response =   UINTTAG_TYPEDEF(s_retry_response);
-tag_typedef_t ntatag_s_recv_retry =       UINTTAG_TYPEDEF(s_recv_retry);
-tag_typedef_t ntatag_s_tout_request =     UINTTAG_TYPEDEF(s_tout_request);
-tag_typedef_t ntatag_s_tout_response =    UINTTAG_TYPEDEF(s_tout_response);
+tag_typedef_t ntatag_s_irq_hash =         USIZETAG_TYPEDEF(s_irq_hash);
+tag_typedef_t ntatag_s_orq_hash =         USIZETAG_TYPEDEF(s_orq_hash);
+tag_typedef_t ntatag_s_leg_hash =         USIZETAG_TYPEDEF(s_leg_hash);
+tag_typedef_t ntatag_s_irq_hash_used =    USIZETAG_TYPEDEF(s_irq_hash_used);
+tag_typedef_t ntatag_s_orq_hash_used =    USIZETAG_TYPEDEF(s_orq_hash_used);
+tag_typedef_t ntatag_s_leg_hash_used =    USIZETAG_TYPEDEF(s_leg_hash_used);
+tag_typedef_t ntatag_s_recv_msg =         USIZETAG_TYPEDEF(s_recv_msg);
+tag_typedef_t ntatag_s_recv_request =     USIZETAG_TYPEDEF(s_recv_request);
+tag_typedef_t ntatag_s_recv_response =    USIZETAG_TYPEDEF(s_recv_response);
+tag_typedef_t ntatag_s_bad_message =      USIZETAG_TYPEDEF(s_bad_message);
+tag_typedef_t ntatag_s_bad_request =      USIZETAG_TYPEDEF(s_bad_request);
+tag_typedef_t ntatag_s_bad_response =     USIZETAG_TYPEDEF(s_bad_response);
+tag_typedef_t ntatag_s_drop_request =     USIZETAG_TYPEDEF(s_drop_request);
+tag_typedef_t ntatag_s_drop_response =    USIZETAG_TYPEDEF(s_drop_response);
+tag_typedef_t ntatag_s_client_tr =        USIZETAG_TYPEDEF(s_client_tr);
+tag_typedef_t ntatag_s_server_tr =        USIZETAG_TYPEDEF(s_server_tr);
+tag_typedef_t ntatag_s_dialog_tr =        USIZETAG_TYPEDEF(s_dialog_tr);
+tag_typedef_t ntatag_s_acked_tr =         USIZETAG_TYPEDEF(s_acked_tr);
+tag_typedef_t ntatag_s_canceled_tr =      USIZETAG_TYPEDEF(s_canceled_tr);
+tag_typedef_t ntatag_s_trless_request =   USIZETAG_TYPEDEF(s_trless_request);
+tag_typedef_t ntatag_s_trless_to_tr =     USIZETAG_TYPEDEF(s_trless_to_tr);
+tag_typedef_t ntatag_s_trless_response =  USIZETAG_TYPEDEF(s_trless_response);
+tag_typedef_t ntatag_s_trless_200 =       USIZETAG_TYPEDEF(s_trless_200);
+tag_typedef_t ntatag_s_merged_request =   USIZETAG_TYPEDEF(s_merged_request);
+tag_typedef_t ntatag_s_sent_msg =      	  USIZETAG_TYPEDEF(s_sent_msg);
+tag_typedef_t ntatag_s_sent_request =  	  USIZETAG_TYPEDEF(s_sent_request);
+tag_typedef_t ntatag_s_sent_response = 	  USIZETAG_TYPEDEF(s_sent_response);
+tag_typedef_t ntatag_s_retry_request = 	  USIZETAG_TYPEDEF(s_retry_request);
+tag_typedef_t ntatag_s_retry_response =   USIZETAG_TYPEDEF(s_retry_response);
+tag_typedef_t ntatag_s_recv_retry =       USIZETAG_TYPEDEF(s_recv_retry);
+tag_typedef_t ntatag_s_tout_request =     USIZETAG_TYPEDEF(s_tout_request);
+tag_typedef_t ntatag_s_tout_response =    USIZETAG_TYPEDEF(s_tout_response);
 
 /* Internal */
 tag_typedef_t ntatag_delay_sending = BOOLTAG_TYPEDEF(delay_sending);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/run_test_nta
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/run_test_nta	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/run_test_nta	Tue Apr 24 10:14:28 2007
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 #
 # Run nta_test with our own name server
 #
@@ -50,11 +50,11 @@
 
 me6="::1"
 
-if ../su/localinfo -6 -n -g -s >& /dev/null ; then
+if ../su/localinfo -6 -n -g -s > /dev/null 2>&1 ; then
     ipv6=true aaaa=aaaa v6flag=-6
     me6=$(../su/localinfo -6 -n -s -g | awk '{print $1; exit(0); }')
 else
-    if ! ../su/localinfo '--help' >& /dev/null ; then
+    if ! ../su/localinfo '--help' > /dev/null 2>&1 ; then
 	echo "warning: $0: missing 'localinfo', cannot test IPv6"
     else
 	echo "warning: $0: no valid IPv6 addresses available"
@@ -62,7 +62,7 @@
     ipv6=false aaaa=a
 fi
 
-if type named >& /dev/null && ./portbind --help >& /dev/null
+if type named > /dev/null 2>&1 && ./portbind --help > /dev/null 2>&1
 then
 
 port=$(./portbind $v6flag) sink=$port

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/run_test_nta_api
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/run_test_nta_api	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/run_test_nta_api	Tue Apr 24 10:14:28 2007
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 #
 # Run test_nta_api
 #

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/sofia-sip/nta.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/sofia-sip/nta.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/sofia-sip/nta.h	Tue Apr 24 10:14:28 2007
@@ -300,6 +300,9 @@
 				   tag_type_t tag, tag_value_t value, ...);
 
 SOFIAPUBFUN
+msg_t *nta_incoming_create_response(nta_incoming_t *irq, int status, char const *phrase);
+
+SOFIAPUBFUN
 int nta_incoming_treply(nta_incoming_t *ireq, 
 			int status, char const *phrase, 
 			tag_type_t tag, tag_value_t value, ...);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/sofia-sip/nta_tag.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/sofia-sip/nta_tag.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/sofia-sip/nta_tag.h	Tue Apr 24 10:14:28 2007
@@ -59,10 +59,10 @@
 
 NTA_DLL extern tag_typedef_t ntatag_mclass;
 /** Message class used by NTA. @HI */
-#define NTATAG_MCLASS(x) ntatag_mclass, tag_ptr_v((x))
+#define NTATAG_MCLASS(x) ntatag_mclass, tag_cptr_v((x))
 
 NTA_DLL extern tag_typedef_t ntatag_mclass_ref;
-#define NTATAG_MCLASS_REF(x) ntatag_mclass_ref, tag_ptr_vr(&(x), (x))
+#define NTATAG_MCLASS_REF(x) ntatag_mclass_ref, tag_cptr_vr(&(x), (x))
 
 NTA_DLL extern tag_typedef_t ntatag_bad_req_mask;
 /** Mask for bad request messages. 
@@ -464,223 +464,223 @@
 /* Tags for statistics. */
 
 NTA_DLL extern tag_typedef_t ntatag_s_irq_hash;
-#define NTATAG_S_IRQ_HASH(x) ntatag_s_irq_hash, tag_uint_v(x)
+#define NTATAG_S_IRQ_HASH(x) ntatag_s_irq_hash, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_irq_hash_ref;
-#define NTATAG_S_IRQ_HASH_REF(x) ntatag_s_irq_hash_ref, tag_uint_vr(&(x))
+#define NTATAG_S_IRQ_HASH_REF(x) ntatag_s_irq_hash_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_orq_hash;
-#define NTATAG_S_ORQ_HASH(x) ntatag_s_orq_hash, tag_uint_v(x)
+#define NTATAG_S_ORQ_HASH(x) ntatag_s_orq_hash, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_orq_hash_ref;
-#define NTATAG_S_ORQ_HASH_REF(x) ntatag_s_orq_hash_ref, tag_uint_vr(&(x))
+#define NTATAG_S_ORQ_HASH_REF(x) ntatag_s_orq_hash_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_leg_hash;
-#define NTATAG_S_LEG_HASH(x) ntatag_s_leg_hash, tag_uint_v(x)
+#define NTATAG_S_LEG_HASH(x) ntatag_s_leg_hash, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_leg_hash_ref;
-#define NTATAG_S_LEG_HASH_REF(x) ntatag_s_leg_hash_ref, tag_uint_vr(&(x))
+#define NTATAG_S_LEG_HASH_REF(x) ntatag_s_leg_hash_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_irq_hash_used;
-#define NTATAG_S_IRQ_HASH_USED(x) ntatag_s_irq_hash_used, tag_uint_v(x)
+#define NTATAG_S_IRQ_HASH_USED(x) ntatag_s_irq_hash_used, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_irq_hash_used_ref;
 #define NTATAG_S_IRQ_HASH_USED_REF(x) \
-ntatag_s_irq_hash_used_ref, tag_uint_vr(&(x))
+ntatag_s_irq_hash_used_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_orq_hash_used;
-#define NTATAG_S_ORQ_HASH_USED(x) ntatag_s_orq_hash_used, tag_uint_v(x)
+#define NTATAG_S_ORQ_HASH_USED(x) ntatag_s_orq_hash_used, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_orq_hash_used_ref;
 #define NTATAG_S_ORQ_HASH_USED_REF(x) \
-ntatag_s_orq_hash_used_ref, tag_uint_vr(&(x))
+ntatag_s_orq_hash_used_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_leg_hash_used;
-#define NTATAG_S_LEG_HASH_USED(x) ntatag_s_leg_hash_used, tag_uint_v(x)
+#define NTATAG_S_LEG_HASH_USED(x) ntatag_s_leg_hash_used, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_leg_hash_used_ref;
 #define NTATAG_S_LEG_HASH_USED_REF(x) \
-ntatag_s_leg_hash_used_ref, tag_uint_vr(&(x))
+ntatag_s_leg_hash_used_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_recv_msg;
-#define NTATAG_S_RECV_MSG(x) ntatag_s_recv_msg, tag_uint_v(x)
+#define NTATAG_S_RECV_MSG(x) ntatag_s_recv_msg, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_recv_msg_ref;
-#define NTATAG_S_RECV_MSG_REF(x) ntatag_s_recv_msg_ref, tag_uint_vr(&(x))
+#define NTATAG_S_RECV_MSG_REF(x) ntatag_s_recv_msg_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_recv_request;
-#define NTATAG_S_RECV_REQUEST(x) ntatag_s_recv_request, tag_uint_v(x)
+#define NTATAG_S_RECV_REQUEST(x) ntatag_s_recv_request, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_recv_request_ref;
 #define NTATAG_S_RECV_REQUEST_REF(x)\
- ntatag_s_recv_request_ref, tag_uint_vr(&(x))
+ ntatag_s_recv_request_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_recv_response;
-#define NTATAG_S_RECV_RESPONSE(x) ntatag_s_recv_response, tag_uint_v(x)
+#define NTATAG_S_RECV_RESPONSE(x) ntatag_s_recv_response, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_recv_response_ref;
 #define NTATAG_S_RECV_RESPONSE_REF(x)\
- ntatag_s_recv_response_ref, tag_uint_vr(&(x))
+ ntatag_s_recv_response_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_bad_message;
-#define NTATAG_S_BAD_MESSAGE(x) ntatag_s_bad_message, tag_uint_v(x)
+#define NTATAG_S_BAD_MESSAGE(x) ntatag_s_bad_message, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_bad_message_ref;
 #define NTATAG_S_BAD_MESSAGE_REF(x)\
- ntatag_s_bad_message_ref, tag_uint_vr(&(x))
+ ntatag_s_bad_message_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_bad_request;
-#define NTATAG_S_BAD_REQUEST(x) ntatag_s_bad_request, tag_uint_v(x)
+#define NTATAG_S_BAD_REQUEST(x) ntatag_s_bad_request, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_bad_request_ref;
 #define NTATAG_S_BAD_REQUEST_REF(x)\
- ntatag_s_bad_request_ref, tag_uint_vr(&(x))
+ ntatag_s_bad_request_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_bad_response;
-#define NTATAG_S_BAD_RESPONSE(x) ntatag_s_bad_response, tag_uint_v(x)
+#define NTATAG_S_BAD_RESPONSE(x) ntatag_s_bad_response, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_bad_response_ref;
 #define NTATAG_S_BAD_RESPONSE_REF(x)\
- ntatag_s_bad_response_ref, tag_uint_vr(&(x))
+ ntatag_s_bad_response_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_drop_request;
-#define NTATAG_S_DROP_REQUEST(x) ntatag_s_drop_request, tag_uint_v(x)
+#define NTATAG_S_DROP_REQUEST(x) ntatag_s_drop_request, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_drop_request_ref;
 #define NTATAG_S_DROP_REQUEST_REF(x)\
- ntatag_s_drop_request_ref, tag_uint_vr(&(x))
+ ntatag_s_drop_request_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_drop_response;
-#define NTATAG_S_DROP_RESPONSE(x) ntatag_s_drop_response, tag_uint_v(x)
+#define NTATAG_S_DROP_RESPONSE(x) ntatag_s_drop_response, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_drop_response_ref;
 #define NTATAG_S_DROP_RESPONSE_REF(x)\
- ntatag_s_drop_response_ref, tag_uint_vr(&(x))
+ ntatag_s_drop_response_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_client_tr;
-#define NTATAG_S_CLIENT_TR(x) ntatag_s_client_tr, tag_uint_v(x)
+#define NTATAG_S_CLIENT_TR(x) ntatag_s_client_tr, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_client_tr_ref;
 #define NTATAG_S_CLIENT_TR_REF(x)\
- ntatag_s_client_tr_ref, tag_uint_vr(&(x))
+ ntatag_s_client_tr_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_server_tr;
-#define NTATAG_S_SERVER_TR(x) ntatag_s_server_tr, tag_uint_v(x)
+#define NTATAG_S_SERVER_TR(x) ntatag_s_server_tr, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_server_tr_ref;
 #define NTATAG_S_SERVER_TR_REF(x)\
- ntatag_s_server_tr_ref, tag_uint_vr(&(x))
+ ntatag_s_server_tr_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_dialog_tr;
-#define NTATAG_S_DIALOG_TR(x) ntatag_s_dialog_tr, tag_uint_v(x)
+#define NTATAG_S_DIALOG_TR(x) ntatag_s_dialog_tr, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_dialog_tr_ref;
 #define NTATAG_S_DIALOG_TR_REF(x)\
- ntatag_s_dialog_tr_ref, tag_uint_vr(&(x))
+ ntatag_s_dialog_tr_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_acked_tr;
-#define NTATAG_S_ACKED_TR(x) ntatag_s_acked_tr, tag_uint_v(x)
+#define NTATAG_S_ACKED_TR(x) ntatag_s_acked_tr, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_acked_tr_ref;
-#define NTATAG_S_ACKED_TR_REF(x) ntatag_s_acked_tr_ref, tag_uint_vr(&(x))
+#define NTATAG_S_ACKED_TR_REF(x) ntatag_s_acked_tr_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_canceled_tr;
-#define NTATAG_S_CANCELED_TR(x) ntatag_s_canceled_tr, tag_uint_v(x)
+#define NTATAG_S_CANCELED_TR(x) ntatag_s_canceled_tr, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_canceled_tr_ref;
 #define NTATAG_S_CANCELED_TR_REF(x)  \
- ntatag_s_canceled_tr_ref, tag_uint_vr(&(x))
+ ntatag_s_canceled_tr_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_trless_request;
-#define NTATAG_S_TRLESS_REQUEST(x) ntatag_s_trless_request, tag_uint_v(x)
+#define NTATAG_S_TRLESS_REQUEST(x) ntatag_s_trless_request, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_trless_request_ref;
 #define NTATAG_S_TRLESS_REQUEST_REF(x)\
- ntatag_s_trless_request_ref, tag_uint_vr(&(x))
+ ntatag_s_trless_request_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_trless_to_tr;
-#define NTATAG_S_TRLESS_TO_TR(x) ntatag_s_trless_to_tr, tag_uint_v(x)
+#define NTATAG_S_TRLESS_TO_TR(x) ntatag_s_trless_to_tr, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_trless_to_tr_ref;
 #define NTATAG_S_TRLESS_TO_TR_REF(x)\
- ntatag_s_trless_to_tr_ref, tag_uint_vr(&(x))
+ ntatag_s_trless_to_tr_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_trless_response;
-#define NTATAG_S_TRLESS_RESPONSE(x) ntatag_s_trless_response, tag_uint_v(x)
+#define NTATAG_S_TRLESS_RESPONSE(x) ntatag_s_trless_response, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_trless_response_ref;
 #define NTATAG_S_TRLESS_RESPONSE_REF(x)\
- ntatag_s_trless_response_ref, tag_uint_vr(&(x))
+ ntatag_s_trless_response_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_trless_200;
-#define NTATAG_S_TRLESS_200(x) ntatag_s_trless_200, tag_uint_v(x)
+#define NTATAG_S_TRLESS_200(x) ntatag_s_trless_200, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_trless_200_ref;
 #define NTATAG_S_TRLESS_200_REF(x)\
- ntatag_s_trless_200_ref, tag_uint_vr(&(x))
+ ntatag_s_trless_200_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_merged_request;
-#define NTATAG_S_MERGED_REQUEST(x) ntatag_s_merged_request, tag_uint_v(x)
+#define NTATAG_S_MERGED_REQUEST(x) ntatag_s_merged_request, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_merged_request_ref;
 #define NTATAG_S_MERGED_REQUEST_REF(x)\
- ntatag_s_merged_request_ref, tag_uint_vr(&(x))
+ ntatag_s_merged_request_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_sent_msg;
-#define NTATAG_S_SENT_MSG(x) ntatag_s_sent_msg, tag_uint_v(x)
+#define NTATAG_S_SENT_MSG(x) ntatag_s_sent_msg, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_sent_msg_ref;
 #define NTATAG_S_SENT_MSG_REF(x)\
- ntatag_s_sent_msg_ref, tag_uint_vr(&(x))
+ ntatag_s_sent_msg_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_sent_request;
-#define NTATAG_S_SENT_REQUEST(x) ntatag_s_sent_request, tag_uint_v(x)
+#define NTATAG_S_SENT_REQUEST(x) ntatag_s_sent_request, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_sent_request_ref;
 #define NTATAG_S_SENT_REQUEST_REF(x)\
- ntatag_s_sent_request_ref, tag_uint_vr(&(x))
+ ntatag_s_sent_request_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_sent_response;
-#define NTATAG_S_SENT_RESPONSE(x) ntatag_s_sent_response, tag_uint_v(x)
+#define NTATAG_S_SENT_RESPONSE(x) ntatag_s_sent_response, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_sent_response_ref;
 #define NTATAG_S_SENT_RESPONSE_REF(x)\
- ntatag_s_sent_response_ref, tag_uint_vr(&(x))
+ ntatag_s_sent_response_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_retry_request;
-#define NTATAG_S_RETRY_REQUEST(x) ntatag_s_retry_request, tag_uint_v(x)
+#define NTATAG_S_RETRY_REQUEST(x) ntatag_s_retry_request, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_retry_request_ref;
 #define NTATAG_S_RETRY_REQUEST_REF(x)\
- ntatag_s_retry_request_ref, tag_uint_vr(&(x))
+ ntatag_s_retry_request_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_retry_response;
-#define NTATAG_S_RETRY_RESPONSE(x) ntatag_s_retry_response, tag_uint_v(x)
+#define NTATAG_S_RETRY_RESPONSE(x) ntatag_s_retry_response, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_retry_response_ref;
 #define NTATAG_S_RETRY_RESPONSE_REF(x)\
- ntatag_s_retry_response_ref, tag_uint_vr(&(x))
+ ntatag_s_retry_response_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_recv_retry;
-#define NTATAG_S_RECV_RETRY(x) ntatag_s_recv_retry, tag_uint_v(x)
+#define NTATAG_S_RECV_RETRY(x) ntatag_s_recv_retry, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_recv_retry_ref;
 #define NTATAG_S_RECV_RETRY_REF(x)\
- ntatag_s_recv_retry_ref, tag_uint_vr(&(x))
+ ntatag_s_recv_retry_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_tout_request;
-#define NTATAG_S_TOUT_REQUEST(x) ntatag_s_tout_request, tag_uint_v(x)
+#define NTATAG_S_TOUT_REQUEST(x) ntatag_s_tout_request, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_tout_request_ref;
 #define NTATAG_S_TOUT_REQUEST_REF(x)\
- ntatag_s_tout_request_ref, tag_uint_vr(&(x))
+ ntatag_s_tout_request_ref, tag_usize_vr(&(x))
 
 NTA_DLL extern tag_typedef_t ntatag_s_tout_response;
-#define NTATAG_S_TOUT_RESPONSE(x) ntatag_s_tout_response, tag_uint_v(x)
+#define NTATAG_S_TOUT_RESPONSE(x) ntatag_s_tout_response, tag_usize_v(x)
 
 NTA_DLL extern tag_typedef_t ntatag_s_tout_response_ref;
 #define NTATAG_S_TOUT_RESPONSE_REF(x)\
- ntatag_s_tout_response_ref, tag_uint_vr(&(x))
+ ntatag_s_tout_response_ref, tag_usize_vr(&(x))
 
 SOFIA_END_DECLS
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/test_nta.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/test_nta.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/test_nta.c	Tue Apr 24 10:14:28 2007
@@ -654,7 +654,7 @@
 
   *contents = buffer;
 
-  return len;
+  return (int)len;
 }
 
 #if HAVE_DIRENT_H
@@ -663,6 +663,8 @@
 
 static int test_bad_messages(agent_t *ag)
 {
+  BEGIN();
+
 #if HAVE_DIRENT_H
   DIR *dir;
   struct dirent *d;
@@ -687,13 +689,10 @@
   if (dir == NULL) {
     fprintf(stderr, "test_nta: cannot find sip torture messages\n"); 
     fprintf(stderr, "test_nta: tried %s\n", name); 
-    return 0;
   }
 
   offset = strlen(name);
 
-  BEGIN();
-
   TEST_1(ag->ag_default_leg = nta_leg_tcreate(ag->ag_agent, 
 					      leg_callback_500,
 					      ag,
@@ -713,14 +712,14 @@
   
   TEST(su_getaddrinfo(host, port, hints, &ai), 0); TEST_1(ai);
   s = su_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); TEST_1(s != -1);
-  memset(su, 0, sulen = sizeof su); 
+  memset(su, 0, sulen = ai->ai_addrlen); 
   su->su_len = sizeof su; su->su_family = ai->ai_family;
   TEST_1(bind(s, &su->su_sa, sulen) == 0);
   TEST_1(getsockname(s, &su->su_sa, &sulen) == 0);
   sprintf(via, "v: SIP/2.0/UDP is.invalid:%u\r\n", ntohs(su->su_port));
   vlen = strlen(via);
 
-  for (d = readdir(dir); d; d = readdir(dir)) {
+  for (d = dir ? readdir(dir) : NULL; d; d = readdir(dir)) {
     size_t len = strlen(d->d_name);
     FILE *f;
     int blen, n;
@@ -733,6 +732,7 @@
     strncpy(name + offset, d->d_name, PATH_MAX - offset);
     TEST_1(f = fopen(name, "rb"));
     TEST_1((blen = readfile(f, &buffer)) > 0);
+    fclose(f);
     r = buffer;
 
     if (strncmp(r, "JUNK ", 5) == 0) {
@@ -751,6 +751,12 @@
     su_root_step(ag->ag_root, 1);
   }
 
+  TEST_SIZE(su_sendto(s, "\r\n\r\n", 4, 0, (void *)ai->ai_addr, ai->ai_addrlen), 4);
+
+  su_root_step(ag->ag_root, 1);
+
+  TEST_SIZE(su_sendto(s, "", 0, 0, ai->ai_addr, ai->ai_addrlen), 0);
+
   su_close(s);
 
   for (i = 0; i < 20; i++)
@@ -758,12 +764,12 @@
 
   nta_leg_destroy(ag->ag_default_leg), ag->ag_default_leg = NULL;
 
-  closedir(dir);
+  if (dir)
+    closedir(dir);
 
-  END();
-#else
-  return 0;
 #endif /* HAVE_DIRENT_H */
+
+  END();
 }
 
 static unsigned char const code[] = 
@@ -3357,6 +3363,7 @@
   "usage: %s OPTIONS\n"
   "where OPTIONS are\n"
   "   -v | --verbose    be verbose\n"
+  "   -a | --abort      abort() on error\n"
   "   -q | --quiet      be quiet\n"
   "   -1                quit on first error\n"
   "   -l level          set logging level (0 by default)\n"
@@ -3368,10 +3375,10 @@
 #endif
   ;
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, nta_test_usage, name);
-  exit(1);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -3384,6 +3391,8 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--abort") == 0)
+      tstflags |= tst_abort;
     else if (strcmp(argv[i], "-q") == 0 || strcmp(argv[i], "--quiet") == 0)
       tstflags &= ~tst_verbatim;
     else if (strcmp(argv[i], "-1") == 0)
@@ -3400,7 +3409,7 @@
 	level = 3, rest = "";
 
       if (rest == NULL || *rest)
-	usage();
+	usage(1);
       
       su_log_set_level(nta_log, level);
       su_log_set_level(tport_log, level);
@@ -3411,7 +3420,7 @@
       else if (argv[i + 1])
 	ag->ag_obp = (url_string_t *)(argv[++i]);
       else
-	usage();
+	usage(1);
     }
     else if (strncmp(argv[i], "-m", 2) == 0) {
       if (argv[i][2])
@@ -3419,7 +3428,7 @@
       else if (argv[i + 1])
 	ag->ag_m = argv[++i];
       else
-	usage();
+	usage(1);
     }
     else if (strcmp(argv[i], "--attach") == 0) {
       o_attach = 1;
@@ -3434,7 +3443,7 @@
       break;
     }
     else
-      usage();
+      usage(1);
   }
 
   if (o_attach) {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/test_nta_api.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/test_nta_api.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nta/test_nta_api.c	Tue Apr 24 10:14:28 2007
@@ -559,18 +559,18 @@
 
   nta_agent_t *nta;
 
-  uint32_t irq_hash = -1, orq_hash = -1, leg_hash = -1;
-  uint32_t recv_msg = -1, sent_msg = -1;
-  uint32_t recv_request = -1, recv_response = -1;
-  uint32_t bad_message = -1, bad_request = -1, bad_response = -1;
-  uint32_t drop_request = -1, drop_response = -1;
-  uint32_t client_tr = -1, server_tr = -1, dialog_tr = -1;
-  uint32_t acked_tr = -1, canceled_tr = -1;
-  uint32_t trless_request = -1, trless_to_tr = -1, trless_response = -1;
-  uint32_t trless_200 = -1, merged_request = -1;
-  uint32_t sent_request = -1, sent_response = -1;
-  uint32_t retry_request = -1, retry_response = -1, recv_retry = -1;
-  uint32_t tout_request = -1, tout_response = -1;
+  usize_t irq_hash = -1, orq_hash = -1, leg_hash = -1;
+  usize_t recv_msg = -1, sent_msg = -1;
+  usize_t recv_request = -1, recv_response = -1;
+  usize_t bad_message = -1, bad_request = -1, bad_response = -1;
+  usize_t drop_request = -1, drop_response = -1;
+  usize_t client_tr = -1, server_tr = -1, dialog_tr = -1;
+  usize_t acked_tr = -1, canceled_tr = -1;
+  usize_t trless_request = -1, trless_to_tr = -1, trless_response = -1;
+  usize_t trless_200 = -1, merged_request = -1;
+  usize_t sent_request = -1, sent_response = -1;
+  usize_t retry_request = -1, retry_response = -1, recv_retry = -1;
+  usize_t tout_request = -1, tout_response = -1;
 
   TEST_1(nta = nta_agent_create(ag->ag_root, (url_string_t *)"sip:*:*",
 				NULL, NULL, TAG_END()));
@@ -1238,6 +1238,7 @@
   "usage: %s OPTIONS\n"
   "where OPTIONS are\n"
   "   -v | --verbose    be verbose\n"
+  "   -a | --abort      abort() on error\n"
   "   -q | --quiet      be quiet\n"
   "   -1                quit on first error\n"
   "   -l level          set logging level (0 by default)\n"
@@ -1247,10 +1248,10 @@
 #endif
   ;
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, nta_test_api_usage, name);
-  exit(1);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -1261,9 +1262,11 @@
   agent_t ag[1] = {{ { SU_HOME_INIT(ag) }, 0, NULL }};
 
   for (i = 1; argv[i]; i++) {
-    if (strcmp(argv[i], "-v") == 0)
+    if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0)
       tstflags |= tst_verbatim;
-    else if (strcmp(argv[i], "-q") == 0)
+    else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--abort") == 0)
+      tstflags |= tst_abort;
+    else if (strcmp(argv[i], "-q") == 0 || strcmp(argv[i], "--quiet") == 0)
       tstflags &= ~tst_verbatim;
     else if (strcmp(argv[i], "-1") == 0)
       quit_on_single_failure = 1;
@@ -1279,7 +1282,7 @@
 	level = 3, rest = "";
 
       if (rest == NULL || *rest)
-	usage();
+	usage(1);
       
       su_log_set_level(nta_log, level);
       su_log_set_level(tport_log, level);
@@ -1297,14 +1300,14 @@
       break;
     }
     else
-      usage();
+      usage(1);
   }
 
   if (o_attach) {
-    char line[10];
+    char *response, line[10];
     printf("nua_test: pid %lu\n", (unsigned long)getpid());
     printf("<Press RETURN to continue>\n");
-    fgets(line, sizeof line, stdin);
+    response = fgets(line, sizeof line, stdin);
   }
 #if HAVE_ALARM
   else if (o_alarm) {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -57,10 +57,10 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile nth.docs $(BUILT_SOURCES) \
+EXTRA_DIST =		nth.docs $(BUILT_SOURCES) \
 			agent.pem cafile.pem
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/http-server.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/http-server.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/http-server.c	Tue Apr 24 10:14:28 2007
@@ -38,7 +38,10 @@
 #include <string.h>
 #include <stdio.h>
 #include <assert.h>
+
+#if HAVE_SIGNAL
 #include <signal.h>
+#endif
 
 typedef struct context_s context_t;
 #define NTH_SITE_MAGIC_T context_t
@@ -77,7 +80,10 @@
 		   http_t const *http,
 		   char const *path);
 su_msg_r server_intr_msg = SU_MSG_R_INIT;
+
+#if HAVE_SIGNAL
 static RETSIGTYPE server_intr_handler(int signum);
+#endif
 static void server_break(context_t *c, su_msg_r msg, su_msg_arg_t *arg);
 
 static msg_payload_t *read_payload(su_home_t *home, char const *fname);
@@ -140,13 +146,13 @@
 		su_root_task(context->c_root),
 		server_break, 0);
 
+#if HAVE_SIGNAL
   signal(SIGINT, server_intr_handler);
-
-#ifndef _WIN32
-  signal(SIGPIPE, server_intr_handler);
+#if HAVE_SIGQUIT
   signal(SIGQUIT, server_intr_handler);
   signal(SIGHUP, server_intr_handler);
 #endif
+#endif
 
   if (context->c_root) {
     context->c_site =

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/nth_client.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/nth_client.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/nth_client.c	Tue Apr 24 10:14:28 2007
@@ -1094,7 +1094,7 @@
 
   assert(status >= 400);
 
-  SU_DEBUG_5(("nth: hc_reply(%p, %u, %s)\n", hc, status, phrase));
+  SU_DEBUG_5(("nth: hc_reply(%p, %u, %s)\n", (void *)hc, status, phrase));
 
   if (hc->hc_pending) {
     tport_release(hc->hc_tport, hc->hc_pending, hc->hc_request, NULL, hc,

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/nth_server.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/nth_server.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/nth_server.c	Tue Apr 24 10:14:28 2007
@@ -704,7 +704,7 @@
 			tag_type_t tag, tag_value_t value, ...)
 {
   server_t *srv;
-  msg_mclass_t *mclass = NULL;
+  msg_mclass_t const *mclass = NULL;
   tp_name_t tpn[1] = {{ NULL }};
   su_root_t *root = NULL;
   http_server_t const *server = NULL;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/sofia-sip/nth_tag.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/sofia-sip/nth_tag.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/sofia-sip/nth_tag.h	Tue Apr 24 10:14:28 2007
@@ -109,7 +109,7 @@
 {return(tag_value_t)vp;}
 #else
 #define nthtag_template_v(v) ((tag_value_t)(v))
-#define nthtag_template_vr(vp) ((tag_value_t)&(vp))
+#define nthtag_template_vr(vp) ((tag_value_t)(vp))
 #endif
 
 NTH_DLL extern tag_typedef_t nthtag_template;
@@ -126,7 +126,7 @@
 { return(tag_value_t)vp; }
 #else
 #define nthtag_message_v(v) ((tag_value_t)(v))
-#define nthtag_message_vr(vp) ((tag_value_t)&(vp))
+#define nthtag_message_vr(vp) ((tag_value_t)(vp))
 #endif
 
 NTH_DLL extern tag_typedef_t nthtag_message;
@@ -142,7 +142,7 @@
 su_inline tag_value_t nthtag_authentication_vr(struct auth_client_s ***vp) {return(tag_value_t)vp;}
 #else
 #define nthtag_authentication_v(v) ((tag_value_t)(v))
-#define nthtag_authentication_vr(vp) ((tag_value_t)&(vp))
+#define nthtag_authentication_vr(vp) ((tag_value_t)(vp))
 #endif
 
 NTH_DLL extern tag_typedef_t nthtag_authentication;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/test_nth.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/test_nth.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nth/test_nth.c	Tue Apr 24 10:14:28 2007
@@ -893,10 +893,10 @@
 }
 #endif
 
-void usage(void)
+void usage(int exitcode)
 {
-  fprintf(stderr, "usage: %s [-v|-q] [-p proxy-uri]\n", name);
-  exit(1);
+  fprintf(stderr, "usage: %s [-v|-q] [-a] [-p proxy-uri]\n", name);
+  exit(exitcode);
 }
 
 int main(int argc, char **argv)
@@ -915,6 +915,8 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else if (strcmp(argv[i], "-q") == 0)
       tstflags &= ~tst_verbatim;
     else if (strcmp(argv[i], "-p") == 0 && argv[i + 1])
@@ -931,7 +933,7 @@
       break;
     }
     else
-      usage();
+      usage(1);
   }
 
   t->t_srcdir = srcdir;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -80,6 +80,7 @@
 			test_init.c \
 			test_nua_api.c test_nua_params.c \
 			test_register.c test_basic_call.c \
+			test_offer_answer.c \
 			test_call_reject.c test_cancel_bye.c \
 			test_call_hold.c test_session_timer.c \
 			test_refer.c test_100rel.c \
@@ -91,11 +92,11 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile nua.docs $(BUILT_SOURCES)
+EXTRA_DIST =		nua.docs $(BUILT_SOURCES)
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
 
 TAG_DLL_FLAGS =		LIST=nua_tag_list

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua.c	Tue Apr 24 10:14:28 2007
@@ -67,7 +67,7 @@
  *
  * The NUA_DEBUG environment variable is used to determine the debug logging
  * level for @nua module. The default level is 3.
- * 
+ *
  * @sa <sofia-sip/su_debug.h>, nua_log, SOFIA_DEBUG
  */
 extern char const NUA_DEBUG[];
@@ -76,8 +76,8 @@
 #define SU_DEBUG 3
 #endif
 
-/**Debug log for @nua module. 
- * 
+/**Debug log for @nua module.
+ *
  * The nua_log is the log object used by @nua module. The level of
  * #nua_log is set using #NUA_DEBUG environment variable.
  */
@@ -104,16 +104,17 @@
  *     NUTAG_UICC()             \n
  *     NUTAG_CERTIFICATE_DIR()  \n
  *     and all tags listed in nua_set_params(), \n
- *     and all relevant NTATAG_* are passed to NTA.
+ *     and all relevant NTATAG_* are passed to NTA \n
+ *     and all tport tags listed in <sofia-sip/tport_tag.h>
  *
  * @note
- * From the @VERSION_1_12_2 all the nua_set_params() tags are processed. 
+ * From the @VERSION_1_12_2 all the nua_set_params() tags are processed.
  * Previously all nutags except NUTAG_SOA_NAME() and NUTAG_MEDIA_ENABLE()
  * were ignored.
  *
  * @note
  * Both the NUTAG_URL() and NUTAG_SIPS_URL() are used to pass arguments to
- * nta_agent_add_tport(). 
+ * nta_agent_add_tport().
  *
  * @par Events:
  *     none
@@ -187,9 +188,9 @@
 
 /** Destroy the @nua stack.
  *
- * Before calling nua_destroy() the application 
+ * Before calling nua_destroy() the application
  * should call nua_shutdown and wait for successful #nua_r_shutdown event.
- * Shuts down and destroys the @nua stack. Ongoing calls, registrations, 
+ * Shuts down and destroys the @nua stack. Ongoing calls, registrations,
  * and subscriptions are left as they are.
  *
  * @param nua         Pointer to @nua stack object
@@ -211,7 +212,8 @@
 
   if (nua) {
     if (!nua->nua_shutdown_final) {
-      SU_DEBUG_0(("nua_destroy(%p): FATAL: nua_shutdown not completed\n", nua));
+      SU_DEBUG_0(("nua_destroy(%p): FATAL: nua_shutdown not completed\n",
+		  (void *)nua));
       assert(nua->nua_shutdown);
       return;
     }
@@ -242,7 +244,7 @@
 
 /** Obtain default operation handle of the @nua stack object.
  *
- * A default operation can be used for operations where the 
+ * A default operation can be used for operations where the
  * ultimate result is not important or can be discarded.
  *
  * @param nua         Pointer to @nua stack object
@@ -262,7 +264,7 @@
   return nua ? nua->nua_handles : NULL;
 }
 
-/** Create an operation handle 
+/** Create an operation handle
  *
  * Allocates a new operation handle and associated storage.
  *
@@ -275,7 +277,7 @@
  *
  * @par Related tags:
  *     Duplicates the provided tags for use with every operation. Note that
- *     NUTAG_URL() is converted to SIPTAG_TO() if there is no SIPTAG_TO(). 
+ *     NUTAG_URL() is converted to SIPTAG_TO() if there is no SIPTAG_TO().
  *     And also vice versa, request-URI is taken from SIPTAG_TO() if there
  *     is no NUTAG_URL(). Note that certain SIP headers cannot be saved with
  *     the handle. They include @ContentLength, @CSeq, @RSeq, @RAck, and
@@ -302,7 +304,7 @@
     ta_start(ta, tag, value);
 
     nh = nh_create_handle(nua, hmagic, ta_args(ta));
-    
+
     if (nh)
       nh->nh_ref_by_user = 1;
 
@@ -312,7 +314,7 @@
   return nh;
 }
 
-/** Bind a callback context to an operation handle. 
+/** Bind a callback context to an operation handle.
  *
  * @param nh          Pointer to operation handle
  * @param hmagic      Pointer to callback context
@@ -334,7 +336,7 @@
     nh->nh_magic = hmagic;
 }
 
-/** Fetch a callback context from an operation handle. 
+/** Fetch a callback context from an operation handle.
  *
  * @param nh          Pointer to operation handle
  *
@@ -356,7 +358,7 @@
 
   if (NH_IS_VALID(nh))
     magic = nh->nh_magic;
-  
+
   return magic;
 }
 
@@ -369,8 +371,8 @@
  *
  * @param nh          Pointer to operation handle
  *
- * @retval 0 no invite in operation or operation handle is invalid 
- * @retval 1 operation has invite 
+ * @retval 0 no invite in operation or operation handle is invalid
+ * @retval 1 operation has invite
  *
  * @par Related tags:
  *     none
@@ -383,15 +385,15 @@
   return nh ? nh->nh_has_invite : 0;
 }
 
-/**Check if operation handle has active event subscriptions. 
+/**Check if operation handle has active event subscriptions.
  *
  * Active subscription can be established either by nua_subscribe() or
  * nua_refer() calls.
  *
  * @param nh          Pointer to operation handle
  *
- * @retval 0    no event subscriptions in operation or 
- *              operation handle is invalid 
+ * @retval 0    no event subscriptions in operation or
+ *              operation handle is invalid
  * @retval !=0  operation has event subscriptions
  *
  * @par Related tags:
@@ -416,7 +418,7 @@
  *
  * @param nh          Pointer to operation handle
  *
- * @retval 0 no active registration in operation or 
+ * @retval 0 no active registration in operation or
  *           operation handle is invalid
  * @retval 1 operation has registration
  *
@@ -433,12 +435,12 @@
   return nh && nh->nh_ds->ds_has_register;
 }
 
-/** Check if operation handle has been used with outgoing SUBSCRIBE of REFER request. 
+/** Check if operation handle has been used with outgoing SUBSCRIBE of REFER request.
  *
  * @param nh          Pointer to operation handle
  *
- * @retval 0 no active subscription in operation or 
- *           operation handle is invalid 
+ * @retval 0 no active subscription in operation or
+ *           operation handle is invalid
  * @retval 1 operation has subscription.
  *
  * @par Related tags:
@@ -470,7 +472,7 @@
   return nh ? nh->nh_has_register : 0;
 }
 
-/** Check if operation handle has an active call 
+/** Check if operation handle has an active call
  *
  * @param nh          Pointer to operation handle
  *
@@ -488,17 +490,17 @@
   return nh ? nh->nh_active_call : 0;
 }
 
-/** Check if operation handle has a call on hold 
+/** Check if operation handle has a call on hold
  *
- * Please note that this status is not affected by remote end putting 
- * this end on hold. Remote end can put each media separately on hold 
- * and status is reflected on SOATAG_ACTIVE_AUDIO(), SOATAG_ACTIVE_VIDEO() 
+ * Please note that this status is not affected by remote end putting
+ * this end on hold. Remote end can put each media separately on hold
+ * and status is reflected on SOATAG_ACTIVE_AUDIO(), SOATAG_ACTIVE_VIDEO()
  * and SOATAG_ACTIVE_CHAT() tag values in #nua_i_state event.
  *
  * @param nh          Pointer to operation handle
  *
- * @retval 0  if no call on hold in operation or operation handle is invalid 
- * @retval 1  if operation has call on hold, for example nua_invite() or 
+ * @retval 0  if no call on hold in operation or operation handle is invalid
+ * @retval 1  if operation has call on hold, for example nua_invite() or
  *            nua_update() has been called with SOATAG_HOLD() with non-NULL
  *            argument.
  *
@@ -515,14 +517,14 @@
 
 /** Get the remote address (From/To header) of operation handle
  *
- * Remote address is used as To header in outgoing operations and 
+ * Remote address is used as To header in outgoing operations and
  * derived from From: header in incoming operations.
  *
  * @param nh          Pointer to operation handle
  *
  * @retval NULL   no remote address for operation or operation handle invalid
  * @retval !=NULL pointer to remote address for operation
- *     
+ *
  * @par Related tags:
  *     none
  *
@@ -536,14 +538,14 @@
 
 /** Get the local address (From/To header) of operation handle
  *
- * Local address is used as From header in outgoing operations and 
+ * Local address is used as From header in outgoing operations and
  * derived from To: header in incoming operations.
  *
  * @param nh          Pointer to operation handle
  *
  * @retval NULL   no local address for operation or operation handle invalid
  * @retval !=NULL pointer to local address for operation
- *     
+ *
  * @par Related tags:
  *     none
  *
@@ -590,7 +592,7 @@
     ta_end(ta); \
   } \
   else { \
-    SU_DEBUG_1(("nua: " #event " with invalid handle %p\n", nh));	\
+    SU_DEBUG_1(("nua: " #event " with invalid handle %p\n", (void *)nh)); \
   }
 
 /* Documented with nua_stack_set_params() */
@@ -658,18 +660,18 @@
   NUA_SIGNAL(nh, nua_r_method, tag, value);
 }
 
-/** Send a chat message. 
+/** Send a chat message.
  *
- * A chat channel can be established during call setup using "message" media. 
- * An active chat channel is indicated using #nua_i_state event containing 
- * SOATAG_ACTIVE_CHAT() tag. Chat messages can be sent using this channel with 
- * nua_chat() function. Currently this is implemented using SIP MESSAGE 
+ * A chat channel can be established during call setup using "message" media.
+ * An active chat channel is indicated using #nua_i_state event containing
+ * SOATAG_ACTIVE_CHAT() tag. Chat messages can be sent using this channel with
+ * nua_chat() function. Currently this is implemented using SIP MESSAGE
  * requests but in future MSRP (message session protocol) will replace it.
 *
  * @param nh              Pointer to operation handle
  * @param tag, value, ... List of tagged parameters
  *
- * @return 
+ * @return
  *    nothing
  *
  * @par Related Tags:
@@ -707,18 +709,18 @@
 
 /* nua_r_notify is documented with process_response_to_notify() */
 
-/** Create an event server. 
+/** Create an event server.
  *
- * This function create an event server taking care of sending NOTIFY 
- * requests and responding to further SUBSCRIBE requests. The event 
- * server can accept multiple subscriptions from several sources and 
- * takes care for distributing the notifications. Unlike other functions 
+ * This function create an event server taking care of sending NOTIFY
+ * requests and responding to further SUBSCRIBE requests. The event
+ * server can accept multiple subscriptions from several sources and
+ * takes care for distributing the notifications. Unlike other functions
  * this call only accepts the SIP tags listed below.
  *
  * @param nh              Pointer to operation handle
  * @param tag, value, ... List of tagged parameters
  *
- * @return 
+ * @return
  *    nothing
  *
  * @par Related Tags:
@@ -736,7 +738,7 @@
   NUA_SIGNAL(nh, nua_r_notifier, tag, value);
 }
 
-/** Terminate an event server. 
+/** Terminate an event server.
  *
  * Terminate an event server with matching event and content type. The event
  * server was created earlier with nua_notifier() function.
@@ -744,7 +746,7 @@
  * @param nh              Pointer to operation handle
  * @param tag, value, ... List of tagged parameters
  *
- * @return 
+ * @return
  *    nothing
  *
  * @par Related Tags:
@@ -809,7 +811,7 @@
  * @param nh              Pointer to operation handle
  * @param tag, value, ... List of tagged parameters
  *
- * @return 
+ * @return
  *    nothing
  *
  * @par Related Tags:
@@ -827,7 +829,7 @@
  *
  * After creating a local presence server by nua_notifier(), an incoming
  * SUBSCRIBE request causes #nua_i_subscription event. Each subscriber is
- * identified with NEATAG_SUB() tag in the #nua_i_subscription event. 
+ * identified with NEATAG_SUB() tag in the #nua_i_subscription event.
  * Application can either authorize the subscriber with
  * NUTAG_SUBSTATE(#nua_substate_active) or terminate the subscription with
  * NUTAG_SUBSTATE(#nua_substate_terminated).
@@ -835,7 +837,7 @@
  * @param nh              Pointer to operation handle
  * @param tag, value, ... List of tagged parameters
  *
- * @return 
+ * @return
  *    nothing
  *
  * @par Related Tags:
@@ -875,11 +877,11 @@
     ta_end(ta);
   }
   else {
-    SU_DEBUG_1(("nua: respond with invalid handle %p\n", nh));
+    SU_DEBUG_1(("nua: respond with invalid handle %p\n", (void *)nh));
   }
 }
 
-/** Destroy a handle 
+/** Destroy a handle
  *
  * Terminate the protocol state associated with an operation handle. The
  * stack discards resources and terminates the ongoing dialog usage,
@@ -893,7 +895,7 @@
  *
  * @param nh              Pointer to operation handle
  *
- * @return 
+ * @return
  *    nothing
  *
  * @par Related Tags:
@@ -954,11 +956,14 @@
     e->e_status = status;
     e->e_phrase = phrase;
 
-    if (su_msg_send(sumsg) != 0)
+    SU_DEBUG_7(("nua(%p): signal %s\n", (void *)nh,
+		nua_event_name(event) + 4));
+
+    if (su_msg_send(sumsg) != 0 && event != nua_r_destroy)
       nua_handle_unref(nh);
-  } 
+  }
   else {
-    /* XXX  - we should return error code to application */
+    /* XXX  - we should return error code to application but we just abort() */
     assert(ENOMEM == 0);
   }
 
@@ -981,8 +986,16 @@
   }
 
   if (!nh || !nh->nh_valid) {	/* Handle has been destroyed */
+    if (nua_log->log_level >= 7) {
+      char const *name = nua_event_name(e->e_event) + 4;
+      SU_DEBUG_7(("nua(%p): event %s dropped\n", (void *)nh, name));
+    }
     if (nh && !NH_IS_DEFAULT(nh) && nua_handle_unref(nh)) {
-      SU_DEBUG_9(("nua(%p): freed by application\n", nh));
+#if HAVE_NUA_HANDLE_DEBUG
+      SU_DEBUG_0(("nua(%p): freed by application\n", (void *)nh));
+#else
+      SU_DEBUG_9(("nua(%p): freed by application\n", (void *)nh));
+#endif
     }
     if (e->e_msg)
       msg_destroy(e->e_msg), e->e_msg = NULL;
@@ -1011,7 +1024,11 @@
 		    e->e_tags);
 
   if (nh && !NH_IS_DEFAULT(nh) && nua_handle_unref(nh)) {
-    SU_DEBUG_9(("nua(%p): freed by application\n", nh));
+#if HAVE_NUA_HANDLE_DEBUG
+    SU_DEBUG_0(("nua(%p): freed by application\n", (void *)nh));
+#else
+    SU_DEBUG_9(("nua(%p): freed by application\n", (void *)nh));
+#endif
   }
 
   if (!su_msg_is_non_null(nua->nua_current))
@@ -1066,7 +1083,7 @@
       msg_destroy(e->e_msg), e->e_msg = NULL;
 
     if (nh && !NH_IS_DEFAULT(nh) && nua_handle_unref(nh)) {
-      SU_DEBUG_9(("nua(%p): freed by application\n", nh));
+      SU_DEBUG_9(("nua(%p): freed by application\n", (void *)nh));
     }
 
     su_msg_destroy(saved);
@@ -1094,20 +1111,35 @@
 
 /**Generate a @Replaces header for handle.
  *
+ * A @Replaces header contains the @CallID value, @From and @To tags
+ * corresponding to SIP dialog associated with handle @a nh. Note that the
+ * @Replaces matches with dialog of the remote peer,
+ * nua_handle_by_replaces() does not return same handle (unless you swap
+ * rp_from_tag and rp_to_tag in @Replaces header).
+ *
+ * A @Replaces header is used in attended transfer, among other things.
+ *
+ * @param nh pointer to operation handle
+ * @param home memory home used to allocate the header
+ * @param early_only if true, include "early-only" parameter in @Replaces, too
+ *
+ * @return A newly created @Replaces header.
+ *
  * @since New in @VERSION_1_12_4.
  *
- * @sa nua_handle_by_replaces(), @Replaces, @RFC3891, nua_refer(),
- * #nua_i_refer, @ReferTo, nta_leg_make_replaces()
+ * @sa nua_handle_by_replaces(), @Replaces, @RFC3891, @RFC3515, nua_refer(),
+ * #nua_i_refer(), @ReferTo, nta_leg_make_replaces(),
+ * sip_headers_as_url_query()
  */
-sip_replaces_t *nua_handle_make_replaces(nua_handle_t *nh, 
+sip_replaces_t *nua_handle_make_replaces(nua_handle_t *nh,
 					 su_home_t *home,
 					 int early_only)
 {
   if (nh && nh->nh_valid && nh->nh_nua) {
     struct nua_stack_handle_make_replaces_args a = { NULL, nh, home, early_only };
 
-    if (su_task_execute(nh->nh_nua->nua_server, 
-			nua_stack_handle_make_replaces_call, (void *)&a, 
+    if (su_task_execute(nh->nh_nua->nua_server,
+			nua_stack_handle_make_replaces_call, (void *)&a,
 			NULL) == 0) {
       return a.retval;
     }
@@ -1134,9 +1166,9 @@
  *
  * @since New in @VERSION_1_12_4.
  *
- * @note 
+ * @note
  * You should release the reference with nua_handle_unref() when you are
- * done with handle.
+ * done with the handle.
  *
  * @sa nua_handle_make_replaces(), @Replaces, @RFC3891, nua_refer(),
  * #nua_i_refer, @ReferTo, nta_leg_by_replaces()
@@ -1146,8 +1178,8 @@
   if (nua) {
     struct nua_stack_handle_by_replaces_args a = { NULL, nua, r };
 
-    if (su_task_execute(nua->nua_server, 
-			nua_stack_handle_by_replaces_call, (void *)&a, 
+    if (su_task_execute(nua->nua_server,
+			nua_stack_handle_by_replaces_call, (void *)&a,
 			NULL) == 0) {
       nua_handle_t *nh = a.retval;
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua.docs
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua.docs	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua.docs	Tue Apr 24 10:14:28 2007
@@ -1124,7 +1124,7 @@
     <td>terminating</td>
     <td>Process answer</td>
     <td>
-   If there was an failure in SDP negotiation or other failure with media,
+   If there was a failure in SDP negotiation or other failure with media,
    the stack will automatically terminate the call. The BYE follows
    immediatelhy after the ACK.
 </td></tr>
@@ -1262,7 +1262,7 @@
      |    +---------------|            |    :         |     :
      |    |               +------------+    :         |     :
      |    |                           |     :         |     :
-     |    |          nua_respond/18X (2)    :         |     :
+     |    |          nua_respond/18X (2a)   :         |     :
      |    |                           |     :         |     :
      |    |                           V     V         |     :
      |    |                          +------------+   |     :
@@ -2029,7 +2029,8 @@
  *               Always present
  * @param nh     Pointer to operation handle.
  * @param hmagic Pointer to callback context from nua_handle().
- * @param sip    Parsed incoming message. May be NULL.
+ * @param sip    Headers in parsed incoming message. May be NULL.
+ *               See also nua_current_request().
  * @param tags   Tag list containing more information about the state of NUA.
  *               May be empty.
  *
@@ -2038,17 +2039,22 @@
  * individual event.
  *
  * The events can be divided into the following categories: \n
- * @par Indications:
+ * @par Status or Error Indications:
  * #nua_i_active           \n
+ * #nua_i_error            \n
+ * #nua_i_fork             \n
+ * #nua_i_media_error      \n
+ * #nua_i_subscription     \n
+ * #nua_i_state            \n
+ * #nua_i_terminated
+ *
+ * @par SIP requests:
  * #nua_i_ack              \n
  * #nua_i_bye              \n
  * #nua_i_cancel           \n
  * #nua_i_chat             \n
- * #nua_i_error            \n
- * #nua_i_fork             \n
  * #nua_i_info             \n
  * #nua_i_invite           \n
- * #nua_i_media_error      \n
  * #nua_i_message          \n
  * #nua_i_method           \n
  * #nua_i_notify           \n
@@ -2058,9 +2064,6 @@
  * #nua_i_refer            \n
  * #nua_i_register         \n
  * #nua_i_subscribe        \n
- * #nua_i_subscription     \n
- * #nua_i_state            \n
- * #nua_i_terminated       \n
  * #nua_i_update
  *
  * @par Responses:
@@ -2122,7 +2125,8 @@
  *
  * Outgoing call has been forked.
  *
- * This is sent when an INVITE request is answered with multiple 200 responses.
+ * This is sent when an INVITE request is answered with multiple 2XX series
+ * responses.
  *
  * @param status response status code
  * @param phrase a short textual description of @a status code
@@ -2219,7 +2223,7 @@
  * @param nh     operation handle associated with the notifier
  * @param hmagic operation magic associated with the notifier
  * @param sip    response to MESSAGE request or NULL upon an error
- *               (error code and message are in status an phrase parameters)
+ *               (error code and message are in status and phrase parameters)
  * @param tags   empty
  *
  * @sa nua_chat(), #nua_r_message

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_common.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_common.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_common.c	Tue Apr 24 10:14:28 2007
@@ -110,13 +110,14 @@
   assert(nua->nua_home);
 
   if ((nh = su_home_clone(nua->nua_home, sizeof(*nh)))) {
-    nh->nh_valid = nua_handle;
+    nh->nh_valid = nua_valid_handle_cookie;
     nh->nh_nua = nua;
     nh->nh_magic = hmagic;
     nh->nh_prefs = nua->nua_dhandle->nh_prefs;
 
     if (nua_handle_save_tags(nh, tags) < 0) {
-      SU_DEBUG_5(("nua(%p): creating handle %p failed\n", nua, nh));
+      SU_DEBUG_5(("nua(%p): creating handle %p failed\n",
+		  (void *)nua, (void *)nh));
       su_home_unref(nh->nh_home), nh = NULL;
     }
     
@@ -136,7 +137,7 @@
       } 
       else {
 	_handle_lifetime = 2;
-	SU_DEBUG_0(("nh_handle_create(%p)\n", nh));
+	SU_DEBUG_0(("nh_handle_create(%p)\n", (void *)nh));
 	su_home_destructor(nh->nh_home, nh_destructor);
       }
     }
@@ -159,10 +160,12 @@
 static void nh_destructor(void *arg)
 {
   nua_handle_t *nh = arg;
-
-  SU_DEBUG_0(("nh_destructor(%p)\n", nh));
+  SU_DEBUG_0(("nh_destructor(%p)\n", (void *)nh));
 }
 
+#undef nua_handle_ref
+#undef nua_handle_unref
+
 /** Make a new reference to handle.
  *
  * The handles use reference counting for memory management. In addition to
@@ -180,7 +183,6 @@
   return (nua_handle_t *)su_home_ref(nh->nh_home);
 }
 
-
 /** Destroy reference to handle. 
  *
  * The handles use reference counting for memory management. In addition to
@@ -214,6 +216,50 @@
   return su_strdup(home, str);
 }
 
+/** Check if event is a request that can be responded with nua_respond().
+ *
+ * Note that if event status is 200 or greater, it already has been
+ * responded. This function is provided for compatibility with future
+ * versions of nua. An unknown event can always be handled in the event
+ * callback like this:
+ * @code
+ * switch (event) {
+ *   ...
+ *   default:
+ *     if (status < 200 && nua_event_is_incoming_request(event))
+ *       nua_respond(nh, SIP_501_NOT_IMPLEMENTED,
+ *                   NUTAG_WITH_THIS(nua), TAG_END());
+ *     if (hmagic == NULL)
+ *       nua_handle_destroy(nh);
+ *     return;
+ *   ...
+ * @endcode
+ *
+ * @sa #nua_event_t, nua_respond()
+ *
+ * @NEW_1_12_6
+ */
+int nua_event_is_incoming_request(nua_event_t event)
+{
+  switch (event) {
+  case nua_i_invite: return 1;
+  case nua_i_cancel: return 1;
+  case nua_i_register: return 1;
+  case nua_i_bye: return 1;
+  case nua_i_options: return 1;
+  case nua_i_refer: return 1;
+  case nua_i_publish: return 1;
+  case nua_i_prack: return 1;
+  case nua_i_info: return 1;
+  case nua_i_update: return 1;
+  case nua_i_message: return 1;
+  case nua_i_subscribe: return 1;
+  case nua_i_notify: return 1;
+  case nua_i_method: return 1;
+  default: return 0;
+  }
+}
+
 /** Get name for a NUA event. */
 char const *nua_event_name(nua_event_t event)
 {
@@ -301,3 +347,34 @@
   default: return "UNKNOWN";
   }
 }
+
+/** Return name of subscription state. @NEW_1_12_5. */
+char const *nua_substate_name(enum nua_substate substate)
+{
+  switch (substate) {
+  case nua_substate_embryonic:
+      /*FALLTHROUGH*/
+  case nua_substate_pending:
+    return "pending";
+  case nua_substate_terminated:
+    return "terminated";
+  case nua_substate_active:
+      /*FALLTHROUGH*/
+  default:
+    return "active";
+  }
+}
+
+/** Convert string to enum nua_substate. @NEW_1_12_5. */
+enum nua_substate nua_substate_make(char const *sip_substate)
+{
+  if (sip_substate == NULL)
+    return nua_substate_active;
+  else if (strcasecmp(sip_substate, "terminated") == 0)
+    return nua_substate_terminated;
+  else if (strcasecmp(sip_substate, "pending") == 0)
+    return nua_substate_pending;
+  else /* if (strcasecmp(sip_substate, "active") == 0) */ 
+    return nua_substate_active;
+}
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_dialog.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_dialog.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_dialog.c	Tue Apr 24 10:14:28 2007
@@ -269,7 +269,7 @@
     du = *prev_du;
     if (du) {		/* Already exists */
       SU_DEBUG_5(("nua(%p): adding already existing %s usage%s%s\n",
-		  own, nua_dialog_usage_name(du), 
+		  (void *)own, nua_dialog_usage_name(du), 
 		  event ? "  with event " : "", event ? event->o_type : ""));
       
       if (prev_du != &ds->ds_usage) {
@@ -297,7 +297,7 @@
       }
 	
       SU_DEBUG_5(("nua(%p): adding %s usage%s%s\n",
-		  own, nua_dialog_usage_name(du), 
+		  (void *)own, nua_dialog_usage_name(du), 
 		  o ? " with event " : "", o ? o->o_type :""));
 
       su_home_ref(own);
@@ -345,6 +345,24 @@
     nua_client_request_t *cr, *cr_next;
     nua_server_request_t *sr, *sr_next;
 
+    *at = du->du_next;
+
+    o = du->du_event;
+
+    SU_DEBUG_5(("nua(%p): removing %s usage%s%s\n",
+		(void *)own, nua_dialog_usage_name(du), 
+		o ? " with event " : "", o ? o->o_type :""));
+    du->du_class->usage_remove(own, ds, du);
+
+    /* Destroy saved client request */
+    if (nua_client_is_bound(du->du_cr)) {
+      nua_client_bind(cr = du->du_cr, NULL);
+      if (!nua_client_is_queued(cr) &&
+	  !nua_client_is_reporting(cr))
+	nua_client_request_destroy(cr);
+    }
+
+    /* Clean references from queued client requests */
     for (cr = ds->ds_cr; cr; cr = cr_next) {
       cr_next = cr->cr_next;
       if (cr->cr_usage == du)
@@ -357,29 +375,19 @@
 	nua_server_request_destroy(sr);
     }
 
-    *at = du->du_next;
-
-    o = du->du_event;
-
-    SU_DEBUG_5(("nua(%p): removing %s usage%s%s\n",
-		own, nua_dialog_usage_name(du), 
-		o ? " with event " : "", o ? o->o_type :""));
-    du->du_class->usage_remove(own, ds, du);
-    msg_destroy(du->du_msg), du->du_msg = NULL;
     su_home_unref(own);
     su_free(own, du);
   }
 
-  /* Zap dialog if there is no more usages */
-  if (ds->ds_usage == NULL) {
-    nta_leg_destroy(ds->ds_leg), ds->ds_leg = NULL;
-    su_free(own, (void *)ds->ds_remote_tag), ds->ds_remote_tag = NULL;
-    ds->ds_route = 0;
+  /* Zap dialog if there are no more usages */
+  if (ds->ds_terminating)
+    ;
+  else if (ds->ds_usage == NULL) {
+    nua_dialog_remove(own, ds, NULL);
     ds->ds_has_events = 0;
-    ds->ds_terminated = 0;
     return;
   }
-  else if (!ds->ds_terminated) {
+  else {
     nua_dialog_log_usage(own, ds);
   }
 }
@@ -412,7 +420,7 @@
       }
     }
     
-    SU_DEBUG_3(("nua(%p): handle with %s%s%s\n", own,
+    SU_DEBUG_3(("nua(%p): handle with %s%s%s\n", (void *)own,
 		ds->ds_has_session ? "session and " : "", 
 		ds->ds_has_events ? "events " : "",
 		buffer));
@@ -423,49 +431,16 @@
 void nua_dialog_deinit(nua_owner_t *own,
 		       nua_dialog_state_t *ds)
 {
-  while (ds->ds_usage) {
-    nua_dialog_usage_remove_at(own, ds, &ds->ds_usage);
-  }
-}
-
-
-/** @internal Dialog has been terminated. Remove all usages. */
-void nua_dialog_terminated(nua_owner_t *own,
-			   struct nua_dialog_state *ds,
-			   int status,
-			   char const *phrase)
-{
-
-  ds->ds_terminated = 1;
+  ds->ds_terminating = 1;
 
   while (ds->ds_usage) {
-#if 0
-    int call = 0;
-
-    if (ds->ds_usage->du_kind == nua_session_usage)
-      call = 1;			/* Delay sending the event */
-    else
-      /* XXX */;
-#endif
     nua_dialog_usage_remove_at(own, ds, &ds->ds_usage);
   }
-}
 
-/**@internal
- * Set expiration time. 
- */
-void nua_dialog_usage_set_expires(nua_dialog_usage_t *du,
-				  unsigned delta)
-{
-  if (delta) {
-    sip_time_t now = sip_now(), expires = now + delta;
-    if (expires < now)
-      expires = SIP_TIME_MAX;
-    du->du_expires = expires;
-    nua_dialog_usage_set_refresh(du, delta);
-  }
-  else
-    du->du_expires = 0, du->du_refresh = 0;
+  nua_dialog_remove(own, ds, NULL);
+
+  ds->ds_has_events = 0;
+  ds->ds_terminating = 0;
 }
 
 /**@internal
@@ -521,10 +496,20 @@
   du->du_refresh = target;
 }
 
+/** Set absolute refresh time */
+void nua_dialog_usage_refresh_at(nua_dialog_usage_t *du,
+				 sip_time_t target)
+{
+  SU_DEBUG_7(("nua(): refresh %s after %lu seconds\n",
+	      nua_dialog_usage_name(du), target - sip_now()));
+  du->du_refresh = target;
+} 
+
 /**@internal Do not refresh. */
 void nua_dialog_usage_reset_refresh(nua_dialog_usage_t *du)
 {
-  du->du_refresh = 0;
+  if (du)
+    du->du_refresh = 0;
 }
 
 /** @internal Refresh usage or shutdown usage if @a now is 0. */
@@ -537,18 +522,52 @@
     du->du_refresh = 0;
 
     if (now > 0) {
-      if (du->du_class->usage_refresh) {
-	du->du_class->usage_refresh(owner, ds, du, now);
-	return;
-      }
+      assert(du->du_class->usage_refresh);
+      du->du_class->usage_refresh(owner, ds, du, now);
     }
     else {
       du->du_shutdown = 1;
-      if (du->du_class->usage_shutdown) {
-	du->du_class->usage_shutdown(owner, ds, du);
-	return;
-      }
+      assert(du->du_class->usage_shutdown);
+      du->du_class->usage_shutdown(owner, ds, du);
     }
   }
 }
 
+/** Terminate all dialog usages gracefully. */
+int nua_dialog_shutdown(nua_owner_t *owner, nua_dialog_state_t *ds)
+{
+  nua_dialog_usage_t *du;
+
+  ds->ds_terminating = 1;
+
+  do {
+    for (du = ds->ds_usage; du; du = du->du_next) {
+      if (!du->du_shutdown) {
+	nua_dialog_usage_shutdown(owner, ds, du);
+	break;
+      }
+    }
+  } while (du);
+
+  return 1;
+}
+
+/** (Gracefully) terminate usage.
+ *
+ * @retval >0  shutdown done
+ * @retval 0   shutdown in progress
+ * @retval <0  try again later
+ */
+int nua_dialog_usage_shutdown(nua_owner_t *owner,
+			       nua_dialog_state_t *ds,
+			       nua_dialog_usage_t *du)
+{
+  if (du) {
+    du->du_refresh = 0;
+    du->du_shutdown = 1;
+    assert(du->du_class->usage_shutdown);
+    return du->du_class->usage_shutdown(owner, ds, du);
+  }
+  else
+    return 200;
+}

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_dialog.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_dialog.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_dialog.h	Tue Apr 24 10:14:28 2007
@@ -48,49 +48,93 @@
 #include <sofia-sip/nta.h>
 #endif
 
+typedef su_msg_r nua_saved_signal_t;
+
 typedef struct nua_server_request nua_server_request_t; 
 typedef struct nua_client_request nua_client_request_t; 
 
-/** Respond to an incoming request. */
-typedef int nua_server_respond_f(nua_server_request_t *, tagi_t const *);
+typedef struct {
+  sip_method_t sm_method; 
+  char const *sm_method_name;
+
+  int sm_event;
+
+  struct {
+    unsigned create_dialog:1, in_dialog:1, target_refresh:1, add_contact:1;
+    unsigned :0;
+  } sm_flags;
+
+  /** Initialize server-side request. */
+  int (*sm_init)(nua_server_request_t *sr);
+
+  /** Preprocess server-side request (after handle has been created). */
+  int (*sm_preprocess)(nua_server_request_t *sr);
+
+  /** Update server-side request parameters */
+  int (*sm_params)(nua_server_request_t *sr, tagi_t const *tags);
 
-/** Restart an outgoing request. */
-typedef void nua_creq_restart_f(nua_owner_t *, tagi_t *tags);
+  /** Respond to server-side request. */
+  int (*sm_respond)(nua_server_request_t *sr, tagi_t const *tags);
+
+  /** Report server-side request to application. */
+  int (*sm_report)(nua_server_request_t *sr, tagi_t const *tags);
+
+} nua_server_methods_t;
 
 /** Server side transaction */
 struct nua_server_request {
   struct nua_server_request *sr_next, **sr_prev;
 
+  nua_server_methods_t const *sr_methods;
+
   nua_owner_t *sr_owner;	/**< Backpointer to handle */
   nua_dialog_usage_t *sr_usage;	/**< Backpointer to usage */
 
-  /** When the application responds to an request with
-   * nua_respond(), the sr_respond() is called
-   */
-  nua_server_respond_f *sr_respond;
-  
   nta_incoming_t *sr_irq;	/**< Server transaction object */
-  msg_t *sr_msg;		/**< Request message */
+  
+  struct {
+    msg_t *msg;			/**< Request message */
+    sip_t const *sip;		/**< Headers in request message */
+  } sr_request;
+
+  struct {
+    msg_t *msg;			/**< Response message */
+    sip_t *sip;			/**< Headers in response message */
+  } sr_response;
 
   sip_method_t sr_method;	/**< Request method */
+
+  int sr_application;		/**< Status by application */
+
   int sr_status;		/**< Status code */
   char const *sr_phrase;	/**< Status phrase */
 
-  unsigned sr_auto:1;		/**< Autoresponse - no event has been sent */
+  unsigned sr_event:1;		/**< Reported to application */
   unsigned sr_initial:1;	/**< Handle was created by this request */
+  unsigned sr_add_contact:1;	/**< Add Contact header to the response */
+  unsigned sr_target_refresh:1;	/**< Refresh target */
+  unsigned sr_terminating:1;	/**< Terminate usage after final response */
+  unsigned sr_gracefully:1;	/**< Terminate usage gracefully */
+
+  unsigned sr_neutral:1;	/**< No effect on session or other usage */
+
+  /* Flags used with 100rel */
+  unsigned sr_100rel:1, sr_pracked:1;
 
   /* Flags used with offer-answer */
   unsigned sr_offer_recv:1;	/**< We have received an offer */
   unsigned sr_answer_sent:2;	/**< We have answered (reliably, if >1) */
 
-  unsigned sr_offer_sent:1;	/**< We have offered SDP */
+  unsigned sr_offer_sent:2;	/**< We have offered SDP (reliably, if >1) */
   unsigned sr_answer_recv:1;	/**< We have received SDP answer */
-};
+  unsigned :0;
+
+  char const *sr_sdp;		/**< SDP received from client */
+  size_t sr_sdp_len;		/**< SDP length */
 
-#define SR_INIT(sr)			     \
-  ((void)memset((sr), 0, sizeof (sr)[0]),    \
-   (void)(SR_STATUS1((sr), SIP_100_TRYING)), \
-   sr)
+  /**< Save 200 OK nua_respond() signal until PRACK has been received */
+  nua_saved_signal_t sr_signal;	
+};
 
 #define SR_STATUS(sr, status, phrase) \
   ((sr)->sr_phrase = (phrase), (sr)->sr_status = (status))
@@ -104,46 +148,194 @@
   return (void)(sr->sr_phrase = phrase), (sr->sr_status = status);
 }
 
+/** Methods for client request */
+typedef struct {
+  sip_method_t crm_method;
+  char const *crm_method_name;
+  size_t crm_extra;		/**< Size of private data */
+
+  struct {
+    unsigned create_dialog:1, in_dialog:1, target_refresh:1;
+    unsigned:0;
+  } crm_flags;
+
+  /** Generate a request message.
+   *
+   * @retval 1 when request message has been created
+   * @retval 0 when request message should be created in normal fashion
+   * @retval -1 upon an error
+   */
+  int (*crm_template)(nua_client_request_t *cr,
+		      msg_t **return_msg,
+		      tagi_t const *tags);
+
+  /**@a crm_init is called when a client request is sent first time. 
+   *
+   * @retval 1 when request has been responded
+   * @retval 0 when request should be sent in normal fashion
+   * @retval -1 upon an error
+   */
+  int (*crm_init)(nua_client_request_t *, msg_t *msg, sip_t *sip,
+		  tagi_t const *tags);
+
+  /** @a crm_send is called each time when a client request is sent.
+   *
+   * @retval 1 when request has been responded
+   * @retval 0 when request has been sent
+   * @retval -1 upon an error (request message has not been destroyed)
+   * @retval -2 upon an error (request message has been destroyed)
+   */
+  int (*crm_send)(nua_client_request_t *,
+		  msg_t *msg, sip_t *sip,
+		  tagi_t const *tags);
+
+  /** @a crm_check_restart is called each time when a response is received.
+   *
+   * It is used to restart reqquest after responses with method-specific
+   * status code or method-specific way of restarting the request.
+   *
+   * @retval 1 when request has been restarted
+   * @retval 0 when response should be processed normally
+   */
+  int (*crm_check_restart)(nua_client_request_t *,
+			   int status, char const *phrase,
+			   sip_t const *sip);
+
+  /** @a crm_recv is called each time a final response is received.
+   *
+   * A final response is in range 200 .. 699 (or internal response) and it
+   * cannot be restarted.
+   *
+   * crm_recv() should call nua_base_client_response() or
+   * nua_base_client_tresponse(). The return values below are documented with
+   * nua_base_client_response(), too.
+   *
+   * @retval 0 if response was preliminary
+   * @retval 1 if response was final
+   * @retval 2 if response destroyed the handle, too.
+   */
+  int (*crm_recv)(nua_client_request_t *,
+		  int status, char const *phrase,
+		  sip_t const *sip);
+
+  /** @a crm_preliminary is called each time a preliminary response is received.
+   *
+   * A preliminary response is in range 101 .. 199.
+   *
+   * crm_preliminary() should call nua_base_client_response() or
+   * nua_base_client_tresponse().
+   *
+   * @retval 0 if response was preliminary
+   * @retval 1 if response was final
+   * @retval 2 if response destroyed the handle, too.
+   */
+  int (*crm_preliminary)(nua_client_request_t *,
+			 int status, char const *phrase,
+			 sip_t const *sip);
+
+  /** @a crm_report is called each time a response is received and it is
+   * reported to the application.
+   *
+   * The status and phrase may be different from the status and phrase
+   * received from the network, e.g., when the request is restarted.
+   *
+   * @return The return value should be 0. It is currently ignored.
+   */
+  int (*crm_report)(nua_client_request_t *,
+		    int status, char const *phrase,
+		    sip_t const *sip,
+		    nta_outgoing_t *orq,
+		    tagi_t const *tags);
+
+  /** @a crm_deinit is called when a client-side request is destroyed.
+   *
+   * @return The return value should be 0. It is currently ignored.
+   */
+  int (*crm_deinit)(nua_client_request_t *);
+
+} nua_client_methods_t;
+
+/* Client-side request. Documented by nua_client_create() */
 struct nua_client_request
 {
-  nua_client_request_t *cr_next;        /**< Linked list of requests */
-  /*nua_event_t*/ int cr_event;		/**< Request event */
-  nua_creq_restart_f *cr_restart;
-  nta_outgoing_t     *cr_orq;
-  msg_t              *cr_msg;
+  nua_client_request_t *cr_next, **cr_prev; /**< Linked list of requests */
+  nua_owner_t        *cr_owner;
   nua_dialog_usage_t *cr_usage;
+
+  nua_saved_signal_t cr_signal;
+  tagi_t const      *cr_tags;
+
+  nua_client_methods_t const *cr_methods;
+
+  msg_t              *cr_msg;
+  sip_t              *cr_sip;
+
+  nta_outgoing_t     *cr_orq;
+
+  /*nua_event_t*/ int cr_event;		/**< Request event */
+  sip_method_t        cr_method;
+  char const         *cr_method_name;
+
+  url_t              *cr_target;
+
+  uint32_t            cr_seq;
+
+  unsigned short      cr_status;        /**< Latest status */
+
   unsigned short      cr_retry_count;   /**< Retry count for this request */
 
   /* Flags used with offer-answer */
   unsigned short      cr_answer_recv;   /**< Recv answer in response 
 					 *  with this status.
 					 */
-  unsigned            cr_offer_sent:1;  /**< Sent offer in this request */
+  unsigned cr_offer_sent:1;	/**< Sent offer in this request */
+
+  unsigned cr_offer_recv:1;	/**< Recv offer in a response */
+  unsigned cr_answer_sent:1;	/**< Sent answer in (PR)ACK */
 
-  unsigned            cr_offer_recv:1;  /**< Recv offer in a response */
-  unsigned            cr_answer_sent:1; /**< Sent answer in (PR)ACK */
+  /* Flags with usage */
+  unsigned cr_neutral:1;	/**< No effect on session or other usage */
 
-  unsigned            cr_has_contact:1; /**< Request has application contact */
+  /* Lifelong flags? */
+  unsigned cr_auto:1;		/**< Request was generated by stack */
+  unsigned cr_has_contact:1;	/**< Request has user Contact */
+  unsigned cr_contactize:1;	/**< Request needs Contact */
+  unsigned cr_dialog:1;		/**< Request can initiate dialog */
+
+  /* Current state */
+  unsigned cr_challenged:1;	/**< Request was challenged */
+  unsigned cr_wait_for_cred:1;	/**< Request is pending authentication */
+  unsigned cr_restarting:1;	/**< Request is being restarted */
+  unsigned cr_reporting:1;	/**< Reporting in progress */
+  unsigned cr_terminating:1;	/**< Request terminates the usage */
+  signed int cr_terminated:2;	/**< Response terminated usage (1) or 
+				    whole dialog (-1) */
+  unsigned cr_graceful:1;	/**< Graceful termination required */
 };
 
 
 struct nua_dialog_state
 {
-  nua_client_request_t ds_cr[1];
-  nua_server_request_t *ds_sr;
-
   /** Dialog usages. */
   nua_dialog_usage_t     *ds_usage;
 
+  /** Client requests */
+  nua_client_request_t   *ds_cr;
+  /** Server requests */
+  nua_server_request_t *ds_sr;
+
   /* Dialog and subscription state */
+  unsigned ds_reporting:1;	/**< We are reporting */
+
   unsigned ds_route:1;		/**< We have route */
-  unsigned ds_terminated:1;	/**< Being terminated */
+  unsigned ds_terminating:1;	/**< Being terminated */
 
   unsigned ds_has_session:1;	/**< We have session */
   unsigned ds_has_register:1;	/**< We have registration */
   unsigned ds_has_publish:1;	/**< We have publish */
 
-  unsigned ds_has_referrals:1;	/**< We have (or have had) referrals */
+  unsigned ds_got_session:1;	/**< We have (or have had) session */
+  unsigned ds_got_referrals:1;	/**< We have (or have had) referrals */
 
   unsigned :0;
 
@@ -196,8 +388,8 @@
 struct nua_dialog_usage {
   nua_dialog_usage_t *du_next;
   nua_usage_class const *du_class;
+  nua_client_request_t *du_cr;	        /**< Client request bound with usage */
 
-  unsigned     du_terminating:1;	/**< Now trying to terminate usage */
   unsigned     du_ready:1;	        /**< Established usage */
   unsigned     du_shutdown:1;	        /**< Shutdown in progress */
   unsigned:0;
@@ -206,13 +398,11 @@
    * Non-zero if the usage is established, SIP_TIME_MAX if there no
    * expiration time.
    */
-  sip_time_t      du_expires;		
 
   sip_time_t      du_refresh;		/**< When to refresh */
 
   sip_event_t const *du_event;		/**< Event of usage */
 
-  msg_t *du_msg;			/**< Template message */
 };
 
 void nua_dialog_uac_route(nua_owner_t *, nua_dialog_state_t *ds,
@@ -225,6 +415,11 @@
 		      nua_dialog_state_t *ds,
 		      nua_dialog_usage_t *usage);
 
+static inline int nua_dialog_is_reporting(nua_dialog_state_t const *ds)
+{
+  return ds && ds->ds_reporting;
+}
+
 char const *nua_dialog_usage_name(nua_dialog_usage_t const *du);
 
 nua_dialog_usage_t *nua_dialog_usage_add(nua_owner_t *, 
@@ -243,18 +438,16 @@
 void nua_dialog_deinit(nua_owner_t *own,
 		       nua_dialog_state_t *ds);
 
-void nua_dialog_terminated(nua_owner_t *,
-			   struct nua_dialog_state *ds,
-			   int status,
-			   char const *phrase);
-
-void nua_dialog_usage_set_expires(nua_dialog_usage_t *du, unsigned delta);
+int nua_dialog_shutdown(nua_owner_t *owner, nua_dialog_state_t *ds);
 
 void nua_dialog_usage_set_refresh(nua_dialog_usage_t *du, unsigned delta);
 
 void nua_dialog_usage_refresh_range(nua_dialog_usage_t *du, 
 				    unsigned min, unsigned max);
 
+void nua_dialog_usage_refresh_at(nua_dialog_usage_t *du, 
+				 sip_time_t target);
+
 void nua_dialog_usage_reset_refresh(nua_dialog_usage_t *du);
 
 void nua_dialog_usage_refresh(nua_owner_t *owner,
@@ -262,6 +455,10 @@
 			      nua_dialog_usage_t *du, 
 			      sip_time_t now);
 
+int nua_dialog_usage_shutdown(nua_owner_t *owner,
+			      nua_dialog_state_t *ds,
+			      nua_dialog_usage_t *du);
+
 static inline
 int nua_dialog_is_established(nua_dialog_state_t const *ds)
 {
@@ -287,18 +484,178 @@
 
 /* ---------------------------------------------------------------------- */
 
+int nua_client_create(nua_owner_t *owner,
+		      int event,
+		      nua_client_methods_t const *methods,
+		      tagi_t const *tags);
+
+int nua_client_tcreate(nua_owner_t *nh, 
+		       int event,
+		       nua_client_methods_t const *methods,
+		       tag_type_t tag, tag_value_t value, ...);
+
+static inline 
+void *nua_private_client_request(nua_client_request_t const *cr)
+{
+  return (void *)(cr + 1);
+}
+
+void nua_client_request_destroy(nua_client_request_t *);
+
+int nua_client_request_queue(nua_client_request_t *cr);
+
+static inline int nua_client_is_queued(nua_client_request_t const *cr)
+{
+  return cr && cr->cr_prev;
+}
+
+nua_client_request_t *nua_client_request_remove(nua_client_request_t *cr);
+
+int nua_client_bind(nua_client_request_t *cr, nua_dialog_usage_t *du);
+
+static inline int nua_client_is_bound(nua_client_request_t const *cr)
+{
+  return cr && cr->cr_usage && cr->cr_usage->du_cr == cr;
+}
+
+static inline int nua_client_is_reporting(nua_client_request_t const *cr)
+{
+  return cr && cr->cr_reporting;
+}
+
+/** Mark client request as a terminating one */
+static inline void nua_client_terminating(nua_client_request_t *cr)
+{
+  cr->cr_terminating = 1;
+}
+
+int nua_client_init_request(nua_client_request_t *cr);
+
+int nua_client_restart_request(nua_client_request_t *cr,
+			       int terminating,
+			       tagi_t const *tags);
+
+int nua_client_resend_request(nua_client_request_t *cr,
+			      int terminating);
+
+int nua_base_client_request(nua_client_request_t *cr,
+			    msg_t *msg,
+			    sip_t *sip,
+			    tagi_t const *tags);
+
+int nua_base_client_trequest(nua_client_request_t *cr,
+			     msg_t *msg,
+			     sip_t *sip,
+			     tag_type_t tag, tag_value_t value, ...);
+
+extern nta_response_f nua_client_orq_response;
+
+int nua_client_return(nua_client_request_t *cr,
+		      int status,
+		      char const *phrase,
+		      msg_t *to_be_destroyed);
+
+int nua_client_response(nua_client_request_t *cr,
+			int status,
+			char const *phrase,
+			sip_t const *sip);
+
+int nua_client_check_restart(nua_client_request_t *cr,
+			     int status,
+			     char const *phrase,
+			     sip_t const *sip);
+
+int nua_base_client_check_restart(nua_client_request_t *cr,
+				  int status,
+				  char const *phrase,
+				  sip_t const *sip);
+
+int nua_client_restart(nua_client_request_t *cr,
+		       int status, char const *phrase);
+
+int nua_base_client_response(nua_client_request_t *cr,
+			     int status, char const *phrase,
+			     sip_t const *sip,
+			     tagi_t const *tags);
+
+int nua_base_client_tresponse(nua_client_request_t *cr,
+			      int status, char const *phrase,
+			      sip_t const *sip,
+			      tag_type_t tag, tag_value_t value, ...);
+
+int nua_client_set_target(nua_client_request_t *cr, url_t const *target);
+
+int nua_client_report(nua_client_request_t *cr,
+		      int status, char const *phrase,
+		      sip_t const *sip,
+		      nta_outgoing_t *orq,
+		      tagi_t const *tags);
+
+nua_client_request_t *nua_client_request_pending(nua_client_request_t const *);
+
+int nua_client_next_request(nua_client_request_t *cr, int invite);
+
+/* ---------------------------------------------------------------------- */
+
+extern nua_server_methods_t const
+  nua_extension_server_methods,
+  nua_invite_server_methods,	/**< INVITE */
+  nua_bye_server_methods,	/**< BYE */
+  nua_options_server_methods,	/**< OPTIONS */
+  nua_register_server_methods,	/**< REGISTER */
+  nua_info_server_methods,	/**< INFO */
+  nua_prack_server_methods,	/**< PRACK */
+  nua_update_server_methods,	/**< UPDATE */
+  nua_message_server_methods,	/**< MESSAGE */
+  nua_subscribe_server_methods, /**< SUBSCRIBE */
+  nua_notify_server_methods,	/**< NOTIFY */
+  nua_refer_server_methods,	/**< REFER */
+  nua_publish_server_methods;	/**< PUBLISH */
+
+/** Return true if we have not sent final response to request */ 
+static inline 
+int nua_server_request_is_pending(nua_server_request_t const *sr)
+{
+  return sr && sr->sr_response.msg;
+}
+
+static inline 
+int nua_server_request_status(nua_server_request_t const *sr)
+{
+  return sr ? nta_incoming_status(sr->sr_irq) : 500;
+}
+
 void nua_server_request_destroy(nua_server_request_t *sr);
 
-int nua_server_respond(nua_server_request_t *sr,
-		       int status, char const *phrase,
-		       tag_type_t tag, tag_value_t value, ...);
+int nua_base_server_init(nua_server_request_t *sr);
 
-msg_t *nua_server_response(nua_server_request_t *sr,
-			   int status, char const *phrase,
-			   tag_type_t tag, tag_value_t value, ...);
+#define nua_base_server_init NULL
+
+int nua_base_server_preprocess(nua_server_request_t *sr);
+
+#define nua_base_server_preprocess NULL
+
+int nua_server_params(nua_server_request_t *sr, tagi_t const *tags);
 
-int nua_default_respond(nua_server_request_t *sr,
-			tagi_t const *tags);
+int nua_base_server_params(nua_server_request_t *sr, tagi_t const *tags);
 
+#define nua_base_server_params NULL
+
+int nua_server_trespond(nua_server_request_t *sr,
+			tag_type_t tag, tag_value_t value, ...);
+int nua_server_respond(nua_server_request_t *sr, tagi_t const *tags);
+
+int nua_base_server_trespond(nua_server_request_t *sr,
+			     tag_type_t tag, tag_value_t value, ...);
+int nua_base_server_respond(nua_server_request_t *sr,
+			    tagi_t const *tags);
+
+int nua_server_report(nua_server_request_t *sr);
+
+int nua_base_server_treport(nua_server_request_t *sr, 
+			    tag_type_t tag, tag_value_t value, ...);
+int nua_base_server_report(nua_server_request_t *sr, tagi_t const *tags);
+
+/* ---------------------------------------------------------------------- */
 
 #endif /* NUA_DIALOG_H */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_event_server.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_event_server.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_event_server.c	Tue Apr 24 10:14:28 2007
@@ -45,9 +45,6 @@
 #include <sofia-sip/sip_status.h>
 #include <sofia-sip/su_tagarg.h>
 
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
-
 #define NEA_SMAGIC_T         struct nua_handle_s
 #define NEA_EMAGIC_T         struct nua_handle_s
 
@@ -121,13 +118,13 @@
     status = 900, phrase = "Error when notifying watchers";
 
   else 
-    nua_stack_event(nua, nh, NULL, e, status = SIP_200_OK, 
-		    SIPTAG_EVENT(event),
-		    SIPTAG_CONTENT_TYPE(ct),
-		    TAG_END());
+    nua_stack_tevent(nua, nh, NULL, e, status = SIP_200_OK, 
+		     SIPTAG_EVENT(event),
+		     SIPTAG_CONTENT_TYPE(ct),
+		     TAG_END());
 	     
   if (status != 200)
-    nua_stack_event(nua, nh, NULL, e, status, phrase, TAG_END());
+    nua_stack_event(nua, nh, NULL, e, status, phrase, NULL);
 
   su_home_deinit(home);
 }
@@ -223,7 +220,7 @@
       what = "active";
     }
 
-    SU_DEBUG_7(("nua(%p): authorize_watcher: %s\n", nh, what)); 
+    SU_DEBUG_7(("nua(%p): authorize_watcher: %s\n", (void *)nh, what)); 
     nea_sub_auth(sn->sn_subscriber, substate,
 		 TAG_IF(substate == nua_substate_pending,
 			NEATAG_FAKE(1)),
@@ -235,13 +232,13 @@
     substate = nua_substate_terminated;
     nea_server_flush(nes, NULL);
     SU_DEBUG_7(("nua(%p): authorize_watcher: %s\n", 
-		nh, "watcher is removed")); 
+		(void *)nh, "watcher is removed")); 
   }
 
-  nua_stack_event(nua, nh, msg, nua_i_subscription, status, phrase,
-	   NUTAG_SUBSTATE(substate),
-	   NEATAG_SUB(sn->sn_subscriber),
-	   TAG_END());
+  nua_stack_tevent(nua, nh, msg, nua_i_subscription, status, phrase,
+		   NUTAG_SUBSTATE(substate),
+		   NEATAG_SUB(sn->sn_subscriber),
+		   TAG_END());
 }
 
 /* ---------------------------------------------------------------------- */
@@ -262,12 +259,11 @@
 
   if (sub && state > 0) {
     nea_sub_auth(sub, state, TAG_NEXT(tags));
-    nua_stack_event(nua, nh, NULL, e, SIP_200_OK, TAG_END());
+    nua_stack_event(nua, nh, NULL, e, SIP_200_OK, NULL);
   }
   else {
-    nua_stack_event(nua, nh, NULL, e, NUA_INTERNAL_ERROR, TAG_END());
+    nua_stack_event(nua, nh, NULL, e, NUA_INTERNAL_ERROR, NULL);
   }
-  return;
 }
 
 /** @internal Shutdown notifier object */
@@ -347,5 +343,5 @@
 		       NEATAG_REASON("noresource"), 
 		       TAG_NEXT(tags));
 
-  nua_stack_event(nua, nh, NULL, e, SIP_200_OK, TAG_END());
+  nua_stack_event(nua, nh, NULL, e, SIP_200_OK, NULL);
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_extension.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_extension.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_extension.c	Tue Apr 24 10:14:28 2007
@@ -43,20 +43,12 @@
 #include <sofia-sip/sip_protos.h>
 #include <sofia-sip/sip_status.h>
 
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
-
 #include "nua_stack.h"
 
-static int process_response_to_method(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip);
-static void restart_method(nua_handle_t *nh, tagi_t *tags);
-static int respond_to_method(nua_server_request_t *sr, tagi_t const *tags);
-
-/** Send an extension request. 
+/**Send a request message with an extension method. 
  *
- * Send an entension request message.
+ * Send a request message with the request method specified with
+ * NUTAG_METHOD().
  *
  * @param nh              Pointer to operation handle
  * @param tag, value, ... List of tagged parameters
@@ -64,6 +56,9 @@
  * @return 
  *    nothing
  *
+ * Note that it is possible to send a request with any method (except
+ * perhaps @b INVITE, @b ACK or @b CANCEL) using this function.
+ *
  * @par Related Tags:
  *    NUTAG_METHOD() \n
  *    NUTAG_URL() \n
@@ -78,32 +73,25 @@
  * @since New in @VERSION_1_12_4.
  */
 
+static nua_client_methods_t const nua_method_client_methods = {
+  SIP_METHOD_UNKNOWN,
+  0,
+  { 
+    /* create_dialog */ 0,
+    /* in_dialog */ 0,
+    /* target_refresh */ 1,
+  },
+  /* nua_method_client_template */ NULL,
+  /* nua_method_client_init */ NULL,
+  /* nua_method_client_request */ NULL,
+  /* nua_method_client_check_restart */ NULL,
+  /* nua_method_client_response */ NULL
+};
+
 int 
 nua_stack_method(nua_t *nua, nua_handle_t *nh, nua_event_t e, tagi_t const *tags)
 { 
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  msg_t *msg;
-
-  if (cr->cr_orq)
-    return UA_EVENT2(e, 900, "Request already in progress");
-
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
-
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
-		     SIP_METHOD_UNKNOWN,
-		     TAG_NEXT(tags));
-  if (msg)
-    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				      process_response_to_method, nh, NULL,
-				      msg,
-				      SIPTAG_END(),
-				      TAG_NEXT(tags));
-  if (!cr->cr_orq) {
-    msg_destroy(msg);
-    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-  }
-
-  return cr->cr_event = e;
+  return nua_client_create(nh, e, &nua_method_client_methods, tags);
 }
 
 /** @NUA_EVENT nua_r_method
@@ -127,20 +115,6 @@
  * @END_NUA_EVENT
  */
 
-static int process_response_to_method(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip)
-{
-  if (nua_creq_check_restart(nh, nh->nh_ds->ds_cr, orq, sip, restart_method))
-    return 0;
-  return nua_stack_process_response(nh, nh->nh_ds->ds_cr, orq, sip, TAG_END());
-}
-
-void restart_method(nua_handle_t *nh, tagi_t *tags)
-{
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_method, tags);
-}
-
 /** @NUA_EVENT nua_i_method
  *
  * @brief Incoming extension request.
@@ -155,50 +129,35 @@
  * @param nh     operation handle associated with the method
  * @param hmagic application context associated with the handle
  *               (maybe NULL if outside session)
- * @param sip    incoming request
+ * @param sip    headers in incoming request (see also nua_current_request())
  * @param tags   NUTAG_METHOD()
  *
- * The extension name is in sip->sip_request->rq_method_name, too.
+ * The extension method name is in sip->sip_request->rq_method_name, too.
+ *
+ * @note If the @a status is < 200, it is up to application to respond to
+ * the request with nua_respond(). If the handle is destroyed, the stack
+ * returns a <i>500 Internal Server Error</i> response to any unresponded
+ * request.
  *
- * @sa nua_method(), #nua_r_method
+ * @sa nua_method(), #nua_r_method, NUTAG_ALLOW(), NUTAG_APPL_METHOD(),
+ * nua_respond(), NUTAG_WITH(), NUTAG_WITH_THIS(), NUTAG_
  *
  * @END_NUA_EVENT
  */
 
-int nua_stack_process_method(nua_t *nua,
-			      nua_handle_t *nh,
-			      nta_incoming_t *irq,
-			      sip_t const *sip)
-{
-  nua_server_request_t *sr, sr0[1];
-  
-  sr = SR_INIT(sr0);
-  
-  sr = nua_server_request(nua, nh, irq, sip, sr, sizeof *sr,
-			  respond_to_method, 0);
-
-  return nua_stack_server_event(nua, sr, nua_i_method, TAG_END());
-}
-
-static
-int respond_to_method(nua_server_request_t *sr, tagi_t const *tags)
-{
-  nua_handle_t *nh = sr->sr_owner;
-  nua_t *nua = nh->nh_nua;
-  msg_t *msg;
-
-  msg = nua_server_response(sr, sr->sr_status, sr->sr_phrase, TAG_NEXT(tags));
-
-  if (msg) {
-    nta_incoming_mreply(sr->sr_irq, msg);
-  }
-  else {
-    SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
-    nta_incoming_treply(sr->sr_irq, sr->sr_status, sr->sr_phrase, TAG_END());
-    nua_stack_event(nua, nh, NULL,
-		    nua_i_error, 900, "Response to Extension Method Fails",
-		    TAG_END());
-  }
-  
-  return sr->sr_status >= 200 ? sr->sr_status : 0;
-}
+nua_server_methods_t const nua_extension_server_methods = 
+  {
+    SIP_METHOD_UNKNOWN,
+    nua_i_method,		/* Event */
+    { 
+      1,			/* Do create dialog */
+      0,			/* Can be an initial request */
+      1,			/* Perhaps a target refresh request? */
+      1,			/* Add a contact? */
+    },
+    nua_base_server_init,
+    nua_base_server_preprocess,
+    nua_base_server_params,
+    nua_base_server_respond,
+    nua_base_server_report,
+  };

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_message.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_message.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_message.c	Tue Apr 24 10:14:28 2007
@@ -43,9 +43,6 @@
 #include <sofia-sip/sip_protos.h>
 #include <sofia-sip/sip_status.h>
 
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
-
 #include "nua_stack.h"
 
 /* ======================================================================== */
@@ -72,48 +69,41 @@
  * @sa #nua_i_message, @RFC3428
  */
 
-static int process_response_to_message(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip);
+static int nua_message_client_init(nua_client_request_t *cr, 
+				   msg_t *, sip_t *,
+				   tagi_t const *tags);
+
+static nua_client_methods_t const nua_message_client_methods = {
+  SIP_METHOD_MESSAGE,
+  0,
+  { 
+    /* create_dialog */ 0,
+    /* in_dialog */ 0,
+    /* target refresh */ 0
+  },
+  /* nua_message_client_template */ NULL,
+  nua_message_client_init,
+  /*nua_message_client_request*/ NULL,
+  /* nua_message_client_check_restart */ NULL,
+  /*nua_message_client_response*/ NULL
+};
 
 int 
-nua_stack_message(nua_t *nua, nua_handle_t *nh, nua_event_t e, tagi_t const *tags)
+nua_stack_message(nua_t *nua,
+		  nua_handle_t *nh,
+		  nua_event_t e,
+		  tagi_t const *tags)
 { 
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  msg_t *msg;
-  sip_t *sip;
-
-  if (nh_is_special(nh)) {
-    return UA_EVENT2(e, 900, "Invalid handle for MESSAGE");
-  }
-  else if (cr->cr_orq) {
-    return UA_EVENT2(e, 900, "Request already in progress");
-  }
-
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
-
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
-			 SIP_METHOD_MESSAGE,
-			 NUTAG_ADD_CONTACT(NH_PGET(nh, win_messenger_enable)),
-			 TAG_NEXT(tags));
-  sip = sip_object(msg);
-
-  if (sip)
-    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				      process_response_to_message, nh, NULL,
-				      msg,
-				      SIPTAG_END(), TAG_NEXT(tags));
-  if (!cr->cr_orq) {
-    msg_destroy(msg);
-    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-  }
-
-  return cr->cr_event = e;
+  return nua_client_create(nh, e, &nua_message_client_methods, tags);
 }
 
-void restart_message(nua_handle_t *nh, tagi_t *tags)
+static int nua_message_client_init(nua_client_request_t *cr, 
+				   msg_t *msg, sip_t *sip,
+				   tagi_t const *tags)
 {
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_message, tags);
+  if (NH_PGET(cr->cr_owner, win_messenger_enable))
+    cr->cr_contactize = 1;
+  return 0;
 }
 
 /** @NUA_EVENT nua_r_message
@@ -137,15 +127,6 @@
  * @END_NUA_EVENT
  */
 
-static int process_response_to_message(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip)
-{
-  if (nua_creq_check_restart(nh, nh->nh_ds->ds_cr, orq, sip, restart_message))
-    return 0;
-  return nua_stack_process_response(nh, nh->nh_ds->ds_cr, orq, sip, TAG_END());
-}
-
 /** @NUA_EVENT nua_i_message
  *
  * @brief Incoming @b MESSAGE request.
@@ -168,32 +149,39 @@
  * @END_NUA_EVENT
  */
 
-int nua_stack_process_message(nua_t *nua,
-			      nua_handle_t *nh,
-			      nta_incoming_t *irq,
-			      sip_t const *sip)
-{
-  msg_t *msg;
-
-  if (nh
-      ? !NH_PGET(nh, message_enable)
-      : !DNH_PGET(nua->nua_dhandle, message_enable))
-    return 403;
+int nua_message_server_init(nua_server_request_t *sr);
+int nua_message_server_params(nua_server_request_t *, tagi_t const *);
 
-  if (nh == NULL)
-    if (!(nh = nua_stack_incoming_handle(nua, irq, sip, 0)))
-      return 500;		/* respond with 500 Internal Server Error */
+nua_server_methods_t const nua_message_server_methods = 
+  {
+    SIP_METHOD_MESSAGE,
+    nua_i_message,		/* Event */
+    { 
+      0,			/* Do not create dialog */
+      0,			/* Can be initial request */
+      0,			/* Perhaps a target refresh request? */
+      0,			/* Do not add contact by default */
+    },
+    nua_message_server_init,
+    nua_base_server_preprocess,
+    nua_message_server_params,
+    nua_base_server_respond,
+    nua_base_server_report,
+  };
 
-  msg = nta_incoming_getrequest(irq);
+int nua_message_server_init(nua_server_request_t *sr)
+{
+  if (!NH_PGET(sr->sr_owner, message_enable))
+    return SR_STATUS1(sr, SIP_403_FORBIDDEN);
 
-  nua_stack_event(nh->nh_nua, nh, msg, nua_i_message, SIP_200_OK, TAG_END());
+  return 0;
+}
 
-#if 0 /* XXX */
-  if (nh->nh_nua->nua_messageRespond) {	
-    nh->nh_irq = irq;
-    return 0;
-  }
-#endif
+int nua_message_server_params(nua_server_request_t *sr,
+			      tagi_t const *tags)
+{
+  if (NH_PGET(sr->sr_owner, win_messenger_enable))
+    sr->sr_add_contact = 1;
 
-  return 200;
+  return 0;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_notifier.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_notifier.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_notifier.c	Tue Apr 24 10:14:28 2007
@@ -44,12 +44,12 @@
 
 #include <sofia-sip/string0.h>
 #include <sofia-sip/sip_protos.h>
+#include <sofia-sip/sip_extra.h>
 #include <sofia-sip/sip_status.h>
 #include <sofia-sip/sip_util.h>
 #include <sofia-sip/su_uniqueid.h>
-
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
+#include <sofia-sip/su_md5.h>
+#include <sofia-sip/token64.h>
 
 #include "nua_stack.h"
 
@@ -59,7 +59,14 @@
 struct notifier_usage
 {
   enum nua_substate  nu_substate;	/**< Subscription state */
-  sip_time_t         nu_expires;
+  sip_time_t         nu_expires; 	/**< Expiration time */
+  sip_time_t         nu_requested;      /**< Requested expiration time */
+#if SU_HAVE_EXPERIMENTAL
+  char              *nu_tag;	        /**< @ETag in last NOTIFY */
+  unsigned           nu_etags:1;	/**< Subscriber supports etags */
+  unsigned           nu_appl_etags:1;   /**< Application generates etags */
+  unsigned           nu_no_body:1;      /**< Suppress body */
+#endif
 };
 
 static char const *nua_notify_usage_name(nua_dialog_usage_t const *du);
@@ -115,8 +122,6 @@
 /* ====================================================================== */
 /* SUBSCRIBE server */
 
-static int respond_to_subscribe(nua_server_request_t *sr, tagi_t const *tags);
-
 /** @NUA_EVENT nua_i_subscribe
  *
  * Incoming @b SUBSCRIBE request.
@@ -130,7 +135,7 @@
  * (or SIPTAG_ALLOW_EVENTS() or SIPTAG_ALLOW_EVENTS_STR()). The application
  * can decide whether to accept the SUBSCRIBE request or reject it. The
  * nua_response() call responding to a SUBSCRIBE request must have
- * NUTAG_WITH() (or NUTAG_WITH_CURRENT()/NUTAG_WITH_SAVED()) tag.
+ * NUTAG_WITH() (or NUTAG_WITH_THIS()/NUTAG_WITH_SAVED()) tag.
  *
  * If the application accepts the SUBSCRIBE request, it must immediately
  * send an initial NOTIFY establishing the dialog. This is because the
@@ -160,152 +165,185 @@
  * @END_NUA_EVENT
  */
 
+static int nua_subscribe_server_init(nua_server_request_t *sr);
+static int nua_subscribe_server_preprocess(nua_server_request_t *sr);
+static int nua_subscribe_server_respond(nua_server_request_t*, tagi_t const *);
+static int nua_subscribe_server_report(nua_server_request_t*, tagi_t const *);
+
+nua_server_methods_t const nua_subscribe_server_methods = 
+  {
+    SIP_METHOD_SUBSCRIBE,
+    nua_i_subscribe,		/* Event */
+    { 
+      1,			/* Create dialog */
+      0,			/* Initial request */
+      1,			/* Target refresh request  */
+      1,			/* Add Contact */
+    },
+    nua_subscribe_server_init,
+    nua_subscribe_server_preprocess,
+    nua_base_server_params,
+    nua_subscribe_server_respond,
+    nua_subscribe_server_report,
+  };
 
-/** @internal Process incoming SUBSCRIBE. */
-int nua_stack_process_subscribe(nua_t *nua,
-				nua_handle_t *nh,
-				nta_incoming_t *irq,
-				sip_t const *sip)
-{
-  nua_server_request_t *sr, sr0[1];
-  nua_dialog_state_t *ds;
-  nua_dialog_usage_t *du = NULL;
+int nua_subscribe_server_init(nua_server_request_t *sr)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_dialog_state_t *ds = nh->nh_ds;
+  sip_allow_events_t const *allow_events = NH_PGET(nh, allow_events);
+  sip_t const *sip = sr->sr_request.sip;
   sip_event_t *o = sip->sip_event;
   char const *event = o ? o->o_type : NULL;
   
-  enum nua_substate substate = nua_substate_terminated;
+  if (sr->sr_initial || !nua_dialog_usage_get(ds, nua_notify_usage, o)) {
+    if (event && str0cmp(event, "refer") == 0)
+      /* refer event subscription should be initiated with REFER */
+      return SR_STATUS1(sr, SIP_403_FORBIDDEN);
 
-  enter;
+    /* XXX - event is case-sensitive, should use msg_header_find_item() */
+    if (!event || !msg_header_find_param(allow_events->k_common, event))
+      return SR_STATUS1(sr, SIP_489_BAD_EVENT);
+  }
+
+  return 0;
+}
 
-  if (nh)
-    du = nua_dialog_usage_get(ds = nh->nh_ds, nua_notify_usage, o);
+int nua_subscribe_server_preprocess(nua_server_request_t *sr)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_dialog_state_t *ds = nh->nh_ds;
+  nua_dialog_usage_t *du;
+  struct notifier_usage *nu;
+  sip_t const *sip = sr->sr_request.sip;
+  sip_event_t *o = sip->sip_event;
+  char const *event = o ? o->o_type : NULL;
+  /* Maximum expiration time */
+  unsigned long expires = 3600;
 
-  sr = SR_INIT(sr0);
+  assert(nh && nh->nh_nua->nua_dhandle != nh);
   
-  if (nh == NULL || du == NULL) {
-    sip_allow_events_t *allow_events = NUA_PGET(nua, nh, allow_events);
+  du = nua_dialog_usage_get(ds, nua_notify_usage, o);
 
-    if (event && str0cmp(event, "refer") == 0)
-      /* refer event subscription should be initiated with REFER */
-      SR_STATUS1(sr, SIP_403_FORBIDDEN);
-    else if (!event || !msg_header_find_param(allow_events->k_common, event))
-      SR_STATUS1(sr, SIP_489_BAD_EVENT);
-    else
-      substate = nua_substate_embryonic;
+  if (du == NULL) {
+    /* Create a new subscription */
+    du = nua_dialog_usage_add(nh, ds, nua_notify_usage, o);
+    if (du == NULL)
+      return SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
   }
   else {
     /* Refresh existing subscription */
-    struct notifier_usage *nu = nua_dialog_usage_private(du);
-    unsigned long expires;
+    if (str0cmp(event, "refer") == 0)
+      expires = NH_PGET(nh, refer_expires);
+
+    SR_STATUS1(sr, SIP_200_OK);
+  }
 
-    assert(nh && du && nu);
+  nu = nua_dialog_usage_private(du);
 
-    expires = str0cmp(event, "refer") ? 3600 : NH_PGET(nh, refer_expires);
+  if (sip->sip_expires && sip->sip_expires->ex_delta < expires)
+    expires = sip->sip_expires->ex_delta;
+  nu->nu_requested = sip_now() + expires;
 
-    if (sip->sip_expires && sip->sip_expires->ex_delta < expires)
-      expires = sip->sip_expires->ex_delta;
+#if SU_HAVE_EXPERIMENTAL
+  nu->nu_etags = 
+    sip_suppress_body_if_match(sip) ||
+    sip_suppress_notify_if_match(sip) ||
+    sip_has_feature(sr->sr_request.sip->sip_supported, "etags");
+#endif
 
-    if (expires == 0)
-      nu->nu_substate = nua_substate_terminated;
+  sr->sr_usage = du;
 
-    nu->nu_expires = sip_now() + expires;
-    substate = nu->nu_substate;
+  return sr->sr_status <= 100 ? 0 : sr->sr_status;
+}
 
-    /* XXX - send notify */
+/** @internal Respond to a SUBSCRIBE request.
+ *
+ */
+static
+int nua_subscribe_server_respond(nua_server_request_t *sr, tagi_t const *tags)
+{
+  struct notifier_usage *nu = nua_dialog_usage_private(sr->sr_usage);
 
-    SR_STATUS1(sr, SIP_200_OK);
-  }
+  msg_t *msg = sr->sr_response.msg;
+  sip_t *sip = sr->sr_response.sip;
 
-  sr = nua_server_request(nua, nh, irq, sip, sr, sizeof *sr,
-			  respond_to_subscribe, 1);
+  if (200 <= sr->sr_status && sr->sr_status < 300) {
+    sip_expires_t ex[1]; 
 
-  if (!du && substate == nua_substate_embryonic && sr->sr_status < 300) {
-    nh = sr->sr_owner; assert(nh && nh != nua->nua_dhandle);
-    du = nua_dialog_usage_add(nh, nh->nh_ds, nua_notify_usage, sip->sip_event);
-    if (du) {
-      struct notifier_usage *nu = nua_dialog_usage_private(du);
-      unsigned long expires = 3600; /* XXX */
-      
-      if (sip->sip_expires && sip->sip_expires->ex_delta < expires)
-	expires = sip->sip_expires->ex_delta;
+    sip_expires_init(ex);
 
-      nu->nu_expires = sip_now() + expires;
-      nu->nu_substate = substate;
-    }
-    else 
-      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
-  }
+    if (nu) {
+      sip_time_t now = sip_now();
 
-  if (substate == nua_substate_embryonic && sr->sr_status >= 300)
-    substate = nua_substate_terminated;
+      if (nu->nu_requested) {
+	if (nu->nu_requested > nu->nu_expires)
+	  nu->nu_expires = nu->nu_requested;
+	else if (nu->nu_expires <= now || nu->nu_requested <= now)
+	  nu->nu_substate = nua_substate_terminated;
+      }
 
-  sr->sr_usage = du;
+      if (nu->nu_expires > now)
+	ex->ex_delta = nu->nu_expires - now;
+    }
+    else {
+      /* Add header Expires: 0 */
+    }
 
-  return nua_stack_server_event(nua, sr, nua_i_subscribe,
-				NUTAG_SUBSTATE(substate), TAG_END());
+    if (!sip->sip_expires || sip->sip_expires->ex_delta > ex->ex_delta)
+      sip_add_dup(msg, sip, (sip_header_t *)ex);
+  }
+
+  return nua_base_server_respond(sr, tags);
 }
 
-/** @internal Respond to an SUBSCRIBE request.
- *
- */
 static
-int respond_to_subscribe(nua_server_request_t *sr, tagi_t const *tags)
+int nua_subscribe_server_report(nua_server_request_t *sr, tagi_t const *tags)
 {
   nua_handle_t *nh = sr->sr_owner;
   nua_dialog_state_t *ds = nh->nh_ds;
-  nua_t *nua = nh->nh_nua;
-  struct notifier_usage *nu;
-  sip_allow_events_t *allow_events = NUA_PGET(nua, nh, allow_events);
-  sip_expires_t ex[1]; 
-  sip_time_t now = sip_now();
-  msg_t *msg;
-
-  sip_expires_init(ex);
+  struct notifier_usage *nu = nua_dialog_usage_private(sr->sr_usage);
+  enum nua_substate substate = nua_substate_terminated;
+  int notify = 0;
+  int retval;
 
-  nu = nua_dialog_usage_private(sr->sr_usage);
-  if (nu && nu->nu_expires > now)
-    ex->ex_delta = nu->nu_expires - now;
+  if (nu && !sr->sr_terminating) {
+    substate = nu->nu_substate;
+  }
 
-  msg = nua_server_response(sr,
-			    sr->sr_status, sr->sr_phrase,
-			    NUTAG_ADD_CONTACT(sr->sr_status < 300),
-			    TAG_IF(nu, SIPTAG_EXPIRES(ex)),
-			    SIPTAG_SUPPORTED(NH_PGET(nh, supported)),
-			    SIPTAG_ALLOW_EVENTS(allow_events),
-			    TAG_NEXT(tags));
-
-  if (msg) {
-    sip_t *sip = sip_object(msg);
-
-    if (nu && sip->sip_expires && sr->sr_status < 300)
-      nu->nu_expires = now + sip->sip_expires->ex_delta;
-
-    nta_incoming_mreply(sr->sr_irq, msg);
-
-    if (nu && nu->nu_substate != nua_substate_embryonic)
-      /* Send NOTIFY (and terminate subscription, when needed) */
-      nua_dialog_usage_refresh(nh, ds, sr->sr_usage, sip_now());
+  /* nu_requested is set by SUBSCRIBE and cleared when NOTIFY is sent */
+  if (nu && nu->nu_requested && substate != nua_substate_embryonic) {
+#if SU_HAVE_EXPERIMENTAL
+    sip_t const *sip = sr->sr_request.sip;
+    sip_suppress_notify_if_match_t *snim = sip_suppress_notify_if_match(sip);
+    sip_suppress_body_if_match_t *sbim = sip_suppress_body_if_match(sip);
+    
+    if (!nu->nu_tag)
+      notify = 1;
+    else if (snim && !strcasecmp(snim->snim_tag, nu->nu_tag))
+      notify = 0;
+    else if (sbim && !strcasecmp(snim->snim_tag, nu->nu_tag))
+      notify = 1, nu->nu_no_body = 1;
+    else 
+#endif
+      notify = 1;
   }
-  else {
-    /* XXX - send nua_i_error */
-    SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
-    nta_incoming_treply(sr->sr_irq, sr->sr_status, sr->sr_phrase, TAG_END());
+
+  retval = nua_base_server_treport(sr, NUTAG_SUBSTATE(substate), TAG_END());
+
+  if (retval >= 2 || nu == NULL)
+    return retval;
+  
+  if (notify) {
+    /* Send NOTIFY (and terminate subscription, when needed) */
+    nua_dialog_usage_refresh(nh, ds, sr->sr_usage, sip_now());
   }
   
-  return sr->sr_status >= 200 ? sr->sr_status : 0;
+  return retval;
 }
 
 /* ======================================================================== */
-/* NOTIFY */
-
-static int process_response_to_notify(nua_handle_t *nh,
-				      nta_outgoing_t *orq,
-				      sip_t const *sip);
-
-static int nua_stack_notify2(nua_t *, nua_handle_t *, nua_event_t, 
-			     nua_dialog_usage_t *du,
-			     tagi_t const *tags);
-
+/* NOTIFY client */
 
 /**@fn void nua_notify(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
  *
@@ -336,175 +374,271 @@
  * @sa @RFC3265, #nua_i_subscribe, #nua_i_refer, NUTAG_ALLOW_EVENTS()
  */
 
+static int nua_notify_client_init(nua_client_request_t *cr, 
+				  msg_t *, sip_t *,
+				  tagi_t const *tags);
+static int nua_notify_client_init_etag(nua_client_request_t *cr,
+				       msg_t *msg, sip_t *sip,
+				       tagi_t const *tags);
+static int nua_notify_client_request(nua_client_request_t *cr,
+				     msg_t *, sip_t *,
+				     tagi_t const *tags);
+static int nua_notify_client_report(nua_client_request_t *cr,
+				    int status, char const *phrase,
+				    sip_t const *sip,
+				    nta_outgoing_t *orq,
+				    tagi_t const *tags);
+
+static nua_client_methods_t const nua_notify_client_methods = {
+  SIP_METHOD_NOTIFY,
+  0,
+  { 
+    /* create_dialog */ 1,
+    /* in_dialog */ 1,
+    /* target refresh */ 1
+  },
+  /* nua_notify_client_template */ NULL,
+  nua_notify_client_init,
+  nua_notify_client_request,
+  /* nua_notify_client_check_restart */ NULL,
+  /* nua_notify_client_response */ NULL,
+  /* nua_notify_client_preliminary */ NULL,
+  nua_notify_client_report
+};
+
 /**@internal Send NOTIFY. */
 int nua_stack_notify(nua_t *nua,
 		     nua_handle_t *nh,
 		     nua_event_t e,
 		     tagi_t const *tags)
 {
-  return nua_stack_notify2(nua, nh, e, NULL, tags);
+  return nua_client_create(nh, e, &nua_notify_client_methods, tags);
 }
 
-
-int nua_stack_notify2(nua_t *nua,
-		      nua_handle_t *nh,
-		      nua_event_t e,
-		      nua_dialog_usage_t *du,
-		      tagi_t const *tags)
+static int nua_notify_client_init(nua_client_request_t *cr,
+				  msg_t *msg, sip_t *sip,
+				  tagi_t const *tags)
 {
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du;
   struct notifier_usage *nu;
-  msg_t *msg;
-  sip_t *sip;
-  sip_event_t const *o;
-  sip_time_t now;
-  int refresh = du != NULL;
-
-  if (cr->cr_orq) {
-    return UA_EVENT2(e, 900, "Request already in progress");
-  }
-
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
-
-  if (refresh) {
-    assert(!cr->cr_msg);
-    if (cr->cr_msg)
-      msg_destroy(cr->cr_msg);
-    cr->cr_msg = msg_copy(du->du_msg);
-  }
-
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count || refresh,
-		     SIP_METHOD_NOTIFY,
-		     NUTAG_ADD_CONTACT(1),
-		     TAG_NEXT(tags));
-  sip = sip_object(msg);
-  if (!sip)
-    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-
-  if (nh->nh_ds->ds_has_notifys == 1 && !sip->sip_event)
+  sip_event_t const *o = sip->sip_event;
+  sip_subscription_state_t *ss = sip->sip_subscription_state;
+  sip_time_t now = sip_now();
+    
+  if (o == NULL && nh->nh_ds->ds_has_notifys == 1)
     o = NONE;
-  else
-    o = sip->sip_event;
 
   du = nua_dialog_usage_get(nh->nh_ds, nua_notify_usage, o);
-  nu = nua_dialog_usage_private(du);
 
-  if (du && du->du_event && !sip->sip_event)
-    sip_add_dup(msg, sip, (sip_header_t *)du->du_event);
+  if (!du) {
+    tagi_t const *newsub = tl_find_last(tags, nutag_newsub);
 
-  now = sip_now();
+    if (!newsub || !newsub->t_value)
+      return 0; /* Rejected eventually by nua_notify_client_request() */
 
-  if (!du)
-    ;
-  else if (sip->sip_subscription_state) {
-    /* SIPTAG_SUBSCRIPTION_STATE() overrides NUTAG_SUBSTATE() */
-    char const *ss_substate = sip->sip_subscription_state->ss_substate;
+    /* Create new notifier */
+    du = nua_dialog_usage_add(nh, nh->nh_ds, nua_notify_usage, o);
+    if (du == NULL)
+      return -1;
 
-    if (strcasecmp(ss_substate, "terminated") == 0)
-      nu->nu_substate = nua_substate_terminated;
-    else if (strcasecmp(ss_substate, "pending") == 0)
-      nu->nu_substate = nua_substate_pending;
-    else /* if (strcasecmp(subs->ss_substate, "active") == 0) */ 
-      nu->nu_substate = nua_substate_active;
+    nu = nua_dialog_usage_private(du);
+    nu->nu_expires = now;
+  }
+  else
+    nu = nua_dialog_usage_private(du);
 
-    if (sip->sip_subscription_state->ss_expires) {
-      unsigned long expires;
-      expires = strtoul(sip->sip_subscription_state->ss_expires, NULL, 10);
-      if (expires > 3600)
-        expires = 3600;
-      nu->nu_expires = now + expires;
-    }
-    else if (nu->nu_substate != nua_substate_terminated) {
-      sip_subscription_state_t *ss = sip->sip_subscription_state;
-      char *param;
-
-      if (now < nu->nu_expires)
-        param = su_sprintf(msg_home(msg), "expires=%lu", nu->nu_expires - now);
-      else
-        param = "expires=0";
 
-      msg_header_add_param(msg_home(msg), ss->ss_common, param);
+  if (nu->nu_substate == nua_substate_terminated) {
+    /*Xyzzy*/;
+  }
+  else if (ss != NULL) {
+    /* SIPTAG_SUBSCRIPTION_STATE() overrides NUTAG_SUBSTATE() */
+    nu->nu_substate = nua_substate_make(ss->ss_substate);
+
+    if (ss->ss_expires) {
+      unsigned long expires = strtoul(ss->ss_expires, NULL, 10);
+      if (now + expires < now)
+	expires = SIP_TIME_MAX - now - 1;
+
+      /* Notifier can only shorten the subscription time */ 
+      if (nu->nu_requested == 0 || nu->nu_requested >= now + expires)
+	nu->nu_expires = nu->nu_requested = now + expires;
     }
   }
   else {
-    sip_subscription_state_t *ss;
-    enum nua_substate substate;
-    char const *name;
-
-    substate = nu->nu_substate;
-
-    if (nu->nu_expires <= now)
-      substate = nua_substate_terminated;
+    enum nua_substate substate = nu->nu_substate;
 
-    if (substate != nua_substate_terminated) {
+    if (nu->nu_expires > now) {
       tagi_t const *t = tl_find_last(tags, nutag_substate);
       if (t)
-	substate = (enum nua_substate)t->t_value;
+        substate = (enum nua_substate)t->t_value;
     }
+    else
+      substate = nua_substate_terminated;
 
     switch (substate) {
     case nua_substate_embryonic:
       /*FALLTHROUGH*/
     case nua_substate_pending:
-      name = "pending";
       nu->nu_substate = nua_substate_pending;
       break;
     case nua_substate_active:
     default:
-      name = "active";
       nu->nu_substate = nua_substate_active;
       break;
     case nua_substate_terminated:
-      name = "terminated";
       nu->nu_substate = nua_substate_terminated;
       break;
     }
+  }
 
-    if (nu->nu_substate != nua_substate_terminated) {
-      unsigned long expires = nu->nu_expires - now;
-      ss = sip_subscription_state_format(msg_home(msg), "%s;expires=%lu",
-					 name, expires);
-    }
-    else {
-      ss = sip_subscription_state_make(msg_home(msg), "terminated; "
-				       "reason=noresource");
-    }
+  if (nu->nu_substate == nua_substate_terminated)
+    cr->cr_terminating = 1;
 
-    msg_header_insert(msg, (void *)sip, (void *)ss);
-  }
+  cr->cr_usage = du;
 
-  if (du) {
-    if (nu->nu_substate == nua_substate_terminated)
-      du->du_terminating = 1;
+  return nua_notify_client_init_etag(cr, msg, sip, tags);
+}
 
-    if (!du->du_terminating && !refresh) {
-      /* Save template */
-      if (du->du_msg)
-        msg_destroy(du->du_msg);
-      du->du_msg = msg_ref_create(cr->cr_msg);
-    }
+static int nua_notify_client_init_etag(nua_client_request_t *cr,
+				       msg_t *msg, sip_t *sip,
+				       tagi_t const *tags)
+{
+#if SU_HAVE_EXPERIMENTAL
+  nua_handle_t *nh = cr->cr_owner;
+  struct notifier_usage *nu = nua_dialog_usage_private(cr->cr_usage);
+  nua_server_request_t *sr;
+
+  if (nu->nu_tag)
+    su_free(nh->nh_home, nu->nu_tag), nu->nu_tag = NULL;
+    nu->nu_no_body = 0;
+
+  if (sip->sip_etag) {
+    nu->nu_appl_etags = 1;
+    nu->nu_tag = su_strdup(nh->nh_home, sip->sip_etag->g_string);
   }
+  else if (!nu->nu_appl_etags && nu->nu_etags) {
+    su_md5_t md5[1];
+    unsigned char digest[SU_MD5_DIGEST_SIZE];
+    sip_payload_t pl[1] = { SIP_PAYLOAD_INIT() };
+    char token[2 * 16];
+
+    su_md5_init(md5);
+
+    if (sip->sip_payload) *pl = *sip->sip_payload;
+
+    if (pl->pl_len)
+      su_md5_update(md5, pl->pl_data, pl->pl_len);
+    su_md5_update(md5, &pl->pl_len, sizeof(pl->pl_len));
+
+    if (sip->sip_content_type)
+      su_md5_striupdate(md5, sip->sip_content_type->c_type);
 
-  /* NOTIFY outside a dialog */
-  cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				    process_response_to_notify, nh, NULL,
-				    msg,
-				    SIPTAG_END(), TAG_NEXT(tags));
-
-  if (!cr->cr_orq) {
-    msg_destroy(msg);
-    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
+    su_md5_digest(md5, digest);
+    token64_e(token, sizeof token, digest, sizeof digest);
+    token[(sizeof token) - 1] = '\0';
+    nu->nu_tag = su_strdup(nh->nh_home, token);
   }
 
-  cr->cr_usage = du;
+  if (!nu->nu_requested || !nu->nu_tag)
+    return 0;
+
+  /* Check if SUBSCRIBE had matching suppression */
+  for (sr = nh->nh_ds->ds_sr; sr; sr = sr->sr_next)
+    if (sr->sr_usage == cr->cr_usage && sr->sr_method == sip_method_subscribe)
+      break;
+
+  if (sr) {
+    sip_t const *sip = sr->sr_request.sip;
+
+    sip_suppress_body_if_match_t *sbim;
+    sip_suppress_notify_if_match_t *snim;
+    
+    if (cr->cr_usage->du_ready) {
+      snim = sip_suppress_notify_if_match(sip);
+
+      if (snim && !strcasecmp(snim->snim_tag, nu->nu_tag)) {
+	if (nu->nu_requested > nu->nu_expires)
+	  nu->nu_expires = nu->nu_requested;
+	nu->nu_requested = 0;
+	return nua_client_return(cr, 202, "NOTIFY Suppressed", msg);
+      }
+    }
 
-  return cr->cr_event = e;
+    sbim = sip_suppress_body_if_match(sip);
+    if (sbim && !strcasecmp(sbim->sbim_tag, nu->nu_tag))
+      nu->nu_no_body = 1;
+  }
+#endif
+
+  return 0;
 }
 
 static
-void restart_notify(nua_handle_t *nh, tagi_t *tags)
+int nua_notify_client_request(nua_client_request_t *cr,
+			      msg_t *msg, sip_t *sip,
+			      tagi_t const *tags)
 {
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_notify, tags);
+  nua_dialog_usage_t *du = cr->cr_usage; 
+  struct notifier_usage *nu = nua_dialog_usage_private(du);
+  su_home_t *home = msg_home(msg);
+  sip_time_t now = sip_now();
+  sip_subscription_state_t *ss = sip->sip_subscription_state;
+  char const *expires;
+
+  if (du == NULL)		/* Subscription has been terminated */
+    return nua_client_return(cr, SIP_481_NO_TRANSACTION, msg);
+
+  assert(du && nu);
+
+  if (du && nua_client_bind(cr, du) < 0)
+    return -1;
+
+  if (nu->nu_requested)
+    nu->nu_expires = nu->nu_requested;
+  nu->nu_requested = 0;
+
+  if (nu->nu_expires <= now || du->du_shutdown) {
+    nu->nu_substate = nua_substate_terminated;
+    expires = "expires=0";
+  }
+  else {
+    expires = su_sprintf(home, "expires=%lu", nu->nu_expires - now);
+  }
+
+  if (ss == NULL || nua_substate_make(ss->ss_substate) != nu->nu_substate) {
+    if (nu->nu_substate == nua_substate_terminated)
+      expires = nu->nu_expires > now ? "noresource" : "timeout";
+
+    ss = sip_subscription_state_format(home, "%s;%s", 
+				       nua_substate_name(nu->nu_substate),
+				       expires);
+
+    msg_header_insert(msg, (void *)sip, (void *)ss);
+  }
+  else if (nu->nu_substate != nua_substate_terminated) {
+    msg_header_replace_param(home, ss->ss_common, expires);
+  }
+
+#if SU_HAVE_EXPERIMENTAL
+  if (nu->nu_tag && !sip->sip_etag)
+    msg_header_add_make(msg, (void *)sip, sip_etag_class, nu->nu_tag);
+
+  if (nu->nu_no_body) {
+    nu->nu_no_body = 0;
+    msg_header_remove(msg, (void *)sip, (void *)sip->sip_payload);
+    msg_header_remove(msg, (void *)sip, (void *)sip->sip_content_length);
+  }
+#endif
+
+  if (nu->nu_substate == nua_substate_terminated)
+    cr->cr_terminating = 1;
+
+  if (du->du_event && !sip->sip_event)
+    sip_add_dup(cr->cr_msg, sip, (sip_header_t *)du->du_event);
+
+  return nua_base_client_request(cr, msg, sip, tags);
 }
 
 /** @NUA_EVENT nua_r_notify
@@ -527,30 +661,46 @@
  *               (status code is in @a status and 
  *               descriptive message in @a phrase parameters)
  * @param tags   NUTAG_SUBSTATE() indicating subscription state
+ *               SIPTAG_EVENT() indicating subscription event
  *
  * @sa nua_notify(), @RFC3265, #nua_i_subscribe, #nua_i_refer
  *
  * @END_NUA_EVENT
  */
 
-static int process_response_to_notify(nua_handle_t *nh,
-				      nta_outgoing_t *orq,
-				      sip_t const *sip)
+static int nua_notify_client_report(nua_client_request_t *cr,
+				    int status, char const *phrase,
+				    sip_t const *sip,
+				    nta_outgoing_t *orq,
+				    tagi_t const *tags)
 {
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  struct notifier_usage *nu = nua_dialog_usage_private(du);
   enum nua_substate substate = nua_substate_terminated;
 
-  if (nua_creq_check_restart(nh, nh->nh_ds->ds_cr, orq, sip, restart_notify))
-    return 0;
-
-  if (nh->nh_ds->ds_cr->cr_usage) {
-    struct notifier_usage *nu = nua_dialog_usage_private(nh->nh_ds->ds_cr->cr_usage);
+  if (nu && !cr->cr_terminated)
     substate = nu->nu_substate;
-    assert(substate != nua_substate_embryonic);
+
+  nua_stack_tevent(nh->nh_nua, nh, 
+		   nta_outgoing_getresponse(orq),
+		   cr->cr_event,
+		   status, phrase,
+		   NUTAG_SUBSTATE(substate),
+		   SIPTAG_EVENT(du ? du->du_event : NULL),
+		   TAG_NEXT(tags));
+
+  if (du && du->du_cr == cr && !cr->cr_terminated) {
+    if (nu->nu_requested) {
+      /* Re-SUBSCRIBEd while NOTIFY was in progress, resend NOTIFY */
+      nua_client_resend_request(cr, 0);
+    }
+    else if (nu->nu_expires) {
+      nua_dialog_usage_refresh_at(du, nu->nu_expires);
+    }
   }
 
-  return nua_stack_process_response(nh, nh->nh_ds->ds_cr, orq, sip, 
-				    NUTAG_SUBSTATE(substate),
-				    TAG_END());
+  return 0;
 }
 
 
@@ -560,29 +710,30 @@
 				     sip_time_t now)
 {
   struct notifier_usage *nu = nua_dialog_usage_private(du);
+  nua_client_request_t *cr = du->du_cr;
+  nua_event_t e = nua_r_notify;
 
-  if (nh->nh_ds->ds_cr->cr_usage == du) /* Already notifying. */
-    return;
+  if (cr) {
+    int terminating = 0;
 
-  if (now >= nu->nu_expires) {
-    sip_subscription_state_t ss[1];
-    char const *params[] = { NULL, NULL };
-    tagi_t tags[2] = {
-      { SIPTAG_SUBSCRIPTION_STATE(ss) }, { TAG_END() }
-    };
-
-    sip_subscription_state_init(ss);
-
-    ss->ss_substate = "terminated";
-    ss->ss_params = params;
-    params[0] = "reason=timeout";
-    ss->ss_reason = "timeout";
+    if (nu->nu_expires && nu->nu_expires <= now)
+      terminating = 1;
+    else if (nu->nu_requested && nu->nu_requested <= now)
+      terminating = 1;
 
-    nua_stack_notify2(nh->nh_nua, nh, nua_r_notify, du, tags);
+    if (nua_client_resend_request(cr, terminating) >= 0)
+      return;
   }
   else {
-    nua_stack_notify2(nh->nh_nua, nh, nua_r_notify, du, NULL);
+    if (nua_client_create(nh, e, &nua_notify_client_methods, NULL) >= 0)
+      return;
   }
+
+  nua_stack_tevent(nh->nh_nua, nh, NULL, e, NUA_INTERNAL_ERROR,
+		   NUTAG_SUBSTATE(nua_substate_terminated),
+		   TAG_END());
+
+  nua_dialog_usage_remove(nh, ds, du);
 }
 
 /** @interal Shut down NOTIFY usage. 
@@ -595,26 +746,110 @@
 				     nua_dialog_state_t *ds,
 				     nua_dialog_usage_t *du)
 {
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
+  struct notifier_usage *nu = nua_dialog_usage_private(du);
+  nua_client_request_t *cr = du->du_cr;
 
-  if (!cr->cr_usage) {
-    /* Unnotify */
-	/* Commenting this line out to supress an attended transfer bug (awaiting fix from pessi) */
-    //nua_stack_notify2(nh->nh_nua, nh, nua_r_destroy, du, NULL);
-    return cr->cr_usage != du;
-  }
+  nu->nu_substate = nua_substate_terminated;
 
-  if (!du->du_ready && !cr->cr_orq)
-    return 1;			/* Unauthenticated NOTIFY? */
+  if (cr) {
+    if (nua_client_resend_request(cr, 1) >= 0)
+      return 0;
+  }
+  else {
+    if (nua_client_create(nh, nua_r_notify, 
+			  &nua_notify_client_methods, NULL) >= 0)
+      return 0;
+  }
 
-  return -1;  /* Request in progress */
+  nua_dialog_usage_remove(nh, ds, du);
+  return 200;
 }
 
-
 /* ======================================================================== */
 /* REFER */
 /* RFC 3515 */
 
+static int nua_refer_server_init(nua_server_request_t *sr);
+static int nua_refer_server_preprocess(nua_server_request_t *sr);
+static int nua_refer_server_respond(nua_server_request_t*, tagi_t const *);
+static int nua_refer_server_report(nua_server_request_t*, tagi_t const *);
+
+nua_server_methods_t const nua_refer_server_methods = 
+  {
+    SIP_METHOD_REFER,
+    nua_i_refer,		/* Event */
+    { 
+      1,			/* Create dialog */
+      0,			/* Initial request */
+      1,			/* Target refresh request  */
+      1,			/* Add Contact */
+    },
+    nua_refer_server_init,
+    nua_refer_server_preprocess,
+    nua_base_server_params,
+    nua_refer_server_respond,
+    nua_refer_server_report,
+  };
+
+static int nua_refer_server_init(nua_server_request_t *sr)
+{
+  return 0;
+}
+
+static int nua_refer_server_preprocess(nua_server_request_t *sr)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  sip_t const *sip = sr->sr_request.sip;
+  struct notifier_usage *nu;
+  sip_event_t *o;
+
+  if (nh->nh_ds->ds_got_referrals || NH_PGET(nh, refer_with_id))
+    o = sip_event_format(nh->nh_home, "refer;id=%u", sip->sip_cseq->cs_seq);
+  else
+    o = sip_event_make(nh->nh_home, "refer");
+
+  if (o) {
+    sr->sr_usage = nua_dialog_usage_add(nh, nh->nh_ds, nua_notify_usage, o);
+    msg_header_free(nh->nh_home, (msg_header_t *)o);
+  }
+
+  if (!sr->sr_usage)
+    return SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+
+  nu = nua_dialog_usage_private(sr->sr_usage);
+  nu->nu_requested = sip_now() + NH_PGET(nh, refer_expires);
+
+  return 0;
+}
+
+static
+int nua_refer_server_respond(nua_server_request_t *sr, tagi_t const *tags)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  struct notifier_usage *nu = nua_dialog_usage_private(sr->sr_usage);
+  sip_refer_sub_t const *rs = sip_refer_sub(sr->sr_response.sip);
+
+  if (sr->sr_status < 200 || nu == NULL) {
+  }
+  else if (sr->sr_status < 300 && 
+	   /* Application included Refer-Sub: false in response */
+	   (rs == NULL || str0casecmp("false", rs->rs_value))) {
+    sr->sr_usage->du_ready = 1;
+
+    nu->nu_expires = sip_now() + NH_PGET(nh, refer_expires);
+
+    if (sr->sr_application)	/* Application responded to REFER */
+      nu->nu_substate = nua_substate_active;
+  }
+  else {
+    /* Destroy the implicit subscription usage */
+    sr->sr_terminating = 1;
+  }
+
+  return nua_base_server_respond(sr, tags);
+}
+
+
 /** @NUA_EVENT nua_i_refer
  *
  * Incoming @b REFER request used to transfer calls.
@@ -635,89 +870,45 @@
  * @END_NUA_EVENT
  */
 
-/** @internal Process incoming REFER. */
-int nua_stack_process_refer(nua_t *nua,
-			    nua_handle_t *nh,
-			    nta_incoming_t *irq,
-			    sip_t const *sip)
+static
+int nua_refer_server_report(nua_server_request_t *sr, tagi_t const *tags)
 {
-  nua_dialog_usage_t *du = NULL;
-  struct notifier_usage *nu;
-  sip_event_t *event;
-  sip_referred_by_t *by = NULL, default_by[1];
-  msg_t *response;
-  sip_time_t expires;
-  int created = 0;
-
-  if (nh == NULL) {
-    if (!(nh = nua_stack_incoming_handle(nua, irq, sip, 1)))
-      return 500;
-    created = 1;
-  }
-
-  if (nh->nh_ds->ds_has_referrals || NH_PGET(nh, refer_with_id))
-    event = sip_event_format(nh->nh_home, "refer;id=%u", sip->sip_cseq->cs_seq);
-  else
-    event = sip_event_make(nh->nh_home, "refer");
-
-  if (event)
-    du = nua_dialog_usage_add(nh, nh->nh_ds, nua_notify_usage, event);
+  nua_handle_t *nh = sr->sr_owner;
+  struct notifier_usage *nu = nua_dialog_usage_private(sr->sr_usage);
+  sip_t const *sip = sr->sr_request.sip;
+  sip_referred_by_t *by = sip->sip_referred_by, default_by[1];
+  sip_event_t const *o = sr->sr_usage->du_event;
+  enum nua_substate substate = nua_substate_terminated;
+  int initial = sr->sr_initial, retval;
 
-  if (!du || du->du_ready) {
-    if (du->du_ready) {
-      SU_DEBUG_1(("nua(%p): REFER with existing refer;id=%u\n", nh,
-		  sip->sip_cseq->cs_seq));
-    }
-    if (created) 
-      nh_destroy(nua, nh);
-    return 500;
+  if (nu) {
+    if (!sr->sr_terminating)
+      substate = nu->nu_substate;
   }
 
-  nu = nua_dialog_usage_private(du);
-  du->du_ready = 1;
-  nh->nh_ds->ds_has_referrals = 1;
-
-  nua_dialog_uas_route(nh, nh->nh_ds, sip, 1);	/* Set route and tags */
-
-  if (!sip->sip_referred_by) {
-    sip_from_t *a = sip->sip_from;
-
-    sip_referred_by_init(by = default_by);
+  if (by == NULL) {
+     by = sip_referred_by_init(default_by);
 
-    *by->b_url = *a->a_url;
-    by->b_display = a->a_display;
+    by->b_display = sip->sip_from->a_display;
+    *by->b_url = *sip->sip_from->a_url;
   }
 
-  response = nh_make_response(nua, nh, irq, 
-			      SIP_202_ACCEPTED, 
-			      NUTAG_ADD_CONTACT(1),
-			      TAG_END());
+  retval = nua_base_server_treport(sr,
+				   NUTAG_SUBSTATE(substate),
+				   NUTAG_REFER_EVENT(o),
+				   TAG_IF(by, SIPTAG_REFERRED_BY(by)),
+				   TAG_END());
 
-  nta_incoming_mreply(irq, response);
+  if (retval >= 2 || nu == NULL)
+    return retval;
 
-  expires = NH_PGET(nh, refer_expires);
-
-  if (sip->sip_expires && sip->sip_expires->ex_delta < expires)
-    expires = sip->sip_expires->ex_delta;
-  nu->nu_substate = nua_substate_pending;
-  nu->nu_expires = sip_now() + expires;
-
-  /* Immediate notify in order to establish the dialog */
-  if (!sip->sip_to->a_tag)
+  if (initial)
     nua_stack_post_signal(nh,
 			  nua_r_notify,
-			  SIPTAG_EVENT(event),
+			  SIPTAG_EVENT(o),
 			  SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
 			  SIPTAG_PAYLOAD_STR("SIP/2.0 100 Trying\r\n"),
 			  TAG_END());
-  
-  nua_stack_event(nh->nh_nua, nh, nta_incoming_getrequest(irq),
-		  nua_i_refer, SIP_202_ACCEPTED, 
-		  NUTAG_REFER_EVENT(event),
-		  TAG_IF(by, SIPTAG_REFERRED_BY(by)),
-		  TAG_END());
-  
-  su_free(nh->nh_home, event);
 
-  return 500;   
+  return retval;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_options.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_options.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_options.c	Tue Apr 24 10:14:28 2007
@@ -45,9 +45,6 @@
 #include <sofia-sip/sip_protos.h>
 #include <sofia-sip/sip_status.h>
 
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
-
 #include "nua_stack.h"
 
 /**@fn void nua_options(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
@@ -69,46 +66,6 @@
  * @sa #nua_i_options, @RFC3261 section 10
  */
 
-static int process_response_to_options(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip);
-
-int
-nua_stack_options(nua_t *nua, nua_handle_t *nh, nua_event_t e, tagi_t const *tags)
-{
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  msg_t *msg;
-
-  if (nh_is_special(nh)) {
-    return UA_EVENT2(e, 900, "Invalid handle for OPTIONS");
-  }
-  else if (cr->cr_orq) {
-    return UA_EVENT2(e, 900, "Request already in progress");
-  }
-
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
-
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
-			 SIP_METHOD_OPTIONS, 
-			 TAG_NEXT(tags));
-
-  cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				    process_response_to_options, nh, NULL,
-				    msg,
-				    SIPTAG_END(), TAG_NEXT(tags));
-  if (!cr->cr_orq) {
-    msg_destroy(msg);
-    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-  }
-
-  return cr->cr_event = e;
-}
-
-void restart_options(nua_handle_t *nh, tagi_t *tags)
-{
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_options, tags);
-}
-
 /** @NUA_EVENT nua_r_options
  *
  * Answer to outgoing OPTIONS.
@@ -130,11 +87,25 @@
  * @END_NUA_EVENT
  */
 
-static int process_response_to_options(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip)
-{
-  if (nua_creq_check_restart(nh, nh->nh_ds->ds_cr, orq, sip, restart_options))
-    return 0;
-  return nua_stack_process_response(nh, nh->nh_ds->ds_cr, orq, sip, TAG_END());
+static nua_client_methods_t const nua_options_client_methods = {
+  SIP_METHOD_OPTIONS,
+  0,
+  { 
+    /* create_dialog */ 0,
+    /* in_dialog */ 0,
+    /* target refresh */ 0
+  },
+  /*nua_options_client_template*/ NULL,
+  /*nua_options_client_init*/ NULL,
+  /*nua_options_client_request*/ NULL,
+  /* nua_options_client_check_restart */ NULL,
+  /*nua_options_client_response*/ NULL
+};
+
+int nua_stack_options(nua_t *nua,
+		      nua_handle_t *nh,
+		      nua_event_t e,
+		      tagi_t const *tags)
+{ 
+  return nua_client_create(nh, e, &nua_options_client_methods, tags);
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_params.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_params.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_params.c	Tue Apr 24 10:14:28 2007
@@ -149,9 +149,10 @@
   NHP_SET(nhp, auto_ack, 1);
   NHP_SET(nhp, invite_timeout, 120);
 
-  NHP_SET(nhp, session_timer, 1800);
+  nhp->nhp_session_timer = 1800;
+  nhp->nhp_refresher = nua_no_refresher;
+
   NHP_SET(nhp, min_se, 120);
-  NHP_SET(nhp, refresher, nua_no_refresher);
   NHP_SET(nhp, update_refresh, 0);
 
   NHP_SET(nhp, message_enable, 1);
@@ -393,6 +394,7 @@
  *   NUTAG_ALLOW(), SIPTAG_ALLOW(), and SIPTAG_ALLOW_STR() \n
  *   NUTAG_ALLOW_EVENTS(), SIPTAG_ALLOW_EVENTS(), and 
  *                         SIPTAG_ALLOW_EVENTS_STR() \n
+ *   NUTAG_AUTH_CACHE() \n
  *   NUTAG_AUTOACK() \n
  *   NUTAG_AUTOALERT() \n
  *   NUTAG_AUTOANSWER() \n
@@ -762,12 +764,6 @@
     else if (tag == nutag_enablemessenger) {
       NHP_SET(nhp, win_messenger_enable, value != 0);
     }
-#if 0
-    /* NUTAG_AUTORESPOND(autorespond) */
-    else if (tag == nutag_autorespond) {
-      NHP_SET(nhp, autorespond, value);
-    }
-#endif
     /* NUTAG_CALLEE_CAPS(callee_caps) */
     else if (tag == nutag_callee_caps) {
       NHP_SET(nhp, callee_caps, value != 0);
@@ -784,6 +780,11 @@
     else if (tag == nutag_path_enable) {
       NHP_SET(nhp, path_enable, value != 0);
     }
+    /* NUTAG_AUTH_CACHE(auth_cache) */
+    else if (tag == nutag_auth_cache) {
+      if (value >= 0 && value < (tag_value_t)_nua_auth_cache_invalid)
+	NHP_SET(nhp, auth_cache, (int)value);
+    }
     /* NUTAG_REFER_EXPIRES(refer_expires) */
     else if (tag == nutag_refer_expires) {
       NHP_SET(nhp, refer_expires, value);
@@ -882,7 +883,8 @@
 			     sip_allow_class,
 			     &appl_method,
 			     (msg_list_t const *)nhp->nhp_appl_method,
-			     NHP_ISSET(nhp, allow), /* already set by tags */
+			     /* already set by tags? */
+			     NHP_ISSET(nhp, appl_method), 
 			     0, /* dup it, don't make */
 			     1, /* merge with old value */
 			     t->t_value);
@@ -1171,10 +1173,10 @@
 
   nh->nh_tags = 
     tl_filtered_tlist(nh->nh_home, tagfilter,
-		      SIPTAG_FROM(p_from),
-		      TAG_FILTER(nua_handle_tags_filter),
-		      SIPTAG_TO(p_to),
-		      TAG_FILTER(nua_handle_tags_filter),
+		      TAG_IF(p_from != SIP_NONE, SIPTAG_FROM(p_from)),
+		      TAG_IF(p_from != SIP_NONE, TAG_FILTER(nua_handle_tags_filter)),
+		      TAG_IF(p_to != SIP_NONE, SIPTAG_TO(p_to)),
+		      TAG_IF(p_to != SIP_NONE, TAG_FILTER(nua_handle_tags_filter)),
 		      TAG_NEXT(tags));
 
   nh->nh_ptags = 
@@ -1366,7 +1368,9 @@
  *               application contact associated with the operation handle 
  *               when responding to nua_get_hparams()
  * @param sip    NULL
- * @param tags   
+ * @param tags
+ *   NUTAG_APPL_METHOD() \n
+ *   NUTAG_AUTH_CACHE() \n
  *   NUTAG_AUTOACK() \n
  *   NUTAG_AUTOALERT() \n
  *   NUTAG_AUTOANSWER() \n
@@ -1500,6 +1504,11 @@
 #define TIF(TAG, pref) \
   TAG_IF(nhp->nhp_set.nhb_##pref, TAG(nhp->nhp_##pref))
 
+  /* Include tag in the list returned to user
+   * if it has been earlier set (by user) returning default parameters */
+#define TIFD(TAG, pref) \
+  TAG_IF(nh == dnh || nhp->nhp_set.nhb_##pref, TAG(nhp->nhp_##pref))
+
   /* Include string tag made out of SIP header
    * if it has been earlier set (by user) */
 #define TIF_STR(TAG, pref)						\
@@ -1537,9 +1546,9 @@
      TIF(NUTAG_AUTOACK, auto_ack),
      TIF(NUTAG_INVITE_TIMER, invite_timeout),
 
-     TIF(NUTAG_SESSION_TIMER, session_timer),
+     TIFD(NUTAG_SESSION_TIMER, session_timer),
      TIF(NUTAG_MIN_SE, min_se),
-     TIF(NUTAG_SESSION_REFRESHER, refresher),
+     TIFD(NUTAG_SESSION_REFRESHER, refresher),
      TIF(NUTAG_UPDATE_REFRESH, update_refresh),
 
      TIF(NUTAG_ENABLEMESSAGE, message_enable),
@@ -1550,6 +1559,7 @@
      TIF(NUTAG_MEDIA_FEATURES, media_features),
      TIF(NUTAG_SERVICE_ROUTE_ENABLE, service_route_enable),
      TIF(NUTAG_PATH_ENABLE, path_enable),
+     TIF(NUTAG_AUTH_CACHE, auth_cache),
      TIF(NUTAG_REFER_EXPIRES, refer_expires),
      TIF(NUTAG_REFER_WITH_ID, refer_with_id),
 
@@ -1559,6 +1569,7 @@
      TIF_STR(SIPTAG_SUPPORTED_STR, supported),
      TIF(SIPTAG_ALLOW, allow),
      TIF_STR(SIPTAG_ALLOW_STR, allow),
+     TIF_STR(NUTAG_APPL_METHOD, appl_method),
      TIF(SIPTAG_ALLOW_EVENTS, allow_events),
      TIF_STR(SIPTAG_ALLOW_EVENTS_STR, allow_events),
      TIF_SIP(SIPTAG_USER_AGENT, user_agent),
@@ -1607,7 +1618,7 @@
 
      TAG_NEXT(media_params));
 
-  nua_stack_event(nua, nh, NULL, nua_r_get_params, SIP_200_OK, TAG_NEXT(lst));
+  nua_stack_event(nua, nh, NULL, nua_r_get_params, SIP_200_OK, lst);
 
   su_home_deinit(tmphome);
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_params.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_params.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_params.h	Tue Apr 24 10:14:28 2007
@@ -95,9 +95,11 @@
   unsigned         nhp_service_route_enable:1;
   /** Enable Path */
   unsigned         nhp_path_enable:1;
+  /** Authentication cache policy */
+  unsigned         nhp_auth_cache:1;
+
   /** Always include id with Event: refer */
   unsigned         nhp_refer_with_id:1;
-
   unsigned:0;
 
   /* Default lifetime for implicit subscriptions created by REFER */
@@ -157,6 +159,7 @@
     unsigned nhb_media_features:1;
     unsigned nhb_service_route_enable:1;
     unsigned nhb_path_enable:1;
+    unsigned nhb_auth_cache:1;
     unsigned nhb_refer_with_id:1;
     unsigned nhb_refer_expires:1;
     unsigned nhb_substate:1;
@@ -166,8 +169,8 @@
 
     unsigned nhb_allow:1;
     unsigned nhb_supported:1;
-    unsigned nhb_allow_events:1;
     unsigned :0;		/* at most 32 bits ... */
+    unsigned nhb_allow_events:1;
     unsigned nhb_user_agent:1;
     unsigned nhb_organization:1;
 
@@ -223,4 +226,9 @@
   (NHP_ISSET((nh)->nh_prefs, pref) &&					\
    (nh)->nh_nua->nua_dhandle->nh_prefs != (nh)->nh_prefs)
 
+/* Check if preference has been set by applicationx */
+#define NUA_PISSET(nua, nh, pref)					\
+  (NHP_ISSET((nua)->nua_dhandle->nh_prefs, pref) ||			\
+   ((nh) && NHP_ISSET((nh)->nh_prefs, pref)))
+
 #endif /* NUA_PARAMS_H */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_publish.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_publish.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_publish.c	Tue Apr 24 10:14:28 2007
@@ -45,9 +45,6 @@
 #include <sofia-sip/sip_protos.h>
 #include <sofia-sip/sip_status.h>
 
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
-
 #include "nua_stack.h"
 
 /* ====================================================================== */
@@ -55,6 +52,7 @@
 
 struct publish_usage {
   sip_etag_t *pu_etag;
+  int pu_published;
 };
 
 static char const *nua_publish_usage_name(nua_dialog_usage_t const *du);
@@ -116,14 +114,6 @@
 /* ======================================================================== */
 /* PUBLISH */
 
-static int nua_stack_publish2(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-			      int refresh, tagi_t const *tags);
-
-static int process_response_to_publish(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip);
-
-
 /**@fn \
  * void nua_publish(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
  *
@@ -237,213 +227,238 @@
  * @END_NUA_EVENT
  */
 
-int nua_stack_publish(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-		      tagi_t const *tags)
-{
-  return nua_stack_publish2(nua, nh, e, 0, tags);
+static int nua_publish_client_template(nua_client_request_t *cr,
+				       msg_t **return_msg,
+				       tagi_t const *tags);
+static int nua_publish_client_init(nua_client_request_t *cr,
+				   msg_t *, sip_t *,
+				   tagi_t const *tags);
+static int nua_publish_client_request(nua_client_request_t *cr,
+				      msg_t *, sip_t *,
+				      tagi_t const *tags);
+static int nua_publish_client_check_restart(nua_client_request_t *cr,
+					    int status, char const *phrase,
+					    sip_t const *sip);
+static int nua_publish_client_response(nua_client_request_t *cr,
+				       int status, char const *phrase,
+				       sip_t const *sip);
+
+static nua_client_methods_t const nua_publish_client_methods = {
+  SIP_METHOD_PUBLISH,
+  0,
+  {
+    /* create_dialog */ 0,
+    /* in_dialog */ 0,
+    /* target refresh */ 0
+  },
+  nua_publish_client_template,
+  nua_publish_client_init,
+  nua_publish_client_request,
+  nua_publish_client_check_restart,
+  nua_publish_client_response,
+  /* nua_publish_client_preliminary */ NULL
+};
+
+/**@internal Send PUBLISH. */
+int nua_stack_publish(nua_t *nua,
+		     nua_handle_t *nh,
+		     nua_event_t e,
+		     tagi_t const *tags)
+{
+  return nua_client_create(nh, e, &nua_publish_client_methods, tags);
 }
 
-static
-int nua_stack_publish2(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-		       int refresh,
-		       tagi_t const *tags)
+static int nua_publish_client_template(nua_client_request_t *cr,
+				       msg_t **return_msg,
+				       tagi_t const *tags)
 {
   nua_dialog_usage_t *du;
-  struct publish_usage *pu;
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  msg_t *msg = NULL;
-  sip_t *sip;
-  int remove_body = 0;
 
-  if (nua_stack_set_handle_special(nh, nh_has_nothing, nua_r_publish) < 0)
-    return UA_EVENT2(e, 900, "Invalid handle for PUBLISH");
+  if (cr->cr_event == nua_r_publish)
+    return 0;
 
-  if (cr->cr_orq) {
-    return UA_EVENT2(e, 900, "Request already in progress");
+  du = nua_dialog_usage_get(cr->cr_owner->nh_ds, nua_publish_usage, NULL);
+  if (du && du->du_cr) {
+    if (nua_client_set_target(cr, du->du_cr->cr_target) < 0)
+      return -1;
+    *return_msg = msg_copy(du->du_cr->cr_msg);
+    return 1;
   }
 
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
+  return 0;
+}
 
-  if (e == nua_r_unpublish) {
-    du = nua_dialog_usage_get(nh->nh_ds, nua_publish_usage, NULL);
-    if (du)
-      refresh = 1;
-    else
-      du = nua_dialog_usage_add(nh, nh->nh_ds, nua_publish_usage, NULL);
-  }
-  else if (!refresh)
+static int nua_publish_client_init(nua_client_request_t *cr,
+				   msg_t *msg, sip_t *sip,
+				   tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du;
+  struct publish_usage *pu;
+
+  if (cr->cr_event == nua_r_publish) {
     du = nua_dialog_usage_add(nh, nh->nh_ds, nua_publish_usage, NULL);
+    if (!du)
+      return -1;
+    pu = nua_dialog_usage_private(du);
+    pu->pu_published = 0;
+    if (sip->sip_if_match) {
+      pu->pu_etag = sip_etag_dup(nh->nh_home, sip->sip_if_match);
+      if (!pu->pu_etag)
+	return -1;
+      sip_header_remove(msg, sip, (sip_header_t *)sip->sip_if_match);
+    }
+  }
   else
     du = nua_dialog_usage_get(nh->nh_ds, nua_publish_usage, NULL);
 
-  if (!du)
-    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-
-  nua_dialog_usage_reset_refresh(du);
-  pu = nua_dialog_usage_private(du); assert(pu);
-
-  if (refresh) {
-    if (cr->cr_msg)
-      msg_destroy(cr->cr_msg);
-    cr->cr_msg = msg_copy(du->du_msg);
-    remove_body = pu->pu_etag != NULL;
-  }
+  cr->cr_usage = du;
 
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count || refresh,
-		     SIP_METHOD_PUBLISH,
-		     NUTAG_ADD_CONTACT(0),
-		     TAG_NEXT(tags));
-  sip = sip_object(msg);
+  return 0;
+}
 
-  if (!msg || !sip) 
-    goto error;
+static
+int nua_publish_client_request(nua_client_request_t *cr,
+			       msg_t *msg, sip_t *sip,
+			       tagi_t const *tags)
+{
+  nua_dialog_usage_t *du = cr->cr_usage;
+  int un, done;
+  sip_etag_t const *etag = NULL;
 
-  du->du_terminating =
-    e != nua_r_publish ||
+  un = cr->cr_terminating ||
+    cr->cr_event != nua_r_publish ||
+    (du && du->du_shutdown) ||
     (sip->sip_expires && sip->sip_expires->ex_delta == 0);
+  cr->cr_terminating = un;
+  done = un;
 
-  if (!du->du_terminating && !refresh) {
-    /* Save template */
-    if (du->du_msg)
-      msg_destroy(du->du_msg);
-    du->du_msg = msg_ref_create(cr->cr_msg);
-  }
-
-  cr->cr_orq =
-    nta_outgoing_mcreate(nua->nua_nta,
-			 process_response_to_publish, nh, NULL,
-			 msg,
-			 SIPTAG_IF_MATCH(pu->pu_etag),
-			 TAG_IF(remove_body, SIPTAG_PAYLOAD(NONE)),
-			 TAG_IF(remove_body, SIPTAG_CONTENT_TYPE(NONE)),
-			 TAG_IF(e != nua_r_publish,
-				SIPTAG_EXPIRES_STR("0")),
-			 SIPTAG_END(), TAG_NEXT(tags));
-  if (!cr->cr_orq)
-    goto error;
-
-  cr->cr_usage = du;
-
-  return cr->cr_event = e;
+  if (du) {
+    struct publish_usage *pu = nua_dialog_usage_private(du);
 
- error:
-  msg_destroy(msg);
-  if (!du->du_ready == 0)
-    nua_dialog_usage_remove(nh, nh->nh_ds, du);
-  return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-}
+    if (nua_client_bind(cr, du) < 0)
+      return -1;
+    if (pu->pu_published)
+      done = 1;
+    etag = pu->pu_etag;
+  }
 
+  return nua_base_client_trequest(cr, msg, sip,
+				  SIPTAG_IF_MATCH(etag),
+				  TAG_IF(done, SIPTAG_PAYLOAD(NONE)),
+				  TAG_IF(done, SIPTAG_CONTENT_TYPE(NONE)),
+				  TAG_IF(un, SIPTAG_EXPIRES_STR("0")),
+				  TAG_NEXT(tags));
+}
+
+static int nua_publish_client_check_restart(nua_client_request_t *cr,
+					    int status, char const *phrase,
+					    sip_t const *sip)
+{
+  char const *restarting = NULL;
+
+  if (cr->cr_terminating || !cr->cr_usage)
+    ;
+  else if (status == 412)
+    restarting = phrase;
+  else if (200 <= status && status < 300 && 
+	   sip->sip_expires && sip->sip_expires->ex_delta == 0)
+    restarting = "Immediate re-PUBLISH";
+
+  if (restarting) {
+    struct publish_usage *pu = nua_dialog_usage_private(cr->cr_usage);
+
+    if (pu) {
+      pu->pu_published = 0;
+      su_free(cr->cr_owner->nh_home, pu->pu_etag), pu->pu_etag = NULL;
+      if (nua_client_restart(cr, 100, restarting))
+	return 0;
+    }
+  }
 
-static void
-restart_publish(nua_handle_t *nh, tagi_t *tags)
-{
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_publish, tags);
+  return nua_base_client_check_restart(cr, status, phrase, sip);
 }
 
-
-static
-int process_response_to_publish(nua_handle_t *nh,
-				nta_outgoing_t *orq,
-				sip_t const *sip)
+static int nua_publish_client_response(nua_client_request_t *cr,
+				       int status, char const *phrase,
+				       sip_t const *sip)
 {
-  int status = sip->sip_status->st_status;
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
+  nua_handle_t *nh = cr->cr_owner;
   nua_dialog_usage_t *du = cr->cr_usage;
-  struct publish_usage *pu = nua_dialog_usage_private(du);
-  unsigned saved_retry_count = cr->cr_retry_count + 1;
-
-  if (nua_creq_check_restart(nh, cr, orq, sip, restart_publish))
-    return 0;
-
-  if (status < 200 || pu == NULL)
-    return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
 
-  if (pu->pu_etag)
-    su_free(nh->nh_home, pu->pu_etag), pu->pu_etag = NULL;
-
-  if (!du->du_terminating) {
-    int retry = 0, invalid_expiration = 0;
+  if (!cr->cr_terminated && du && sip) {
+    struct publish_usage *pu = nua_dialog_usage_private(du);
+    sip_expires_t const *ex = sip->sip_expires;
+
+    /* Reset state */
+    pu->pu_published = 0;
+    if (pu->pu_etag)
+      su_free(nh->nh_home, pu->pu_etag), pu->pu_etag = NULL;
 
     if (status < 300) {
-      if (!sip->sip_expires)
-	invalid_expiration = 1;
-      else if (sip->sip_expires->ex_delta == 0)
-	retry = 1, invalid_expiration = 1;
-    }
-    else if (status == 412)
-      retry = 1;
-
-    if (status < 300 && !invalid_expiration && !retry) {
+      pu->pu_published = 1;
       pu->pu_etag = sip_etag_dup(nh->nh_home, sip->sip_etag);
-      du->du_ready = 1;
-      nua_dialog_usage_set_expires(du, sip->sip_expires->ex_delta);
-    }
-    else if (retry && saved_retry_count < NH_PGET(nh, retry_count)) {
-      msg_t *response = nta_outgoing_getresponse(orq);
-      nua_stack_event(nh->nh_nua, nh, response, cr->cr_event,
-      		100, "Trying re-PUBLISH",
-      		TAG_END());
-      nua_creq_deinit(cr, orq);
-      nua_stack_publish2(nh->nh_nua, nh, cr->cr_event, 1, NULL);
-      cr->cr_retry_count = saved_retry_count;
-      return 0;
-    }
-    else if (invalid_expiration) {
-      msg_t *response = nta_outgoing_getresponse(orq);
-      nua_stack_event(nh->nh_nua, nh, response, cr->cr_event,
-      		900, "Received Invalid Expiration Time",
-      		TAG_END());
-      nua_dialog_usage_remove(nh, nh->nh_ds, cr->cr_usage);
-      nua_creq_deinit(cr, orq);
-      cr->cr_usage = NULL;
-      return 0;
+
+      if (!ex || ex->ex_delta == 0 || !pu->pu_etag) {
+	cr->cr_terminated = 1;
+
+	if (!ex || ex->ex_delta == 0)
+	  SET_STATUS(900, "Received Invalid Expiration Time");
+	else
+	  SET_STATUS1(NUA_INTERNAL_ERROR);
+      }
+      else
+	nua_dialog_usage_set_refresh(du, ex->ex_delta);
     }
   }
 
-  return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
+  return nua_base_client_response(cr, status, phrase, sip, NULL);
 }
 
-
 static void nua_publish_usage_refresh(nua_handle_t *nh,
-				      nua_dialog_state_t *ds,
-				      nua_dialog_usage_t *du,
-				      sip_time_t now)
-{
-  if (ds->ds_cr->cr_usage == du) /* Already publishing. */
-    return;
-  nua_stack_publish2(nh->nh_nua, nh, nua_r_publish, 1, NULL);
+				     nua_dialog_state_t *ds,
+				     nua_dialog_usage_t *du,
+				     sip_time_t now)
+{
+  nua_client_request_t *cr = du->du_cr;
+
+  if (cr) {
+    if (nua_client_resend_request(cr, 0) >= 0)
+      return;
+  }
+
+  nua_stack_event(nh->nh_nua, nh, NULL,
+		  nua_r_publish, NUA_INTERNAL_ERROR,
+		  NULL);
+
+  nua_dialog_usage_remove(nh, ds, du);
 }
 
-/** @interal Shut down PUBLISH usage. 
+/** @interal Shut down PUBLISH usage.
  *
  * @retval >0  shutdown done
  * @retval 0   shutdown in progress
  * @retval <0  try again later
  */
 static int nua_publish_usage_shutdown(nua_handle_t *nh,
-				      nua_dialog_state_t *ds,
-				      nua_dialog_usage_t *du)
+				     nua_dialog_state_t *ds,
+				     nua_dialog_usage_t *du)
 {
-  nua_client_request_t *cr = ds->ds_cr;
+  nua_client_request_t *cr = du->du_cr;
 
-  if (!cr->cr_usage) {
-    /* Unpublish */
-    nua_stack_publish2(nh->nh_nua, nh, nua_r_destroy, 1, NULL);
-    return cr->cr_usage != du;
+  if (cr) {
+    if (nua_client_resend_request(cr, 1) >= 0)
+      return 0;
   }
 
-  if (!du->du_ready && !cr->cr_orq)
-    return 1;			/* had unauthenticated initial request */
-
-  return -1;  /* Request in progress */
+  /* XXX - report to user */
+  nua_dialog_usage_remove(nh, ds, du);
+  return 200;
 }
 
 /* ---------------------------------------------------------------------- */
 /* Server side */
 
-static
-int respond_to_publish(nua_server_request_t *sr, tagi_t const *tags);
-
 /** @NUA_EVENT nua_i_publish
  *
  * Incoming PUBLISH request.
@@ -453,7 +468,7 @@
  * events with nua_set_params() tag NUTAG_ALLOW_EVENTS(). 
  *
  * The nua_response() call responding to a PUBLISH request must have
- * NUTAG_WITH() (or NUTAG_WITH_CURRENT()/NUTAG_WITH_SAVED()) tag. Note that
+ * NUTAG_WITH() (or NUTAG_WITH_THIS()/NUTAG_WITH_SAVED()) tag. Note that
  * a successful response to PUBLISH @b MUST include @Expires and @SIPETag
  * headers.
  *
@@ -481,48 +496,35 @@
  * @END_NUA_EVENT
  */
 
-int nua_stack_process_publish(nua_t *nua,
-			      nua_handle_t *nh,
-			      nta_incoming_t *irq,
-			      sip_t const *sip)
-{
-  nua_server_request_t *sr, sr0[1];
-  sip_allow_events_t *allow_events = NUA_PGET(nua, nh, allow_events);
-  sip_event_t *o = sip->sip_event;
+int nua_publish_server_init(nua_server_request_t *sr);
+
+nua_server_methods_t const nua_publish_server_methods = 
+  {
+    SIP_METHOD_PUBLISH,
+    nua_i_publish,		/* Event */
+    { 
+      0,			/* Do not create dialog */
+      0,			/* Initial request */
+      0,			/* Not a target refresh request  */
+      1,			/* Add Contact */
+    },
+    nua_publish_server_init,
+    nua_base_server_preprocess,
+    nua_base_server_params,
+    nua_base_server_respond,
+    nua_base_server_report,
+  };
+
+int nua_publish_server_init(nua_server_request_t *sr)
+{
+  sip_allow_events_t *allow_events = NH_PGET(sr->sr_owner, allow_events);
+  sip_event_t *o = sr->sr_request.sip->sip_event;
   char const *event = o ? o->o_type : NULL;
   
-  sr = SR_INIT(sr0);
-  
   if (!allow_events)
-    SR_STATUS1(sr, SIP_501_NOT_IMPLEMENTED);
+    return SR_STATUS1(sr, SIP_501_NOT_IMPLEMENTED);
   else if (!event || !msg_header_find_param(allow_events->k_common, event))
-    SR_STATUS1(sr, SIP_489_BAD_EVENT);
-
-  sr = nua_server_request(nua, nh, irq, sip, sr, sizeof *sr,
-			  respond_to_publish, 0);
+    return SR_STATUS1(sr, SIP_489_BAD_EVENT);
 
-  return nua_stack_server_event(nua, sr, nua_i_publish, TAG_END());
-}
-
-static
-int respond_to_publish(nua_server_request_t *sr, tagi_t const *tags)
-{
-  nua_handle_t *nh = sr->sr_owner;
-  nua_t *nua = nh->nh_nua;
-  msg_t *msg;
-
-  msg = nua_server_response(sr, sr->sr_status, sr->sr_phrase, TAG_NEXT(tags));
-
-  if (msg) {
-    nta_incoming_mreply(sr->sr_irq, msg);
-  }
-  else {
-    SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
-    nta_incoming_treply(sr->sr_irq, sr->sr_status, sr->sr_phrase, TAG_END());
-    nua_stack_event(nua, nh, NULL,
-		    nua_i_error, 900, "PUBLISH Response Fails",
-		    TAG_END());
-  }
-  
-  return sr->sr_status >= 200 ? sr->sr_status : 0;
+  return 0;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_register.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_register.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_register.c	Tue Apr 24 10:14:28 2007
@@ -27,6 +27,7 @@
  *
  * @author Pekka Pessi <Pekka.Pessi at nokia.com>
  * @author Martti Mela <Martti.Mela at nokia.com>
+ * @author Kai Vehmanen <Kai.Vehmanen at nokia.com>
  *
  * @date Created: Wed Mar  8 11:48:49 EET 2006 ppessi
  */
@@ -45,8 +46,6 @@
 #include <sofia-sip/sip_util.h>
 #include <sofia-sip/sip_status.h>
 
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
 #define NTA_UPDATE_MAGIC_T   struct nua_s
 
 #include "nua_stack.h"
@@ -120,8 +119,11 @@
   nua_registration_t *nr_next, **nr_prev, **nr_list; /* Doubly linked list and its head */
   sip_from_t *nr_aor;		/**< AoR for this registration, NULL if none */
   sip_contact_t *nr_contact;	/**< Our Contact */
+  sip_contact_t nr_dcontact[1];	/**< Contact in dialog */
   sip_via_t *nr_via;		/**< Corresponding Via headers */
 
+  unsigned long nr_min_expires;	/**< Value from 423 negotiation */
+
   /** Status of registration */
   unsigned nr_ready:1;
   /** Kind of registration.
@@ -220,25 +222,16 @@
 /* ======================================================================== */
 /* REGISTER */
 
-static void restart_register(nua_handle_t *nh, tagi_t *tags);
-
-static int process_response_to_register(nua_handle_t *nh,
-					nta_outgoing_t *orq,
-					sip_t const *sip);
-
-static void unregister_expires_contacts(msg_t *msg, sip_t *sip);
-
 /* Interface towards outbound_t */
 sip_contact_t *nua_handle_contact_by_via(nua_handle_t *nh,
 					 su_home_t *home,
+					 int in_dialog,
 					 char const *extra_username,
 					 sip_via_t const *v,
 					 char const *transport,
 					 char const *m_param,
 					 ...);
 
-static int nua_stack_outbound_features(nua_handle_t *nh, outbound_t *ob);
-
 static int nua_stack_outbound_refresh(nua_handle_t *,
 				      outbound_t *ob);
 
@@ -440,6 +433,11 @@
  * the desired transport-layer keepalive interval for stream-based
  * transports like TLS and TCP.
  *
+ * As alternative to OPTIONS/STUN keepalives, the client can propose
+ * a more frequent registration refresh interval with
+ * NUTAG_M_FEATURES() (e.g. NUTAG_M_FEATURES("expires=120") given as 
+ * parameter to nua_register()).
+ * 
  * @sa #nua_r_register, nua_unregister(), #nua_r_unregister, 
  * #nua_i_register,
  * @RFC3261 section 10,
@@ -537,384 +535,353 @@
  * @END_NUA_EVENT
  */
 
-int
-nua_stack_register(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-		   tagi_t const *tags)
+static int nua_register_client_template(nua_client_request_t *cr,
+					msg_t **return_msg,
+					tagi_t const *tags);
+static int nua_register_client_init(nua_client_request_t *cr,
+				    msg_t *, sip_t *,
+				    tagi_t const *tags);
+static int nua_register_client_request(nua_client_request_t *cr,
+				       msg_t *, sip_t *,
+				       tagi_t const *tags);
+static int nua_register_client_check_restart(nua_client_request_t *cr,
+					     int status, char const *phrase,
+					     sip_t const *sip);
+static int nua_register_client_response(nua_client_request_t *cr,
+					int status, char const *phrase,
+					sip_t const *sip);
+
+static nua_client_methods_t const nua_register_client_methods = {
+  SIP_METHOD_REGISTER,
+  0,
+  {
+    /* create_dialog */ 1,
+    /* in_dialog */ 0,
+    /* target refresh */ 0
+  },
+  nua_register_client_template,
+  nua_register_client_init,
+  nua_register_client_request,
+  nua_register_client_check_restart,
+  nua_register_client_response
+};
+
+/**@internal Send REGISTER. */
+int nua_stack_register(nua_t *nua,
+		       nua_handle_t *nh,
+		       nua_event_t e,
+		       tagi_t const *tags)
+{
+  return nua_client_create(nh, e, &nua_register_client_methods, tags);
+}
+
+static int nua_register_client_template(nua_client_request_t *cr,
+					msg_t **return_msg,
+					tagi_t const *tags)
 {
   nua_dialog_usage_t *du;
-  nua_registration_t *nr = NULL;
-  outbound_t *ob = NULL;
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  msg_t *msg = NULL;
-  sip_t *sip;
-  int terminating = e != nua_r_register;
-
-  if (nua_stack_set_handle_special(nh, nh_has_register, nua_r_register) < 0)
-    return UA_EVENT2(e, 900, "Invalid handle for REGISTER");
-  if (cr->cr_orq)
-    return UA_EVENT2(e, 900, "Request already in progress");
 
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
+  if (cr->cr_event == nua_r_register)
+    return 0;
+
+  /* Use a copy of REGISTER message as the template for un-REGISTER */
+  du = nua_dialog_usage_get(cr->cr_owner->nh_ds, nua_register_usage, NULL);
+  if (du && du->du_cr) {
+    if (nua_client_set_target(cr, du->du_cr->cr_target) < 0)
+      return -1;
+    *return_msg = msg_copy(du->du_cr->cr_msg);
+    return 1;
+  }
+
+  return 0;
+}
+
+static int nua_register_client_init(nua_client_request_t *cr,
+				    msg_t *msg, sip_t *sip,
+				    tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du;
+  nua_registration_t *nr;
+  sip_to_t const *aor = sip->sip_to;
+
+  int unreg;
+
+  /* Explicit empty (NULL) contact - used for CPL store/remove? */
+  if (!sip->sip_contact && cr->cr_has_contact)
+    /* Do not create any usage */
+    return 0;
+
+  unreg = cr->cr_event != nua_r_register ||
+    (sip->sip_expires && sip->sip_expires->ex_delta == 0);
+  if (unreg)
+    nua_client_terminating(cr);
 
   du = nua_dialog_usage_add(nh, nh->nh_ds, nua_register_usage, NULL);
-  if (!du)
-    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-  nr = nua_dialog_usage_private(du); assert(nr);
-  nua_registration_add(&nh->nh_nua->nua_registrations, nr);
-  if (!terminating && du->du_terminating)
-    return UA_EVENT2(e, 900, "Unregister in progress");
-
-  if (cr->cr_msg)
-    msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
-  /* Use original message as template when unregistering */
-  if (terminating)		
-    cr->cr_msg = msg_ref_create(du->du_msg);
-
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_msg != NULL,
-		     SIP_METHOD_REGISTER,
-		     TAG_IF(!terminating, NUTAG_USE_DIALOG(1)),
-		     TAG_NEXT(tags));
-  sip = sip_object(msg);
-  if (!msg || !sip)
-    goto error;
-
-  if (!nr->nr_aor) {
-    if (nua_registration_set_aor(nh->nh_home, nr, sip->sip_to) < 0)
-      goto error;
-  }
-
-  if (terminating)
-    /* Add Expires: 0 and remove the expire parameters from contacts */
-    unregister_expires_contacts(msg, sip);
-
-  if (!sip->sip_contact && cr->cr_has_contact) {
-    terminating = 1;
-  }
-  else if (nua_registration_set_contact(nh, nr, sip->sip_contact, terminating)
-	   < 0)
-    goto error;
+  if (du == NULL)
+    return -1;
+  nr = nua_dialog_usage_private(du);
 
-  du->du_terminating = terminating;
+  if (nua_client_bind(cr, du) < 0)
+    return -1;
 
-  if (du->du_msg == NULL && !terminating)
-    du->du_msg = msg_ref_create(cr->cr_msg); /* Save original message */
+  if (!nr->nr_list) {
+    nua_registration_add(&nh->nh_nua->nua_registrations, nr);
 
-  ob = nr->nr_ob;
-  
-  if (!ob && (NH_PGET(nh, outbound) || NH_PGET(nh, instance))) {
-    nr->nr_ob = ob = outbound_new(nh, &nua_stack_outbound_callbacks,
-				  nh->nh_nua->nua_root,
-				  nh->nh_nua->nua_nta,
-				  NH_PGET(nh, instance));
-    if (!ob)
-      goto error;
+    if (aor == NULL)
+      aor = sip->sip_from;
+    if (aor == NULL)
+      aor = nh->nh_nua->nua_from;
+
+    if (nua_registration_set_aor(nh->nh_home, nr, aor) < 0)
+      return -1;
   }
 
-  if (ob) {
+  if (nua_registration_set_contact(nh, nr, sip->sip_contact, unreg) < 0)
+    return -1;
+
+  if (!nr->nr_ob && (NH_PGET(nh, outbound) || NH_PGET(nh, instance))) {
+    nr->nr_ob = outbound_new(nh, &nua_stack_outbound_callbacks,
+			     nh->nh_nua->nua_root,
+			     nh->nh_nua->nua_nta,
+			     NH_PGET(nh, instance));
+    if (!nr->nr_ob)
+      return nua_client_return(cr, 900, "Cannot create outbound", msg);
+  }
+
+  if (nr->nr_ob) {
+    outbound_t *ob = nr->nr_ob;
+    sip_contact_t *m;
+
+    if (!unreg && sip->sip_contact) {
+      for (m = sip->sip_contact; m; m = m->m_next)
+	if (!m->m_expires || strtoul(m->m_expires, NULL, 10) != 0)
+	  break;
+      
+      if (m == NULL)
+	unreg = 1;	/* All contacts have expires=0 */
+    }
+
     outbound_set_options(ob,
 			 NH_PGET(nh, outbound),
 			 NH_PGET(nh, keepalive),
 			 NH_PISSET(nh, keepalive_stream)
 			 ? NH_PGET(nh, keepalive_stream)
 			 : NH_PGET(nh, keepalive));
-    nua_stack_outbound_features(nh, ob);
-    outbound_stop_keepalive(ob);
 
-    if (outbound_set_contact(ob, sip->sip_contact, nr->nr_via, terminating) < 0)
-      goto error;
+    if (outbound_set_contact(ob, sip->sip_contact, nr->nr_via, unreg) < 0)
+      return nua_client_return(cr, 900, "Cannot set outbound contact", msg);
   }
 
-  /* This calls nta_outgoing_mcreate() but adds a few tags */
-  cr->cr_orq =
-    outbound_register_request(ob, terminating,
-			      nr->nr_by_stack ? nr->nr_contact : NULL,
-			      nua->nua_nta,
-			      process_response_to_register, nh, NULL,
-			      msg,
-			      SIPTAG_END(), 
-			      TAG_IF(terminating, NTATAG_SIGCOMP_CLOSE(1)),
-			      TAG_IF(!terminating, NTATAG_COMP("sigcomp")),
-			      TAG_NEXT(tags));
-
-  if (!cr->cr_orq)
-    goto error;
-
-  cr->cr_usage = du;
-  return cr->cr_event = e;
-
- error:
-  msg_destroy(msg);
-  msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
-  nua_dialog_usage_remove(nh, nh->nh_ds, du);    
-  return UA_EVENT1(e, NUA_INTERNAL_ERROR);
+  return 0;
 }
 
-static void
-restart_register(nua_handle_t *nh, tagi_t *tags)
+static
+int nua_register_client_request(nua_client_request_t *cr,
+				msg_t *msg, sip_t *sip,
+				tagi_t const *tags)
 {
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  msg_t *msg;
+  nua_handle_t *nh = cr->cr_owner;
   nua_dialog_usage_t *du = cr->cr_usage;
-  nua_registration_t *nr = nua_dialog_usage_private(du);
-  int terminating = du && du->du_terminating;
-
-  cr->cr_restart = NULL;
-
-  if (!cr->cr_msg)
-    return;
+  nua_registration_t *nr;
+  sip_contact_t *m, *contacts = sip->sip_contact;
+  char const *min_expires = NULL;
+  int unreg;
+
+  (void)nh;
+
+  /* Explicit empty (NULL) contact - used for CPL store/remove? */
+  if (!contacts && cr->cr_has_contact)
+    return nua_base_client_request(cr, msg, sip, tags);
+
+  if ((du && du->du_shutdown) ||
+      (sip->sip_expires && sip->sip_expires->ex_delta == 0))
+    nua_client_terminating(cr);
+
+  if (contacts) {
+    if (!cr->cr_terminating) {
+      for (m = contacts; m; m = m->m_next)
+	if (!m->m_expires || strtoul(m->m_expires, NULL, 10) != 0)
+	  break;
+      /* All contacts have expires=0 */
+      if (m == NULL)
+	nua_client_terminating(cr);
+    }
+  }
 
-  msg = nua_creq_msg(nh->nh_nua, nh, cr, 1,
-		     SIP_METHOD_UNKNOWN,
-		     TAG_NEXT(tags));
+  unreg = cr->cr_terminating;
 
-  if (!msg)
-    return;			/* XXX - Uh-oh */
+  nr = nua_dialog_usage_private(du);
 
-  if (terminating)
-    unregister_expires_contacts(msg, sip_object(msg));
+  if (nr) {
+    if (nr->nr_ob) {
+      outbound_stop_keepalive(nr->nr_ob);
+      outbound_start_registering(nr->nr_ob);
+    }
 
-  /* This calls nta_outgoing_mcreate() but adds a few tags */
-  cr->cr_orq =
-    outbound_register_request(nr->nr_ob, terminating,
-			      nr->nr_by_stack ? nr->nr_contact : NULL,
-			      nh->nh_nua->nua_nta,
-			      process_response_to_register, nh, NULL,
-			      msg,
-			      SIPTAG_END(), 
-			      TAG_IF(terminating, NTATAG_SIGCOMP_CLOSE(1)),
-			      TAG_IF(!terminating, NTATAG_COMP("sigcomp")),
-			      TAG_NEXT(tags));
+    if (nr->nr_by_stack) {
+      sip_contact_t *m = nr->nr_contact, *previous = NULL;
 
-  if (!cr->cr_orq)
-    msg_destroy(msg);
-}
+      outbound_get_contacts(nr->nr_ob, &m, &previous);
 
-/** Refresh registration */
-static
-void nua_register_usage_refresh(nua_handle_t *nh,
-				nua_dialog_state_t *ds,
-				nua_dialog_usage_t *du,
-				sip_time_t now)
-{
-  nua_t *nua = nh->nh_nua;
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  nua_registration_t *nr = nua_dialog_usage_private(du);
-  msg_t *msg;
-  sip_t *sip;
-
-  if (du->du_terminating || du->du_shutdown)
-    return;
+      sip_add_dup(msg, sip, (sip_header_t *)m);
+      /* previous is an outdated contact generated by stack 
+       * and it is now unregistered */
+      if (previous)
+	sip_add_dup(msg, sip, (sip_header_t *)previous);
+    }
+  }
 
-  if (cr->cr_msg) {
-    /* Dialog is busy, delay of 5 .. 15 seconds */
-    nua_dialog_usage_refresh_range(du, 5, 15);
-    return;
-  }
-
-  outbound_stop_keepalive(nr->nr_ob);
-
-  cr->cr_msg = msg_copy(du->du_msg);
-  msg = nua_creq_msg(nua, nh, cr, 1,
-		     SIP_METHOD_REGISTER,
-		     NUTAG_USE_DIALOG(1),
-		     TAG_END());
-  sip = sip_object(msg);
-  if (!msg || !sip)
-    goto error;
-
-  cr->cr_orq =
-    outbound_register_request(nr->nr_ob, 0,
-			      nr->nr_by_stack ? nr->nr_contact : NULL,
-			      nh->nh_nua->nua_nta,
-			      process_response_to_register, nh, NULL,
-			      msg,
-			      SIPTAG_END(), 
-			      NTATAG_COMP("sigcomp"),
-			      TAG_END());
-  if (!cr->cr_orq)
-    goto error;
+  for (m = sip->sip_contact; m; m = m->m_next) {
+    if (m->m_url->url_type == url_any) {
+      /* If there is a '*' in contact list, remove everything else */
+      while (m != sip->sip_contact)
+	sip_header_remove(msg, sip, (sip_header_t *)sip->sip_contact);
+      while (m->m_next)
+	sip_header_remove(msg, sip, (sip_header_t *)m->m_next);
+      contacts = m;
+      break;
+    }
 
-  cr->cr_usage = du;
-  cr->cr_event = nua_r_register;
-  return;
+    if (!m->m_expires)
+      continue;
+    if (unreg) {
+      /* Remove the expire parameters from contacts */
+      msg_header_remove_param(m->m_common, "expires");
+    }
+    else if (nr && nr->nr_min_expires && 
+	     strtoul(m->m_expires, 0, 10) < nr->nr_min_expires) {
+      if (min_expires == NULL) 
+	min_expires = su_sprintf(msg_home(msg), "expires=%lu", 
+				 nr->nr_min_expires);
+      msg_header_replace_param(msg_home(msg), m->m_common, min_expires);
+    }
+  }
 
- error:
-  msg_destroy(msg);
-  msg_destroy(cr->cr_msg);
-  UA_EVENT2(nua_r_register, NUA_INTERNAL_ERROR, TAG_END());
-  return;
+  return nua_base_client_trequest(cr, msg, sip,
+				  TAG_IF(unreg, SIPTAG_EXPIRES_STR("0")),
+#if 0
+				  TAG_IF(unreg, NTATAG_SIGCOMP_CLOSE(1)),
+				  TAG_IF(!unreg, NTATAG_COMP("sigcomp")),
+#endif
+				  TAG_NEXT(tags));
 }
 
-/** Shutdown register usage. 
- *
- * Called when stack is shut down or handle is destroyed. Unregister.
- */
-static
-int nua_register_usage_shutdown(nua_handle_t *nh, 
-				nua_dialog_state_t *ds,
-				nua_dialog_usage_t *du)
+static int nua_register_client_check_restart(nua_client_request_t *cr,
+					     int status, char const *phrase,
+					     sip_t const *sip)
 {
-  nua_t *nua = nh->nh_nua;
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  nua_registration_t *nr = nua_dialog_usage_private(du);
-  msg_t *msg;
-  sip_t *sip;
+  nua_registration_t *nr = nua_dialog_usage_private(cr->cr_usage);
+  unsigned short retry_count = cr->cr_retry_count;
+  int restart = 0, retry;
 
-  if (du->du_terminating)	/* Already terminating? */
-    return 100;
+  if (nr && nr->nr_ob) {
+    msg_t *_reqmsg = nta_outgoing_getrequest(cr->cr_orq);
+    sip_t *req = sip_object(_reqmsg); msg_destroy(_reqmsg);
 
-  du->du_terminating = 1;
+    retry = outbound_register_response(nr->nr_ob, cr->cr_terminating,
+				       req, sip);
 
-  if (cr->cr_msg)    /* Busy */
-    return 100;
-
-  outbound_stop_keepalive(nr->nr_ob);
-
-  cr->cr_msg = msg_copy(du->du_msg);
-  msg = nua_creq_msg(nua, nh, cr, 1,
-		     SIP_METHOD_REGISTER,
-		     NUTAG_USE_DIALOG(1),
-		     TAG_END());
-  sip = sip_object(msg);
-  if (!msg || !sip)
-    goto error;
-
-  unregister_expires_contacts(msg, sip);
-
-  cr->cr_orq =
-    outbound_register_request(nr->nr_ob, 1,
-			      nr->nr_by_stack ? nr->nr_contact : NULL,
-			      nh->nh_nua->nua_nta,
-			      process_response_to_register, nh, NULL,
-			      msg,
-			      SIPTAG_END(), 
-			      NTATAG_SIGCOMP_CLOSE(1),
-			      TAG_END());
-  if (!cr->cr_orq)
-    goto error;
+    restart = retry >= ob_reregister_now;
+    
+    if (retry == ob_reregister)
+      /* outbound restarts REGISTER later */;
 
-  cr->cr_usage = du;
-  cr->cr_event = nua_r_destroy;
-  return 200;
+    if (retry < 0)
+      /* XXX - report an error? */;
+  }
 
- error:
-  nua_dialog_usage_remove(nh, nh->nh_ds, du);
-  msg_destroy(msg);
-  msg_destroy(cr->cr_msg);
-  return 500;
-}
+  if (nr && status == 423) {
+    if (sip->sip_min_expires)
+      nr->nr_min_expires = sip->sip_min_expires->me_delta;
+  }
 
+  /* Check for status-specific reasons to retry */
+  if (nua_base_client_check_restart(cr, status, phrase, sip))
+    return 1;
 
-static
-int process_response_to_register(nua_handle_t *nh,
-				 nta_outgoing_t *orq,
-				 sip_t const *sip)
+  /* Restart only if nua_base_client_check_restart() did not try to restart */
+  if (restart && retry_count == cr->cr_retry_count)
+    return nua_client_restart(cr, 100, "Outbound NAT Detected");
+  
+  return 0;
+}
+
+static int nua_register_client_response(nua_client_request_t *cr,
+					int status, char const *phrase,
+					sip_t const *sip)
 {
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
+  nua_handle_t *nh = cr->cr_owner;
   nua_dialog_usage_t *du = cr->cr_usage;
   nua_registration_t *nr = nua_dialog_usage_private(du);
-  int status, ready, reregister, terminating;
-  char const *phrase;
-  msg_t *_reqmsg = nta_outgoing_getrequest(orq);
-  sip_t *req = sip_object(_reqmsg); msg_destroy(_reqmsg);
-
-  assert(sip);
-  assert(du && du->du_class == nua_register_usage);
-  status = sip->sip_status->st_status;
-  phrase = sip->sip_status->st_phrase;
-
-  if (status < 200 || !du)
-    return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
-
-  terminating = du->du_terminating;
-  if (!terminating)
-    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
-
-  reregister = outbound_register_response(nr->nr_ob, terminating, req, sip);
-  if (reregister < 0)
-    SET_STATUS1(NUA_INTERNAL_ERROR);
-  else if (reregister >= ob_reregister) {
-    /* Save msg otherwise nua_creq_check_restart() will zap it */
-    msg_t *msg = msg_ref_create(cr->cr_msg);
+  int ready;
 
-    if (nua_creq_check_restart(nh, cr, orq, sip, restart_register)) {
-      msg_destroy(msg);
-      return 0;
-    }
+  ready = du && !cr->cr_terminated && status < 300;
+
+  if (ready) {
+    sip_time_t mindelta = 0;
+    sip_time_t now = sip_now(), delta, reqdelta, mdelta;
 
-    assert(cr->cr_msg == NULL);
-    cr->cr_msg = msg;
+    sip_contact_t const *m, *sent;
 
-    if (reregister >= ob_reregister_now) {
-      /* We can try to reregister immediately */
-      nua_creq_restart_with(nh, cr, orq, 100, "Updated Contact",
-			    restart_register,
-			    TAG_END());
-    }
-    else {
-      /* Outbound will invoke refresh_register() later */
-      nua_creq_save_restart(nh, cr, orq, 100, "Updated Contact",
-			    restart_register);
+    msg_t *_reqmsg = nta_outgoing_getrequest(cr->cr_orq);
+    sip_t *req = sip_object(_reqmsg);
+
+    msg_destroy(_reqmsg);
+
+    assert(nr); assert(sip); assert(req);
+
+#if HAVE_SIGCOMP
+    {
+      struct sigcomp_compartment *cc;
+      cc = nta_outgoing_compartment(cr->cr_orq);
+      sigcomp_compartment_unref(nr->nr_compartment);
+      nr->nr_compartment = cc;
     }
-    return 0;
-  }
+#endif
 
-  if (status >= 300)
-    if (nua_creq_check_restart(nh, cr, orq, sip, restart_register))
-      return 0;
+    /* XXX - if store/remove, remove 
+       Content-Disposition
+       Content-Type
+       body
+    */
+
+    /** Search for lowest delta of SIP contacts we tried to register */
+    mindelta = SIP_TIME_MAX;
+
+    reqdelta = req->sip_expires ? req->sip_expires->ex_delta : 0;
+
+    for (m = sip->sip_contact; m; m = m->m_next) {
+      if (m->m_url->url_type != url_sip && 
+	  m->m_url->url_type != url_sips)
+	continue;
 
-  ready = !terminating && status < 300;
-  du->du_ready = ready;
+      for (sent = req->sip_contact; sent; sent = sent->m_next) {
+	if (url_cmp(m->m_url, sent->m_url))
+	  continue;
+
+	if (sent->m_expires)
+	  mdelta = strtoul(sent->m_expires, NULL, 10);
+	else
+	  mdelta = reqdelta;
+
+	if (mdelta == 0)
+	  mdelta = 3600;
+	  
+	delta = sip_contact_expires(m, sip->sip_expires, sip->sip_date,
+				    mdelta, now);
+	if (delta > 0 && delta < mindelta)
+	  mindelta = delta;
 
-  if (status < 300) {
-    if (!du->du_terminating) {
-      sip_time_t mindelta = 0;
-      sip_time_t now = sip_now(), delta, reqdelta;
-      sip_contact_t const *m, *sent;
-
-      /** Search for lowest delta of SIP contacts we tried to register */
-      mindelta = SIP_TIME_MAX;
-
-      reqdelta = req->sip_expires ? req->sip_expires->ex_delta : 0;
-
-      for (m = sip->sip_contact; m; m = m->m_next) {
-        if (m->m_url->url_type != url_sip && 
-            m->m_url->url_type != url_sips)
-          continue;
-        for (sent = req->sip_contact; sent; sent = sent->m_next)
-          if (url_cmp(m->m_url, sent->m_url) == 0) {
-            sip_time_t mdelta = reqdelta;
-
-            if (sent->m_expires)
-              mdelta = strtoul(sent->m_expires, NULL, 10);
-            if (mdelta == 0)
-              mdelta = 3600;
-
-            delta = sip_contact_expires(m, sip->sip_expires, sip->sip_date,
-       				 mdelta, now);
-            if (delta > 0 && delta < mindelta)
-              mindelta = delta;
-            if (url_cmp_all(m->m_url, sent->m_url) == 0)
-              break;
-          }
+	if (url_cmp_all(m->m_url, sent->m_url) == 0)
+	  break;
       }
-
-      if (mindelta == SIP_TIME_MAX)
-        mindelta = 3600;
-      nua_dialog_usage_set_expires(du, mindelta);
     }
-    else
-      nua_dialog_usage_set_expires(du, 0);
-  }
 
-#if HAVE_SIGCOMP
-  if (ready) {
-    struct sigcomp_compartment *cc;
-    cc = nta_outgoing_compartment(orq);
-    sigcomp_compartment_unref(nr->nr_compartment);
-    nr->nr_compartment = cc;
-  }
-#endif
+    if (mindelta == SIP_TIME_MAX)
+      mindelta = 3600;
+
+    nua_dialog_usage_set_refresh(du, mindelta);
 
   /*  RFC 3608 Section 6.1 Procedures at the UA
 
@@ -934,46 +901,103 @@
    route for that address-of-record.
 
   */
-  if (ready) {
     su_free(nh->nh_home, nr->nr_route);
     nr->nr_route = sip_route_dup(nh->nh_home, sip->sip_service_route);
+
+    {
+      /* RFC 3327 */
+      /* Store last URI in Path header */
+      sip_path_t *path = sip->sip_path;
+
+      while (path && path->r_next)
+	path = path->r_next;
+
+      if (!nr->nr_path || !path ||
+	  url_cmp_all(nr->nr_path->r_url, path->r_url)) {
+	su_free(nh->nh_home, nr->nr_path);
+	nr->nr_path = sip_path_dup(nh->nh_home, path);
+      }
+    }
+
+    if (sip->sip_to->a_url->url_type == url_sips)
+      nr->nr_secure = 1;
+
+    if (nr->nr_ob) {
+      outbound_gruuize(nr->nr_ob, sip);
+      outbound_start_keepalive(nr->nr_ob, cr->cr_orq);
+    }
+
+    /* persistant connection for registration */
+    if (!nr->nr_tport)
+      /* note: nta_outgoing_transport() takes a ref */
+      nr->nr_tport = nta_outgoing_transport (cr->cr_orq); 
+
+    nua_registration_set_ready(nr, 1);
   }
-  else {
+  else if (du) {
+    nua_dialog_usage_set_refresh(du, 0);
+
     su_free(nh->nh_home, nr->nr_route);
     nr->nr_route = NULL;
+
+    outbound_stop_keepalive(nr->nr_ob);
+
+    /* release the persistant transport for registration */
+    if (nr->nr_tport)
+      tport_decref(&nr->nr_tport), nr->nr_tport = NULL;
+
+    nua_registration_set_ready(nr, 0);
   }
 
-  if (ready) {
-    /* RFC 3327 */
-    /* Store last URI in Path header */
-    sip_path_t *path = sip->sip_path;
 
-    while (path && path->r_next)
-      path = path->r_next;
+  return nua_base_client_response(cr, status, phrase, sip, NULL);
+}
 
-    if (!nr->nr_path || !path ||
-        url_cmp_all(nr->nr_path->r_url, path->r_url)) {
-      su_free(nh->nh_home, nr->nr_path);
-      nr->nr_path = sip_path_dup(nh->nh_home, path);
-    }
+static void nua_register_usage_refresh(nua_handle_t *nh,
+				       nua_dialog_state_t *ds,
+				       nua_dialog_usage_t *du,
+				       sip_time_t now)
+{
+  nua_t *nua = nh->nh_nua;
+  nua_client_request_t *cr = du->du_cr;
+
+  if (cr) {
+    if (nua_client_resend_request(cr, 0) >= 0)
+      return;
   }
 
-  if (ready)
-    if (sip->sip_to->a_url->url_type == url_sips)
-      nr->nr_secure = 1;
+  /* Report that we have de-registered */
+  nua_stack_event(nua, nh, NULL, nua_r_register, NUA_INTERNAL_ERROR, NULL);
+  nua_dialog_usage_remove(nh, ds, du);
+}
 
-  if (nr->nr_ob) {
-    if (ready) {
-      outbound_gruuize(nr->nr_ob, sip);
-      outbound_start_keepalive(nr->nr_ob, orq);
-    }
-    else
-      outbound_stop_keepalive(nr->nr_ob);
+/** @interal Shut down REGISTER usage.
+ *
+ * @retval >0  shutdown done
+ * @retval 0   shutdown in progress
+ * @retval <0  try again later
+ */
+static int nua_register_usage_shutdown(nua_handle_t *nh,
+				     nua_dialog_state_t *ds,
+				     nua_dialog_usage_t *du)
+{
+  nua_client_request_t *cr = du->du_cr;
+  nua_registration_t *nr = nua_dialog_usage_private(du);
+
+  if (cr) {
+    if (nua_client_is_queued(cr)) /* Already registering. */
+      return -1;
+    cr->cr_event = nua_r_unregister;
+    if (nua_client_resend_request(cr, 1) >= 0)
+      return 0;
   }
 
-  nua_registration_set_ready(nr, ready);
+  /* release the persistant transport for registration */
+  if (nr->nr_tport)
+    tport_decref(&nr->nr_tport), nr->nr_tport = NULL;
 
-  return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
+  nua_dialog_usage_remove(nh, ds, du);
+  return 200;
 }
 
 /* ---------------------------------------------------------------------- */
@@ -984,7 +1008,8 @@
 #endif
 
 static void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta);
-static int nua_registration_add_contact_and_route(nua_registration_t *nr,
+static int nua_registration_add_contact_and_route(nua_handle_t *nh,
+						  nua_registration_t *nr,
 						  msg_t *msg,
 						  sip_t *sip,
 						  int add_contact,
@@ -1081,9 +1106,7 @@
 
   switch (nw_updates) {
   case NUA_NW_DETECT_ONLY_INFO:
-    nua_stack_event(nua, NULL, NULL, nua_i_network_changed,
-		    SIP_200_OK, TAG_END());
-
+    nua_stack_event(nua, NULL, NULL, nua_i_network_changed, SIP_200_OK, NULL);
     break;
     
   case NUA_NW_DETECT_TRY_FULL:
@@ -1095,10 +1118,10 @@
     if (nua_stack_init_transport(nua, nua->nua_args) < 0)
       /* We are hosed */
       nua_stack_event(nua, NULL, NULL, nua_i_network_changed,
-		      900, "Internal Error", TAG_END());
+		      900, "Internal Error", NULL);
     else
       nua_stack_event(nua, NULL, NULL, nua_i_network_changed,
-		      SIP_200_OK, TAG_END());
+		      SIP_200_OK, NULL);
 
     break;
     
@@ -1262,11 +1285,8 @@
 
     v2[1].v_next = NULL;
 
-#if 1
-    contact = nua_handle_contact_by_via(nh, home, NULL, v2, protocol, NULL);
-#else
-    contact = sip_contact_create_from_via_with_transport(home, v2, NULL, protocol);
-#endif
+    contact = nua_handle_contact_by_via(nh, home, 0, NULL, v2, protocol, NULL);
+
     v = sip_via_dup(home, v2);
 
     if (!contact || !v) {
@@ -1277,6 +1297,7 @@
     nr->nr_ready = 1, nr->nr_default = 1, nr->nr_public = public;
     nr->nr_secure = contact->m_url->url_type == url_sips;
     nr->nr_contact = contact;
+    *nr->nr_dcontact = *contact, nr->nr_dcontact->m_params = NULL;
     nr->nr_via = v;
     nr->nr_ip4 = host_is_ip4_address(contact->m_url->url_host);
     nr->nr_ip6 = !nr->nr_ip4 && host_is_ip6_reference(contact->m_url->url_host);
@@ -1446,7 +1467,10 @@
       return m;
   }
 
-  return nr->nr_contact;
+  if (nr->nr_contact)
+    return nr->nr_dcontact;
+  else
+    return NULL;
 }
 
 /** Return initial route. */
@@ -1458,7 +1482,7 @@
 sip_contact_t const *nua_stack_get_contact(nua_registration_t const *nr)
 {
   nr = nua_registration_by_aor(nr, NULL, NULL, 1);
-  return nr ? nr->nr_contact : NULL;
+  return nr && nr->nr_contact ? nr->nr_dcontact : NULL;
 }
 
 /** Add a Contact (and Route) header to request */
@@ -1482,7 +1506,7 @@
   if (nr == NULL)
     nr = nua_registration_for_request(nh->nh_nua->nua_registrations, sip);
 
-  return nua_registration_add_contact_and_route(nr, msg, sip, 
+  return nua_registration_add_contact_and_route(nh, nr, msg, sip, 
 						add_contact, 
 						add_service_route);
 }
@@ -1513,12 +1537,15 @@
     nr = nua_registration_for_response(nh->nh_nua->nua_registrations, sip,
 				       record_route, remote_contact);
 
-  return nua_registration_add_contact_and_route(nr, msg, sip, 1, 0);
+  return nua_registration_add_contact_and_route(nh, nr, msg, sip, 
+						1,
+						0);
 }
 
 /** Add a Contact (and Route) header to request */
 static 
-int nua_registration_add_contact_and_route(nua_registration_t *nr,
+int nua_registration_add_contact_and_route(nua_handle_t *nh,
+					   nua_registration_t *nr,
 					   msg_t *msg,
 					   sip_t *sip,
 					   int add_contact,
@@ -1528,8 +1555,63 @@
     return -1;
 
   if (add_contact) {
-    sip_contact_t const *m = nua_registration_contact(nr);
-    if (!m || msg_header_add_dup(msg, (msg_pub_t *)sip, (void const *)m) < 0)
+    sip_contact_t const *m = NULL;
+    char const *m_display;
+    char const *m_username;
+    char const *m_params;
+    url_t const *u;
+
+    if (nr->nr_by_stack && nr->nr_ob) {
+      m = outbound_dialog_gruu(nr->nr_ob);
+
+      if (m)
+	return msg_header_add_dup(msg, (msg_pub_t *)sip, (void const *)m);
+
+      m = outbound_dialog_contact(nr->nr_ob);
+    }
+
+    if (m == NULL)
+      m = nr->nr_contact;
+
+    if (!m)
+      return -1;
+
+    u = m->m_url;
+
+    if (NH_PISSET(nh, m_display))
+      m_display = NH_PGET(nh, m_display);
+    else
+      m_display = m->m_display;
+
+    if (NH_PISSET(nh, m_username))
+      m_username = NH_PGET(nh, m_username);
+    else
+      m_username = m->m_url->url_user;
+
+    if (NH_PISSET(nh, m_params)) {
+      m_params = NH_PGET(nh, m_params);
+
+      if (u->url_params && m_params && strstr(u->url_params, m_params) == 0)
+	m_params = NULL;
+    }
+    else
+      m_params = NULL;
+
+    m = sip_contact_format(msg_home(msg),
+			   "%s<%s:%s%s%s%s%s%s%s%s%s>",
+			   m_display ? m_display : "",
+			   u->url_scheme,
+			   m_username ? m_username : "",
+			   m_username ? "@" : "",
+			   u->url_host,
+			   u->url_port ? ":" : "",
+			   u->url_port ? u->url_port : "",
+			   u->url_params ? ";" : "",
+			   u->url_params ? u->url_params : "",
+			   m_params ? ";" : "",
+			   m_params ? m_params : "");
+
+    if (msg_header_insert(msg, (msg_pub_t *)sip, (void *)m) < 0)
       return -1;
   }
 
@@ -1618,7 +1700,7 @@
 
     if (nr0 && nr0->nr_via) {
       char const *tport = nr0->nr_via->v_next ? NULL : nr0->nr_via->v_protocol;
-      m = nua_handle_contact_by_via(nh, nh->nh_home,
+      m = nua_handle_contact_by_via(nh, nh->nh_home, 0,
 				    NULL, nr0->nr_via, tport, NULL);
     }
   }
@@ -1627,6 +1709,7 @@
     return -1;
 
   nr->nr_contact = m;
+  *nr->nr_dcontact = *m, nr->nr_dcontact->m_params = NULL;
   nr->nr_ip4 = host_is_ip4_address(m->m_url->url_host);
   nr->nr_ip6 = !nr->nr_ip4 && host_is_ip6_reference(m->m_url->url_host);
   nr->nr_by_stack = !application_contact;
@@ -1639,8 +1722,10 @@
 /** Mark registration as ready */
 void nua_registration_set_ready(nua_registration_t *nr, int ready)
 {
-  assert(!ready || nr->nr_contact);
-  nr->nr_ready = ready;
+  if (nr) {
+    assert(!ready || nr->nr_contact);
+    nr->nr_ready = ready;
+  }
 }
 
 /** @internal Hook for processing incoming request by registration.
@@ -1670,48 +1755,6 @@
   return 481;			/* Call/Transaction does not exist */
 }
 
-/**@internal
- * Fix contacts for un-REGISTER.
- *
- * Remove (possible non-zero) "expires" parameters from contacts and extra
- * contacts, add Expire: 0.
- */
-static
-void unregister_expires_contacts(msg_t *msg, sip_t *sip)
-{
-  sip_contact_t *m;
-  int unregister_all;
-
-  if (msg == NULL || sip == NULL)
-    return;
-
-  /* Remove payload */
-  while (sip->sip_payload)
-    sip_header_remove(msg, sip, (sip_header_t *)sip->sip_payload);
-  while (sip->sip_content_type)
-    sip_header_remove(msg, sip, (sip_header_t *)sip->sip_content_type);
-
-  for (m = sip->sip_contact; m; m = m->m_next) {
-    if (m->m_url->url_type == url_any)
-      break;
-    msg_header_remove_param(m->m_common, "expires");
-#if 0
-    msg_header_add_param(msg_home(msg), m->m_common, "expires=0");
-#endif
-  }
-
-  unregister_all = m && (m != sip->sip_contact || m->m_next);
-
-  sip_add_tl(msg, sip,
-             /* Remove existing contacts */
-             TAG_IF(unregister_all, SIPTAG_CONTACT(NONE)),
-             /* Add '*' contact: 0 */
-             TAG_IF(unregister_all, SIPTAG_CONTACT_STR("*")),
-             SIPTAG_EXPIRES_STR("0"),
-             TAG_END());
-}
-
-
 /** Outbound requests us to refresh registration */
 static int nua_stack_outbound_refresh(nua_handle_t *nh,
 				      outbound_t *ob)
@@ -1758,7 +1801,7 @@
 
   nua_stack_event(nh->nh_nua, nh, NULL,
 		  nua_i_outbound, status, phrase,
-		  ta_tags(ta));
+		  ta_args(ta));
 
   ta_end(ta);
 
@@ -1775,7 +1818,7 @@
 
   nua_stack_event(nh->nh_nua, nh, NULL,
 		  nua_i_outbound, status, phrase,
-		  ta_tags(ta));
+		  ta_args(ta));
 
   ta_end(ta);
 
@@ -1795,6 +1838,7 @@
 /** @internal Generate a @Contact header. */
 sip_contact_t *nua_handle_contact_by_via(nua_handle_t *nh,
 					 su_home_t *home,
+					 int in_dialog,
 					 char const *extra_username,
 					 sip_via_t const *v,
 					 char const *transport,
@@ -1841,10 +1885,11 @@
     /* Make transport parameter lowercase */
     if (strlen(transport) < (sizeof _transport)) {
       char *s = strcpy(_transport, transport);
+      short c;
 
-      for (s = _transport; *s && *s != ';'; s++)
-	if (isupper(*s))
-	  *s = tolower(*s);
+      for (s = _transport; (c = *s) && c != ';'; s++)
+	if (isupper(c))
+	  *s = tolower(c);
 
       transport = _transport;
     }
@@ -1878,7 +1923,7 @@
     su_strlst_append(l, ";comp="), su_strlst_append(l, comp);
   s = NH_PGET(nh, m_params);
   if (s) 
-    su_strlst_append(l, s[0] == ';' ? "" : ";"), su_strlst_append(l, s);
+    s[0] == ';' ? "" : su_strlst_append(l, ";"), su_strlst_append(l, s);
   su_strlst_append(l, ">");
 
   va_start(va, m_param);
@@ -1892,81 +1937,42 @@
   
   va_end(va);
 
-  m = sip_contact_make(home, su_strlst_join(l, su_strlst_home(l), ""));
-  
-  su_strlst_destroy(l);
-  
-  return m;
-}
-
-/** @internal Return a string describing our features. */
-static char *nua_handle_features(nua_handle_t *nh)
-{
-  char *retval = NULL;
-  su_strlst_t *l = su_strlst_create(NULL);
-  su_home_t *home = su_strlst_home(l);
-
-  if (!l)
-    return NULL;
-
-  if (NH_PGET(nh, m_features)) {
-    char const *m_features = NH_PGET(nh, m_features);
-
-    if (m_features[0] != ';')
-      su_strlst_append(l, ";");
-
-    su_strlst_append(l, m_features);
-  }
-
-  if (NH_PGET(nh, callee_caps)) {
-    sip_allow_t const *allow = NH_PGET(nh, allow);
-
-    if (allow) {
-      /* Skip ";" if this is first one */
-      su_strlst_append(l, ";methods=\"" + (su_strlst_len(l) == 0));
-      if (allow->k_items) {
-        size_t i;
-        for (i = 0; allow->k_items[i]; i++) {
-          su_strlst_append(l, allow->k_items[i]);
-          if (allow->k_items[i + 1])
-            su_strlst_append(l, ",");
-        }
+  if (!in_dialog) {
+    s = NH_PGET(nh, m_features);
+    if (s) 
+      s[0] == ';' ? "" : su_strlst_append(l, ";"), su_strlst_append(l, s);
+
+    if (NH_PGET(nh, callee_caps)) {
+      sip_allow_t const *allow = NH_PGET(nh, allow);
+
+      if (allow) {
+	su_strlst_append(l, ";methods=\"");
+	if (allow->k_items) {
+	  size_t i;
+	  for (i = 0; allow->k_items[i]; i++) {
+	    su_strlst_append(l, allow->k_items[i]);
+	    if (allow->k_items[i + 1])
+	      su_strlst_append(l, ",");
+	  }
+	}
+	su_strlst_append(l, "\"");
       }
-      su_strlst_append(l, "\"");
-    }
-
-    if (nh->nh_soa) {
-      char **media = soa_media_features(nh->nh_soa, 0, home);
 
-      while (*media) {
-        if (su_strlst_len(l))
-          su_strlst_append(l, ";");
-        su_strlst_append(l, *media++);
+      if (nh->nh_soa) {
+	char **media = soa_media_features(nh->nh_soa, 0, home);
+	
+	while (*media) {
+	  if (su_strlst_len(l))
+	    su_strlst_append(l, ";");
+	  su_strlst_append(l, *media++);
+	}
       }
     }
   }
 
-  if (su_strlst_len(l))
-    retval = su_strlst_join(l, nh->nh_home, "");
-
+  m = sip_contact_make(home, su_strlst_join(l, su_strlst_home(l), ""));
+  
   su_strlst_destroy(l);
-
-  return retval;
-}
-
-static int nua_stack_outbound_features(nua_handle_t *nh, outbound_t *ob)
-{
-  char *features;
-  int retval;
-
-  if (!nh)
-    return -1;
-  if (!ob)
-    return 0;
-
-  features = nua_handle_features(nh);
-  retval = outbound_set_features(ob, features);
-  su_free(nh->nh_home, features);
-
-  return retval;
+  
+  return m;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_registrar.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_registrar.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_registrar.c	Tue Apr 24 10:14:28 2007
@@ -44,8 +44,6 @@
 #include <sofia-sip/sip_status.h>
 #include <sofia-sip/sip_util.h>
 
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
 #define NTA_INCOMING_MAGIC_T struct nua_handle_s
 #define NTA_RELIABLE_MAGIC_T struct nua_handle_s
 
@@ -62,7 +60,7 @@
  * the REGISTER method with NUTAG_ALLOW() tag.
  *
  * The nua_response() call responding to a REGISTER request must have
- * NUTAG_WITH() (or NUTAG_WITH_CURRENT()/NUTAG_WITH_SAVED()) tag. Note that
+ * NUTAG_WITH() (or NUTAG_WITH_THIS()/NUTAG_WITH_SAVED()) tag. Note that
  * a successful response to REGISTER @b MUST include the @Contact header
  * bound to the the AoR URI (in @To header).
  *
@@ -89,15 +87,19 @@
  * @END_NUA_EVENT
  */
 
-int nua_stack_process_register(nua_t *nua,
-			       nua_handle_t *nh,
-			       nta_incoming_t *irq,
-			       sip_t const *sip)
-{
-  nua_server_request_t *sr, sr0[1];
-
-  sr = nua_server_request(nua, nh, irq, sip, SR_INIT(sr0), sizeof *sr,
-			  nua_default_respond, 0);
-
-  return nua_stack_server_event(nua, sr, nua_i_register, TAG_END());
-}
+nua_server_methods_t const nua_register_server_methods = 
+  {
+    SIP_METHOD_REGISTER,
+    nua_i_register,		/* Event */
+    { 
+      0,			/* Do not create dialog */
+      0,			/* Initial request */
+      0,			/* Not a target refresh request  */
+      0,			/* Do not add Contact */
+    },
+    nua_base_server_init,
+    nua_base_server_preprocess,
+    nua_base_server_params,
+    nua_base_server_respond,
+    nua_base_server_report,
+  };

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_session.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_session.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_session.c	Tue Apr 24 10:14:28 2007
@@ -45,10 +45,9 @@
 #include <sofia-sip/sip_util.h>
 #include <sofia-sip/su_uniqueid.h>
 
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
 #define NTA_INCOMING_MAGIC_T struct nua_server_request
-#define NTA_RELIABLE_MAGIC_T struct nua_handle_s
+#define NTA_OUTGOING_MAGIC_T struct nua_client_request
+#define NTA_RELIABLE_MAGIC_T struct nua_server_request
 
 #include "nua_stack.h"
 #include <sofia-sip/soa.h>
@@ -141,8 +140,7 @@
 /** Session-related state */
 typedef struct nua_session_usage
 {
-  /* enum nua_callstate */
-  unsigned        ss_state:4;		/**< Session status (enum nua_callstate) */
+  enum nua_callstate ss_state;		/**< Session status (enum nua_callstate) */
   
   unsigned        ss_100rel:1;	        /**< Use 100rel, send 183 */
   unsigned        ss_alerting:1;	/**< 180 is sent/received */
@@ -151,18 +149,28 @@
 
   unsigned        ss_precondition:1;	/**< Precondition required */
 
-  unsigned        ss_timer_set:1;       /**< We have active session timer. */
+  unsigned        ss_reporting:1;       /**< True if reporting state */
   unsigned        : 0;
-  
-  unsigned        ss_session_timer;	/**< Value of Session-Expires (delta) */
-  unsigned        ss_min_se;		/**< Minimum session expires */
-  enum nua_session_refresher ss_refresher; /**< none, local or remote */
-
-  char const     *ss_ack_needed;	/**< If non-null, need to send an ACK
-					 * (do O/A, if "offer" or "answer")
-					 */
 
-  nua_client_request_t ss_crequest[1];  /* Outgoing invite */
+  struct session_timer {
+    unsigned  interval;		/**< Negotiated expiration time */
+    enum nua_session_refresher refresher; /**< Our Negotiated role */
+
+    struct {
+      unsigned expires, defaults; /**< Value of Session-Expires (delta) */
+      unsigned min_se;	/**< Minimum session expires */
+      /** none, local or remote */
+      enum nua_session_refresher refresher;
+      unsigned    supported:1, require:1, :0;
+    } local, remote;
+
+    unsigned      timer_set:1;  /**< We have active session timer. */
+  } ss_timer[1];
+
+  char const     *ss_reason;	        /**< Reason for termination. */
+
+  /* Offer-Answer status */
+  char const     *ss_oa_recv, *ss_oa_sent;
 } nua_session_usage_t;
 
 static char const *nua_session_usage_name(nua_dialog_usage_t const *du);
@@ -180,6 +188,9 @@
 				      nua_dialog_state_t *,
 				      nua_dialog_usage_t *);
 
+static int nua_invite_client_ack(nua_client_request_t *cr, tagi_t const *tags);
+static int nua_invite_client_deinit(nua_client_request_t *cr);
+
 static nua_usage_class const nua_session_usage[1] = {
   {
     sizeof (nua_session_usage_t),
@@ -202,14 +213,16 @@
 			   nua_dialog_state_t *ds,
 			   nua_dialog_usage_t *du)
 {
-  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);  
 
   if (ds->ds_has_session)
     return -1;
   ds->ds_has_session = 1;
+  ds->ds_got_session = 1;
+
+  ss->ss_timer->local.refresher = nua_any_refresher;
+  ss->ss_timer->remote.refresher = nua_any_refresher;
 
-  nh->nh_ds->ds_cr->cr_next = ss->ss_crequest;
- 
   return 0;
 }
 
@@ -219,17 +232,57 @@
 			       nua_dialog_usage_t *du)
 {
   nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  nua_client_request_t *cr, *cr_next;
+
+  cr = du->du_cr;
+
+  if (cr && cr->cr_orq && cr->cr_status >= 200) {
+    ss->ss_reporting = 1;
+    nua_invite_client_ack(cr, NULL);
+    ss->ss_reporting = 0;
+  }
+
+  /* Destroy queued INVITE transactions */
+  for (cr = ds->ds_cr; cr; cr = cr_next) {
+    cr_next = cr->cr_next;
+
+    if (cr->cr_method != sip_method_invite)
+      continue;
+    if (cr == du->du_cr)
+      continue;
+
+    nua_stack_event(nh->nh_nua, nh, 
+		    NULL,
+		    cr->cr_event,
+		    SIP_481_NO_TRANSACTION,
+		    NULL);
+
+    nua_client_request_destroy(cr);
+
+    cr_next = ds->ds_cr;
+  }
 
+  
   ds->ds_has_session = 0;
+  nh->nh_has_invite = 0;
+  nh->nh_active_call = 0;
+  nh->nh_hold_remote = 0;
+
+  if (nh->nh_soa)
+    soa_destroy(nh->nh_soa), nh->nh_soa = NULL;
+}
 
-  if (ss->ss_crequest)
-    nua_creq_deinit(ss->ss_crequest, NULL);
+static
+nua_dialog_usage_t *nua_dialog_usage_for_session(nua_dialog_state_t const *ds)
+{
+  if (ds == ((nua_handle_t *)NULL)->nh_ds)
+    return NULL;
 
-  ds->ds_cr->cr_next = NULL;
+  return nua_dialog_usage_get(ds, nua_session_usage, NULL);
 }
 
 static
-nua_session_usage_t *nua_session_usage_get(nua_dialog_state_t const *ds)
+nua_session_usage_t *nua_session_usage_for_dialog(nua_dialog_state_t const *ds)
 {
   nua_dialog_usage_t *du;
 
@@ -241,63 +294,59 @@
   return (nua_session_usage_t *)nua_dialog_usage_private(du);
 }
 
+/** Zap the session associated with the handle */
+static
+void nua_session_usage_destroy(nua_handle_t *nh,
+			       nua_session_usage_t *ss)
+{
+  /* Remove usage */
+  nua_dialog_usage_remove(nh, nh->nh_ds, nua_dialog_usage_public(ss));
+
+  SU_DEBUG_5(("nua: terminated session %p\n", (void *)nh));
+}
+
 /* ======================================================================== */
 /* INVITE and call (session) processing */
 
-static int nua_stack_invite2(nua_t *, nua_handle_t *, nua_event_t e,
-			     int restarted, tagi_t const *tags);
-static int process_response_to_invite(nua_handle_t *nh,
-				      nta_outgoing_t *orq,
-				      sip_t const *sip);
-static void
-  session_timeout(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now);
+int nua_stack_prack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
+		    tagi_t const *tags);
 
-static void restart_invite(nua_handle_t *nh, tagi_t *tags);
+static int session_timer_is_supported(struct session_timer const *t);
 
-static int process_100rel(nua_handle_t *nh,
-			  nua_session_usage_t *ss,
-			  nta_outgoing_t *orq,
-			  sip_t const *sip);
+static void session_timer_preferences(struct session_timer *t,
+				      sip_t const *sip,
+				      sip_supported_t const *supported,
+				      unsigned expires, int isset,
+				      enum nua_session_refresher refresher,
+				      unsigned min_se);
 
-int nua_stack_prack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-		    tagi_t const *tags);
+static void session_timer_store(struct session_timer *t,
+				sip_t const *sip);
 
-static int process_response_to_prack(nua_handle_t *nh,
-				     nta_outgoing_t *orq,
-				     sip_t const *sip);
+static int session_timer_check_min_se(msg_t *msg, sip_t *sip,
+				      sip_t const *request,
+				      unsigned long min_se);
 
-static void nua_session_usage_destroy(nua_handle_t *, nua_session_usage_t *);
+static int session_timer_add_headers(struct session_timer *t,
+				     int initial,
+				     msg_t *msg, sip_t *sip);
 
-static void session_timer_preferences(nua_session_usage_t *ss,
-				      unsigned expires,
-				      unsigned min_se,
-				      enum nua_session_refresher refresher);
-static int session_timer_is_supported(nua_handle_t const *nh);
-static int prefer_session_timer(nua_handle_t const *nh);
-
-static int use_session_timer(nua_session_usage_t *ss, int uas, int always,
-			     msg_t *msg, sip_t *);
-static int init_session_timer(nua_session_usage_t *ss, sip_t const *, int refresher);
-static void set_session_timer(nua_session_usage_t *ss);
+static void session_timer_negotiate(struct session_timer *t);
 
-static int
-check_session_timer_restart(nua_handle_t *nh,
-			    nua_session_usage_t *ss,
-			    nua_client_request_t *cr,
-			    nta_outgoing_t *orq,
-			    sip_t const *sip,
-			    nua_creq_restart_f *restart_function);
+static void session_timer_set(nua_session_usage_t *ss);
+
+static int session_timer_check_restart(nua_client_request_t *cr,
+				       int status, char const *phrase,
+				       sip_t const *sip);
 
 static int nh_referral_check(nua_handle_t *nh, tagi_t const *tags);
 static void nh_referral_respond(nua_handle_t *,
 				int status, char const *phrase);
 
 static void signal_call_state_change(nua_handle_t *nh,
-				     nua_session_usage_t *ss,
-				     int status, char const *phrase,
-				     enum nua_callstate next_state,
-				     char const *oa_recv,
-				     char const *oa_sent);
+				      nua_session_usage_t *ss,
+				      int status, char const *phrase,
+				      enum nua_callstate next_state);
 
 static
 int session_get_description(sip_t const *sip,
@@ -319,16 +368,9 @@
 			     sip_payload_t **return_pl);
 
 static
-int session_process_response(nua_handle_t *nh,
-			     nua_client_request_t *cr,
-			     nta_outgoing_t *orq,
-			     sip_t const *sip,
-			     char const **return_received);
-
-static
-int respond_with_retry_after(nua_handle_t *nh, nta_incoming_t *irq,
-			     int status, char const *phrase,
-			     int min, int max);
+int nua_server_retry_after(nua_server_request_t *sr,
+			   int status, char const *phrase,
+			   int min, int max);
 
 /**@fn void nua_invite(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
  *
@@ -475,128 +517,157 @@
 /* Tags not implemented
  *    NUTAG_REFER_PAUSE() \n
  */
-int
-nua_stack_invite(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-		 tagi_t const *tags)
-{
-  char const *what;
-
-  if (nh_is_special(nh) || 
-      nua_stack_set_handle_special(nh, nh_has_invite, nua_i_error))
-    what = "Invalid handle for INVITE";
-  else if (nh_referral_check(nh, tags) < 0) {
-    what = "Invalid referral";
-  }
-  else if (nua_stack_init_handle(nua, nh, TAG_NEXT(tags)) < 0) {
-    what = "Handle initialization failed";
-  }
-  else
-    return nua_stack_invite2(nua, nh, e, 0, tags);
 
-  UA_EVENT2(e, 900, what);
+static int nua_invite_client_init(nua_client_request_t *cr, 
+				  msg_t *msg, sip_t *sip,
+				  tagi_t const *tags);
+static int nua_invite_client_request(nua_client_request_t *cr,
+				     msg_t *msg, sip_t *sip,
+				     tagi_t const *tags);
+static int nua_invite_client_preliminary(nua_client_request_t *cr,
+					 int status, char const *phrase,
+					 sip_t const *sip);
+static int nua_invite_client_response(nua_client_request_t *cr,
+				      int status, char const *phrase,
+				      sip_t const *sip);
+static int nua_session_client_response(nua_client_request_t *cr,
+				       int status, char const *phrase,
+				       sip_t const *sip);
+static int nua_invite_client_report(nua_client_request_t *cr,
+				    int status, char const *phrase,
+				    sip_t const *sip,
+				    nta_outgoing_t *orq,
+				    tagi_t const *tags);
 
-  signal_call_state_change(nh, NULL, 900, what, nua_callstate_init, 0, 0);
+nua_client_methods_t const nua_invite_client_methods = {
+  SIP_METHOD_INVITE,
+  0,
+  { 
+    /* create_dialog */ 1,
+    /* in_dialog */ 1,
+    /* target refresh */ 1
+  },
+  NULL,
+  nua_invite_client_init,
+  nua_invite_client_request,
+  session_timer_check_restart,
+  nua_invite_client_response,
+  nua_invite_client_preliminary,
+  nua_invite_client_report,
+  nua_invite_client_deinit
+};
+
+extern nua_client_methods_t const nua_bye_client_methods;
+extern nua_client_methods_t const nua_cancel_client_methods;
+extern nua_client_methods_t const nua_info_client_methods;
+extern nua_client_methods_t const nua_update_client_methods;
+extern nua_client_methods_t const nua_prack_client_methods;
 
-  return e;
+int nua_stack_invite(nua_t *nua, nua_handle_t *nh, nua_event_t e,
+		     tagi_t const *tags)
+{
+  return nua_client_create(nh, e, &nua_invite_client_methods, tags);
 }
 
-static int
-nua_stack_invite2(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-		  int restarted,
-		  tagi_t const *tags)
+static int nua_invite_client_init(nua_client_request_t *cr, 
+				  msg_t *msg, sip_t *sip,
+				  tagi_t const *tags)
 {
+  nua_handle_t *nh = cr->cr_owner;
   nua_dialog_usage_t *du;
   nua_session_usage_t *ss;
-  nua_client_request_t *cr;
-  int offer_sent = 0;
 
-  msg_t *msg = NULL;
-  sip_t *sip = NULL;
+  cr->cr_usage = du = nua_dialog_usage_for_session(nh->nh_ds);
+  /* Errors returned by nua_invite_client_init() 
+     are neutral to session state */
+  cr->cr_neutral = 1;	
+  
+  if (nh_is_special(nh) || 
+      nua_stack_set_handle_special(nh, nh_has_invite, nua_i_error))
+    return nua_client_return(cr, 900, "Invalid handle for INVITE", msg);
+  else if (nh_referral_check(nh, tags) < 0)
+    return nua_client_return(cr, 900, "Invalid referral", msg);
+
+  if (du) {
+    nua_server_request_t *sr;
+    for (sr = nh->nh_ds->ds_sr; sr; sr = sr->sr_next)
+      /* INVITE in progress? */
+      if (sr->sr_usage == du && sr->sr_method == sip_method_invite &&
+	  nua_server_request_is_pending(sr))
+	return nua_client_return(cr, SIP_491_REQUEST_PENDING, msg);
+  }
+  else
+    du = nua_dialog_usage_add(nh, nh->nh_ds, nua_session_usage, NULL);
+
+  if (!du)
+    return -1;
 
-  char const *what;
+  if (nua_client_bind(cr, du) < 0)
+    return nua_client_return(cr, 900, "INVITE already in progress", msg);
 
-  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_session_usage, NULL);
   ss = nua_dialog_usage_private(du);
-  cr = ss->ss_crequest;
-  what = nua_internal_error;		/* Internal error */
 
-  if (du == NULL)
-    goto failure;
+  session_timer_preferences(ss->ss_timer,
+			    sip,
+			    NH_PGET(nh, supported),		     
+			    NH_PGET(nh, session_timer),
+			    NUA_PISSET(nh->nh_nua, nh, session_timer),
+			    NH_PGET(nh, refresher),
+			    NH_PGET(nh, min_se));
 
-  if (cr->cr_orq) {
-    what = "INVITE request already in progress";
-    goto failure;
-  }
+  cr->cr_neutral = 0;
 
-  if (ss->ss_state == nua_callstate_terminated)
-    ss->ss_state = nua_callstate_init;
+  return 0;
+}
 
-  if (!restarted) {
-    session_timer_preferences(ss, 
-			      NH_PGET(nh, session_timer),
-			      NH_PGET(nh, min_se),
-			      NH_PGET(nh, refresher));
-  }
+static int nua_invite_client_request(nua_client_request_t *cr,
+				     msg_t *msg, sip_t *sip,
+				     tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  int offer_sent = 0, retval;
+  sip_time_t invite_timeout;
 
-  if (restarted && !cr->cr_msg) {
-    if (du->du_msg)
-      cr->cr_msg = msg_dup(du->du_msg);
-    else
-      restarted = 0;
-  }
+  if (du == NULL)		/* Call terminated */ 
+    return nua_client_return(cr, SIP_481_NO_TRANSACTION, msg);
 
-  msg = nua_creq_msg(nua, nh, cr, restarted,
-		     SIP_METHOD_INVITE,
-		     NUTAG_USE_DIALOG(1),
-		     NUTAG_ADD_CONTACT(1),
-		     TAG_NEXT(tags));
-  sip = sip_object(msg);
+  assert(ss);
 
-  if (!sip) {
-    what = "Cannot Initialize Request";
-    goto failure;
-  }
+  invite_timeout = NH_PGET(nh, invite_timeout);
+  if (invite_timeout == 0)
+    invite_timeout = UINT_MAX;
+  /* Send CANCEL if we don't get response within timeout*/
+  /* nua_dialog_usage_set_expires(du, invite_timeout); Xyzzy */
+  nua_dialog_usage_set_refresh(du, 0);
+
+  /* Add session timer headers */
+  if (session_timer_is_supported(ss->ss_timer))
+    session_timer_add_headers(ss->ss_timer, ss->ss_state == nua_callstate_init,
+			      msg, sip);
 
-  if (!restarted) {
-    msg_destroy(du->du_msg), du->du_msg = msg_dup(msg);
-  }
+  ss->ss_100rel = NH_PGET(nh, early_media);
+  ss->ss_precondition = sip_has_feature(sip->sip_require, "precondition");
+  if (ss->ss_precondition)
+    ss->ss_update_needed = ss->ss_100rel = 1;
 
   if (nh->nh_soa) {
     soa_init_offer_answer(nh->nh_soa);
 
     if (sip->sip_payload)
-      offer_sent = 0;
+      offer_sent = 0;		/* XXX - kludge */
     else if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0)
-      offer_sent = -1;
+      return -1;
     else
       offer_sent = 1;
-  }
-
-  if (offer_sent >= 0) {
-    sip_time_t invite_timeout = NH_PGET(nh, invite_timeout);
-    if (invite_timeout == 0)
-      invite_timeout = UINT_MAX;
-    /* Cancel if we don't get response within timeout*/
-    nua_dialog_usage_set_expires(du, invite_timeout);
-    nua_dialog_usage_set_refresh(du, 0);
-
-    /* Add session timer headers */
-    if (session_timer_is_supported(nh))
-      use_session_timer(ss, 0, prefer_session_timer(nh), msg, sip);
-
-    ss->ss_100rel = NH_PGET(nh, early_media);
-    ss->ss_precondition = sip_has_feature(sip->sip_require, "precondition");
-
-    if (ss->ss_precondition)
-      ss->ss_update_needed = ss->ss_100rel = 1;
 
     if (offer_sent > 0 &&
-	session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
-      what = "Internal media error"; goto failure;
-    }
+	session_include_description(nh->nh_soa, 1, msg, sip) < 0)
+      return nua_client_return(cr, 900, "Internal media error", msg);
 
-    if (nh->nh_soa &&
-	NH_PGET(nh, media_features) && !nua_dialog_is_established(nh->nh_ds) &&
+    if (NH_PGET(nh, media_features) &&
+	!nua_dialog_is_established(nh->nh_ds) &&
 	!sip->sip_accept_contact && !sip->sip_reject_contact) {
       sip_accept_contact_t ac[1];
       sip_accept_contact_init(ac);
@@ -609,188 +680,308 @@
 	sip_add_dup(msg, sip, (sip_header_t *)ac);
       }
     }
-
-    if (nh->nh_auth) {
-      if (auc_authorize(&nh->nh_auth, msg, sip) < 0) {
-	what = "Internal authentication error"; goto failure;
-      }
-    }
-
-      cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-					process_response_to_invite, nh, NULL,
-					msg,
-					NTATAG_REL100(ss->ss_100rel),
-					SIPTAG_END(), TAG_NEXT(tags));
-
-    if (cr->cr_orq) {
-      cr->cr_offer_sent = offer_sent;
-      cr->cr_usage = du;
-      du->du_refresh = 0;
-      signal_call_state_change(nh, ss, 0, "INVITE sent",
-			       nua_callstate_calling, 0,
-			       offer_sent ? "offer" : 0);
-      return cr->cr_event = e;
-    }
+  }
+  else {
+    offer_sent = session_get_description(sip, NULL, NULL);
   }
 
- failure:
-
-  msg_destroy(msg);
-  if (du && !du->du_ready)
-    nua_dialog_usage_remove(nh, nh->nh_ds, du), ss = NULL;
-
-  UA_EVENT2(e, 900, what);
-  signal_call_state_change(nh, ss, 900, what, nua_callstate_init, 0, 0);
+  retval = nua_base_client_trequest(cr, msg, sip,
+				    NTATAG_REL100(ss->ss_100rel),
+				    TAG_NEXT(tags));
+  if (retval == 0) {
+    cr->cr_offer_sent = offer_sent;
+    ss->ss_oa_sent = offer_sent ? "offer" : NULL;
+
+    if (!cr->cr_restarting)
+      signal_call_state_change(nh, ss, 0, "INVITE sent", 
+			       nua_callstate_calling);
+  }
 
-  return e;
+  return retval;
 }
 
-/** @NUA_EVENT nua_r_invite
- *
- * Answer to outgoing INVITE.
- *
- * The INVITE may be sent explicitly by nua_invite() or
- * implicitly by NUA state machine.
- *
- * @param status response status code
- *               (if the request is retried, @a status is 100, the @a
- *               sip->sip_status->st_status contain the real status code
- *               from the response message, e.g., 302, 401, or 407)
- * @param phrase a short textual description of @a status code
- * @param nh     operation handle associated with the call
- * @param hmagic application context associated with the call
- * @param sip    response message to INVITE or NULL upon an error
- *               (status code is in @a status and 
- *                descriptive message in @a phrase parameters)
- * @param tags   empty
- *
- * @sa nua_invite(), @ref nua_call_model, #nua_i_state, #nua_i_invite, 
- * nua_ack(), NUTAG_AUTOACK()
- * 
- * @END_NUA_EVENT
- */
-
-static int process_response_to_invite(nua_handle_t *nh,
-				      nta_outgoing_t *orq,
+static int nua_invite_client_response(nua_client_request_t *cr,
+				      int status, char const *phrase,
 				      sip_t const *sip)
 {
-  nua_t *nua = nh->nh_nua;
-  nua_client_request_t *cr;
-  nua_dialog_usage_t *du;
-  nua_session_usage_t *ss;
-  int status = sip->sip_status->st_status;
-  char const *phrase = sip->sip_status->st_phrase;
-  int terminated = 0;
-  int gracefully = 1;
-  char const *received = NULL;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
 
-  cr = nua_client_request_by_orq(nh->nh_ds->ds_cr, orq);
-  du = cr ? cr->cr_usage : NULL;
-  ss = nua_dialog_usage_private(du);
-  
-  assert(cr && du && ss);
+  if (ss == NULL || sip == NULL) {
+    /* Xyzzy */
+  }
+  else if (status < 300) {
+    du->du_ready = 1;
 
-  if (ss->ss_state == nua_callstate_terminating && 200 <= status) {
-    /*
-     * If the call is being terminated but re-INVITE was responded with 2XX
-     * re-send the BYE, otherwise terminate the call.
-     */
-    gracefully = status < 300, terminated = !gracefully;
+    if (session_timer_is_supported(ss->ss_timer))
+      session_timer_store(ss->ss_timer, sip);
+
+    session_timer_set(ss);
   }
-  else if (status >= 300) {
-    if (sip->sip_retry_after)
-      gracefully = 0;
+  
+  return nua_session_client_response(cr, status, phrase, sip);
+}
 
-    terminated = sip_response_terminates_dialog(status, sip_method_invite,
-						&gracefully);
+static int nua_invite_client_preliminary(nua_client_request_t *cr,
+					 int status, char const *phrase,
+					 sip_t const *sip)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
 
-    if (!terminated) {
-      if (check_session_timer_restart(nh, ss, cr, orq, sip, restart_invite))
-	return 0;
+  assert(sip); assert(ss);
 
-      if (ss->ss_state < nua_callstate_ready)
-	terminated = 1;
+  if (ss && sip && sip->sip_rseq) {
+    /* Handle 100rel responses */
+    sip_rseq_t *rseq = sip->sip_rseq;
+
+    /* Establish early dialog - we should fork here */
+    if (!nua_dialog_is_established(nh->nh_ds)) {
+      nta_outgoing_t *tagged;
+
+      nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
+      nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
+      
+      /* Tag the INVITE request */
+      tagged = nta_outgoing_tagged(cr->cr_orq,
+				   nua_client_orq_response, cr,
+				   sip->sip_to->a_tag, sip->sip_rseq);
+      if (tagged) {
+	nta_outgoing_destroy(cr->cr_orq), cr->cr_orq = tagged;
+      }
+      else {
+	cr->cr_graceful = 1;
+	ss->ss_reason = "SIP;cause=500;text=\"Cannot Create Early Dialog\"";
+      }
+    }
+  
+    if (!rseq) {
+      SU_DEBUG_5(("nua(%p): 100rel missing RSeq\n", (void *)nh));
+    }
+    else if (nta_outgoing_rseq(cr->cr_orq) > rseq->rs_response) {
+      SU_DEBUG_5(("nua(%p): 100rel bad RSeq %u (got %u)\n", (void *)nh, 
+		  (unsigned)rseq->rs_response,
+		  nta_outgoing_rseq(cr->cr_orq)));
+      return 1;    /* Do not send event */
+    }
+    else if (nta_outgoing_setrseq(cr->cr_orq, rseq->rs_response) < 0) {
+      SU_DEBUG_1(("nua(%p): cannot set RSeq %u\n", (void *)nh, 
+		  (unsigned)rseq->rs_response));
+      cr->cr_graceful = 1;
+      ss->ss_reason = "SIP;cause=400;text=\"Bad RSeq\"";
     }
   }
-  else if (status >= 200) {
-    du->du_ready = 1;
-    cr->cr_usage = NULL;
 
-    /* XXX - check remote tag, handle forks */
-    /* Set route, contact, nh_ds->ds_remote_tag */
-    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
-    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
-
-    init_session_timer(ss, sip, NH_PGET(nh, refresher));
-    set_session_timer(ss);
-
-    /* signal_call_state_change */
-    if (session_process_response(nh, cr, orq, sip, &received) >= 0) {
-      ss->ss_ack_needed = received ? received : "";
-
-      if (NH_PGET(nh, auto_ack) ||
-	  /* Auto-ACK response to re-INVITE unless auto_ack is set to 0 */
-	  (ss->ss_state == nua_callstate_ready &&
-	   !NH_PISSET(nh, auto_ack)))
-	nua_stack_ack(nua, nh, nua_r_ack, NULL);
-      else
-	signal_call_state_change(nh, ss, status, phrase,
-				 nua_callstate_completing, received, 0);
-      nh_referral_respond(nh, SIP_200_OK);
-      return 0;
-    }
+  return nua_session_client_response(cr, status, phrase, sip);
+}
+
+/** Process response to a session request (INVITE, PRACK, UPDATE) */
+static int nua_session_client_response(nua_client_request_t *cr,
+				       int status, char const *phrase,
+				       sip_t const *sip)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+
+  char const *sdp = NULL;
+  size_t len;
+  char const *received = NULL;
 
-    status = 500, phrase = "Malformed Session in Response";
+#define LOG3(m) \
+  SU_DEBUG_3(("nua(%p): %s: %s %s in %u %s\n", \
+	      (void *)nh, cr->cr_method_name, (m),		\
+	      received ? received : "SDP", status, phrase))
+#define LOG5(m) \
+  SU_DEBUG_5(("nua(%p): %s: %s %s in %u %s\n", \
+	      (void *)nh, cr->cr_method_name, (m), received, status, phrase))
 
-    nua_stack_ack(nua, nh, nua_r_ack, NULL);
-    gracefully = 1;
+  if (!ss || !sip || 300 <= status)
+    /* Xyzzy */;
+  else if (!session_get_description(sip, &sdp, &len))
+    /* No SDP */;
+  else if (cr->cr_answer_recv) {
+    /* Ignore spurious answers after completing O/A */
+    LOG3("ignoring duplicate");
+    sdp = NULL;
   }
-  else if (sip->sip_rseq) {
-    /* Reliable provisional response */
-    nh_referral_respond(nh, status, phrase);
+  else if (cr->cr_offer_sent) {
+    /* case 1: incoming answer */
+    cr->cr_answer_recv = status;
+    received = "answer";
 
-    return process_100rel(nh, ss, orq, sip); /* signal_call_state_change */
+    if (nh->nh_soa == NULL)
+      LOG5("got SDP");
+    else if (soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0) {
+      LOG3("error parsing SDP");
+      sdp = NULL;
+      cr->cr_graceful = 1;
+      ss->ss_reason = "SIP;cause=400;text=\"Malformed Session Description\"";
+    }
+    else if (soa_process_answer(nh->nh_soa, NULL) < 0) {
+      LOG5("error processing SDP");
+      /* XXX */
+      sdp = NULL;
+    }
+    else if (soa_activate(nh->nh_soa, NULL) < 0)
+      /* XXX - what about errors? */
+      LOG3("error activating media after");
+    else
+      LOG5("processed SDP");
+  }
+  else if (cr->cr_method != sip_method_invite) {
+    /* If non-invite request did not have offer, ignore SDP in response */
+    LOG3("ignoring extra");
+    sdp = NULL;
   }
   else {
-    /* Provisional response */
-    nh_referral_respond(nh, status, phrase);
-    session_process_response(nh, cr, orq, sip, &received);
-    signal_call_state_change(nh, ss, status, phrase,
-			     nua_callstate_proceeding, received, 0);
-    return 0;
+    /* case 2: answer to our offer */
+    cr->cr_offer_recv = 1, cr->cr_answer_sent = 0;
+    received = "offer";
+
+    if (nh->nh_soa && soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0) {
+      LOG3("error parsing SDP");
+      sdp = NULL;
+      cr->cr_graceful = 1;
+      ss->ss_reason = "SIP;cause=400;text=\"Malformed Session Description\"";
+    }
+    else 
+      LOG5("got SDP");
   }
 
-  cr->cr_usage = NULL;
+  if (ss && received)
+    ss->ss_oa_recv = received;
+
+  if (sdp && nh->nh_soa)
+    return nua_base_client_tresponse(cr, status, phrase, sip,
+				     NH_REMOTE_MEDIA_TAGS(1, nh->nh_soa),
+				     TAG_END());
+  else
+    return nua_base_client_response(cr, status, phrase, sip, NULL);
+}
+
+static int nua_invite_client_report(nua_client_request_t *cr,
+				    int status, char const *phrase,
+				    sip_t const *sip,
+				    nta_outgoing_t *orq,
+				    tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  unsigned next_state;
+  int error;
 
   nh_referral_respond(nh, status, phrase);
-  nua_stack_process_response(nh, cr, orq, sip, TAG_END());
 
-  if (terminated)
-    signal_call_state_change(nh, ss, status, phrase,
-			     nua_callstate_terminated, 0, 0);
+  nua_stack_event(nh->nh_nua, nh, 
+		  nta_outgoing_getresponse(orq),
+		  cr->cr_event,
+		  status, phrase,
+		  tags);
+
+  if (orq != cr->cr_orq && status != 100)
+    return 1;
 
-  if (terminated < 0) {
-    nua_dialog_terminated(nh, nh->nh_ds, status, phrase);
+  if (ss == NULL) {
+    signal_call_state_change(nh, ss, status, phrase, nua_callstate_terminated);
+    return 1;
   }
-  else if (terminated > 0) {
-    nua_dialog_usage_remove(nh, nh->nh_ds, du);
+
+  ss->ss_reporting = 1;
+
+  if (cr->cr_neutral) {
+    signal_call_state_change(nh, ss, status, phrase, ss->ss_state);
+    ss->ss_reporting = 0;
+    return 1;
   }
-  else if (gracefully) {
-    char *reason =
-      su_sprintf(NULL, "SIP;cause=%u;text=\"%s\"", 
-		 status > 699 ? 500 : status, phrase);
 
-    signal_call_state_change(nh, ss, status, phrase,
-			     nua_callstate_terminating, 0, 0);
+  if (status == 100) {
+    next_state = nua_callstate_calling;
+  }
+  else if (status < 300 && cr->cr_graceful) {
+    next_state = nua_callstate_terminating;
+    if (200 <= status) {
+      nua_invite_client_ack(cr, NULL);
+    }
+  }
+  else if (status < 200) {
+    next_state = nua_callstate_proceeding;
+
+    if (sip && sip->sip_rseq && 
+	!SIP_IS_ALLOWED(NH_PGET(nh, appl_method), sip_method_prack)) {
+      sip_rack_t rack[1];
 
-    nua_stack_post_signal(nh, nua_r_bye,
-			  SIPTAG_REASON_STR(reason),
-			  TAG_END());
+      sip_rack_init(rack);
+      rack->ra_response    = sip->sip_rseq->rs_response;
+      rack->ra_cseq        = sip->sip_cseq->cs_seq;
+      rack->ra_method      = sip->sip_cseq->cs_method;
+      rack->ra_method_name = sip->sip_cseq->cs_method_name;
+
+      error = nua_client_tcreate(nh, nua_r_prack, &nua_prack_client_methods, 
+				 SIPTAG_RACK(rack),
+				 TAG_END());
+      if (error < 0) {
+	cr->cr_graceful = 1;
+	next_state = nua_callstate_terminating;
+      }
+    }
+  }
+  else if (status < 300) {
+    next_state = nua_callstate_completing;
+  }
+  else if (cr->cr_terminated) {
+    next_state = nua_callstate_terminated;
+  }
+  else if (cr->cr_graceful && ss->ss_state >= nua_callstate_completing) {
+    next_state = nua_callstate_terminating;
+  }
+  else {
+    next_state = nua_callstate_init;
+  }
 
-    su_free(NULL, reason);
+  if (next_state == nua_callstate_calling) {
+    if (sip && sip->sip_status && sip->sip_status->st_status == 100) {
+      ss->ss_reporting = 0;
+      return 1;
+    }
   }
 
-  return 0;
+  if (next_state == nua_callstate_completing) {
+    if (NH_PGET(nh, auto_ack) ||
+	/* Auto-ACK response to re-INVITE unless auto_ack is set to 0 */
+	(ss->ss_state == nua_callstate_ready &&
+	 !NH_PISSET(nh, auto_ack))) {
+
+      if (nua_invite_client_ack(cr, NULL) > 0)
+	next_state = nua_callstate_ready;
+      else
+	next_state = nua_callstate_terminating;
+    }
+  }
+
+  if (next_state == nua_callstate_terminating) {
+    /* Send BYE or CANCEL */
+    /* XXX - Forking - send BYE to early dialog?? */
+    if (ss->ss_state > nua_callstate_proceeding || status >= 200)
+      error = nua_client_create(nh, nua_r_bye, &nua_bye_client_methods, NULL);
+    else
+      error = nua_client_create(nh, nua_r_cancel, 
+				&nua_cancel_client_methods, tags);
+
+    if (error) {
+      next_state = nua_callstate_terminated;
+      cr->cr_terminated = 1;
+    }
+    cr->cr_graceful = 0;
+  }
+
+  ss->ss_reporting = 0;
+
+  signal_call_state_change(nh, ss, status, phrase, next_state);
+
+  return 1;
 }
 
 /**@fn void nua_ack(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
@@ -798,7 +989,7 @@
  * Acknowledge a succesful response to INVITE request.
  *
  * Acknowledge a successful response (200..299) to INVITE request with the
- * SIP ACK request message. This function is need only if NUTAG_AUTOACK()
+ * SIP ACK request message. This function is needed only if NUTAG_AUTOACK()
  * parameter has been cleared.
  *
  * @param nh              Pointer to operation handle
@@ -820,201 +1011,200 @@
 int nua_stack_ack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
 		  tagi_t const *tags)
 {
-  nua_session_usage_t *ss;
-  nua_client_request_t *cr;
-  nta_outgoing_t *ack = NULL;
-  msg_t *msg;
-  sip_t *sip;
-  int status = 200;
-  char const *phrase = "OK", *reason = NULL, *sent = NULL;
-  char const *received;
+  nua_dialog_usage_t *du = nua_dialog_usage_for_session(nh->nh_ds);
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  nua_client_request_t *cr = du ? du->du_cr : NULL;
+  int error;
 
-  ss = nua_session_usage_get(nh->nh_ds);
-  cr = ss->ss_crequest;
+  if (!cr || cr->cr_orq == NULL || cr->cr_status < 200) {
+    UA_EVENT2(nua_i_error, 900, "No response to ACK");
+    return 1;
+  }
 
-  received = ss ? ss->ss_ack_needed : NULL;
+  if (tags) {
+    nua_stack_set_params(nua, nh, nua_i_error, tags);
+    if (nh->nh_soa)
+      soa_set_params(nh->nh_soa, TAG_NEXT(tags));
+  }
 
-  if (!received)
-    return UA_EVENT2(nua_i_error, 900, "No response to ACK");
+  error = nua_invite_client_ack(cr, tags);
 
-  ss->ss_ack_needed = 0;
+  if (error < 0) {
+    if (ss->ss_reason == NULL)
+      ss->ss_reason = "SIP;cause=500;text=\"Internal Error\"";
+    ss->ss_reporting = 1;	/* We report state here if BYE fails */
+    error = nua_client_create(nh, nua_r_bye, &nua_bye_client_methods, NULL);
+    ss->ss_reporting = 0;
+    signal_call_state_change(nh, ss, 500, "Internal Error", 
+			     error 
+			     ? nua_callstate_terminated
+			     : nua_callstate_terminating);
+  }
+  else if (ss)
+    signal_call_state_change(nh, ss, 200, "ACK sent", nua_callstate_ready);
 
-  if (!received[0])
-    received = NULL;
+  if (!nua_client_is_queued(cr) && !nua_client_is_bound(cr))
+    nua_client_request_destroy(cr);
 
-  if (tags)
-    nua_stack_set_params(nua, nh, nua_i_error, tags);
+  nua_client_next_request(nh->nh_ds->ds_cr, 1);
 
-  msg = nua_creq_msg(nua, nh, cr, 0,
-		     SIP_METHOD_ACK,
-		     /* NUTAG_COPY(0), */
-		     TAG_NEXT(tags));
-  sip = sip_object(msg);
+  return 0;
+}
 
-  if (sip && nh->nh_soa) {
-    if (tags)
-      soa_set_params(nh->nh_soa, TAG_NEXT(tags));
+/** Send ACK, destroy INVITE transaction.
+ *
+ *  @retval 1 if successful
+ *  @retval < 0 if an error occurred
+ */
+static
+int nua_invite_client_ack(nua_client_request_t *cr, tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_state_t *ds = nh->nh_ds;
+  nua_session_usage_t *ss = nua_dialog_usage_private(cr->cr_usage);
 
-    if (cr->cr_offer_recv && !cr->cr_answer_sent) {
-      if (soa_generate_answer(nh->nh_soa, NULL) < 0 ||
+  msg_t *msg;
+  sip_t *sip;
+  int error = -1;
+  sip_authorization_t *wa;
+  sip_proxy_authorization_t *pa;
+  sip_cseq_t *cseq;
+  nta_outgoing_t *ack;
+  int status = 200;
+  char const *phrase = "OK", *reason = NULL;
+
+  assert(ds->ds_leg);
+  assert(cr->cr_orq);
+
+  msg = nta_outgoing_getrequest(cr->cr_orq);
+  sip = sip_object(msg);  
+  if (!msg)
+    return -1;
+  
+  wa = sip_authorization(sip);
+  pa = sip_proxy_authorization(sip);
+  
+  msg_destroy(msg);
+
+  msg = nta_msg_create(nh->nh_nua->nua_nta, 0);
+  sip = sip_object(msg);  
+  if (!msg)
+    return -1;
+
+  cseq = sip_cseq_create(msg_home(msg), cr->cr_seq, SIP_METHOD_ACK);
+
+  if (!cseq)
+    ;
+  else if (nh->nh_tags && sip_add_tl(msg, sip, TAG_NEXT(nh->nh_tags)) < 0)
+    ;
+  else if (tags && sip_add_tl(msg, sip, TAG_NEXT(tags)) < 0)
+    ;
+  else if (wa && sip_add_dup(msg, sip, (sip_header_t *)wa) < 0)
+    ;
+  else if (pa && sip_add_dup(msg, sip, (sip_header_t *)pa) < 0)
+    ;
+  else if (sip_header_insert(msg, sip, (sip_header_t *)cseq) < 0)
+    ;
+  else if (nta_msg_request_complete(msg, ds->ds_leg, SIP_METHOD_ACK, NULL) < 0)
+    ;
+  else {
+    /* Remove extra headers */
+    while (sip->sip_allow)
+      sip_header_remove(msg, sip, (sip_header_t*)sip->sip_allow);
+    while (sip->sip_priority)
+      sip_header_remove(msg, sip, (sip_header_t*)sip->sip_priority);
+    while (sip->sip_proxy_require)
+      sip_header_remove(msg, sip, (sip_header_t*)sip->sip_proxy_require);
+    while (sip->sip_require)
+      sip_header_remove(msg, sip, (sip_header_t*)sip->sip_require);
+    while (sip->sip_subject)
+      sip_header_remove(msg, sip, (sip_header_t*)sip->sip_subject);
+    while (sip->sip_supported)
+      sip_header_remove(msg, sip, (sip_header_t*)sip->sip_supported);
+
+    if (ss == NULL || ss->ss_state >= nua_callstate_ready)
+      ;
+    else if (cr->cr_offer_recv && !cr->cr_answer_sent) {
+      if (nh->nh_soa == NULL) {
+	if (session_get_description(sip, NULL, NULL))
+	  cr->cr_answer_sent = 1, ss->ss_oa_sent = "answer";
+      }
+      else if (soa_generate_answer(nh->nh_soa, NULL) < 0 ||
 	  session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
-	reason = soa_error_as_sip_reason(nh->nh_soa);
 	status = 900, phrase = "Internal media error";
 	reason = "SIP;cause=500;text=\"Internal media error\"";
+	/* reason = soa_error_as_sip_reason(nh->nh_soa); */
       }
       else {
-	cr->cr_answer_sent = 1;
-	soa_activate(nh->nh_soa, NULL);
-
-	/* signal that O/A round is complete */
-	sent = "answer";
+	cr->cr_answer_sent = 1, ss->ss_oa_sent = "answer";
       }
     }
 
-    if (!reason &&
-	/* ss->ss_offer_sent && !ss->ss_answer_recv */
-	!soa_is_complete(nh->nh_soa)) {
-      /* No SDP answer in 2XX response -> terminate call */
+    if (ss == NULL || ss->ss_state >= nua_callstate_ready || reason)
+      ;
+    else if (nh->nh_soa
+	     ? soa_is_complete(nh->nh_soa)
+	     : !(cr->cr_offer_sent && !cr->cr_answer_recv)) {
+      /* signal that O/A round(s) is (are) complete */
+      if (nh->nh_soa) 
+	soa_activate(nh->nh_soa, NULL);
+    }
+    else {
+      /* No SDP answer -> terminate call */
       status = 988, phrase = "Incomplete offer/answer";
       reason = "SIP;cause=488;text=\"Incomplete offer/answer\"";
     }
-  }
-
-  if (sip) {
-    msg_t *imsg = nta_outgoing_getrequest(cr->cr_orq);
-    sip_t const *isip = sip_object(imsg);
-    if (isip->sip_proxy_authorization)
-      sip_add_dup(msg, sip, (void *)isip->sip_proxy_authorization);
-    if (isip->sip_authorization)
-      sip_add_dup(msg, sip, (void *)isip->sip_authorization);
-    msg_destroy(imsg);
-  }
-
-  if (sip)
-    ack = nta_outgoing_mcreate(nua->nua_nta, NULL, NULL, NULL, msg,
-			       SIPTAG_END(), TAG_NEXT(tags));
+    
+    if ((ack = nta_outgoing_mcreate(nh->nh_nua->nua_nta, NULL, NULL, NULL,
+				    msg,
+				    SIPTAG_END(),
+				    TAG_NEXT(tags)))) {
+      nta_outgoing_destroy(ack);	/* TR engine keeps this around for T2 */
 
-  if (!ack) {
-    if (!reason) {
+      if (nh->nh_soa && reason && ss && ss->ss_state <= nua_callstate_ready)
+	nua_stack_event(nh->nh_nua, nh, NULL,
+			nua_i_media_error, status, phrase,
+			NULL);
+    }
+    else if (!reason) {
       status = 900, phrase = "Cannot send ACK";
       reason = "SIP;cause=500;text=\"Internal Error\"";
     }
-    msg_destroy(msg);
-  }
 
-  nua_creq_deinit(cr, NULL);	/* Destroy INVITE transaction */
-  nta_outgoing_destroy(ack);	/* TR engine keeps this around for T2 */
+    if (ss && reason)
+      ss->ss_reason = reason;
 
-  if (status < 300) {
-    signal_call_state_change(nh, ss, status, phrase, nua_callstate_ready,
-			     received, sent);
-  }
-  else {
-    signal_call_state_change(nh, ss, status, phrase, nua_callstate_terminating,
-			     0, 0);
-    nua_stack_post_signal(nh, nua_r_bye,
-			  SIPTAG_REASON_STR(reason),
-			  TAG_END());
+    if (status < 300)
+      error = 1;
+    else
+      error = -2;
   }
 
-  return 0;
-}
-
-
-/* Process reliable provisional response */
-static int
-process_100rel(nua_handle_t *nh,
-	       nua_session_usage_t *ss,
-	       nta_outgoing_t *orq,
-	       sip_t const *sip)
-{
-  nua_client_request_t *cr_invite = ss->ss_crequest;
-  nua_client_request_t *cr_prack = nh->nh_ds->ds_cr;
-  
-  sip_rseq_t *rseq;
-  char const *recv = NULL;
-  int status; char const *phrase;
-
-  if (cr_prack->cr_orq) {
-    /* XXX - better luck next time */
-    SU_DEBUG_3(("nua(%p): cannot send PRACK because %s is pending\n", nh,
-		nta_outgoing_method_name(cr_prack->cr_orq)));
-    return 0; /* Wait until this response is re-transmitted */
-  }
+  if (error == -1)
+    msg_destroy(msg);
 
-  if (!nua_dialog_is_established(nh->nh_ds)) {
-    /* Establish early dialog */
-    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
-    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
-    
-    /* Tag the INVITE request */
-    cr_invite->cr_orq =
-      nta_outgoing_tagged(orq, process_response_to_invite, nh,
-			  sip->sip_to->a_tag, sip->sip_rseq);
-    nta_outgoing_destroy(orq);
-    orq = cr_invite->cr_orq;
-  }
+  nta_outgoing_destroy(cr->cr_orq), cr->cr_orq = NULL;
+  nua_client_request_remove(cr);
   
-  assert(sip);
-
-  status = sip->sip_status->st_status, phrase = sip->sip_status->st_phrase;
-  rseq = sip->sip_rseq;
-
-  if (!rseq) {
-    SU_DEBUG_5(("nua(%p): 100rel missing RSeq\n", nh));
-  }
-  else if (rseq->rs_response <= nta_outgoing_rseq(orq)) {
-    SU_DEBUG_5(("nua(%p): 100rel bad RSeq %u (got %u)\n", nh, 
-		(unsigned)rseq->rs_response,
-		nta_outgoing_rseq(orq)));
-    /* XXX - send nua_r_invite event or not? */
-    return 0;
-  }
-  else if (nta_outgoing_setrseq(orq, rseq->rs_response) < 0) {
-    SU_DEBUG_1(("nua(%p): cannot set RSeq %u\n", nh, 
-		(unsigned)rseq->rs_response));
-  }
-  else if (session_process_response(nh, cr_invite, orq, sip, &recv) < 0) {
-    assert(nh->nh_soa);
-    status = soa_error_as_sip_response(nh->nh_soa, &phrase);
-    nua_stack_event(nh->nh_nua, nh, NULL,
-		    nua_i_media_error, status, phrase, TAG_END());
-  }
-  /* Here we could let application PRACK and just send state event */
-  else {
-    sip_rack_t rack[1];
-    tagi_t tags[] = {
-      { TAG_SKIP(nua_stack_prack) }, /* this is autoprack */
-      { NUTAG_STATUS(status), },
-      { NUTAG_PHRASE(phrase), },
-      { NUTAG_PHRASE(recv), },
-      { SIPTAG_RACK(rack) }, 
-      { TAG_END() }
-    };
-
-    sip_rack_init(rack);
-
-    rack->ra_response    = sip->sip_rseq->rs_response;
-    rack->ra_cseq        = sip->sip_cseq->cs_seq;
-    rack->ra_method      = sip->sip_cseq->cs_method;
-    rack->ra_method_name = sip->sip_cseq->cs_method_name;
-
-    nua_stack_prack(nh->nh_nua, nh, nua_r_prack, tags);
-
-    return 0;
-  }
+  return error;
+}
 
-  /* XXX - CANCEL INVITE or BYE this session? */
-  /* Because we don't do forking very well we just cancel INVITE */
-  nua_stack_cancel(nh->nh_nua, nh, nua_r_cancel, NULL);
+/** Deinitialize client request */
+static int nua_invite_client_deinit(nua_client_request_t *cr)
+{
+  if (cr->cr_orq == NULL)
+    /* Xyzzy */;
+  else if (cr->cr_status < 200)
+    nta_outgoing_cancel(cr->cr_orq);
+  else
+    nua_invite_client_ack(cr, NULL);
 
   return 0;
 }
 
-/**@fn void nua_prack(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
- * Send a PRACK request. 
+/**@fn void nua_cancel(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
  *
- * PRACK is used to acknowledge receipt of 100rel responses. See @RFC3262.
+ * Cancel an INVITE operation 
  *
  * @param nh              Pointer to operation handle
  * @param tag, value, ... List of tagged parameters
@@ -1023,300 +1213,137 @@
  *    nothing
  *
  * @par Related Tags:
- *    Tags in <sofia-sip/soa_tag.h>, <sofia-sip/sip_tag.h>.
+ *    Tags in <sip_tag.h>
  *
  * @par Events:
- *    #nua_r_prack
+ *    #nua_r_cancel, #nua_i_state  (#nua_i_active, #nua_i_terminated)
+ *
+ * @sa @ref nua_call_model, nua_invite(), #nua_i_cancel
  */
 
-/** @NUA_EVENT nua_r_prack
+static int nua_cancel_client_request(nua_client_request_t *cr,
+				     msg_t *msg, sip_t *sip,
+				     tagi_t const *tags);
+
+nua_client_methods_t const nua_cancel_client_methods = {
+  SIP_METHOD_CANCEL,
+  0,
+  { 
+    /* create_dialog */ 0,
+    /* in_dialog */ 1,
+    /* target refresh */ 0
+  },
+  NULL,
+  NULL,
+  nua_cancel_client_request,
+  /* nua_cancel_client_check_restart */ NULL,
+  /* nua_cancel_client_response */ NULL
+};
+
+int nua_stack_cancel(nua_t *nua, nua_handle_t *nh, nua_event_t e,
+		     tagi_t const *tags)
+{
+  return nua_client_create(nh, e, &nua_cancel_client_methods, tags);
+}
+
+static int nua_cancel_client_request(nua_client_request_t *cr,
+				     msg_t *msg, sip_t *sip,
+				     tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = nua_dialog_usage_for_session(nh->nh_ds);
+
+  if (!du || !du->du_cr || !du->du_cr->cr_orq || 
+      nta_outgoing_status(du->du_cr->cr_orq) >= 200) {
+    return nua_client_return(cr, 481, "No transaction to CANCEL", msg);
+  }
+
+  cr->cr_orq = nta_outgoing_tcancel(du->du_cr->cr_orq,
+				    nua_client_orq_response, cr,
+				    TAG_NEXT(tags));
+
+  return cr->cr_orq ? 0 : -1;
+}
+
+/** @NUA_EVENT nua_r_cancel
  *
- * Response to an outgoing @b PRACK request. PRACK request is used to
- * acknowledge reliable preliminary responses and it is usually sent
- * automatically by the nua stack.
+ * Answer to outgoing CANCEL.
  *
- * @param status response status code
- *               (if the request is retried, @a status is 100, the @a
- *               sip->sip_status->st_status contain the real status code
- *               from the response message, e.g., 302, 401, or 407)
+ * The CANCEL may be sent explicitly by nua_cancel() or implicitly by NUA
+ * state machine.
+ *
+ * @param status response status code 
  * @param phrase a short textual description of @a status code
  * @param nh     operation handle associated with the call
  * @param hmagic application context associated with the call
- * @param sip    response to @b PRACK or NULL upon an error
+ * @param sip    response to CANCEL request or NULL upon an error
  *               (status code is in @a status and 
  *                descriptive message in @a phrase parameters)
  * @param tags   empty
  *
- * @sa nua_prack(), #nua_i_prack, @RFC3262
+ * @sa nua_cancel(), @ref nua_uac_call_model, #nua_r_invite, nua_invite(),
+ * #nua_i_state
  *
  * @END_NUA_EVENT
  */
 
-
-int nua_stack_prack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-		    tagi_t const *tags)
-{
-  nua_session_usage_t *ss;
-  nua_client_request_t *cr;
-  msg_t *msg;
-  sip_t *sip;
-  int offer_sent_in_prack = 0, answer_sent_in_prack = 0;
-
-  int status = 0; char const *phrase = "PRACK sent";
-  char const *recv = NULL, *sent = NULL;
-
-  int autoprack =		/* XXX - should have common indication */
-    tags && tags->t_tag == tag_skip && 
-    tags->t_value == (tag_value_t)nua_stack_prack;
-
-  if (autoprack) {
-    status = (int)tags[1].t_value; 
-    phrase = (char const *)tags[2].t_value;
-    recv = (char const *)tags[3].t_value;
-    tags += 4;
-  }
-
-  ss = nua_session_usage_get(nh->nh_ds);
-
-  if (!ss || !ss->ss_crequest || !nta_outgoing_rseq(ss->ss_crequest->cr_orq))
-    return UA_EVENT2(e, 900, "Nothing to PRACK");
-  else if (nh->nh_ds->ds_cr->cr_orq)
-    return UA_EVENT2(e, 900, "Request already in progress");
-
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
-
-  cr = nh->nh_ds->ds_cr;
-
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
-		     SIP_METHOD_PRACK,
-		     NUTAG_USE_DIALOG(1),
-		     NUTAG_ADD_CONTACT(1),
-		     TAG_NEXT(tags));
-
-  sip = sip_object(msg);
-
-  if (sip) {
-    nua_client_request_t *cri = ss->ss_crequest;
-    if (nh->nh_soa == NULL)
-      /* It is up to application to handle SDP */;
-    else if (sip->sip_payload)
-      /* XXX - we should just do MIME in session_include_description() */;
-    else if (cri->cr_offer_recv && !cri->cr_answer_sent) {
-
-      if (soa_generate_answer(nh->nh_soa, NULL) < 0 ||
-	  session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
-
-	status = soa_error_as_sip_response(nh->nh_soa, &phrase);
-	SU_DEBUG_3(("nua(%p): PRACK answer: %d %s\n", nh, status, phrase));
-	nua_stack_event(nh->nh_nua, nh, NULL,
-			nua_i_media_error, status, phrase, TAG_END());
-
-	goto error;
-      }
-      else {
-	answer_sent_in_prack = 1, sent = "answer";
-	soa_activate(nh->nh_soa, NULL);
-      }
-    }
-    /* When 100rel response status was 183 fake support for preconditions */
-    else if (autoprack && status == 183 && ss->ss_precondition) {
-
-      if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0 ||
-	  session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
-
-	status = soa_error_as_sip_response(nh->nh_soa, &phrase);
-	SU_DEBUG_3(("nua(%p): PRACK offer: %d %s\n", nh, status, phrase));
-	nua_stack_event(nh->nh_nua, nh, NULL,
-			nua_i_media_error, status, phrase, TAG_END());
-	goto error;
-      }
-      else {
-	offer_sent_in_prack = 1, sent = "offer";
-      }
-    }
-
-    if (nh->nh_auth) {
-      if (auc_authorize(&nh->nh_auth, msg, sip) < 0)
-	/* xyzzy */;
-    }
-
-    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				      process_response_to_prack, nh, NULL,
-				      msg,
-				      SIPTAG_END(), TAG_NEXT(tags));
-    if (cr->cr_orq) {
-      cr->cr_usage = nua_dialog_usage_public(ss);
-      cr->cr_event = nua_r_prack;
-
-      if (answer_sent_in_prack)
-	cri->cr_answer_sent = 1;
-      else if (offer_sent_in_prack)
-	cr->cr_offer_sent = 1;
-
-      if (autoprack) 
-	signal_call_state_change(nh, ss, status, phrase,
-				 nua_callstate_proceeding, recv, sent);
-      else
-	signal_call_state_change(nh, ss, 0, "PRACK sent",
-				 nua_callstate_proceeding, NULL, sent);
-	
-
-      return cr->cr_event = e;
-    }
-  }
-
- error:
-  msg_destroy(msg);
-  return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-}
-
-void restart_prack(nua_handle_t *nh, tagi_t *tags)
-{
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_prack, tags);
-}
-
-
-static int
-process_response_to_prack(nua_handle_t *nh,
-			  nta_outgoing_t *orq,
-			  sip_t const *sip)
-{
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  nua_session_usage_t *ss = nua_dialog_usage_private(cr->cr_usage);
-  int status;
-  char const *phrase = "OK", *reason = NULL, *recv = NULL;
-
-  assert(cr->cr_usage && cr->cr_usage->du_class == nua_session_usage);
-
-  if (sip)
-    status = sip->sip_status->st_status, phrase = sip->sip_status->st_phrase;
-  else
-    status = 408, phrase = sip_408_Request_timeout;
-
-  SU_DEBUG_5(("nua: process_response_to_prack: %u %s\n", status, phrase));
-
-  if (nua_creq_check_restart(nh, cr, orq, sip, restart_prack))
-    return 0;
-
-  if (status < 200)
-    return 0;
-
-  cr->cr_usage = NULL;
-
-  if (status < 300) {
-    if (session_process_response(nh, cr, orq, sip, &recv) < 0) {
-      status = 900, phrase = "Malformed Session in Response";
-      reason = "SIP;status=400;phrase=\"Malformed Session in Response\"";
-    }
-  }
-  else
-    nua_stack_process_response(nh, cr, orq, sip, TAG_END());
-
-  if (recv)
-    signal_call_state_change(nh, ss, status, phrase,
-			     nua_callstate_proceeding, recv, NULL);
-
-  if (status < 300 && ss->ss_update_needed)
-    nua_stack_update(nh->nh_nua, nh, nua_r_update, NULL);
-
-  return 0;
-}
-
-/** Refresh session usage */
 static void nua_session_usage_refresh(nua_handle_t *nh,
 				      nua_dialog_state_t *ds,
 				      nua_dialog_usage_t *du,
 				      sip_time_t now)
 {
-  tagi_t const timer_tags[2] = {
-    { SIPTAG_SUBJECT_STR("Session refresh") }, 
-    { TAG_END() }
-  };
-  tagi_t const refresh_tags[2] = {
-    { SIPTAG_SUBJECT_STR("Dialog refresh") }, 
-    { TAG_END() }
-  };
-
-  nua_session_usage_t const *ss = nua_dialog_usage_private(du);
-  nua_client_request_t const *cri = ss->ss_crequest, *cro = ds->ds_cr;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  nua_client_request_t const *cr = du->du_cr;
   nua_server_request_t const *sr;
 
+  if (ss->ss_state >= nua_callstate_terminating || 
+      /* INVITE is in progress or being authenticated */
+      (cr && (cr->cr_orq || cr->cr_wait_for_cred)))
+    return;
+
+  /* UPDATE has been queued */
+  for (cr = ds->ds_cr; cr; cr = cr->cr_next) 
+    if (cr->cr_method == sip_method_update)
+      return;
+
+  /* INVITE or UPDATE in progress on server side */
   for (sr = ds->ds_sr; sr; sr = sr->sr_next)
     if (sr->sr_usage == du && 
 	(sr->sr_method == sip_method_invite || 
 	 sr->sr_method == sip_method_update))
-      break;
+      return;
 
-  /* INVITE or UPDATE in progress or being authenticated */
-  if ((cri && cri->cr_orq) || sr)	
-    return;
-  if (ss->ss_state >= nua_callstate_terminating)
+  if (ss->ss_timer->refresher == nua_remote_refresher) {
+    ss->ss_reason = "SIP;cause=408;text=\"Session timeout\""; 
+    nua_stack_bye(nh->nh_nua, nh, nua_r_bye, NULL);
     return;
-
-  if (!ss->ss_refresher) {
-    if (now >= du->du_expires)
-      session_timeout(nh, du, now);
-    else
-      /* Refreshing contact & route set */
-      nua_stack_invite2(nh->nh_nua, nh, nua_r_invite, 1, refresh_tags);
   }
   else if (NH_PGET(nh, update_refresh)) {
-    if (!cro->cr_orq)
-      nua_stack_update(nh->nh_nua, nh, nua_r_update, timer_tags);
-    else
-      nua_dialog_usage_refresh_range(du, 5, 15);
+    nua_stack_update(nh->nh_nua, nh, nua_r_update, NULL);
   }
-  else {
-    nua_stack_invite2(nh->nh_nua, nh, nua_r_invite, 1, timer_tags);
+  else if (du->du_cr) {
+    nua_client_resend_request(du->du_cr, 0);
   }
-}
-
-static
-char const reason_timeout[] = "SIP;cause=408;text=\"Session timeout\"";
-
-static void
-session_timeout(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now)
-{
-  if (now > 1) {
-    nua_session_usage_t *ss = nua_dialog_usage_private(du);
-
-    signal_call_state_change(nh, ss, 408, "Session Timeout",
-			     nua_callstate_terminating, NULL, NULL);
-
-    nua_stack_post_signal(nh, nua_r_bye,
-			  SIPTAG_REASON_STR(reason_timeout),
-			  TAG_END());
+  else {
+    nua_stack_invite(nh->nh_nua, nh, nua_r_invite, NULL);
   }
 }
 
-/** Terminate usage/dialog/handle/agent gracefully */
+/** @interal Shut down session usage. 
+ *
+ * @retval >0  shutdown done
+ * @retval 0   shutdown in progress
+ * @retval <0  try again later
+ */
 static int nua_session_usage_shutdown(nua_handle_t *nh,
 				      nua_dialog_state_t *ds,
 				      nua_dialog_usage_t *du)
 {
   nua_session_usage_t *ss = nua_dialog_usage_private(du);
-  nua_client_request_t *cr;
   nua_server_request_t *sr, *sr_next;
-  int status;
+  nua_client_request_t *cri;
 
-  /* Zap client-side invite transaction */
-  if (ss->ss_crequest->cr_orq) {
-    cr = ss->ss_crequest;
-    status = nta_outgoing_status(cr->cr_orq);
-
-    if (status < 200) 
-      nta_outgoing_tcancel(cr->cr_orq, NULL, NULL, TAG_END());
-
-    if (ss->ss_ack_needed) {
-      msg_t *ack = nua_creq_msg(nh->nh_nua, nh, cr, 0,
-				SIP_METHOD_ACK,
-				TAG_END());
-      nta_outgoing_mcreate(nh->nh_nua->nua_nta, NULL, NULL, NULL, 
-			   ack, TAG_END());
-    }
-
-    nua_creq_deinit(cr, NULL);
-  }
+  assert(ss == nua_session_usage_for_dialog(nh->nh_ds));
 
   /* Zap server-side transactions */
   for (sr = ds->ds_sr; sr; sr = sr_next) {
@@ -1324,54 +1351,58 @@
     if (sr->sr_usage == du) {
       assert(sr->sr_usage == du);
       sr->sr_usage = NULL;
-      if (sr->sr_respond) 
-	nua_server_respond(sr, SIP_480_TEMPORARILY_UNAVAILABLE, TAG_END());
+
+      if (nua_server_request_is_pending(sr)) {
+	SR_STATUS1(sr, SIP_480_TEMPORARILY_UNAVAILABLE);
+	nua_server_respond(sr, NULL);
+	if (nua_server_report(sr) >= 2)
+	  return 480;
+      }
       else
 	nua_server_request_destroy(sr);
     }
   }
 
-  assert(ss == nua_session_usage_get(nh->nh_ds));
+  cri = du->du_cr;
 
   switch (ss->ss_state) {
+  case nua_callstate_calling:
+  case nua_callstate_proceeding:
+    return nua_client_create(nh, nua_r_cancel, &nua_cancel_client_methods, NULL);
+
   case nua_callstate_completing:
-  case nua_callstate_ready:
   case nua_callstate_completed:
-    {
-      msg_t *bye;
-
-      cr = ds->ds_cr;
-      nua_creq_deinit(cr, NULL);
-      bye = nua_creq_msg(nh->nh_nua, nh, ds->ds_cr, 0, 
-			 SIP_METHOD_BYE,
-			 TAG_END());
-      cr->cr_orq = nta_outgoing_mcreate(nh->nh_nua->nua_nta,
-					NULL, NULL, NULL,
-					bye,
-					TAG_END());
-      nua_creq_deinit(cr, NULL);
+  case nua_callstate_ready:
+    if (cri && cri->cr_orq) {
+      if (cri->cr_status < 200)
+	nua_client_create(nh, nua_r_cancel, &nua_cancel_client_methods, NULL);
+      else if (cri->cr_status < 300)
+	nua_invite_client_ack(cri, NULL);
     }
-  }
+    if (nua_client_create(nh, nua_r_bye, &nua_bye_client_methods, NULL) != 0)
+      break;
 
-  nua_dialog_usage_remove(nh, ds, du);
+    signal_call_state_change(nh, ss, 487, "BYE sent",
+			     nua_callstate_terminating);
+    return 0;
 
-  return 0;
-}
+  case nua_callstate_terminating:
+  case nua_callstate_terminated: /* XXX */
+    return 0;
 
-/** Restart invite (e.g., after 302 or 407) */
-void
-restart_invite(nua_handle_t *nh, tagi_t *tags)
-{
-  nua_stack_invite2(nh->nh_nua, nh, nua_r_invite, 1, tags);
-}
+  default:
+    break;
+  }
+  
+  nua_dialog_usage_remove(nh, ds, du);
 
-static int process_response_to_cancel(nua_handle_t *nh,
-				      nta_outgoing_t *orq,
-				      sip_t const *sip);
+  return 200;
+}
 
-/**@fn void nua_cancel(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
+/**@fn void nua_prack(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
+ * Send a PRACK request. 
  *
- * Cancel an INVITE operation 
+ * PRACK is used to acknowledge receipt of 100rel responses. See @RFC3262.
  *
  * @param nh              Pointer to operation handle
  * @param tag, value, ... List of tagged parameters
@@ -1380,108 +1411,205 @@
  *    nothing
  *
  * @par Related Tags:
- *    Tags in <sip_tag.h>
+ *    Tags in <sofia-sip/soa_tag.h>, <sofia-sip/sip_tag.h>.
  *
  * @par Events:
- *    #nua_r_cancel, #nua_i_state  (#nua_i_active, #nua_i_terminated)
- *
- * @sa @ref nua_call_model, nua_invite(), #nua_i_cancel
+ *    #nua_r_prack
  */
 
-int
-nua_stack_cancel(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-		 tagi_t const *tags)
-{
-  nua_session_usage_t *ss;
-  nua_client_request_t *cri, *crc;
-
-  ss = nua_session_usage_get(nh->nh_ds);
-
-  if (!nh || !ss || !ss->ss_crequest->cr_usage ||
-      nta_outgoing_status(ss->ss_crequest->cr_orq) >= 200) {
-    return UA_EVENT2(e, 481, "No transaction to CANCEL");
-  }
-
-  cri = ss->ss_crequest;
-  crc = nh->nh_ds->ds_cr;
-
-  if (tags)
-    nua_stack_set_params(nua, nh, nua_i_error, tags);
-
-  if (nh && cri->cr_orq && cri->cr_usage) {
-    nta_outgoing_t *orq;
-
-    /* nh_referral_respond(nh, SIP_487_REQUEST_TERMINATED); */
-
-    if (e)
-      orq = nta_outgoing_tcancel(cri->cr_orq, process_response_to_cancel, nh,
-				 TAG_NEXT(tags));
-    else
-      orq = nta_outgoing_tcancel(cri->cr_orq, NULL, NULL, TAG_NEXT(tags));
-
-    if (orq == NULL)
-      return nua_stack_event(nua, nh, NULL, e, 400, "Internal error",
-			     TAG_END());
-
-    if (e && crc->cr_orq == NULL)
-      crc->cr_orq = orq, crc->cr_event = e;
-  }
-
-  return 0;
-}
-
-/** @NUA_EVENT nua_r_cancel
- *
- * Answer to outgoing CANCEL.
+/** @NUA_EVENT nua_r_prack
  *
- * The CANCEL may be sent explicitly by nua_cancel() or implicitly by NUA
- * state machine.
+ * Response to an outgoing @b PRACK request. PRACK request is used to
+ * acknowledge reliable preliminary responses and it is usually sent
+ * automatically by the nua stack.
  *
- * @param status response status code 
+ * @param status response status code
+ *               (if the request is retried, @a status is 100, the @a
+ *               sip->sip_status->st_status contain the real status code
+ *               from the response message, e.g., 302, 401, or 407)
  * @param phrase a short textual description of @a status code
  * @param nh     operation handle associated with the call
  * @param hmagic application context associated with the call
- * @param sip    response to CANCEL request or NULL upon an error
+ * @param sip    response to @b PRACK or NULL upon an error
  *               (status code is in @a status and 
  *                descriptive message in @a phrase parameters)
  * @param tags   empty
  *
- * @sa nua_cancel(), @ref nua_uac_call_model, #nua_r_invite, nua_invite(),
- * #nua_i_state
+ * @sa nua_prack(), #nua_i_prack, @RFC3262
  *
  * @END_NUA_EVENT
  */
 
+static int nua_prack_client_init(nua_client_request_t *cr, 
+				 msg_t *msg, sip_t *sip,
+				 tagi_t const *tags);
+static int nua_prack_client_request(nua_client_request_t *cr,
+				    msg_t *msg, sip_t *sip,
+				    tagi_t const *tags);
+static int nua_prack_client_response(nua_client_request_t *cr,
+				     int status, char const *phrase,
+				     sip_t const *sip);
+static int nua_prack_client_report(nua_client_request_t *cr,
+				   int status, char const *phrase,
+				   sip_t const *sip,
+				   nta_outgoing_t *orq,
+				   tagi_t const *tags);
+
+nua_client_methods_t const nua_prack_client_methods = {
+  SIP_METHOD_PRACK,
+  0,
+  { 
+    /* create_dialog */ 0,
+    /* in_dialog */ 1,
+    /* target refresh */ 0
+  },
+  NULL,
+  nua_prack_client_init,
+  nua_prack_client_request,
+  /* nua_prack_client_check_restart */ NULL,
+  nua_prack_client_response,
+  NULL,
+  nua_prack_client_report
+};
+
+int nua_stack_prack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
+		     tagi_t const *tags)
+{
+  return nua_client_create(nh, e, &nua_prack_client_methods, tags);
+}
+
+static int nua_prack_client_init(nua_client_request_t *cr, 
+				 msg_t *msg, sip_t *sip,
+				 tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = nua_dialog_usage_for_session(nh->nh_ds);
+
+  cr->cr_usage = du;
+
+  return 0;
+}
+
+static int nua_prack_client_request(nua_client_request_t *cr,
+				    msg_t *msg, sip_t *sip,
+				    tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  nua_client_request_t *cri;
+  int offer_sent = 0, answer_sent = 0, retval;
+  int status = 0; char const *phrase = "PRACK Sent";
+  uint32_t rseq = 0;
+
+  if (du == NULL)		/* Call terminated */
+    return nua_client_return(cr, SIP_481_NO_TRANSACTION, msg);
+  assert(ss);
+
+  cri = du->du_cr;
+
+  if (sip->sip_rack)
+    rseq = sip->sip_rack->ra_response;
+
+  if (cri->cr_offer_recv && !cri->cr_answer_sent) {
+    if (nh->nh_soa == NULL) 
+      /* It is up to application to handle SDP */
+      answer_sent = session_get_description(sip, NULL, NULL);
+    else if (sip->sip_payload)
+      /* XXX - we should just do MIME in session_include_description() */;
+    else if (soa_generate_answer(nh->nh_soa, NULL) < 0 ||
+	     session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
+      status = soa_error_as_sip_response(nh->nh_soa, &phrase);
+      SU_DEBUG_3(("nua(%p): local response to PRACK: %d %s\n",
+		  (void *)nh, status, phrase));
+      nua_stack_event(nh->nh_nua, nh, NULL,
+		      nua_i_media_error, status, phrase,
+		      NULL);
+      return nua_client_return(cr, status, phrase, msg);
+    }
+    else {
+      answer_sent = 1;
+      soa_activate(nh->nh_soa, NULL);
+    }
+  }
+  else if (nh->nh_soa == NULL) {
+    offer_sent = session_get_description(sip, NULL, NULL);
+  }
+  /* When 100rel response status was 183 do support for preconditions */
+  else if (cri->cr_status == 183 && ss->ss_precondition) {
+    if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0 ||
+	session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
+      status = soa_error_as_sip_response(nh->nh_soa, &phrase);
+      SU_DEBUG_3(("nua(%p): PRACK offer: %d %s\n", (void *)nh,
+		  status, phrase));
+      nua_stack_event(nh->nh_nua, nh, NULL,
+		      nua_i_media_error, status, phrase, NULL);
+      return nua_client_return(cr, status, phrase, msg);
+    }
+    else {
+      offer_sent = 1;
+    }
+  }
+
+  retval = nua_base_client_request(cr, msg, sip, NULL);
 
+  if (retval == 0) {
+    cr->cr_offer_sent = offer_sent;
+    cr->cr_answer_sent = answer_sent;
+
+    if (!cr->cr_restarting) {
+      if (offer_sent) 
+	ss->ss_oa_sent = "offer";
+      else if (answer_sent)
+	ss->ss_oa_sent = "answer";
 
-static int process_response_to_cancel(nua_handle_t *nh,
-				      nta_outgoing_t *orq,
-				      sip_t const *sip)
+      if (!ss->ss_reporting)
+	signal_call_state_change(nh, ss, status, phrase, ss->ss_state);
+    }
+  }
+
+  return retval;
+}
+
+static int nua_prack_client_response(nua_client_request_t *cr,
+				     int status, char const *phrase,
+				     sip_t const *sip)
 {
-  return nua_stack_process_response(nh, nh->nh_ds->ds_cr, orq, sip, TAG_END());
+  /* XXX - fatal error cases? */
+
+  return nua_session_client_response(cr, status, phrase, sip);
 }
 
-/* ---------------------------------------------------------------------- */
-/* UAS side of INVITE */
+static int nua_prack_client_report(nua_client_request_t *cr,
+				   int status, char const *phrase,
+				   sip_t const *sip,
+				   nta_outgoing_t *orq,
+				   tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_session_usage_t *ss = nua_dialog_usage_private(cr->cr_usage);
 
-static int respond_to_invite(nua_server_request_t *sr, tagi_t const *tags);
+  nua_stack_event(nh->nh_nua, nh, 
+		  nta_outgoing_getresponse(orq),
+		  cr->cr_event,
+		  status, phrase,
+		  tags);
 
-static int
-  preprocess_invite(nua_t *, nua_handle_t *, nua_server_request_t **, sip_t *),
-  session_check_request(nua_t *nua,
-			nua_handle_t *nh,
-			nta_incoming_t *irq,
-			sip_t const *sip),
-  process_invite(nua_t *, nua_handle_t *, nua_server_request_t *, sip_t *),
-  process_prack(nua_handle_t *, nta_reliable_t *, nta_incoming_t *,
-		sip_t const *);
+  if (!ss || orq != cr->cr_orq || cr->cr_terminated || cr->cr_graceful)
+    return 1;
 
-static int
-  process_ack_or_cancel(nua_server_request_t *, nta_incoming_t *, 
-			sip_t const *),
-  process_ack(nua_server_request_t *, nta_incoming_t *, sip_t const *),
-  process_cancel(nua_server_request_t *, nta_incoming_t *, sip_t const *),
-  process_timeout(nua_server_request_t *, nta_incoming_t *);
+  if (cr->cr_offer_sent)
+    signal_call_state_change(nh, ss, status, phrase, ss->ss_state);
+
+  if (ss->ss_update_needed && 200 <= status && status < 300 &&
+      !SIP_IS_ALLOWED(NH_PGET(nh, appl_method), sip_method_update))
+    nua_client_create(nh, nua_r_update, &nua_update_client_methods, NULL);
+  
+  return 1;
+}
+
+/* ---------------------------------------------------------------------- */
+/* UAS side of INVITE */
 
 /** @NUA_EVENT nua_i_invite
  *
@@ -1528,16 +1656,18 @@
  * the 2XX response. If @soa is not disabled with NUTAG_MEDIA_ENABLE(0), the
  * SDP should be included in the SOATAG_USER_SDP() or SOATAG_USER_SDP_STR()
  * parameter given to nua_respond(). If it is disabled, the SDP should be
- * included in message
+ * included in the response message using SIPTAG_PAYLOAD() or
+ * SIPTAG_PAYLOAD_STR(). Also, the @ContentType should be set using
+ * SIPTAG_CONTENT_TYPE() or SIPTAG_CONTENT_TYPE_STR().
  *
  * @par Preliminary Responses and 100rel
  *
  * Call progress can be signaled with preliminary responses (with status
  * code in the range 101..199). It is possible to conclude the SDP
  * Offer-Answer negotiation using preliminary responses, too. If
- * SOATAG_USER_SDP() or SOATAG_USER_SDP_STR() parameter is included with in
- * a preliminary nua_response(), the SDP answer is generated and sent with
- * the preliminary responses, too.
+ * NUTAG_EARLY_ANSWER(1), SOATAG_USER_SDP() or SOATAG_USER_SDP_STR()
+ * parameter is included with in a preliminary nua_response(), the SDP
+ * answer is generated and sent with the preliminary responses, too.
  *
  * The preliminary responses are sent reliably if feature tag "100rel" is
  * included in the @Require header of the response or if
@@ -1560,7 +1690,8 @@
  *
  * @sa nua_respond(), @ref nua_uas_call_model, #nua_i_state,
  * NUTAG_MEDIA_ENABLE(), SOATAG_USER_SDP(), SOATAG_USER_SDP_STR(),
- * @RFC3262, NUTAG_EARLY_MEDIA(), NUTAG_ONLY183_100REL(), 
+ * @RFC3262, NUTAG_EARLY_ANSWER(), NUTAG_EARLY_MEDIA(), 
+ * NUTAG_ONLY183_100REL(), 
  * NUTAG_INCLUDE_EXTRA_SDP(),
  * #nua_i_prack, #nua_i_update, nua_update(),
  * nua_invite(), #nua_r_invite
@@ -1579,208 +1710,202 @@
  * @END_NUA_EVENT
  */
 
-/** @internal Process incoming INVITE. */
-int nua_stack_process_invite(nua_t *nua,
-			     nua_handle_t *nh,
-			     nta_incoming_t *irq,
-			     sip_t const *sip)
-{
-  nua_server_request_t *sr, sr0[1];
-  int status;
-  
-  sr = SR_INIT(sr0);
-  sr->sr_irq = irq;
-
-  status = preprocess_invite(nua, nh, &sr, (sip_t *)sip);
+static int nua_invite_server_init(nua_server_request_t *sr);
+static int nua_session_server_init(nua_server_request_t *sr);
+static int nua_invite_server_preprocess(nua_server_request_t *sr);
+static int nua_invite_server_respond(nua_server_request_t *sr, tagi_t const *);
+static int nua_invite_server_is_100rel(nua_server_request_t *, tagi_t const *);
+static int nua_invite_server_report(nua_server_request_t *sr, tagi_t const *);
 
-  if (status) {
-    if (sr->sr_status > 100) 
-      nta_incoming_treply(irq, sr->sr_status, sr->sr_phrase,
-			  SIPTAG_USER_AGENT_STR(NUA_PGET(nua, nh, user_agent)),
-			  TAG_END());
-    nua_server_request_destroy(sr);
-    /* if something has failed, respond with 500 Internal Server Error */
-    return 500; 
-  }
+static int
+  process_ack_or_cancel(nua_server_request_t *, nta_incoming_t *, 
+			sip_t const *),
+  process_ack(nua_server_request_t *, nta_incoming_t *, sip_t const *),
+  process_cancel(nua_server_request_t *, nta_incoming_t *, sip_t const *),
+  process_timeout(nua_server_request_t *, nta_incoming_t *),
+  process_prack(nua_server_request_t *,
+		nta_reliable_t *rel,
+		nta_incoming_t *irq,
+		sip_t const *sip);
 
-  assert(sr != sr0);
+nua_server_methods_t const nua_invite_server_methods = 
+  {
+    SIP_METHOD_INVITE,
+    nua_i_invite,		/* Event */
+    { 
+      1,			/* Create dialog */
+      0,			/* Initial request */
+      1,			/* Target refresh request  */
+      1,			/* Add Contact */
+    },
+    nua_invite_server_init,
+    nua_invite_server_preprocess,
+    nua_base_server_params,
+    nua_invite_server_respond,
+    nua_invite_server_report,
+  };
 
-  return process_invite(nua, sr->sr_owner, sr, (sip_t *)sip);
-}
 
 /** @internal Preprocess incoming invite - sure we have a valid request. 
  * 
- * @return 0 if request is valid, or error statuscode when request has been 
- * responded.
+ * @return 0 if request is valid, or error statuscode otherwise
  */
-static
-int preprocess_invite(nua_t *nua,
-		      nua_handle_t *nh,
-		      nua_server_request_t **inout_sr,
-		      sip_t *sip)
-{
-  nua_dialog_state_t *ds;
-  nua_server_request_t *sr = *inout_sr;
-  nua_server_request_t const *sr0;
-  nua_dialog_usage_t *du;
-  nua_session_usage_t *ss;
-  int have_sdp;
-  char const *sdp;
-  size_t len;
-
-  if (nh) {
-    ds = nh->nh_ds;
-    du = nua_dialog_usage_get(ds, nua_session_usage, NULL);
-    ss = nua_dialog_usage_private(du);
-  }
-  else {
-    nh = nua->nua_dhandle, ds = NULL, du = NULL, ss = NULL;
-  }
+static int
+nua_invite_server_init(nua_server_request_t *sr)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_t *nua = nh->nh_nua;
 
-  sr->sr_usage = du;
+  sr->sr_neutral = 1;
 
   if (!NUA_PGET(nua, nh, invite_enable))
     return SR_STATUS1(sr, SIP_403_FORBIDDEN);
 
-  if (session_check_request(nua, nh, sr->sr_irq, sip))
-    return 500;
-
-  have_sdp = session_get_description(sip, &sdp, &len);
+  if (nua_session_server_init(sr))
+    return sr->sr_status;
+    
+  if (sr->sr_usage) {
+    /* Existing session - check for overlap and glare */ 
 
-  if (ss) {
-    /* Existing session */ 
+    nua_server_request_t const *sr0;
+    nua_client_request_t const *cr;
 
-    for (sr0 = ds->ds_sr; sr0; sr0 = sr0->sr_next) {
+    for (sr0 = nh->nh_ds->ds_sr; sr0; sr0 = sr0->sr_next) {
       /* Final response have not been sent to previous INVITE */
-      if (sr0->sr_method == sip_method_invite && sr0->sr_respond)
+      if (sr0->sr_method == sip_method_invite && 
+	  nua_server_request_is_pending(sr0))
 	break;
-      /* Or we have sent offer but have not received answer */
-      if (have_sdp && sr0->sr_offer_sent && !sr0->sr_answer_recv)
+      /* Or we have sent offer but have not received an answer */
+      if (sr->sr_sdp && sr0->sr_offer_sent && !sr0->sr_answer_recv)
 	break;
-      /* Or we have received request with offer but not sent answer */
-      if (have_sdp && sr0->sr_offer_recv && !sr0->sr_answer_sent)
+      /* Or we have received request with offer but not sent an answer */
+      if (sr->sr_sdp && sr0->sr_offer_recv && !sr0->sr_answer_sent)
 	break;
     }
     
-    if (sr0)
+    if (sr0) {
       /* Overlapping invites - RFC 3261 14.2 */
-      return respond_with_retry_after(nh, sr->sr_irq, 
-				      500, "Overlapping Requests",
-				      0, 10);
+      return nua_server_retry_after(sr, 500, "Overlapping Requests", 0, 10);
+    }
 
-    if ((ss->ss_crequest && ss->ss_crequest->cr_orq) ||
-	(have_sdp && ds && ds->ds_cr->cr_orq && ds->ds_cr->cr_offer_sent)) {
-      /* Glare - RFC 3261 14.2 and RFC 3311 section 5.2 */
-      return SR_STATUS1(sr, SIP_491_REQUEST_PENDING);
+    for (cr = nh->nh_ds->ds_cr; cr; cr = cr->cr_next) {
+      if (cr->cr_usage == sr->sr_usage && cr->cr_orq && cr->cr_offer_sent)
+	/* Glare - RFC 3261 14.2 and RFC 3311 section 5.2 */
+	return SR_STATUS1(sr, SIP_491_REQUEST_PENDING);
     }
   }
 
-  /* Create handle and server request structure when needed */
-  sr = nua_server_request(nua, nh, sr->sr_irq, sip, sr, sizeof *sr,
-			  respond_to_invite, create_dialog);
-  *inout_sr = sr;
+  sr->sr_neutral = 0;
 
-  if (sr->sr_status > 100)
-    return sr->sr_status;
+  return 0;
+}
+
+/** Initialize session server request.
+ *
+ * Ensure that the request is valid.
+ */
+static int
+nua_session_server_init(nua_server_request_t *sr)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_t *nua = nh->nh_nua;
+
+  msg_t *msg = sr->sr_response.msg;
+  sip_t *sip = sr->sr_response.sip;
 
-  nh = sr->sr_owner; assert(nh != nua->nua_dhandle);
-  ds = nh->nh_ds;
+  sip_t const *request = sr->sr_request.sip;
+
+  if (!sr->sr_initial)
+    sr->sr_usage = nua_dialog_usage_get(nh->nh_ds, nua_session_usage, NULL);
+
+  if (sr->sr_method != sip_method_invite && sr->sr_usage == NULL) {
+    /* UPDATE/PRACK sent within an existing dialog? */
+    return SR_STATUS(sr, 481, "Call Does Not Exist");
+  }
 
   if (nh->nh_soa) {
-    soa_init_offer_answer(nh->nh_soa);
+    sip_accept_t *a = nua->nua_invite_accept;
 
-    if (have_sdp) {
-      if (soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0) {
-	SU_DEBUG_5(("nua(%p): error parsing SDP in INVITE\n", nh));
-	return SR_STATUS(sr, 400, "Bad Session Description");
-      }
-      else
-	sr->sr_offer_recv = 1;
+    /* XXX - soa should know what it supports */
+    sip_add_dup(msg, sip, (sip_header_t *)a);
+
+    /* Make sure caller uses application/sdp without compression */
+    if (nta_check_session_content(NULL, request, a, TAG_END())) {
+      sip_add_make(msg, sip, sip_accept_encoding_class, "");
+      return SR_STATUS1(sr, SIP_415_UNSUPPORTED_MEDIA);
     }
-  }
 
-  /* Add the session usage */
-  if (du == NULL)
-    du = nua_dialog_usage_add(nh, nh->nh_ds, nua_session_usage, NULL);
+    /* Make sure caller accepts application/sdp */
+    if (nta_check_accept(NULL, request, a, NULL, TAG_END())) {
+      sip_add_make(msg, sip, sip_accept_encoding_class, "");
+      return SR_STATUS1(sr, SIP_406_NOT_ACCEPTABLE);
+    }
+  }
 
-  if (!du)
-    return SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+  if (request->sip_session_expires &&
+      sip_has_feature(NH_PGET(nh, supported), "timer") &&
+      session_timer_check_min_se(msg, sip, request, NH_PGET(nh, min_se))) {
+    if (sip->sip_min_se)
+      return SR_STATUS1(sr, SIP_422_SESSION_TIMER_TOO_SMALL);
+    else
+      return SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+  }
 
-  sr->sr_usage = du;
+  session_get_description(request, &sr->sr_sdp, &sr->sr_sdp_len);
 
   return 0;
 }
 
-static int
-session_check_request(nua_t *nua,
-		      nua_handle_t *nh,
-		      nta_incoming_t *irq,
-		      sip_t const *sip)
+/** Preprocess INVITE.
+ *
+ * This is called after a handle has been created for an incoming INVITE.
+ */
+int nua_invite_server_preprocess(nua_server_request_t *sr)
 {
-  char const *user_agent = NUA_PGET(nua, nh, user_agent);
+  nua_handle_t *nh = sr->sr_owner;
+  nua_dialog_state_t *ds = nh->nh_ds;
+  nua_session_usage_t *ss;
 
-  if (nh->nh_soa) {
-    /* Make sure caller uses application/sdp without compression */
-    if (nta_check_session_content(irq, sip,
-				  nua->nua_invite_accept,
-				  SIPTAG_USER_AGENT_STR(user_agent),
-				  SIPTAG_ACCEPT_ENCODING_STR(""),
-				  TAG_END()))
-      return 415;
+  sip_t const *request = sr->sr_request.sip;
 
-    /* Make sure caller accepts application/sdp */
-    if (nta_check_accept(irq, sip,
-			 nua->nua_invite_accept,
-			 NULL,
-			 SIPTAG_USER_AGENT_STR(user_agent),
-			 SIPTAG_ACCEPT_ENCODING_STR(""),
-			 TAG_END()))
-      return 406;
-  }
-
-  if (sip->sip_session_expires) {
-    unsigned min_se = NH_PGET(nh, min_se);
-    if (sip->sip_min_se && min_se < sip->sip_min_se->min_delta)
-      min_se = sip->sip_min_se->min_delta;
-    if (nta_check_session_expires(irq, sip,
-				  min_se,
-				  SIPTAG_USER_AGENT_STR(user_agent),
-				  TAG_END()))
-      return 422;
+  assert(sr->sr_status == 100);
+  assert(nh != nh->nh_nua->nua_dhandle);
+
+  if (sr->sr_status > 100)
+    return sr->sr_status;
+
+  if (nh->nh_soa)
+    soa_init_offer_answer(nh->nh_soa);
+
+  if (sr->sr_sdp) {
+    if (nh->nh_soa && 
+	soa_set_remote_sdp(nh->nh_soa, NULL, sr->sr_sdp, sr->sr_sdp_len) < 0) {
+      SU_DEBUG_5(("nua(%p): %s server: error parsing SDP\n", (void *)nh, 
+		  "INVITE"));
+      return SR_STATUS(sr, 400, "Bad Session Description");
+    }
+    else
+      sr->sr_offer_recv = 1;
   }
 
-  return 0;
-}
+  /* Add the session usage */
+  if (sr->sr_usage == NULL) {
+    sr->sr_usage = nua_dialog_usage_add(nh, ds, nua_session_usage, NULL);
+    if (sr->sr_usage == NULL)
+      return SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+  }
 
-/** @internal Process incoming invite - initiate media, etc. */
-static
-int process_invite(nua_t *nua,
-		   nua_handle_t *nh,
-		   nua_server_request_t *sr,
-		   sip_t *sip)
-{
-  nua_session_usage_t *ss = nua_dialog_usage_private(sr->sr_usage);
-  int status = sr->sr_status; char const *phrase = sr->sr_phrase;
+  ss = nua_dialog_usage_private(sr->sr_usage);
 
-  assert(ss); assert(status == 100);
+  if (sr->sr_offer_recv)
+    ss->ss_oa_recv = "offer";
 
   ss->ss_100rel = NH_PGET(nh, early_media);
-  ss->ss_precondition = sip_has_feature(sip->sip_require, "precondition");
+  ss->ss_precondition = sip_has_feature(request->sip_require, "precondition");
   if (ss->ss_precondition)
     ss->ss_100rel = 1;
 
-  session_timer_preferences(ss, 
-			    NH_PGET(nh, session_timer),
-			    NH_PGET(nh, min_se),
-			    NH_PGET(nh, refresher));
-
-  /* Session Timer negotiation */
-  if (sip_has_supported(NH_PGET(nh, supported), "timer"))
-    init_session_timer(ss, sip, ss->ss_refresher);
-
-  nua_dialog_uas_route(nh, nh->nh_ds, sip, 1);	/* Set route and tags */
-
-  nta_incoming_bind(sr->sr_irq, process_ack_or_cancel, sr);
+  session_timer_store(ss->ss_timer, request);
 
   assert(ss->ss_state >= nua_callstate_ready ||
 	 ss->ss_state == nua_callstate_init);
@@ -1793,432 +1918,282 @@
 	*/
        nh->nh_soa &&
        !NH_PISSET(nh, auto_answer))) {
-    SET_STATUS1(SIP_200_OK);
+    SR_STATUS1(sr, SIP_200_OK);
   }
   else if (NH_PGET(nh, auto_alert)) {
     if (ss->ss_100rel &&
-	(sip_has_feature(nh->nh_ds->ds_remote_ua->nr_supported, "100rel") ||
-	 sip_has_feature(nh->nh_ds->ds_remote_ua->nr_require, "100rel"))) {
-      SET_STATUS1(SIP_183_SESSION_PROGRESS);
+	(sip_has_feature(request->sip_supported, "100rel") ||
+	 sip_has_feature(request->sip_require, "100rel"))) {
+      SR_STATUS1(sr, SIP_183_SESSION_PROGRESS);
     }
     else {
-      SET_STATUS1(SIP_180_RINGING);
+      SR_STATUS1(sr, SIP_180_RINGING);
     }
   }
 
-  /* Magical value indicating autoanswer within respond_to_invite() */
-#define AUTOANSWER ((void*)-1)
-
-  if (status > 100) {
-    sr->sr_auto = 1;
-    nua_server_respond(sr, status, phrase, TAG_END());
-    sr->sr_auto = 0;
-    return 0;
-  }
-
-  nta_incoming_treply(sr->sr_irq, SIP_100_TRYING, 
-		      SIPTAG_USER_AGENT_STR(NUA_PGET(nua, nh, user_agent)),
-		      TAG_END());
-
-  nua_stack_event(nh->nh_nua, nh, 
-		  sr->sr_msg = nta_incoming_getrequest(sr->sr_irq),
-		  nua_i_invite, SIP_100_TRYING,
-		  NH_ACTIVE_MEDIA_TAGS(1, nh->nh_soa),
-		  TAG_END());
-
-  signal_call_state_change(nh, ss, SIP_100_TRYING,
-			   nua_callstate_received,
-			   sr->sr_offer_recv ? "offer" : 0, 0);
-
   return 0;
 }
 
+
 /** @internal Respond to an INVITE request.
  *
- * XXX - use tags to indicate when to use reliable responses.
- * XXX - change prototype.
  */
 static
-int respond_to_invite(nua_server_request_t *sr, tagi_t const *tags)
+int nua_invite_server_respond(nua_server_request_t *sr, tagi_t const *tags)
 {
   nua_handle_t *nh = sr->sr_owner;
-  nua_t *nua = nh->nh_nua;
-  nua_dialog_state_t *ds = nh->nh_ds;
-  nua_dialog_usage_t *du;
-  nua_session_usage_t *ss;
-  msg_t *msg;
-  sip_t *sip;
-  int reliable;
-  int status = sr->sr_status; char const *phrase = sr->sr_phrase;
-  sip_warning_t *warning = NULL;
+  nua_dialog_usage_t *du = sr->sr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  msg_t *msg = sr->sr_response.msg; 
+  sip_t *sip = sr->sr_response.sip; 
 
-  int offer = 0, answer = 0, early_answer = 0;
+  int reliable = 0, offer = 0, answer = 0, early_answer = 0, extra = 0;
 
   enter;
 
-  du = sr->sr_usage, ss = nua_dialog_usage_private(du);
-
-  if (du == NULL)
-    return nua_default_respond(sr, tags);
-
-  assert(ss == nua_session_usage_get(nh->nh_ds));
-
-  if (tags) {
-    nua_stack_set_params(nua, nh, nua_i_error, tags);
-
-    if (!NHP_ISSET(nh->nh_prefs, early_answer)
-	&& 100 < status && status < 200) {
-      sdp_session_t const *user_sdp = NULL;
-      char const *user_sdp_str = NULL;
-
-      tl_gets(tags,
-	      SOATAG_USER_SDP_REF(user_sdp),
-	      SOATAG_USER_SDP_STR_REF(user_sdp_str),
-	      TAG_END());
-
-      early_answer = user_sdp || user_sdp_str;
-    }
-    else
-      early_answer = NH_PGET(nh, early_answer);
+  if (du == NULL) {
+    if (sr->sr_status < 300)
+      sr_status(sr, SIP_500_INTERNAL_SERVER_ERROR);
+    return nua_base_server_respond(sr, tags);
   }
 
-  msg = nua_server_response(sr,
-			    status, phrase,
-			    TAG_IF(status < 300, NUTAG_ADD_CONTACT(1)),
-			    SIPTAG_SUPPORTED(NH_PGET(nh, supported)),
-			    TAG_NEXT(tags));
-  sip = sip_object(msg);
-
-  if (!sip) {
-    SET_STATUS1(SIP_500_INTERNAL_SERVER_ERROR), reliable = 0;
-    goto send_response;
-  }
-
-  reliable =
-    (status >= 200)
-    || (status > 100 && sip->sip_require &&
-	sip_has_feature(sip->sip_require, "100rel"))
-    || (status > 100 &&
-	ds->ds_remote_ua->nr_require &&
-	sip_has_feature(ds->ds_remote_ua->nr_require, "100rel"))
-    || (status > 100 && !NH_PGET(nh, only183_100rel) &&
-	(NH_PGET(nh, early_media) ||
-	 (ds->ds_remote_ua->nr_require &&
-	  sip_has_feature(ds->ds_remote_ua->nr_require, "precondition"))) &&
-	ds->ds_remote_ua->nr_supported &&
-	sip_has_feature(ds->ds_remote_ua->nr_supported, "100rel"))
-    || (status == 183 &&
-	ds->ds_remote_ua->nr_supported &&
-	sip_has_feature(ds->ds_remote_ua->nr_supported, "100rel"))
-    || (status == 183 &&
-	ds->ds_remote_ua->nr_require &&
-	sip_has_feature(ds->ds_remote_ua->nr_require, "precondition"))
-    || (status > 100 &&
-	ds->ds_remote_ua->nr_require &&
-	sip_has_feature(ds->ds_remote_ua->nr_require, "precondition") &&
-	sr->sr_offer_recv && !sr->sr_answer_sent);
+  if (nua_invite_server_is_100rel(sr, tags)) {
+    reliable = 1, early_answer = 1;
+  }
+  else if (!nh->nh_soa || sr->sr_status >= 300) {
+    
+  }
+  else if (tags && 100 < sr->sr_status && sr->sr_status < 200 && 
+	   !NHP_ISSET(nh->nh_prefs, early_answer)) {
+    sdp_session_t const *user_sdp = NULL;
+    char const *user_sdp_str = NULL;
+
+    tl_gets(tags,
+	    SOATAG_USER_SDP_REF(user_sdp),
+	    SOATAG_USER_SDP_STR_REF(user_sdp_str),
+	    TAG_END());
 
-  if (!nh->nh_soa)
-    /* Xyzzy */;
-  else if (status >= 300) {
-    soa_clear_remote_sdp(nh->nh_soa);
+    early_answer = user_sdp || user_sdp_str;
   }
   else {
-    int extra = 0;
+    early_answer = NH_PGET(nh, early_answer);
+  }
 
-    if (sr->sr_offer_sent && !sr->sr_answer_recv)
-      /* Wait for answer */;
-    else if (sr->sr_offer_recv && sr->sr_answer_sent > 1) {
-      /* We have sent answer */
-      /* ...  but we may want to send it again */
-      tagi_t const *t = tl_find_last(tags, nutag_include_extra_sdp);
-      extra = t && t->t_value;
-    }
-    else if (sr->sr_offer_recv && !sr->sr_answer_sent && 
-	     (reliable || early_answer)) {
-      /* Generate answer */ 
-      if (soa_generate_answer(nh->nh_soa, NULL) >= 0) {
+  if (!nh->nh_soa) {
+    if (session_get_description(sip, NULL, NULL)) {
+      if (sr->sr_offer_recv)
 	answer = 1;
-	soa_activate(nh->nh_soa, NULL);
-	/* signal that O/A answer sent (answer to invite) */
-      }
-      else if (status >= 200) {
-	int wcode;
-	char const *text;
-	char const *host = "invalid.";
-	status = soa_error_as_sip_response(nh->nh_soa, &phrase);
-
-	wcode = soa_get_warning(nh->nh_soa, &text);
-	if (wcode) {
-	  if (sip->sip_contact)
-	    host = sip->sip_contact->m_url->url_host;
-	  warning = sip_warning_format(msg_home(msg), "%u %s \"%s\"",
-				       wcode, host, text);
-	}
-      }
-      else {
-	/* 1xx - we don't have to send answer */
-      }
+      else if (sr->sr_offer_sent < 2)
+	offer = 1;
     }
-    else if (sr->sr_offer_recv && sr->sr_answer_sent == 1 && 
-	     (reliable || early_answer)) {
-      /* The answer was sent unreliably, keep sending it */
+  }
+  else if (sr->sr_status >= 300) {
+    soa_clear_remote_sdp(nh->nh_soa);
+  }
+  else if (sr->sr_offer_sent && !sr->sr_answer_recv)
+    /* Wait for answer */;
+  else if (sr->sr_offer_recv && sr->sr_answer_sent > 1) {
+    /* We have sent answer */
+    /* ...  but we may want to send it again */
+    tagi_t const *t = tl_find_last(tags, nutag_include_extra_sdp);
+    extra = t && t->t_value;
+  }
+  else if (sr->sr_offer_recv && !sr->sr_answer_sent && early_answer) {
+    /* Generate answer */ 
+    if (soa_generate_answer(nh->nh_soa, NULL) >= 0) {
       answer = 1;
+      soa_activate(nh->nh_soa, NULL);
+      /* signal that O/A answer sent (answer to invite) */
     }
-    else if (!sr->sr_offer_recv && !sr->sr_offer_sent && reliable) {
-      /* Generate offer */
-      if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0)
-	status = soa_error_as_sip_response(nh->nh_soa, &phrase);
-      else
-	offer = 1;
+    else if (sr->sr_status >= 200) {
+      sip_warning_t *warning = NULL;
+      int wcode;
+      char const *text;
+      char const *host = "invalid.";
+      
+      sr->sr_status = soa_error_as_sip_response(nh->nh_soa, &sr->sr_phrase);
+      
+      wcode = soa_get_warning(nh->nh_soa, &text);
+      
+      if (wcode) {
+	if (sip->sip_contact)
+	  host = sip->sip_contact->m_url->url_host;
+	warning = sip_warning_format(msg_home(msg), "%u %s \"%s\"",
+				     wcode, host, text);
+	sip_header_insert(msg, sip, (sip_header_t *)warning);
+      }
     }
-
-    if (offer || answer || extra) {
-      if (session_include_description(nh->nh_soa, 1, msg, sip) < 0)
-	SET_STATUS1(SIP_500_INTERNAL_SERVER_ERROR);
+    else {
+      /* 1xx - we don't have to send answer */
     }
   }
-
-  if (ss->ss_refresher && 200 <= status && status < 300)
-    if (session_timer_is_supported(nh))
-      use_session_timer(ss, 1, 1, msg, sip);
-
-  if (reliable && status < 200) {
-    nta_reliable_t *rel;
-    rel = nta_reliable_mreply(sr->sr_irq,
-			      process_prack, nh, msg);
-    if (!rel)
-      SET_STATUS1(SIP_500_INTERNAL_SERVER_ERROR);
-  }
-
- send_response:
-
-  if (reliable && status < 200)
-    /* we are done */;
-  else if (status != sr->sr_status) {    /* Error responding */
-    assert(status >= 200);
-    sr->sr_respond = NULL;
-    nta_incoming_treply(sr->sr_irq,
-			status, phrase,
-			SIPTAG_WARNING(warning),
-			SIPTAG_USER_AGENT_STR(NH_PGET(nh, user_agent)),
-			TAG_END());
-    msg_destroy(msg), msg = NULL;
+  else if (sr->sr_offer_recv && sr->sr_answer_sent == 1 && early_answer) {
+    /* The answer was sent unreliably, keep sending it */
+    answer = 1;
   }
-  else {
-    if (status >= 200)
-      sr->sr_respond = NULL;
-    nta_incoming_mreply(sr->sr_irq, msg);
-  }
-
-  if (sr->sr_auto) {
-    msg_t *request = nta_incoming_getrequest(sr->sr_irq);
-    if (status < 200)
-      sr->sr_msg = request;
-    nua_stack_event(nh->nh_nua, nh, request,
-		    nua_i_invite, status, phrase,
-		    NH_ACTIVE_MEDIA_TAGS(1, nh->nh_soa),
-		    TAG_END());
+  else if (!sr->sr_offer_recv && !sr->sr_offer_sent && reliable) {
+    /* Generate offer */
+    if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0)
+      sr->sr_status = soa_error_as_sip_response(nh->nh_soa, &sr->sr_phrase);
+    else
+      offer = 1;
   }
-  else if (status != sr->sr_status)
-    nua_stack_event(nua, nh, NULL, nua_i_error, status, phrase, TAG_END());
-
-  sr->sr_status = status, sr->sr_phrase = phrase;
-
-  if (status >= 300)
-    offer = 0, answer = 0;
-
-  if (offer)
-    sr->sr_offer_sent = 1;
-  else if (answer)
-    sr->sr_answer_sent = 1 + reliable;
-
-  /* Update session state */
-  assert(ss->ss_state != nua_callstate_calling);
-  assert(ss->ss_state != nua_callstate_proceeding);
-
-  signal_call_state_change(nh, ss, status, phrase,
-			   status >= 300
-			   ? nua_callstate_init
-			   : status >= 200
-			   ? nua_callstate_completed
-			   : nua_callstate_early,
-			   sr->sr_auto && sr->sr_offer_recv ? "offer" : 0,
-			   offer ? "offer" : answer ? "answer" : 0);
-
-  if (status == 180)
-    ss->ss_alerting = 1;
-  else if (status >= 200)
-    ss->ss_alerting = 0;
 
-  if (status >= 200 && status < 300) {
-    du->du_ready = 1;
-  }
-  else if (status >= 300) {
-    sr->sr_usage = NULL;
-    if (nh->nh_soa)
-      soa_init_offer_answer(nh->nh_soa);
+  if (sr->sr_status < 300 && (offer || answer || extra)) {
+    if (nh->nh_soa && session_include_description(nh->nh_soa, 1, msg, sip) < 0)
+      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+    else if (offer)
+      sr->sr_offer_sent = 1 + reliable, ss->ss_oa_sent = "offer";
+    else if (answer)
+      sr->sr_answer_sent = 1 + reliable, ss->ss_oa_sent = "answer";
   }
 
-  if (ss->ss_state == nua_callstate_init) {
-    assert(status >= 300);
-    nua_session_usage_destroy(nh, ss);
+  if (reliable && sr->sr_status < 200) {
+    sr->sr_response.msg = NULL, sr->sr_response.sip = NULL;
+    if (nta_reliable_mreply(sr->sr_irq, process_prack, sr, msg) == NULL)
+      return -1;
+    sr->sr_100rel = 1;
+    return 0;
   }
 
-  return status >= 300 ? status : 0;
-}
-
-
-/** @internal Process ACK or CANCEL or timeout (no ACK) for incoming INVITE */
-static
-int process_ack_or_cancel(nua_server_request_t *sr,
-			  nta_incoming_t *irq,
-			  sip_t const *sip)
-{
-  enter;
+  if (200 <= sr->sr_status && sr->sr_status < 300) {
+    session_timer_preferences(ss->ss_timer,
+			      sip,
+			      NH_PGET(nh, supported),		     
+			      NH_PGET(nh, session_timer),
+			      NUA_PISSET(nh->nh_nua, nh, session_timer),
+			      NH_PGET(nh, refresher),
+			      NH_PGET(nh, min_se));
 
-  assert(sr->sr_usage);
-  assert(sr->sr_usage->du_class == nua_session_usage);
+    if (session_timer_is_supported(ss->ss_timer))
+      session_timer_add_headers(ss->ss_timer, 0, msg, sip);
+  }
 
-  if (sip && sip->sip_request->rq_method == sip_method_ack)
-    return process_ack(sr, irq, sip);
-  else if (sip && sip->sip_request->rq_method == sip_method_cancel)
-    return process_cancel(sr, irq, sip);
-  else
-    return process_timeout(sr, irq);
+  return nua_base_server_respond(sr, tags);  
 }
 
-/** @NUA_EVENT nua_i_prack
- *
- * Incoming PRACK request. PRACK request is used to acknowledge reliable
- * preliminary responses and it is usually sent automatically by the nua
- * stack.
- *
- * @param status status code of response sent automatically by stack
- * @param phrase a short textual description of @a status code
- * @param nh     operation handle associated with the call
- * @param hmagic application context associated with the call
- * @param sip    incoming INFO request
- * @param tags   empty
- *
- * @sa nua_prack(), #nua_r_prack, @RFC3262, NUTAG_EARLY_MEDIA()
- * 
- * @END_NUA_EVENT
+/** Check if the response should be sent reliably.
+ * XXX - use tags to indicate when to use reliable responses ???
  */
-
-/** @internal Process PRACK or (timeout from 100rel) */
 static
-int process_prack(nua_handle_t *nh,
-		  nta_reliable_t *rel,
-		  nta_incoming_t *irq,
-		  sip_t const *sip)
+int nua_invite_server_is_100rel(nua_server_request_t *sr, tagi_t const *tags)
 {
-  nua_dialog_state_t *ds = nh->nh_ds;
-  nua_dialog_usage_t *du;
-  nua_session_usage_t *ss;
-  nua_server_request_t *sri;
-  int status = 200; char const *phrase = sip_200_OK;
-  char const *recv = NULL, *sent = NULL;
-
-  nta_reliable_destroy(rel);
-
-  ss = nua_session_usage_get(ds); du = nua_dialog_usage_public(ss);
+  nua_handle_t *nh = sr->sr_owner;
+  sip_t const *sip = sr->sr_response.sip;
+  sip_require_t *require = sr->sr_request.sip->sip_require;
+  sip_supported_t *supported = sr->sr_request.sip->sip_supported;
+
+  if (sr->sr_status >= 200)
+    return 1;
+  else if (sr->sr_status == 100)
+    return 0;
 
-  for (sri = ds->ds_sr; sri; sri = sri->sr_next) {
-    if (sri->sr_method == sip_method_invite && sri->sr_usage == du)
-      break;
-  }
-                     
-  if (!sri || !sri->sr_respond) /* XXX */
-    return 481;
+  if (sip_has_feature(sip->sip_require, "100rel"))
+    return 1;
 
-  if (sip)
-    /* received PRACK */;
-  else if (!sri || irq == NULL) { /* Final response interrupted 100rel */
-    /* Ignore */
-    return 200;
-  }
-  else if (sip == NULL) {
-    SET_STATUS(504, "Reliable Response Timeout");
+  if (require == NULL && supported == NULL)
+    return 0;
 
-    nua_stack_event(nh->nh_nua, nh, NULL,
-		    nua_i_error, status, phrase,
-		    TAG_END());
+  if (sip_has_feature(require, "100rel"))
+    return 1;
+  if (!sip_has_feature(supported, "100rel"))
+    return 0;
+  if (sr->sr_status == 183)
+    return 1;
 
-    nua_server_respond(sri, status, phrase, TAG_END());
+  if (NH_PGET(nh, early_media) && !NH_PGET(nh, only183_100rel))
+    return 1;
 
-    return status;
+  if (sip_has_feature(require, "precondition")) {
+    if (!NH_PGET(nh, only183_100rel))
+      return 1;
+    if (sr->sr_offer_recv && !sr->sr_answer_sent)
+      return 1;
   }
 
-  if (nh->nh_soa) {
-    msg_t *msg = nta_incoming_getrequest(irq);
-    char const *sdp;
-    size_t len;
-
-    if (session_get_description(sip, &sdp, &len)) {
-      su_home_t home[1] = { SU_HOME_INIT(home) };
+  return 0;
+}
 
-      sip_content_disposition_t *cd = NULL;
-      sip_content_type_t *ct = NULL;
-      sip_payload_t *pl = NULL;
-
-      if (soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0) {
-	SU_DEBUG_5(("nua(%p): error parsing SDP in INVITE\n", nh));
-	msg_destroy(msg);
-	status = 400, phrase = "Bad Session Description";
-      }
 
-      /* Respond to PRACK */
+int nua_invite_server_report(nua_server_request_t *sr, tagi_t const *tags)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_dialog_usage_t *du = sr->sr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(sr->sr_usage);
+  int initial = sr->sr_initial && !sr->sr_event;
+  int neutral = sr->sr_neutral;
+  int application = sr->sr_application;
+  int status = sr->sr_status; char const *phrase = sr->sr_phrase;
+  int retval;
 
-      if (status >= 300)
-	;
-      else if (sri->sr_offer_sent) {
-	recv = "answer";
-	sri->sr_answer_recv = 1;
-	if (soa_process_answer(nh->nh_soa, NULL) < 0)
-	  status = soa_error_as_sip_response(nh->nh_soa, &phrase);
-      }
-      else {
-	recv = "offer";
-	if (soa_generate_answer(nh->nh_soa, NULL) < 0) {
-	  status = soa_error_as_sip_response(nh->nh_soa, &phrase);
-	}
-	else {
-	  if (session_make_description(home, nh->nh_soa, 1, &cd, &ct, &pl) > 0)
-	    sent = "answer";
-	}
-      }
+  if (!sr->sr_event && status < 300) {	/* Not reported yet */
+    nta_incoming_bind(sr->sr_irq, process_ack_or_cancel, sr);
+  }
 
-      if (nta_incoming_treply(irq, status, phrase,
-			      SIPTAG_CONTENT_DISPOSITION(cd),
-			      SIPTAG_CONTENT_TYPE(ct),
-			      SIPTAG_PAYLOAD(pl),
-			      TAG_END()) < 0)
-	/* Respond with 500 if nta_incoming_treply() failed */
-	SET_STATUS1(SIP_500_INTERNAL_SERVER_ERROR);
+  retval = nua_base_server_report(sr, tags), sr = NULL; /* destroys sr */
+  
+  if (retval >= 2 || ss == NULL) {
+    /* Session has been terminated. */ 
+    if (!initial && !neutral)
+      signal_call_state_change(nh, NULL, status, phrase,
+			       nua_callstate_terminated);
+    return retval;
+  }
 
-      su_home_deinit(home);
-    }
+  assert(ss);
 
-    msg_destroy(msg);
+  /* Update session state */
+  if (status < 300 || application != 0) {
+    assert(ss->ss_state != nua_callstate_calling);
+    assert(ss->ss_state != nua_callstate_proceeding);
+    signal_call_state_change(nh, ss, status, phrase,
+			     status >= 300
+			     ? nua_callstate_init
+			     : status >= 200
+			     ? nua_callstate_completed
+			     : status > 100
+			     ? nua_callstate_early
+			     : nua_callstate_received);
   }
 
-  nua_stack_event(nh->nh_nua, nh, nta_incoming_getrequest(irq),
-		  nua_i_prack, status, phrase, TAG_END());
+  if (status == 180)
+    ss->ss_alerting = 1;
+  else if (status >= 200)
+    ss->ss_alerting = 0;
 
-  if (status >= 300)
-    return status;
+  if (200 <= status && status < 300) {
+     du->du_ready = 1;
+  }
+  else if (300 <= status && !neutral) {
+    if (nh->nh_soa)
+      soa_init_offer_answer(nh->nh_soa);
+  }
 
-  if (recv || sent) {
-    soa_activate(nh->nh_soa, NULL);
-    signal_call_state_change(nh, ss, status, phrase,
-			     nua_callstate_early, recv, sent);
+  if (ss->ss_state == nua_callstate_init) {
+    assert(status >= 300);
+    nua_session_usage_destroy(nh, ss);
   }
 
-  if (NH_PGET(nh, auto_alert) && !ss->ss_alerting && !ss->ss_precondition)
-    nua_server_respond(sri, SIP_180_RINGING, TAG_END());
+  return retval;
+}
+
+/** @internal Process ACK or CANCEL or timeout (no ACK) for incoming INVITE */
+static
+int process_ack_or_cancel(nua_server_request_t *sr,
+			  nta_incoming_t *irq,
+			  sip_t const *sip)
+{
+  enter;
+
+  assert(sr->sr_usage);
+  assert(sr->sr_usage->du_class == nua_session_usage);
 
-  return status;
+  if (sip && sip->sip_request->rq_method == sip_method_ack)
+    return process_ack(sr, irq, sip);
+  else if (sip && sip->sip_request->rq_method == sip_method_cancel)
+    return process_cancel(sr, irq, sip);
+  else
+    return process_timeout(sr, irq);
 }
 
 /** @NUA_EVENT nua_i_ack
@@ -2249,39 +2224,54 @@
   if (ss == NULL)
     return 0;
 
-  if (nh->nh_soa && sr->sr_offer_sent && !sr->sr_answer_recv) {
+  if (sr->sr_offer_sent && !sr->sr_answer_recv) {
     char const *sdp;
     size_t len;
+    int error;
+
+    if (session_get_description(sip, &sdp, &len))
+      recv = "answer";
 
-    if (!session_get_description(sip, &sdp, &len) ||
-	!(recv = "answer") ||
-	soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0 ||
-	soa_process_answer(nh->nh_soa, NULL) < 0 ||
-	soa_activate(nh->nh_soa, NULL)) {
+    if (recv) {
+      assert(ss->ss_oa_recv == NULL);
+      ss->ss_oa_recv = recv;
+    }
+
+    if (nh->nh_soa == NULL)
+      ;
+    else if (recv == NULL ||
+	     soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0 ||
+	     soa_process_answer(nh->nh_soa, NULL) < 0 ||
+	     soa_activate(nh->nh_soa, NULL) < 0) {
       int status; char const *phrase, *reason;
 
       status = soa_error_as_sip_response(nh->nh_soa, &phrase);
       reason = soa_error_as_sip_reason(nh->nh_soa);
 
       nua_stack_event(nh->nh_nua, nh, msg,
-	       nua_i_ack, status, phrase, TAG_END());
+		      nua_i_ack, status, phrase, NULL);
       nua_stack_event(nh->nh_nua, nh, NULL,
-	       nua_i_media_error, status, phrase, TAG_END());
+		      nua_i_media_error, status, phrase, NULL);
+
+      ss->ss_reporting = 1;	/* We report state here if BYE fails */
+      error = nua_client_create(nh, nua_r_bye, &nua_bye_client_methods, NULL);
+      ss->ss_reporting = 0;
 
       signal_call_state_change(nh, ss, 488, "Offer-Answer Error",
-			       nua_callstate_terminating, recv, 0);
-      nua_stack_post_signal(nh, nua_r_bye,
-			    SIPTAG_REASON_STR(reason),
-			    TAG_END());
+			       error
+			       ? nua_callstate_terminated
+			       : nua_callstate_terminating);
 
       return 0;
     }
   }
 
-  soa_clear_remote_sdp(nh->nh_soa);
-  nua_stack_event(nh->nh_nua, nh, msg, nua_i_ack, SIP_200_OK, TAG_END());
-  signal_call_state_change(nh, ss, 200, "OK", nua_callstate_ready, recv, 0);
-  set_session_timer(ss);
+  if (nh->nh_soa)
+    soa_clear_remote_sdp(nh->nh_soa);
+
+  nua_stack_event(nh->nh_nua, nh, msg, nua_i_ack, SIP_200_OK, NULL);
+  signal_call_state_change(nh, ss, 200, "OK", nua_callstate_ready);
+  session_timer_set(ss);
 
   nua_server_request_destroy(sr);
 
@@ -2314,12 +2304,14 @@
   nua_session_usage_t *ss = nua_dialog_usage_private(sr->sr_usage);
   msg_t *cancel = nta_incoming_getrequest_ackcancel(irq);
 
-  assert(nta_incoming_status(irq) < 200);  assert(sr->sr_respond);
-  assert(ss); assert(ss == nua_session_usage_get(nh->nh_ds)); (void)ss;
+  assert(ss); assert(ss == nua_session_usage_for_dialog(nh->nh_ds)); (void)ss;
 
-  nua_stack_event(nh->nh_nua, nh, cancel, nua_i_cancel, SIP_200_OK, TAG_END());
+  assert(nta_incoming_status(irq) < 200);
 
-  nua_server_respond(sr, SIP_487_REQUEST_TERMINATED, TAG_END());
+  nua_stack_event(nh->nh_nua, nh, cancel, nua_i_cancel, SIP_200_OK, NULL);
+  sr->sr_application = SR_STATUS1(sr, SIP_487_REQUEST_TERMINATED);
+  nua_server_respond(sr, NULL);
+  nua_server_report(sr);
 
   return 0;
 }
@@ -2331,31 +2323,41 @@
 {
   nua_handle_t *nh = sr->sr_owner;
   nua_session_usage_t *ss = nua_dialog_usage_private(sr->sr_usage);
+  char const *phrase = "ACK Timeout";
+  char const *reason = "SIP;cause=408;text=\"ACK Timeout\"";
+  int error;
+
+  assert(ss); assert(ss == nua_session_usage_for_dialog(nh->nh_ds));
 
-  assert(ss); assert(ss == nua_session_usage_get(nh->nh_ds));
+  if (nua_server_request_is_pending(sr)) {
+    phrase = "PRACK Timeout";
+    reason = "SIP;cause=504;text=\"PRACK Timeout\"";
+  }
 
-  nua_stack_event(nh->nh_nua, nh, 0, nua_i_error,
-		  408, "Response timeout",
-		  TAG_END());
+  nua_stack_event(nh->nh_nua, nh, 0, nua_i_error, 408, phrase, NULL);
 
-  if (sr->sr_respond) {
+  if (nua_server_request_is_pending(sr)) {
     /* PRACK timeout */
-    nua_server_respond(sr, SIP_504_GATEWAY_TIME_OUT,
-		       SIPTAG_REASON_STR("SIP;cause=504;"
-					 "text=\"PRACK Timeout\""),
-		       TAG_END());
-    ss = nua_session_usage_get(nh->nh_ds);
+    SR_STATUS1(sr, SIP_504_GATEWAY_TIME_OUT);
+    nua_server_trespond(sr, 
+			SIPTAG_REASON_STR(reason),
+			TAG_END());
+    if (nua_server_report(sr) >= 2)
+      return 0;			/* Done */
     sr = NULL;
   }
 
-  if (ss) {
-    /* send BYE, too if 200 OK (or 183 to re-INVITE) timeouts  */
-    signal_call_state_change(nh, ss, 0, "Timeout",
-			     nua_callstate_terminating, 0, 0);
-    nua_stack_post_signal(nh, nua_r_bye,
-			  SIPTAG_REASON_STR("SIP;cause=408;text=\"ACK Timeout\""),
-			  TAG_END());
-  }
+  /* send BYE, too, if 200 OK (or 183 to re-INVITE) timeouts  */
+  ss->ss_reason = reason;
+
+  ss->ss_reporting = 1;		/* We report state here if BYE fails */
+  error = nua_client_create(nh, nua_r_bye, &nua_bye_client_methods, NULL);
+  ss->ss_reporting = 0;
+
+  signal_call_state_change(nh, ss, 0, phrase,
+			   error
+			   ? nua_callstate_terminated
+			   : nua_callstate_terminating);
 
   if (sr)
     nua_server_request_destroy(sr);
@@ -2364,176 +2366,219 @@
 }
 
 
-/* ---------------------------------------------------------------------- */
-/* Session timer - RFC 4028 */
+/** @NUA_EVENT nua_i_prack
+ *
+ * Incoming PRACK request. PRACK request is used to acknowledge reliable
+ * preliminary responses and it is usually sent automatically by the nua
+ * stack.
+ *
+ * @param status status code of response sent automatically by stack
+ * @param phrase a short textual description of @a status code
+ * @param nh     operation handle associated with the call
+ * @param hmagic application context associated with the call
+ * @param sip    incoming PRACK request
+ * @param tags   empty
+ *
+ * @sa nua_prack(), #nua_r_prack, @RFC3262, NUTAG_EARLY_MEDIA()
+ * 
+ * @END_NUA_EVENT
+ */
 
-static int session_timer_is_supported(nua_handle_t const *nh)
-{
-  /* Is timer feature supported? */
-  return sip_has_supported(NH_PGET(nh, supported), "timer");
-}
+int nua_prack_server_init(nua_server_request_t *sr);
+int nua_prack_server_respond(nua_server_request_t *sr, tagi_t const *tags);
+int nua_prack_server_report(nua_server_request_t *sr, tagi_t const *tags);
 
-static int prefer_session_timer(nua_handle_t const *nh)
-{
-  return 
-    NH_PGET(nh, refresher) != nua_no_refresher || 
-    NH_PGET(nh, session_timer) != 0;
-}
+nua_server_methods_t const nua_prack_server_methods = 
+  {
+    SIP_METHOD_PRACK,
+    nua_i_prack,		/* Event */
+    { 
+      0,			/* Do not create dialog */
+      1,			/* In-dialog request */
+      1,			/* Target refresh request  */
+      1,			/* Add Contact */
+    },
+    nua_prack_server_init,
+    nua_base_server_preprocess,
+    nua_base_server_params,
+    nua_prack_server_respond,
+    nua_prack_server_report,
+  };
 
-/* Initialize session timer */ 
-static
-void session_timer_preferences(nua_session_usage_t *ss,
-			       unsigned expires,
-			       unsigned min_se,
-			       enum nua_session_refresher refresher)
+/** @internal Process reliable response PRACK or (timeout from 100rel) */
+static int process_prack(nua_server_request_t *sr,
+			 nta_reliable_t *rel,
+			 nta_incoming_t *irq,
+			 sip_t const *sip)
 {
-  if (expires < min_se)
-    expires = min_se;
-  if (refresher && expires == 0)
-    expires = 3600;
+  nua_handle_t *nh;
+  nua_dialog_usage_t *du;
 
-  ss->ss_min_se = min_se;
-  ss->ss_session_timer = expires;
-  ss->ss_refresher = refresher;
-}
+  nta_reliable_destroy(rel);
+  if (irq == NULL)  
+    /* Final response interrupted 100rel, we did not actually receive PRACK */
+    return 200;
 
+  sr->sr_pracked = 1;
 
-/** Add timer featuretag and Session-Expires/Min-SE headers */
-static int
-use_session_timer(nua_session_usage_t *ss, int uas, int always,
-		  msg_t *msg, sip_t *sip)
-{
-  sip_min_se_t min_se[1];
-  sip_session_expires_t session_expires[1];
+  if (!nua_server_request_is_pending(sr)) /* There is no INVITE anymore */
+    return 481;
 
-  static sip_param_t const x_params_uac[] = {"refresher=uac", NULL};
-  static sip_param_t const x_params_uas[] = {"refresher=uas", NULL};
+  nh = sr->sr_owner;
 
-  /* Session-Expires timer */
-  if (ss->ss_refresher == nua_no_refresher && !always)
-    return 0;
+  if (nh->nh_ds->ds_leg == NULL)
+    return 500;
 
-  sip_min_se_init(min_se)->min_delta = ss->ss_min_se;
-  sip_session_expires_init(session_expires)->x_delta = ss->ss_session_timer;
+  du = nua_dialog_usage_for_session(nh->nh_ds);
 
-  if (ss->ss_refresher == nua_remote_refresher)
-    session_expires->x_params = uas ? x_params_uac : x_params_uas;
-  else if (ss->ss_refresher == nua_local_refresher)
-    session_expires->x_params = uas ? x_params_uas : x_params_uac;
+  if (sip == NULL) {
+    /* 100rel timeout */
+    SR_STATUS(sr, 504, "Reliable Response Timeout");
+    nua_stack_event(nh->nh_nua, nh, NULL, nua_i_error,
+		    sr->sr_status, sr->sr_phrase,
+		    NULL);
+    nua_server_trespond(sr,
+			SIPTAG_REASON_STR("SIP;cause=504;"
+					  "text=\"PRACK Timeout\""),
+			TAG_END());
+    nua_server_report(sr);
+    return 504;
+  }
 
-  sip_add_tl(msg, sip,
-	     TAG_IF(ss->ss_session_timer,
-		    SIPTAG_SESSION_EXPIRES(session_expires)),
-	     TAG_IF(ss->ss_min_se != 0
-		    /* Min-SE: 0 is optional with initial INVITE */
-		    || ss->ss_state != nua_callstate_init,
-		    SIPTAG_MIN_SE(min_se)),
-	     TAG_IF(ss->ss_refresher == nua_remote_refresher,
-		    SIPTAG_REQUIRE_STR("timer")),
-	     TAG_END());
+  nta_incoming_bind(irq, NULL, (void *)sr);
 
-  return 1;
+  return nua_stack_process_request(nh, nh->nh_ds->ds_leg, irq, sip);
 }
 
-static int
-init_session_timer(nua_session_usage_t *ss,
-		   sip_t const *sip,
-		   int refresher)
-{
-  int server;
-
-  /* Session timer is not needed */
-  if (!sip->sip_session_expires) {
-    if (!sip_has_supported(sip->sip_supported, "timer"))
-      ss->ss_refresher = nua_local_refresher;
-    return 0;
-  }
 
-  ss->ss_refresher = nua_no_refresher;
-  ss->ss_session_timer = sip->sip_session_expires->x_delta;
+int nua_prack_server_init(nua_server_request_t *sr)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_server_request_t *sri = nta_incoming_magic(sr->sr_irq, NULL);
+
+  if (sri == NULL)
+    return SR_STATUS(sr, 481, "No Such Preliminary Response");
+  
+  if (nua_session_server_init(sr))
+    return sr->sr_status;
 
-  if (sip->sip_min_se != NULL
-      && sip->sip_min_se->min_delta > ss->ss_min_se)
-    ss->ss_min_se = sip->sip_min_se->min_delta;
-
-  server = sip->sip_request != NULL;
-
-  if (!sip_has_supported(sip->sip_supported, "timer"))
-    ss->ss_refresher = nua_local_refresher;
-  else if (!str0casecmp("uac", sip->sip_session_expires->x_refresher))
-    ss->ss_refresher = server ? nua_remote_refresher : nua_local_refresher;
-  else if (!str0casecmp("uas", sip->sip_session_expires->x_refresher))
-    ss->ss_refresher = server ? nua_local_refresher : nua_remote_refresher;
-  else if (!server)
-    return 0;			/* XXX */
-  /* User preferences */
-  else if (refresher == nua_local_refresher)
-    ss->ss_refresher = nua_local_refresher;
-  else
-    ss->ss_refresher = nua_remote_refresher;
+  if (sr->sr_sdp) {
+    nua_session_usage_t *ss = nua_dialog_usage_private(sr->sr_usage);
 
-  SU_DEBUG_7(("nua session: session expires in %u refreshed by %s (%s %s)\n",
-	      ss->ss_session_timer,
-	      ss->ss_refresher == nua_local_refresher ? "local" : "remote",
-	      server ? sip->sip_request->rq_method_name : "response to",
-	      server ? "request" : sip->sip_cseq->cs_method_name));
+    /* XXX - check for overlap? */
+    
+    if (sri->sr_offer_sent)
+      sr->sr_answer_recv = 1, ss->ss_oa_recv = "answer";
+    else 
+      sr->sr_offer_recv = 1, ss->ss_oa_recv = "offer";
 
-  return 1;
+    if (nh->nh_soa &&
+	soa_set_remote_sdp(nh->nh_soa, NULL, sr->sr_sdp, sr->sr_sdp_len) < 0) {
+      SU_DEBUG_5(("nua(%p): %s server: error parsing %s\n", (void *)nh,
+		  "PRACK", "offer"));
+      return 
+	sr->sr_status = soa_error_as_sip_response(nh->nh_soa, &sr->sr_phrase);
+    }
+  }
+
+  return 0;
 }
 
-static void
-set_session_timer(nua_session_usage_t *ss)
+int nua_prack_server_respond(nua_server_request_t *sr, tagi_t const *tags)
 {
-  nua_dialog_usage_t *du = nua_dialog_usage_public(ss);
+  nua_handle_t *nh = sr->sr_owner;
 
-  if (ss == NULL)
-    return;
+  if (sr->sr_status < 200 || 300 <= sr->sr_status) 
+    return nua_base_server_respond(sr, tags);
 
-  if (ss->ss_refresher == nua_local_refresher) {
-    ss->ss_timer_set = 1;
-    nua_dialog_usage_set_expires(du, ss->ss_session_timer);
-  }
-  else if (ss->ss_refresher == nua_remote_refresher) {
-    ss->ss_timer_set = 1;
-    nua_dialog_usage_set_expires(du, ss->ss_session_timer + 32);
-    nua_dialog_usage_reset_refresh(du);
-  }
-  else {
-    ss->ss_timer_set = 0;
-    nua_dialog_usage_set_expires(du, UINT_MAX);
-    nua_dialog_usage_reset_refresh(du);
+  if (sr->sr_sdp) {
+    nua_session_usage_t *ss = nua_dialog_usage_private(sr->sr_usage);
+    msg_t *msg = sr->sr_response.msg;
+    sip_t *sip = sr->sr_response.sip;
+
+    if (nh->nh_soa == NULL) {
+      if (sr->sr_offer_recv && session_get_description(sip, NULL, NULL))
+	sr->sr_answer_sent = 1, ss->ss_oa_sent = "answer";
+    }
+    else if ((sr->sr_offer_recv && soa_generate_answer(nh->nh_soa, NULL) < 0) ||
+	     (sr->sr_answer_recv && soa_process_answer(nh->nh_soa, NULL) < 0)) {
+      SU_DEBUG_5(("nua(%p): %s server: %s %s\n", 
+		  (void *)nh, "PRACK", 
+		  "error processing",
+		  sr->sr_offer_recv ? "offer" : "answer"));
+      sr->sr_status = soa_error_as_sip_response(nh->nh_soa, &sr->sr_phrase);
+    }
+    else if (sr->sr_offer_recv) {
+      if (session_include_description(nh->nh_soa, 1, msg, sip) < 0)
+	sr_status(sr, SIP_500_INTERNAL_SERVER_ERROR);
+      else
+      sr->sr_answer_sent = 1, ss->ss_oa_sent = "answer";
+    }
   }
+
+  return nua_base_server_respond(sr, tags);
 }
 
-static int
-check_session_timer_restart(nua_handle_t *nh,
-			    nua_session_usage_t *ss,
-			    nua_client_request_t *cr,
-			    nta_outgoing_t *orq,
-			    sip_t const *sip,
-			    nua_creq_restart_f *restart_function)
-{
-  if (ss && sip && sip->sip_status->st_status == 422) {
-    if (sip->sip_min_se && ss->ss_min_se < sip->sip_min_se->min_delta)
-      ss->ss_min_se = sip->sip_min_se->min_delta;
-    if (ss->ss_min_se > ss->ss_session_timer)
-      ss->ss_session_timer = ss->ss_min_se;
-  
-    if (orq == cr->cr_orq)
-      cr->cr_orq = NULL;
+int nua_prack_server_report(nua_server_request_t *sr, tagi_t const *tags)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_session_usage_t *ss = nua_dialog_usage_private(sr->sr_usage);
+  nua_server_request_t *sri = nta_incoming_magic(sr->sr_irq, NULL);
+  int status = sr->sr_status; char const *phrase = sr->sr_phrase;
+  int offer_recv_or_answer_sent = sr->sr_offer_recv || sr->sr_answer_sent;
+  int retval;
+
+  retval = nua_base_server_report(sr, tags), sr = NULL; /* destroys sr */
 
-    return nua_creq_restart_with(nh, cr, orq,
-				 100, "Re-Negotiating Session Timer",
-				 restart_function, TAG_END());
+  if (retval >= 2 || ss == NULL) {
+    signal_call_state_change(nh, NULL,
+			     status, phrase, 
+			     nua_callstate_terminated);
+    return retval;
   }
 
-  return nua_creq_check_restart(nh, cr, orq, sip, restart_function);
-}
+  if (offer_recv_or_answer_sent) {
+    /* signal offer received, answer sent */
+    signal_call_state_change(nh, ss,
+			     status, phrase, 
+			     ss->ss_state);
+    if (nh->nh_soa)
+      soa_activate(nh->nh_soa, NULL);
+  }
 
-static inline int
-is_session_timer_set(nua_session_usage_t *ss)
-{
-  return ss->ss_timer_set;
+  if (status < 200 || 300 <= status)
+    return retval;
+
+  assert(sri);
+
+  if (sri == NULL) {
+    
+  }
+  else if (su_msg_is_non_null(sri->sr_signal)) {
+    su_msg_r signal;
+    event_t *e;
+    
+    su_msg_save(signal, sri->sr_signal);
+    
+    e = su_msg_data(signal);
+    sri->sr_application = SR_STATUS(sri, e->e_status, e->e_phrase);
+    
+    nua_server_params(sri, e->e_tags);
+    nua_server_respond(sri, e->e_tags);
+    nua_server_report(sri);
+    
+    su_msg_destroy(signal);
+  }
+  else if (ss->ss_state < nua_callstate_ready
+	   && !ss->ss_alerting
+	   && !ss->ss_precondition
+	   && NH_PGET(nh, auto_alert))  {
+    SR_STATUS1(sri, SIP_180_RINGING);
+    nua_server_respond(sri, NULL);
+    nua_server_report(sri);
+  }
+
+  return retval;
 }
 
 /* ---------------------------------------------------------------------- */
@@ -2599,7 +2644,6 @@
   return 0;
 }
 
-
 static void
 nh_referral_respond(nua_handle_t *nh, int status, char const *phrase)
 {
@@ -2611,7 +2655,7 @@
     if (ref) {
       if (ref->ref_handle)
 	SU_DEBUG_1(("nh_handle_referral: stale referral handle %p\n",
-		    ref->ref_handle));
+		    (void *)ref->ref_handle));
       ref->ref_handle = NULL;
     }
     return;
@@ -2647,33 +2691,9 @@
   nua_handle_unref(ref->ref_handle), ref->ref_handle = NULL;
 }
 
-
-/** Zap the session associated with the handle */
-static
-void nua_session_usage_destroy(nua_handle_t *nh,
-			       nua_session_usage_t *ss)
-{
-  nh->nh_has_invite = 0;
-  nh->nh_active_call = 0;
-  nh->nh_hold_remote = 0;
-
-  if (nh->nh_soa)
-    soa_destroy(nh->nh_soa), nh->nh_soa = NULL;
-
-  /* Remove usage */
-  nua_dialog_usage_remove(nh, nh->nh_ds, nua_dialog_usage_public(ss));
-
-  SU_DEBUG_5(("nua: terminated session %p\n", nh));
-}
-
-
 /* ======================================================================== */
 /* INFO */
 
-static int process_response_to_info(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip);
-
 /**@fn void nua_info(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
  *
  * Send an INFO request. 
@@ -2696,41 +2716,59 @@
  * @sa #nua_i_info
  */
 
+static int nua_info_client_init(nua_client_request_t *cr, 
+				msg_t *msg, sip_t *sip,
+				tagi_t const *tags);
+
+static int nua_info_client_request(nua_client_request_t *cr,
+				   msg_t *msg, sip_t *sip,
+				   tagi_t const *tags);
+
+nua_client_methods_t const nua_info_client_methods = {
+  SIP_METHOD_INFO,
+  0,
+  { 
+    /* create_dialog */ 0,
+    /* in_dialog */ 1,
+    /* target refresh */ 0
+  },
+  /*nua_info_client_template*/ NULL,
+  nua_info_client_init,
+  nua_info_client_request,
+  /*nua_info_client_check_restart*/ NULL,
+  /*nua_info_client_response*/ NULL
+};
+
 int
 nua_stack_info(nua_t *nua, nua_handle_t *nh, nua_event_t e, tagi_t const *tags)
 {
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  msg_t *msg;
-
-  if (nh_is_special(nh)) {
-    return UA_EVENT2(e, 900, "Invalid handle for INFO");
-  }
-  else if (cr->cr_orq) {
-    return UA_EVENT2(e, 900, "Request already in progress");
-  }
+  return nua_client_create(nh, e, &nua_info_client_methods, tags);
+}
 
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
+static int nua_info_client_init(nua_client_request_t *cr, 
+				msg_t *msg, sip_t *sip,
+				tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = nua_dialog_usage_for_session(nh->nh_ds);
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
 
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
-			 SIP_METHOD_INFO ,
-			 NUTAG_ADD_CONTACT(1),
-			 TAG_NEXT(tags));
+  if (!ss || ss->ss_state >= nua_callstate_terminating)
+    return nua_client_return(cr, 900, "Invalid handle for INFO", msg);
 
-  cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				    process_response_to_info, nh, NULL,
-				    msg,
-				    SIPTAG_END(), TAG_NEXT(tags));
-  if (!cr->cr_orq) {
-    msg_destroy(msg);
-    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-  }
+  cr->cr_usage = du;
 
-  return cr->cr_event = e;
+  return 0;
 }
 
-void restart_info(nua_handle_t *nh, tagi_t *tags)
+static int nua_info_client_request(nua_client_request_t *cr,
+				   msg_t *msg, sip_t *sip,
+				   tagi_t const *tags)
 {
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_info, tags);
+  if (cr->cr_usage == NULL)
+    return nua_client_return(cr, SIP_481_NO_TRANSACTION, msg);
+  else
+    return nua_base_client_request(cr, msg, sip, tags);
 }
 
 /** @NUA_EVENT nua_r_info
@@ -2754,15 +2792,6 @@
  * @END_NUA_EVENT
  */
 
-static int process_response_to_info(nua_handle_t *nh,
-				    nta_outgoing_t *orq,
-				    sip_t const *sip)
-{
-  if (nua_creq_check_restart(nh, nh->nh_ds->ds_cr, orq, sip, restart_info))
-    return 0;
-  return nua_stack_process_response(nh, nh->nh_ds->ds_cr, orq, sip, TAG_END());
-}
-
 /** @NUA_EVENT nua_i_info
  *
  * Incoming session INFO request.
@@ -2779,25 +2808,26 @@
  * @END_NUA_EVENT
  */
 
-int nua_stack_process_info(nua_t *nua,
-			   nua_handle_t *nh,
-			   nta_incoming_t *irq,
-			   sip_t const *sip)
-{
-  nua_stack_event(nh->nh_nua, nh, nta_incoming_getrequest(irq),
-		  nua_i_info, SIP_200_OK, TAG_END());
-
-  return 200;		/* Respond automatically with 200 Ok */
-}
-
+nua_server_methods_t const nua_info_server_methods = 
+  {
+    SIP_METHOD_INFO,
+    nua_i_info,			/* Event */
+    { 
+      0,			/* Do not create dialog */
+      1,			/* In-dialog request */
+      0,			/* Not a target refresh request  */
+      0,			/* Do not add Contact */
+    },
+    nua_base_server_init,
+    nua_base_server_preprocess,
+    nua_base_server_params,
+    nua_base_server_respond,
+    nua_base_server_report,
+  };
 
 /* ======================================================================== */
 /* UPDATE */
 
-static int process_response_to_update(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip);
-
 /**@fn void nua_update(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
  *
  * Update a session. 
@@ -2826,91 +2856,166 @@
  * @sa @ref nua_call_model, @RFC3311, nua_update(), #nua_i_update
  */
 
+static int nua_update_client_init(nua_client_request_t *cr, 
+				  msg_t *msg, sip_t *sip,
+				  tagi_t const *tags);
+static int nua_update_client_request(nua_client_request_t *cr,
+				     msg_t *msg, sip_t *sip,
+				     tagi_t const *tags);
+static int nua_update_client_response(nua_client_request_t *cr,
+				      int status, char const *phrase,
+				      sip_t const *sip);
+static int nua_update_client_report(nua_client_request_t *cr,
+				    int status, char const *phrase,
+				    sip_t const *sip,
+				    nta_outgoing_t *orq,
+				    tagi_t const *tags);
+
+nua_client_methods_t const nua_update_client_methods = {
+  SIP_METHOD_UPDATE,
+  0,				/* size of private data */
+  { 
+    /* create_dialog */ 0,
+    /* in_dialog */ 1,
+    /* target refresh */ 1
+  },
+  NULL,
+  nua_update_client_init,
+  nua_update_client_request,
+  session_timer_check_restart,
+  nua_update_client_response,
+  NULL,
+  nua_update_client_report
+};
+
 int nua_stack_update(nua_t *nua, nua_handle_t *nh, nua_event_t e,
 		     tagi_t const *tags)
 {
-  nua_dialog_state_t *ds = nh->nh_ds;
-  nua_session_usage_t *ss;
-  nua_client_request_t *cr;
-  msg_t *msg;
-  sip_t *sip;
-  char const *offer_sent = 0;
+  return nua_client_create(nh, e, &nua_update_client_methods, tags);
+}
+
+static int nua_update_client_init(nua_client_request_t *cr, 
+				  msg_t *msg, sip_t *sip,
+				  tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = nua_dialog_usage_for_session(nh->nh_ds);
+
+  cr->cr_usage = du;
+
+  return 0;
+}
+
+static int nua_update_client_request(nua_client_request_t *cr,
+				     msg_t *msg, sip_t *sip,
+				     tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  nua_server_request_t *sr;
+  nua_client_request_t *cri;
+  int offer_sent = 0, retval;
+  
+  if (du == NULL)		/* Call terminated */
+    return nua_client_return(cr, SIP_481_NO_TRANSACTION, msg);
+  assert(ss);
+
+  cri = du->du_cr;
+
+  for (sr = nh->nh_ds->ds_sr; sr; sr = sr->sr_next)
+    if ((sr->sr_offer_sent && !sr->sr_answer_recv) ||
+	(sr->sr_offer_recv && !sr->sr_answer_sent))
+      break;
+
+  if (sr ||
+      (cri && cri->cr_offer_sent && !cri->cr_answer_recv) ||
+      (cri && cri->cr_offer_recv && !cri->cr_answer_sent)) {
+    if (nh->nh_soa == NULL) {
+      if (session_get_description(sip, NULL, NULL))
+	return nua_client_return(cr, 500, "Overlapping Offer/Answer", msg);
+    }
+  }
+  else if (nh->nh_soa == NULL) {
+    offer_sent = session_get_description(sip, NULL, NULL);
+  }
+  else if (!sip->sip_payload) {
+    soa_init_offer_answer(nh->nh_soa);
 
-  ss = nua_session_usage_get(ds);
-  cr = ds->ds_cr;
+    if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0 ||
+	session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
+      if (ss->ss_state < nua_callstate_ready) {
+	/* XXX - use soa_error_as_sip_reason(nh->nh_soa) */
+	cr->cr_graceful = 1;
+	ss->ss_reason = "SIP;cause=400;text=\"Local media failure\"";
+      }
+      return nua_client_return(cr, 900, "Local media failed", msg);
+    }
+    offer_sent = 1;
+  }
 
-  if (!ss)
-    return UA_EVENT2(e, 900, "Invalid handle for UPDATE");
-  else if (cr->cr_orq)
-    return UA_EVENT2(e, 900, "Request already in progress");
+  /* Add session timer headers */
+  session_timer_preferences(ss->ss_timer,
+			    sip,
+			    NH_PGET(nh, supported),		     
+			    NH_PGET(nh, session_timer),
+			    NUA_PISSET(nh->nh_nua, nh, session_timer),
+			    NH_PGET(nh, refresher),
+			    NH_PGET(nh, min_se));
 
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
+  if (session_timer_is_supported(ss->ss_timer))
+    session_timer_add_headers(ss->ss_timer, ss->ss_state < nua_callstate_ready,
+			      msg, sip);
 
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
-		     SIP_METHOD_UPDATE,
-		     NUTAG_USE_DIALOG(1),
-		     NUTAG_ADD_CONTACT(1),
-		     TAG_NEXT(tags));
+  retval = nua_base_client_request(cr, msg, sip, NULL);
 
-  sip = sip_object(msg);
+  if (retval == 0) {
+    cr->cr_offer_sent = offer_sent;
+    ss->ss_update_needed = 0;
 
-  if (sip) {
-    nua_client_request_t *cri = ss->ss_crequest;
-    nua_server_request_t *sr;
+    if (!cr->cr_restarting) {
+      enum nua_callstate state = ss->ss_state;
 
-    for (sr = ds->ds_sr; sr; sr = sr->sr_next)
-      if ((sr->sr_offer_sent && !sr->sr_answer_recv) ||
-	  (sr->sr_offer_recv && !sr->sr_answer_sent))
-	break;
-    
-    if (nh->nh_soa && !sip->sip_payload && 
-	!sr &&
-	!(cri && cri->cr_offer_sent && !cri->cr_answer_recv) &&
-	!(cri && cri->cr_offer_recv && !cri->cr_answer_sent)) {
-      soa_init_offer_answer(nh->nh_soa);
+      if (state == nua_callstate_ready)
+	state = nua_callstate_calling;
 
-      if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0 ||
-	  session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
-	if (ss->ss_state < nua_callstate_ready) {
-	  /* XXX */
-	}
-	msg_destroy(msg);
-	return UA_EVENT2(e, 900, "Local media failed");
-      }
+      if (offer_sent)
+	ss->ss_oa_sent = "offer";
 
-      offer_sent = "offer";
+      signal_call_state_change(nh, ss, 0, "UPDATE sent", state);
     }
+  }
 
-    /* Add session timer headers */
-    if (session_timer_is_supported(nh))
-      use_session_timer(ss, 0, prefer_session_timer(nh), msg, sip);
+  return retval;
+}
 
-    if (nh->nh_auth) {
-      if (auc_authorize(&nh->nh_auth, msg, sip) < 0)
-	/* xyzzy */;
-    }
+static int nua_update_client_response(nua_client_request_t *cr,
+				      int status, char const *phrase,
+				      sip_t const *sip)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
 
-    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				      process_response_to_update, nh, NULL,
-				      msg,
-				      SIPTAG_END(), TAG_NEXT(tags));
-    if (cr->cr_orq) {
-      if (offer_sent)
-	cr->cr_offer_sent = 1;
-      ss->ss_update_needed = 0;
-      signal_call_state_change(nh, ss, 0, "UPDATE sent",
-			       ss->ss_state, 0, offer_sent);
-      return cr->cr_event = e;
+  assert(200 <= status);
+
+  if (ss && sip && status < 300) {
+    if (session_timer_is_supported(ss->ss_timer)) {
+      nua_server_request_t *sr;
+
+      for (sr = nh->nh_ds->ds_sr; sr; sr = sr->sr_next)
+	if (sr->sr_method == sip_method_invite ||
+	    sr->sr_method == sip_method_update)
+	  break;
+
+      if (!sr && (!du->du_cr || !du->du_cr->cr_orq)) {
+	session_timer_store(ss->ss_timer, sip);
+	session_timer_set(ss);
+      }
     }
   }
 
-  msg_destroy(msg);
-  return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-}
-
-void restart_update(nua_handle_t *nh, tagi_t *tags)
-{
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_update, tags);
+  return nua_session_client_response(cr, status, phrase, sip);
 }
 
 /** @NUA_EVENT nua_r_update
@@ -2937,134 +3042,74 @@
  * @END_NUA_EVENT
  */
 
-static int process_response_to_update(nua_handle_t *nh,
-				       nta_outgoing_t *orq,
-				       sip_t const *sip)
+static int nua_update_client_report(nua_client_request_t *cr,
+				    int status, char const *phrase,
+				    sip_t const *sip,
+				    nta_outgoing_t *orq,
+				    tagi_t const *tags)
 {
-  nua_t *nua = nh->nh_nua;
-  nua_session_usage_t *ss;
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-
-  int status = sip->sip_status->st_status;
-  char const *phrase = sip->sip_status->st_phrase;
-  char const *recv = NULL;
-  int terminate = 0, gracefully = 1;
-
-  ss = nua_session_usage_get(nh->nh_ds); assert(ss);
-
-  if (status >= 300) {
-    if (sip->sip_retry_after)
-      gracefully = 0;
-
-    terminate = sip_response_terminates_dialog(status, sip_method_update,
-					       &gracefully);
-
-    if (!terminate &&
-	check_session_timer_restart(nh, ss, cr, orq, sip, restart_update)) {
-      return 0;
-    }
-    /* XXX - if we have a concurrent INVITE, what we do with it? */
-  }
-  else if (status >= 200) {
-    /* XXX - check remote tag, handle forks */
-    /* Set (route), contact, (remote tag) */
-    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
-    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
-
-    if (is_session_timer_set(ss)) {
-      init_session_timer(ss, sip, NH_PGET(nh, refresher));
-      set_session_timer(ss);
-    }
-
-    if (session_process_response(nh, cr, orq, sip, &recv) < 0) {
-      nua_stack_event(nua, nh, NULL, nua_i_error,
-	       400, "Bad Session Description", TAG_END());
-    }
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
 
-    signal_call_state_change(nh, ss, status, phrase, ss->ss_state, recv, 0);
+  nua_stack_event(nh->nh_nua, nh, 
+		  nta_outgoing_getresponse(orq),
+		  cr->cr_event,
+		  status, phrase,
+		  tags);
 
-    return 0;
-  }
-  else
-    gracefully = 0;
+  if (!ss || orq != cr->cr_orq || 
+      cr->cr_terminated || cr->cr_graceful || !cr->cr_offer_sent)
+    return 1;
 
-  nua_stack_process_response(nh, cr, orq, sip, TAG_END());
+  signal_call_state_change(nh, ss, status, phrase, ss->ss_state);
 
-  if (!terminate && !gracefully)
-    return 0;
+  return 1;
+}
 
-  nh_referral_respond(nh, status, phrase);
-  
-  if (ss == NULL) {
+/* ---------------------------------------------------------------------- */
+/* UPDATE server */
 
-  } 
-  else if (terminate || 
-      (ss->ss_state < nua_callstate_completed &&
-       ss->ss_state != nua_callstate_completing)) {
-    signal_call_state_change(nh, ss, status, phrase,
-			     nua_callstate_terminated, recv, 0);
-    nua_session_usage_destroy(nh, ss);
-  }
-  else /* if (gracefully) */ {
-    signal_call_state_change(nh, ss, status, phrase,
-			     nua_callstate_terminating, recv, 0);
-#if 0
-    if (nh->nh_ss->ss_crequest->cr_orq)
-      nua_stack_post_signal(nh, nua_r_cancel, TAG_END());
-    else
-#endif
-      nua_stack_post_signal(nh, nua_r_bye, TAG_END());
-  }
+int nua_update_server_init(nua_server_request_t *sr);
+int nua_update_server_respond(nua_server_request_t *sr, tagi_t const *tags);
+int nua_update_server_report(nua_server_request_t *, tagi_t const *);
 
-  return 0;
-}
+nua_server_methods_t const nua_update_server_methods = 
+  {
+    SIP_METHOD_UPDATE,
+    nua_i_update,		/* Event */
+    { 
+      0,			/* Do not create dialog */
+      1,			/* In-dialog request */
+      1,			/* Target refresh request  */
+      1,			/* Add Contact */
+    },
+    nua_update_server_init,
+    nua_base_server_preprocess,
+    nua_base_server_params,
+    nua_update_server_respond,
+    nua_update_server_report,
+  };
 
-int nua_stack_process_update(nua_t *nua,
-			     nua_handle_t *nh,
-			     nta_incoming_t *irq,
-			     sip_t const *sip)
+int nua_update_server_init(nua_server_request_t *sr)
 {
-  nua_dialog_state_t *ds = nh->nh_ds;
+  nua_handle_t *nh = sr->sr_owner;
   nua_session_usage_t *ss;
-  nua_dialog_usage_t *du;
-  msg_t *msg = nta_incoming_getrequest(irq);
-
-  char const *sdp;
-  size_t len;
-
-  int original_status = 200, status = 200;
-  char const *phrase = sip_200_OK;
-
-  char const *offer_recv = NULL, *answer_sent = NULL;
-  int use_timer = 0;
 
-  msg_t *rmsg;
-  sip_t *rsip;
+  sip_t const *request = sr->sr_request.sip;
 
-  ss = nua_session_usage_get(ds); du = nua_dialog_usage_public(ss);
-  if (!ss) {
-    /* RFC 3261 section 12.2.2:
-       If the UAS wishes to reject the request because it does not wish to
-       recreate the dialog, it MUST respond to the request with a 481
-       (Call/Transaction Does Not Exist) status code and pass that to the
-       server transaction.
-    */
-    return 481;
-  }
+  if (nua_session_server_init(sr))
+    return sr->sr_status;
 
-  if (session_check_request(nua, nh, irq, sip))
-    return 501;
+  ss = nua_dialog_usage_private(sr->sr_usage);
 
   /* Do session timer negotiation */
-  if (sip->sip_session_expires) {
-    use_timer = 1;
-    init_session_timer(ss, sip, NH_PGET(nh, refresher));
-  }
+  if (request->sip_session_expires)
+    session_timer_store(ss->ss_timer, request);
 
-  if (status < 300 && nh->nh_soa &&
-      session_get_description(sip, &sdp, &len)) {
+  if (sr->sr_sdp) {		/* Check for overlap */
     nua_client_request_t *cr;
-    nua_server_request_t *sr;
+    nua_server_request_t *sr0;
     int overlap = 0;
 
     /*
@@ -3082,71 +3127,91 @@
       reject the UPDATE with a 500 response, and MUST include a Retry-After
       header field with a randomly chosen value between 0 and 10 seconds.
     */
-    for (cr = ds->ds_cr; cr && !overlap; cr = cr->cr_next)
-      overlap = cr->cr_offer_sent && !cr->cr_answer_recv;
-    for (sr = ds->ds_sr; sr && !overlap; sr = sr->sr_next)
-      overlap = (sr->sr_offer_recv && !sr->sr_answer_sent) ||
-	(sr->sr_method == sip_method_update && sr->sr_respond);
+    for (cr = nh->nh_ds->ds_cr; cr; cr = cr->cr_next)
+      if ((overlap = cr->cr_offer_sent && !cr->cr_answer_recv))
+	break;
+
+    if (!overlap)
+      for (sr0 = nh->nh_ds->ds_sr; sr0; sr0 = sr0->sr_next)
+	if ((overlap = sr0->sr_offer_recv && !sr0->sr_answer_sent))
+	  break;
 
     if (overlap)
-      return respond_with_retry_after(nh, irq, 
-				      500, "Overlapping Offer/Answer",
-				      0, 10);
-
-    offer_recv = "offer";
-
-    if (soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0) {
-      SU_DEBUG_5(("nua(%p): error parsing SDP in UPDATE\n", nh));
-      msg_destroy(msg);
-      status = soa_error_as_sip_response(nh->nh_soa, &phrase);
-      offer_recv = NULL;
+      return nua_server_retry_after(sr, 500, "Overlapping Offer/Answer", 1, 9);
+
+    if (nh->nh_soa &&
+	soa_set_remote_sdp(nh->nh_soa, NULL, sr->sr_sdp, sr->sr_sdp_len) < 0) {
+      SU_DEBUG_5(("nua(%p): %s server: error parsing %s\n", (void *)nh,
+		  "UPDATE", "offer"));
+      return 
+	sr->sr_status = soa_error_as_sip_response(nh->nh_soa, &sr->sr_phrase);
+    }
+
+    sr->sr_offer_recv = 1;
+    ss->ss_oa_recv = "offer";
+  }
+
+  return 0;
+}
+
+/** @internal Respond to an UPDATE request.
+ *
+ */
+int nua_update_server_respond(nua_server_request_t *sr, tagi_t const *tags)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_session_usage_t *ss = nua_dialog_usage_private(sr->sr_usage);
+  msg_t *msg = sr->sr_response.msg;
+  sip_t *sip = sr->sr_response.sip;
+
+  if (200 <= sr->sr_status && sr->sr_status < 300 && sr->sr_sdp) {
+    if (nh->nh_soa == NULL) {
+      sr->sr_answer_sent = 1, ss->ss_oa_sent = "answer";
     }
-    /* Respond to UPDATE */
     else if (soa_generate_answer(nh->nh_soa, NULL) < 0) {
-      SU_DEBUG_5(("nua(%p): error processing SDP in UPDATE\n", nh));
-      msg_destroy(msg);
-      status = soa_error_as_sip_response(nh->nh_soa, &phrase);
+      SU_DEBUG_5(("nua(%p): %s server: %s %s\n", 
+		  (void *)nh, "UPDATE", "error processing", "offer"));
+      sr->sr_status = soa_error_as_sip_response(nh->nh_soa, &sr->sr_phrase);
     }
     else if (soa_activate(nh->nh_soa, NULL) < 0) {
-      SU_DEBUG_5(("nua(%p): error activating media after %s\n",
-		  nh, "UPDATE"));
+      SU_DEBUG_5(("nua(%p): %s server: error activating media\n",
+		  (void *)nh, "UPDATE"));
       /* XXX */
     }
+    else if (session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
+      sr_status(sr, SIP_500_INTERNAL_SERVER_ERROR);
+    }
     else {
-      answer_sent = "answer";
+      sr->sr_answer_sent = 1, ss->ss_oa_sent = "answer";
     }
   }
 
-  rmsg = nh_make_response(nua, nh, irq,
-			  status, phrase,
-			  TAG_IF(status < 300, NUTAG_ADD_CONTACT(1)),
-			  SIPTAG_SUPPORTED(NH_PGET(nh, supported)),
-			  TAG_NEXT(NULL));
-  rsip = sip_object(rmsg);
-  assert(sip);			/* XXX */
+  if (200 <= sr->sr_status && sr->sr_status < 300) {
+    session_timer_preferences(ss->ss_timer,
+			      sip,
+			      NH_PGET(nh, supported),		     
+			      NH_PGET(nh, session_timer),
+			      NUA_PISSET(nh->nh_nua, nh, session_timer),
+			      NH_PGET(nh, refresher),
+			      NH_PGET(nh, min_se));
 
-  if (answer_sent && 
-      session_include_description(nh->nh_soa, 1, rmsg, rsip) < 0) {
-    status = 500, phrase = sip_500_Internal_server_error;
-    answer_sent = NULL;
-  }
+    if (ss && session_timer_is_supported(ss->ss_timer)) {
+      nua_server_request_t *sr0;
 
-  if (200 <= status && status < 300 && session_timer_is_supported(nh)) {
-    use_session_timer(ss, 1, use_timer, rmsg, rsip);
-    set_session_timer(ss);
-  }
+      session_timer_add_headers(ss->ss_timer, 0, msg, sip);
 
-  if (status == original_status) {
-    if (nta_incoming_mreply(irq, rmsg) < 0)
-      status = 500, phrase = sip_500_Internal_server_error;
-  }
+      for (sr0 = nh->nh_ds->ds_sr; sr0; sr0 = sr0->sr_next)
+	if (sr0->sr_method == sip_method_invite)
+	  break;
 
-  if (status != original_status) {
-    nua_stack_event(nua, nh, NULL, nua_i_error, status, phrase, TAG_END());
-    nta_incoming_treply(irq, status, phrase, TAG_END());
-    msg_destroy(rmsg), rmsg = NULL;
+      if (!sr0 && (!sr->sr_usage->du_cr || !sr->sr_usage->du_cr->cr_orq))
+	session_timer_set(ss);
+    }
   }
 
+  return nua_base_server_respond(sr, tags);
+}
+
 /** @NUA_EVENT nua_i_update
  *
  * @brief Incoming session UPDATE request.
@@ -3163,39 +3228,58 @@
  * @END_NUA_EVENT
  */
 
-  nua_stack_event(nh->nh_nua, nh, msg, nua_i_update, status, phrase, TAG_END());
+int nua_update_server_report(nua_server_request_t *sr, tagi_t const *tags)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_dialog_usage_t *du = sr->sr_usage;
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
+  int status = sr->sr_status; char const *phrase = sr->sr_phrase;
+  int offer_recv_or_answer_sent = sr->sr_offer_recv || sr->sr_answer_sent;
+  int retval;
+
+  retval = nua_base_server_report(sr, tags), sr = NULL; /* destroys sr */
+
+  if (retval >= 2 || ss == NULL) {
+    signal_call_state_change(nh, NULL, status, phrase, 
+			     nua_callstate_terminated);
+    return retval;
+  }
 
-  if (offer_recv || answer_sent)
+  if (offer_recv_or_answer_sent) {
     /* signal offer received, answer sent */
-    signal_call_state_change(nh, ss, 200, "OK", ss->ss_state,
-			     offer_recv, answer_sent);
+    enum nua_callstate state = ss->ss_state;
+    
+    if (state == nua_callstate_ready && status < 200)
+      state = nua_callstate_received;
+
+    signal_call_state_change(nh, ss, status, phrase, state);
+  }
 
-  if (NH_PGET(nh, auto_alert)
+  if (200 <= status && status < 300
       && ss->ss_state < nua_callstate_ready
+      && ss->ss_precondition 
       && !ss->ss_alerting
-      && ss->ss_precondition) {
-    nua_server_request_t *sr;
+      && NH_PGET(nh, auto_alert))  {
+    nua_server_request_t *sri;
     
-    for (sr = ds->ds_sr; sr; sr = sr->sr_next)
-      if (sr->sr_method == sip_method_invite && 
-	  sr->sr_usage == du && sr->sr_respond)
+    for (sri = nh->nh_ds->ds_sr; sri; sri = sr->sr_next)
+      if (sri->sr_method == sip_method_invite && 
+	  nua_server_request_is_pending(sri))
 	break;
 
-    if (sr)
-      nua_server_respond(sr, SIP_180_RINGING, TAG_END());
+    if (sri) {
+      SR_STATUS1(sri, SIP_180_RINGING);
+      nua_server_respond(sri, NULL);
+      nua_server_report(sri);
+    }
   }
 
-  return status;
+  return retval;
 }
 
-
 /* ======================================================================== */
 /* BYE */
 
-static int process_response_to_bye(nua_handle_t *nh,
-				   nta_outgoing_t *orq,
-				   sip_t const *sip);
-
 /**@fn void nua_bye(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
  *
  * Hangdown a call.
@@ -3217,87 +3301,95 @@
  *    #nua_i_media_error
  */
 
+static int nua_bye_client_init(nua_client_request_t *cr, 
+			       msg_t *msg, sip_t *sip,
+			       tagi_t const *tags);
+static int nua_bye_client_request(nua_client_request_t *cr,
+				  msg_t *msg, sip_t *sip,
+				  tagi_t const *tags);
+static int nua_bye_client_report(nua_client_request_t *cr,
+				 int status, char const *phrase,
+				 sip_t const *sip,
+				 nta_outgoing_t *orq,
+				 tagi_t const *tags);
+
+nua_client_methods_t const nua_bye_client_methods = {
+  SIP_METHOD_BYE,
+  0,
+  { 
+    /* create_dialog */ 0,
+    /* in_dialog */ 1,
+    /* target refresh */ 0
+  },
+  NULL,
+  nua_bye_client_init,
+  nua_bye_client_request,
+  /*nua_bye_client_check_restart*/ NULL,
+  /*nua_bye_client_response*/ NULL,
+  /*nua_bye_client_preliminary*/ NULL,
+  nua_bye_client_report
+};
+
 int
 nua_stack_bye(nua_t *nua, nua_handle_t *nh, nua_event_t e, tagi_t const *tags)
 {
-  nua_session_usage_t *ss;
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  msg_t *msg;
-  nta_outgoing_t *orq;
-
-  ss = nua_session_usage_get(nh->nh_ds);
-  
-  if (!ss || ss->ss_state >= nua_callstate_terminating)
-    return UA_EVENT2(e, 900, "Invalid handle for BYE");
-
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
-
-  if (!nua_dialog_is_established(nh->nh_ds)) {
-    nua_client_request_t *cri = ss->ss_crequest;
-
-    if (cri->cr_orq == NULL)
-      return UA_EVENT2(e, 900, "No session to BYE");
-
-    /* No (early) dialog. BYE is invalid action, do CANCEL instead */
-    orq = nta_outgoing_tcancel(cri->cr_orq,
-			       process_response_to_cancel, nh,
-			       TAG_NEXT(tags));
-    if (!cr->cr_orq)
-      cr->cr_orq = orq, cr->cr_event = e;
+  nua_session_usage_t *ss = nua_session_usage_for_dialog(nh->nh_ds);
 
-    return 0;
-  }
-
-  if (cr->cr_orq) {
-    if (cr->cr_usage == nua_dialog_usage_public(ss)) {
-      nua_creq_deinit(cr, cr->cr_orq);
-    }
-    else {
-      cr = ss->ss_crequest;
-      if (cr->cr_orq)
-	nua_creq_deinit(cr, cr->cr_orq);
-    }
-  }
+  if (ss && 
+      nua_callstate_calling <= ss->ss_state &&
+      ss->ss_state <= nua_callstate_proceeding)
+    return nua_client_create(nh, e, &nua_cancel_client_methods, tags);
+  else
+    return nua_client_create(nh, e, &nua_bye_client_methods, tags);
+}
 
-  assert(!cr->cr_orq);
+static int nua_bye_client_init(nua_client_request_t *cr, 
+			       msg_t *msg, sip_t *sip,
+			       tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = nua_dialog_usage_for_session(nh->nh_ds);
+  nua_session_usage_t *ss = nua_dialog_usage_private(du);
 
-  msg = nua_creq_msg(nua, nh, cr, 0, SIP_METHOD_BYE, TAG_NEXT(tags));
+  if (!ss || (ss->ss_state >= nua_callstate_terminating && !cr->cr_auto))
+    return nua_client_return(cr, 900, "Invalid handle for BYE", msg);
 
-  cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				    process_response_to_bye, nh, NULL,
-				    msg,
-				    SIPTAG_END(), TAG_NEXT(tags));
+  if (!cr->cr_auto)
+    /* Implicit state transition by nua_bye() */
+    ss->ss_state = nua_callstate_terminating;
 
-  ss->ss_state = nua_callstate_terminating;
   if (nh->nh_soa)
     soa_terminate(nh->nh_soa, 0);
-
-  if (cr->cr_orq) {
-    cr->cr_event = e;
-  }
-  else {
-    msg_destroy(msg);
-    UA_EVENT2(e, 400, "Internal error");
-    signal_call_state_change(nh, ss, 400, "Failure sending BYE",
-			     nua_callstate_terminated, 0, 0);
-    nua_session_usage_destroy(nh, ss);
-  }
+  cr->cr_usage = du;
 
   return 0;
 }
 
-
-void restart_bye(nua_handle_t *nh, tagi_t *tags)
+static int nua_bye_client_request(nua_client_request_t *cr,
+				  msg_t *msg, sip_t *sip,
+				  tagi_t const *tags)
 {
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_bye, tags);
+  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_session_usage_t *ss;
+  char const *reason = NULL;
+
+  if (du == NULL)
+    return nua_client_return(cr, SIP_481_NO_TRANSACTION, msg);
+
+  ss = nua_dialog_usage_private(du);
+  reason = ss->ss_reason;
+
+  return nua_base_client_trequest(cr, msg, sip,
+				  SIPTAG_REASON_STR(reason),
+				  TAG_NEXT(tags));
 }
 
 /** @NUA_EVENT nua_r_bye
  *
  * Answer to outgoing BYE.
  *
- * The BYE may be sent explicitly by nua_bye() or
- * implicitly by NUA state machine.
+ * The BYE may be sent explicitly by nua_bye() or implicitly by NUA state
+ * machine.
  *
  * @param status response status code
  *               (if the request is retried, @a status is 100, the @a
@@ -3316,45 +3408,47 @@
  * @END_NUA_EVENT
  */
 
-static int process_response_to_bye(nua_handle_t *nh,
-				   nta_outgoing_t *orq,
-				   sip_t const *sip)
+static int nua_bye_client_report(nua_client_request_t *cr,
+				 int status, char const *phrase,
+				 sip_t const *sip,
+				 nta_outgoing_t *orq,
+				 tagi_t const *tags)
 {
-  nua_client_request_t *cr = NULL;
-  nua_session_usage_t *ss;
-  int status = sip ? sip->sip_status->st_status : 400;
-  char const *phrase = sip ? sip->sip_status->st_phrase : "";
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
 
-  cr = nua_client_request_by_orq(nh->nh_ds->ds_cr, orq); assert(cr);
+  nua_stack_event(nh->nh_nua, nh, 
+		  nta_outgoing_getresponse(orq),
+		  cr->cr_event,
+		  status, phrase,
+		  tags);
 
-  if (cr) {
-    if (nua_creq_check_restart(nh, cr, orq, sip, restart_bye))
-      return 0;
-    nua_stack_process_response(nh, cr, orq, sip, TAG_END());
+  if (du == NULL) {
+    /* No more session */
   }
-  else {			/* No cr for BYE */
-    msg_t *msg = nta_outgoing_getresponse(orq);
-    nua_stack_event(nh->nh_nua, nh, msg, nua_r_bye, status, phrase, TAG_END());
-    nta_outgoing_destroy(orq);
+  else if (status < 200) {
+    /* Preliminary */
   }
+  else {
+    nua_session_usage_t *ss = nua_dialog_usage_private(du);
 
-  ss = nua_session_usage_get(nh->nh_ds);
+    signal_call_state_change(nh, ss, status, "to BYE", 
+			     nua_callstate_terminated);
 
-  if (status >= 200 && ss) {
-    if (ss->ss_crequest->cr_orq) {
-      /* Do not destroy usage while INVITE is alive */
-    }
-    else {
-      signal_call_state_change(nh, ss, status, "to BYE",
-			       nua_callstate_terminated, 0, 0);
-      nua_session_usage_destroy(nh, ss);
+    if (ss && !ss->ss_reporting) {
+      if (du->du_cr == NULL ||
+	  !nua_client_is_queued(du->du_cr) ||
+	  du->du_cr->cr_status >= 200) {
+	/* INVITE is completed, we can zap the session... */;
+	cr->cr_usage = NULL;
+	nua_session_usage_destroy(nh, ss);
+      }
     }
   }
 
-  return 0;
+  return 1;
 }
 
-
 /** @NUA_EVENT nua_i_bye
  *
  * Incoming BYE request, call hangup.
@@ -3371,52 +3465,144 @@
  * @END_NUA_EVENT
  */
 
-int nua_stack_process_bye(nua_t *nua,
-			  nua_handle_t *nh,
-			  nta_incoming_t *irq,
-			  sip_t const *sip)
+int nua_bye_server_init(nua_server_request_t *sr);
+int nua_bye_server_report(nua_server_request_t *sr, tagi_t const *tags);
+
+nua_server_methods_t const nua_bye_server_methods = 
+  {
+    SIP_METHOD_BYE,
+    nua_i_bye,			/* Event */
+    { 
+      0,			/* Do not create dialog */
+      1,			/* In-dialog request */
+      0,			/* Not a target refresh request  */
+      0,			/* Do not add Contact */
+    },
+    nua_bye_server_init,
+    nua_base_server_preprocess,
+    nua_base_server_params,
+    nua_base_server_respond,
+    nua_bye_server_report,
+  };
+
+
+int nua_bye_server_init(nua_server_request_t *sr)
 {
-  nua_dialog_state_t *ds = nh->nh_ds;
-  nua_session_usage_t *ss;
-  nua_server_request_t *sr, *sr_next;
-  int early = 0;
+  nua_handle_t *nh = sr->sr_owner;
+  nua_dialog_usage_t *du = nua_dialog_usage_for_session(nh->nh_ds);
 
-  ss = nua_session_usage_get(ds);
-  if (!ss)
-    return 481;
+  sr->sr_terminating = 1;
 
-  assert(nh && ss);
+  if (du)
+    sr->sr_usage = du;
+  else
+    return SR_STATUS(sr, 481, "No Such Call");
 
-  nua_stack_event(nh->nh_nua, nh, nta_incoming_getrequest(irq),
-		  nua_i_bye, SIP_200_OK, TAG_END());
-  nta_incoming_treply(irq, SIP_200_OK, TAG_END());
-  nta_incoming_destroy(irq), irq = NULL;
+  return 0;
+}
 
-  for (sr = ds->ds_sr; sr; sr = sr_next) {
-    sr_next = sr->sr_next;
-    if (sr->sr_respond && sr->sr_usage == nua_dialog_usage_public(ss)) {
-      char const *phrase;
-      early = ss->ss_state < nua_callstate_ready;
-      phrase = early ? "Early Session Terminated" : "Session Terminated";
-      sr->sr_usage = NULL;
-      if (sr->sr_respond)
-	nua_server_respond(sr, 487, phrase, TAG_END());
-      else
-	nua_server_request_destroy(sr);
+int nua_bye_server_report(nua_server_request_t *sr, tagi_t const *tags)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_session_usage_t *ss = nua_dialog_usage_private(sr->sr_usage);
+  int early = 0, retval;
+
+  if (sr->sr_status < 200)
+    return nua_base_server_report(sr, tags);
+
+  if (ss) {
+    nua_server_request_t *sr0 = NULL, *sr_next;
+    char const *phrase;
+
+    early = ss->ss_state < nua_callstate_ready;
+    phrase = early ? "Early Session Terminated" : "Session Terminated";
+    
+    for (sr0 = nh->nh_ds->ds_sr; sr0; sr0 = sr_next) {
+      sr_next = sr0->sr_next;
+
+      if (sr == sr0 || sr0->sr_usage != sr->sr_usage)
+	continue;
+
+      if (nua_server_request_is_pending(sr0)) {
+	SR_STATUS(sr0, 487, phrase);
+	nua_server_respond(sr0, NULL);
+      }
+      nua_server_request_destroy(sr0);
     }
   }
 
-  signal_call_state_change(nh, ss, 200,
-			   early ? "Received early BYE" : "Received BYE",
-			   nua_callstate_terminated, 0, 0);
+  retval = nua_base_server_report(sr, tags);
 
-  nua_session_usage_destroy(nh, ss);
+  assert(2 <= retval && retval < 4);
 
-  return 0;
+  if (ss)
+    signal_call_state_change(nh, NULL, 200,
+			     early ? "Received early BYE" : "Received BYE",
+			     nua_callstate_terminated);
+
+  return retval;
 }
 
 /* ---------------------------------------------------------------------- */
 
+/** @NUA_EVENT nua_i_state
+ *
+ * @brief Call state has changed.
+ *
+ * This event will be sent whenever the call state changes. 
+ *
+ * In addition to basic changes of session status indicated with enum
+ * ::nua_callstate, the @RFC3264 SDP Offer/Answer negotiation status is also
+ * included. The tags NUTAG_OFFER_RECV() or NUTAG_ANSWER_RECV() indicate
+ * whether the remote SDP that was received was considered as an offer or an
+ * answer. Tags NUTAG_OFFER_SENT() or NUTAG_ANSWER_SENT() indicate whether
+ * the local SDP which was sent was considered as an offer or answer.
+ *
+ * If the @b soa SDP negotiation is enabled (by default or with
+ * NUTAG_MEDIA_ENABLE(1)), the received remote SDP is included in tags
+ * SOATAG_REMOTE_SDP() and SOATAG_REMOTE_SDP_STR(). The SDP negotiation
+ * result from @b soa is included in the tags SOATAG_LOCAL_SDP() and
+ * SOATAG_LOCAL_SDP_STR().
+ *
+ * SOATAG_ACTIVE_AUDIO() and SOATAG_ACTIVE_VIDEO() are informational tags
+ * used to indicate what is the status of audio or video.
+ *
+ * Note that #nua_i_state also covers the information relayed in call
+ * establisment (#nua_i_active) and termination (#nua_i_terminated) events.
+ *
+ * @param status protocol status code \n
+ *               (always present)
+ * @param phrase short description of status code \n
+ *               (always present)
+ * @param nh     operation handle associated with the call
+ * @param hmagic application context associated with the call
+ * @param sip    NULL
+ * @param tags   NUTAG_CALLSTATE(), 
+ *               SOATAG_LOCAL_SDP(), SOATAG_LOCAL_SDP_STR(),
+ *               NUTAG_OFFER_SENT(), NUTAG_ANSWER_SENT(),
+ *               SOATAG_REMOTE_SDP(), SOATAG_REMOTE_SDP_STR(),
+ *               NUTAG_OFFER_RECV(), NUTAG_ANSWER_RECV(),
+ *               SOATAG_ACTIVE_AUDIO(), SOATAG_ACTIVE_VIDEO(),
+ *               SOATAG_ACTIVE_IMAGE(), SOATAG_ACTIVE_CHAT().
+ *
+ * @sa @ref nua_call_model, #nua_i_active, #nua_i_terminated,
+ * nua_invite(), #nua_r_invite, #nua_i_invite, nua_respond(), 
+ * NUTAG_MEDIA_ENABLE(),
+ * NUTAG_AUTOALERT(), NUTAG_AUTOANSWER(), NUTAG_EARLY_MEDIA(),
+ * NUTAG_EARLY_ANSWER(), NUTAG_INCLUDE_EXTRA_SDP(),
+ * nua_ack(), NUTAG_AUTOACK(), nua_bye(), #nua_r_bye, #nua_i_bye,
+ * nua_cancel(), #nua_r_cancel, #nua_i_cancel,
+ * nua_prack(), #nua_r_prack, #nua_i_prack,
+ * nua_update(), #nua_r_update, #nua_i_update
+ *
+ * @par History
+ * Prior @VERSION_1_12_6 the tags NUTAG_OFFER_RECV(), NUTAG_ANSWER_RECV(),
+ * NUTAG_ANSWER_SENT(), NUTAG_OFFER_SENT() were not included with
+ * nua_i_state eventif media was disabled.
+ *
+ * @END_NUA_EVENT
+ */
+
 /**
  * Delivers call state changed event to the nua client. @internal
  *
@@ -3430,65 +3616,68 @@
 static void signal_call_state_change(nua_handle_t *nh,
 				     nua_session_usage_t *ss,
 				     int status, char const *phrase,
-				     enum nua_callstate next_state,
-				     char const *oa_recv,
-				     char const *oa_sent)
-{
-  enum nua_callstate ss_state;
-
-  sdp_session_t const *remote_sdp = NULL;
-  char const *remote_sdp_str = NULL;
-  sdp_session_t const *local_sdp = NULL;
-  char const *local_sdp_str = NULL;
+				     enum nua_callstate next_state)
+{
+  enum nua_callstate ss_state = nua_callstate_init;
+
+  char const *oa_recv = NULL;
+  char const *oa_sent = NULL;
 
   int offer_recv = 0, answer_recv = 0, offer_sent = 0, answer_sent = 0;
 
-  ss_state = ss ? ss->ss_state : nua_callstate_init;
+  if (ss) {
+    if (ss->ss_reporting)
+      return;
+
+    ss_state = ss->ss_state;
+    oa_recv = ss->ss_oa_recv, ss->ss_oa_recv = NULL;
+    oa_sent = ss->ss_oa_sent, ss->ss_oa_sent = NULL;
+
+    if (oa_recv) {
+      offer_recv = strcasecmp(oa_recv, "offer") == 0;
+      answer_recv = strcasecmp(oa_recv, "answer") == 0;
+    }
+
+    if (oa_sent) {
+      offer_sent = strcasecmp(oa_sent, "offer") == 0;
+      answer_sent = strcasecmp(oa_sent, "answer") == 0;
+    }
+  }
 
   if (ss_state < nua_callstate_ready || next_state > nua_callstate_ready)
     SU_DEBUG_5(("nua(%p): call state changed: %s -> %s%s%s%s%s\n",
-		nh, nua_callstate_name(ss_state),
+		(void *)nh, nua_callstate_name(ss_state),
 		nua_callstate_name(next_state),
 		oa_recv ? ", received " : "", oa_recv ? oa_recv : "",
 		oa_sent && oa_recv ? ", and sent " :
 		oa_sent ? ", sent " : "", oa_sent ? oa_sent : ""));
   else
     SU_DEBUG_5(("nua(%p): ready call updated: %s%s%s%s%s\n",
-		nh, nua_callstate_name(next_state),
+		(void *)nh, nua_callstate_name(next_state),
 		oa_recv ? " received " : "", oa_recv ? oa_recv : "",
 		oa_sent && oa_recv ? ", sent " :
 		oa_sent ? " sent " : "", oa_sent ? oa_sent : ""));
 
-  if (oa_recv) {
-    soa_get_remote_sdp(nh->nh_soa, &remote_sdp, &remote_sdp_str, 0);
-    offer_recv = strcasecmp(oa_recv, "offer") == 0;
-    answer_recv = strcasecmp(oa_recv, "answer") == 0;
-  }
-
-  if (oa_sent) {
-    soa_get_local_sdp(nh->nh_soa, &local_sdp, &local_sdp_str, 0);
-    offer_sent = strcasecmp(oa_sent, "offer") == 0;
-    answer_sent = strcasecmp(oa_sent, "answer") == 0;
-  }
-
-  if (answer_recv || answer_sent) {
-    /* Update nh_hold_remote */
-
-    char const *held;
-
-    soa_get_params(nh->nh_soa, SOATAG_HOLD_REF(held), TAG_END());
-
-    nh->nh_hold_remote = held && strlen(held) > 0;
-  }
+  if (next_state == nua_callstate_terminating &&
+      ss_state >= nua_callstate_terminating)
+    return;
 
   if (ss) {
     /* Update state variables */
-    if (next_state > ss_state)
+    if (next_state == nua_callstate_init) {
+      if (ss_state < nua_callstate_ready)
+	ss->ss_state = next_state;
+      else
+	/* Do not change state - we are ready, terminating, or terminated */
+	next_state = ss_state;
+    }
+    else if (next_state > ss_state)
       ss->ss_state = next_state;
-    else if (next_state == nua_callstate_init && ss_state < nua_callstate_ready)
-      ss->ss_state = nua_callstate_init, next_state = nua_callstate_terminated;
   }
 
+  if (next_state == nua_callstate_init) 
+    next_state = nua_callstate_terminated;
+
   if (ss && ss->ss_state == nua_callstate_ready)
     nh->nh_active_call = 1;
   else if (next_state == nua_callstate_terminated)
@@ -3498,69 +3687,56 @@
   if (phrase == NULL)
     phrase = "Call state";
 
-/** @NUA_EVENT nua_i_state
- *
- * @brief Call state has changed.
- *
- * This event will be sent whenever the call state changes. 
- *
- * In addition to basic changes of session status indicated with enum
- * ::nua_callstate, the @RFC3264 SDP Offer/Answer negotiation status is also
- * included if it is enabled (by default or with NUTAG_MEDIA_ENABLE(1)). The
- * received remote SDP is included in tag SOATAG_REMOTE_SDP(). The tags
- * NUTAG_OFFER_RECV() or NUTAG_ANSWER_RECV() indicate whether the remote SDP
- * was an offer or an answer. The SDP negotiation result is included in the
- * tags SOATAG_LOCAL_SDP() and SOATAG_LOCAL_SDP_STR() and tags
- * NUTAG_OFFER_SENT() or NUTAG_ANSWER_SENT() indicate whether the local SDP
- * was an offer or answer.
- *
- * SOATAG_ACTIVE_AUDIO() and SOATAG_ACTIVE_VIDEO() are informational tags
- * used to indicate what is the status of audio or video.
- *
- * Note that #nua_i_state also covers call establisment events
- * (#nua_i_active) and termination (#nua_i_terminated).
- *
- * @param status protocol status code \n
- *               (always present)
- * @param phrase short description of status code \n
- *               (always present)
- * @param nh     operation handle associated with the call
- * @param hmagic application context associated with the call
- * @param sip    NULL
- * @param tags   NUTAG_CALLSTATE(), 
- *               SOATAG_LOCAL_SDP(), SOATAG_LOCAL_SDP_STR(),
- *               NUTAG_OFFER_SENT(), NUTAG_ANSWER_SENT(),
- *               SOATAG_REMOTE_SDP(), SOATAG_REMOTE_SDP_STR(),
- *               NUTAG_OFFER_RECV(), NUTAG_ANSWER_RECV(),
- *               SOATAG_ACTIVE_AUDIO(), SOATAG_ACTIVE_VIDEO(),
- *               SOATAG_ACTIVE_IMAGE(), SOATAG_ACTIVE_CHAT().
- *
- * @sa @ref nua_call_model, #nua_i_active, #nua_i_terminated,
- * nua_invite(), #nua_r_invite, #nua_i_invite, nua_respond(), 
- * NUTAG_AUTOALERT(), NUTAG_AUTOANSWER(), NUTAG_EARLY_MEDIA(),
- * NUTAG_EARLY_ANSWER(), NUTAG_INCLUDE_EXTRA_SDP(),
- * nua_ack(), NUTAG_AUTOACK(), nua_bye(), #nua_r_bye, #nua_i_bye,
- * nua_cancel(), #nua_r_cancel, #nua_i_cancel,
- * nua_prack(), #nua_r_prack, #nua_i_prack,
- * nua_update(), #nua_r_update, #nua_i_update
- *
- * @END_NUA_EVENT
- */
+  {
+    sdp_session_t const *remote_sdp = NULL;
+    char const *remote_sdp_str = NULL;
+    sdp_session_t const *local_sdp = NULL;
+    char const *local_sdp_str = NULL;
+
+    if (nh->nh_soa) {
+      if (oa_recv)
+	soa_get_remote_sdp(nh->nh_soa, &remote_sdp, &remote_sdp_str, 0);
+      if (oa_sent)
+	soa_get_local_sdp(nh->nh_soa, &local_sdp, &local_sdp_str, 0);
+
+      if (answer_recv || answer_sent) {      /* Update nh_hold_remote */
+	char const *held = NULL;
+	soa_get_params(nh->nh_soa, SOATAG_HOLD_REF(held), TAG_END());
+	nh->nh_hold_remote = held && strlen(held) > 0;
+      }
+    }
+    else
+      oa_recv = NULL, oa_sent = NULL;
 
-  nua_stack_event(nh->nh_nua, nh, NULL, nua_i_state,
-		  status, phrase,
-		  NUTAG_CALLSTATE(next_state),
-		  NH_ACTIVE_MEDIA_TAGS(1, nh->nh_soa),
-		  /* NUTAG_SOA_SESSION(nh->nh_soa), */
-		  TAG_IF(offer_recv, NUTAG_OFFER_RECV(offer_recv)),
-		  TAG_IF(answer_recv, NUTAG_ANSWER_RECV(answer_recv)),
-		  TAG_IF(offer_sent, NUTAG_OFFER_SENT(offer_sent)),
-		  TAG_IF(answer_sent, NUTAG_ANSWER_SENT(answer_sent)),
-		  TAG_IF(oa_recv, SOATAG_REMOTE_SDP(remote_sdp)),
-		  TAG_IF(oa_recv, SOATAG_REMOTE_SDP_STR(remote_sdp_str)),
-		  TAG_IF(oa_sent, SOATAG_LOCAL_SDP(local_sdp)),
-		  TAG_IF(oa_sent, SOATAG_LOCAL_SDP_STR(local_sdp_str)),
-		  TAG_END());
+    nua_stack_tevent(nh->nh_nua, nh, NULL, nua_i_state,
+		     status, phrase,
+		     NUTAG_CALLSTATE(next_state),
+		     NH_ACTIVE_MEDIA_TAGS(1, nh->nh_soa),
+		     /* NUTAG_SOA_SESSION(nh->nh_soa), */
+		     TAG_IF(offer_recv, NUTAG_OFFER_RECV(offer_recv)),
+		     TAG_IF(answer_recv, NUTAG_ANSWER_RECV(answer_recv)),
+		     TAG_IF(offer_sent, NUTAG_OFFER_SENT(offer_sent)),
+		     TAG_IF(answer_sent, NUTAG_ANSWER_SENT(answer_sent)),
+		     TAG_IF(oa_recv, SOATAG_REMOTE_SDP(remote_sdp)),
+		     TAG_IF(oa_recv, SOATAG_REMOTE_SDP_STR(remote_sdp_str)),
+		     TAG_IF(oa_sent, SOATAG_LOCAL_SDP(local_sdp)),
+		     TAG_IF(oa_sent, SOATAG_LOCAL_SDP_STR(local_sdp_str)),
+		     TAG_END());
+  }
+
+  if (next_state == nua_callstate_ready && ss_state <= nua_callstate_ready) {
+    nua_stack_tevent(nh->nh_nua, nh, NULL, nua_i_active, status, "Call active",
+		     NH_ACTIVE_MEDIA_TAGS(1, nh->nh_soa),
+		     /* NUTAG_SOA_SESSION(nh->nh_soa), */
+		     TAG_END());
+  }
+
+  else if (next_state == nua_callstate_terminated) {
+    nua_stack_event(nh->nh_nua, nh, NULL,
+		    nua_i_terminated, status, phrase,
+		    NULL);
+  }
+}
 
 /** @NUA_EVENT nua_i_active
  *
@@ -3583,13 +3759,6 @@
  * @END_NUA_EVENT
  */
 
-  if (next_state == nua_callstate_ready && ss_state <= nua_callstate_ready) {
-    nua_stack_event(nh->nh_nua, nh, NULL, nua_i_active, status, "Call active",
-	     NH_ACTIVE_MEDIA_TAGS(1, nh->nh_soa),
-	     /* NUTAG_SOA_SESSION(nh->nh_soa), */
-	     TAG_END());
-  }
-
 /** @NUA_EVENT nua_i_terminated
  *
  * A call has been terminated.
@@ -3614,18 +3783,13 @@
  * @END_NUA_EVENT
  */
 
-  else if (next_state == nua_callstate_terminated) {
-    nua_stack_event(nh->nh_nua, nh, NULL, nua_i_terminated, status, phrase,
-	     TAG_END());
-  }
-}
 
 /* ======================================================================== */
 
 static
-int respond_with_retry_after(nua_handle_t *nh, nta_incoming_t *irq,
-			     int status, char const *phrase,
-			     int min, int max)
+int nua_server_retry_after(nua_server_request_t *sr,
+			   int status, char const *phrase,
+			   int min, int max)
 {
   sip_retry_after_t af[1];
 
@@ -3633,17 +3797,299 @@
   af->af_delta = (unsigned)su_randint(min, max);
   af->af_comment = phrase;
 
-  nta_incoming_treply(irq, status, phrase,
-		      SIPTAG_RETRY_AFTER(af),
-		      SIPTAG_USER_AGENT_STR(NH_PGET(nh, user_agent)),
-		      TAG_END());
+  sip_add_dup(sr->sr_response.msg, sr->sr_response.sip, (sip_header_t *)af);
+
+  return sr_status(sr, status, phrase);
+}
+
+/* ======================================================================== */
+/* Session timer - RFC 4028 */
+
+static int session_timer_is_supported(struct session_timer const *t)
+{
+  return t->local.supported;
+}
+
+/** Set session timer preferences  */ 
+static
+void session_timer_preferences(struct session_timer *t,
+			       sip_t const *sip,
+			       sip_supported_t const *supported,
+			       unsigned expires,
+			       int isset,
+			       enum nua_session_refresher refresher,
+			       unsigned min_se)
+{
+  memset(&t->local, 0, sizeof t->local);
+
+  t->local.require = sip_has_feature(sip->sip_require, "timer");
+  t->local.supported =
+    sip_has_feature(supported, "timer") ||
+    sip_has_feature(sip->sip_supported, "timer");
+  if (isset || refresher != nua_no_refresher)
+    t->local.expires = expires;
+  else
+    t->local.defaults = expires;
+  t->local.min_se = min_se;
+  t->local.refresher = refresher;
+}
+
+static int session_timer_check_restart(nua_client_request_t *cr,
+				       int status, char const *phrase,
+				       sip_t const *sip)
+{
+  if (status == 422) {
+    nua_session_usage_t *ss = nua_dialog_usage_private(cr->cr_usage);
+
+    if (ss && session_timer_is_supported(ss->ss_timer)) {
+      struct session_timer *t = ss->ss_timer;
+
+      if (sip->sip_min_se && t->local.min_se < sip->sip_min_se->min_delta)
+	t->local.min_se = sip->sip_min_se->min_delta;
+      if (t->local.expires != 0 && t->local.min_se > t->local.expires)
+	t->local.expires = t->local.min_se;
+  
+      return nua_client_restart(cr, 100, "Re-Negotiating Session Timer");
+    }
+  }
+
+  return nua_base_client_check_restart(cr, status, phrase, sip);
+}
+
+/** Check that received Session-Expires is longer than Min-SE */
+static
+int session_timer_check_min_se(msg_t *msg,
+			       sip_t *sip,
+			       sip_t const *request,
+			       unsigned long min)
+{
+  if (min == 0)
+    min = 1;
+
+  /*
+   If an incoming request contains a Supported header field with a value
+   'timer' and a Session Expires header field, the UAS MAY reject the
+   INVITE request with a 422 (Session Interval Too Small) response if
+   the session interval in the Session-Expires header field is smaller
+   than the minimum interval defined by the UAS' local policy.  When
+   sending the 422 response, the UAS MUST include a Min-SE header field
+   with the value of its minimum interval.  This minimum interval MUST
+   NOT be lower than 90 seconds.
+  */
+  if (request->sip_session_expires &&
+      sip_has_feature(request->sip_supported, "timer") &&
+      request->sip_session_expires->x_delta < min) {
+    sip_min_se_t min_se[1];
+
+    if (min < 90)
+      min = 90;
+
+    sip_min_se_init(min_se)->min_delta = min;
+
+    /* Include extension parameters, if any */
+    if (request->sip_min_se)
+      min_se->min_params = request->sip_min_se->min_params;
+    
+    sip_add_dup(msg, sip, (sip_header_t *)min_se);
+
+    return 422;
+  }
+
+  return 0;
+}
+
+/** Store session timer parameters in request from uac / response from uas */ 
+static
+void session_timer_store(struct session_timer *t,
+			 sip_t const *sip)
+{
+  sip_require_t const *require = sip->sip_require;
+  sip_supported_t const *supported = sip->sip_supported;
+  sip_session_expires_t const *x = sip->sip_session_expires;
+
+  t->remote.require = require && sip_has_feature(require, "timer");
+  t->remote.supported =
+    t->remote.supported || (supported && sip_has_feature(supported, "timer"));
+
+  t->remote.expires = 0;
+  t->remote.refresher = nua_any_refresher;
+  t->remote.min_se = 0;
+
+  if (x) {
+    t->remote.expires = x->x_delta;
+
+    if (x->x_refresher) {
+      int uas = sip->sip_request != NULL;
+
+      if (strcasecmp(x->x_refresher, "uac") == 0)
+	t->remote.refresher = uas ? nua_remote_refresher : nua_local_refresher;
+      else if (strcasecmp(x->x_refresher, "uas") == 0)
+	t->remote.refresher = uas ? nua_local_refresher : nua_remote_refresher;
+    }
+  }
+
+  if (sip->sip_min_se)
+    t->remote.min_se = sip->sip_min_se->min_delta;
+}
+
+/** Add timer feature and Session-Expires/Min-SE headers to request/response
+ * 
+ */
+static int
+session_timer_add_headers(struct session_timer *t,
+			  int initial,
+			  msg_t *msg, sip_t *sip)
+{
+  unsigned long expires, min;
+  sip_min_se_t min_se[1];
+  sip_session_expires_t x[1];
+  int uas;
+
+  enum nua_session_refresher refresher = nua_any_refresher;
+
+  static sip_param_t const x_params_uac[] = {"refresher=uac", NULL};
+  static sip_param_t const x_params_uas[] = {"refresher=uas", NULL};
+
+  if (!t->local.supported)
+    return 0;
+
+  uas = sip->sip_status != NULL;
+
+  min = t->local.min_se;
+  if (min < t->remote.min_se)
+    min = t->remote.min_se;
+
+  if (uas) {
+    session_timer_negotiate(t);
+    
+    refresher = t->refresher;
+    expires = t->interval;
+  }
+  else {
+    /* RFC 4028:
+     * The UAC MAY include the refresher parameter with value 'uac' if it
+     * wants to perform the refreshes.  However, it is RECOMMENDED that the
+     * parameter be omitted so that it can be selected by the negotiation
+     * mechanisms described below.
+     */
+    if (t->local.refresher == nua_local_refresher)
+      refresher = nua_local_refresher;
+
+    expires = t->local.expires;
+    if (expires != 0 && expires < min)
+      expires = min;
+  }
+
+  sip_min_se_init(min_se)->min_delta = min;
+
+  sip_session_expires_init(x)->x_delta = expires;
+  if (refresher == nua_remote_refresher)
+    x->x_params = uas ? x_params_uac : x_params_uas;
+  else if (refresher == nua_local_refresher)
+    x->x_params = uas ? x_params_uas : x_params_uac;
+
+  sip_add_tl(msg, sip,
+	     TAG_IF(expires != 0, SIPTAG_SESSION_EXPIRES(x)),
+	     TAG_IF(min != 0
+		    /* Min-SE: 0 is optional with initial INVITE */
+		    || !initial,
+		    SIPTAG_MIN_SE(min_se)),
+	     TAG_IF(refresher == nua_remote_refresher && expires != 0,
+		    SIPTAG_REQUIRE_STR("timer")),
+	     TAG_END());
+
+  return 1;
+}
+
+static
+void session_timer_negotiate(struct session_timer *t)
+{
+  if (!t->local.supported)
+    t->refresher = nua_no_refresher;
+  else if (!t->remote.supported)
+    t->refresher = nua_local_refresher;
+  else if (t->remote.refresher == nua_local_refresher)
+    t->refresher = nua_local_refresher;
+  else if (t->remote.refresher == nua_remote_refresher)
+    t->refresher = nua_remote_refresher;
+  else if (t->local.refresher == nua_local_refresher)
+    t->refresher = nua_local_refresher;
+  else
+    t->refresher = nua_remote_refresher;
+
+  t->interval = t->remote.expires;
+  if (t->interval == 0)
+    t->interval = t->local.expires;
+  if (t->local.expires != 0 && t->interval > t->local.expires)
+    t->interval = t->local.expires;
+  if (t->local.defaults != 0 && t->interval > t->local.defaults)
+    t->interval = t->local.defaults;
+    
+  if (t->interval != 0) {
+    if (t->interval < t->local.min_se)
+      t->interval = t->local.min_se;
+    if (t->interval < t->remote.min_se)
+      t->interval = t->remote.min_se;
+  }
+
+  if (t->interval == 0)
+    t->refresher = nua_no_refresher;
+}
+
+static void
+session_timer_set(nua_session_usage_t *ss)
+{
+  nua_dialog_usage_t *du = nua_dialog_usage_public(ss);
+  struct session_timer *t;
+
+  if (ss == NULL)
+    return;
+
+  t = ss->ss_timer;
+
+  session_timer_negotiate(t);
+
+  if (t->refresher == nua_local_refresher) {
+    unsigned low = t->interval / 2, high = t->interval / 2;
+
+    if (t->interval >= 90)
+      low -=5, high += 5;
+
+    nua_dialog_usage_refresh_range(du, low, high);
+    t->timer_set = 1;
+  }
+  else if (t->refresher == nua_remote_refresher) {
+    /* if the side not performing refreshes does not receive a
+       session refresh request before the session expiration, it SHOULD send
+       a BYE to terminate the session, slightly before the session
+       expiration.  The minimum of 32 seconds and one third of the session
+       interval is RECOMMENDED. */
+    unsigned interval = t->interval;
+
+    interval -= 32 > interval / 6 ? interval / 3 : 32 + interval / 3;
+
+    nua_dialog_usage_refresh_range(du, interval, interval);
+    t->timer_set = 1;
+  }
+  else {
+    nua_dialog_usage_reset_refresh(du);
+    t->timer_set = 0;
+  }
+}
 
-  return 500;
+static inline int
+session_timer_has_been_set(struct session_timer const *t)
+{
+  return t->timer_set;
 }
 
 /* ======================================================================== */
 
-/** Get SDP from a SIP message */
+/** Get SDP from a SIP message.
+ *
+ * @retval 1 if message contains SDP
+ * @retval 0 if message does not contain valid SDP
+ */
 static
 int session_get_description(sip_t const *sip,
 			    char const **return_sdp,
@@ -3680,8 +4126,10 @@
       return 0;
   }
 
-  *return_sdp = pl->pl_data;
-  *return_len = pl->pl_len;
+  if (return_sdp && return_len) {
+    *return_sdp = pl->pl_data;
+    *return_len = pl->pl_len;
+  }
 
   return 1;
 }
@@ -3746,7 +4194,7 @@
     else
       *return_cd = NULL;
 
-    if (!*return_pl || !*return_cd)
+    if (!*return_pl || !*return_ct)
       return -1;
 
     if (session && !*return_cd)
@@ -3756,145 +4204,7 @@
   return retval;
 }
 
-/**
- * Stores and processes SDP from incoming response, then calls
- * nua_stack_process_response().
- *
- * @retval 1 if there was SDP to process.
- */
-static
-int session_process_response(nua_handle_t *nh,
-			     nua_client_request_t *cr,
-			     nta_outgoing_t *orq,
-			     sip_t const *sip,
-			     char const **return_received)
-{
-  char const *method = nta_outgoing_method_name(orq);
-  msg_t *msg = nta_outgoing_getresponse(orq);
-  int retval = 0;
-  char const *sdp = NULL;
-  size_t len;
-
-  if (nh->nh_soa == NULL)
-    /* Xyzzy */;
-  else if (!session_get_description(sip, &sdp, &len))
-    /* No SDP */;
-  else if (cr->cr_answer_recv) {
-    /* Ignore spurious answers after completing O/A */
-    SU_DEBUG_3(("nua(%p): %s: ignoring duplicate SDP in %u %s\n",
-		nh, method,
-		sip->sip_status->st_status, sip->sip_status->st_phrase));
-    sdp = NULL;
-  }
-  else if (!cr->cr_offer_sent &&
-	   nta_outgoing_method(orq) != sip_method_invite) {
-    /* If non-invite request did not have offer, ignore SDP in response */
-    SU_DEBUG_3(("nua(%p): %s: ignoring extra SDP in %u %s\n",
-		nh, method,
-		sip->sip_status->st_status, sip->sip_status->st_phrase));
-    sdp = NULL;
-  }
-  else {
-    if (cr->cr_offer_sent) {
-      cr->cr_answer_recv = sip->sip_status->st_status;
-      *return_received = "answer";
-    }
-    else {
-      cr->cr_offer_recv = 1, cr->cr_answer_sent = 0;
-      *return_received = "offer";
-    }
-
-    if (soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0) {
-      SU_DEBUG_5(("nua(%p): %s: error parsing SDP in %u %s\n",
-		  nh, method,
-		  sip->sip_status->st_status,
-		  sip->sip_status->st_phrase));
-      retval = -1;
-      sdp = NULL;
-    }
-    else if (cr->cr_offer_recv) {
-      /* note: case 1: incoming offer */
-      SU_DEBUG_5(("nua(%p): %s: get SDP %s in %u %s\n",
-		  nh, method, "offer",
-		  sip->sip_status->st_status,
-		  sip->sip_status->st_phrase));
-      retval = 1;
-    }
-    else if (soa_process_answer(nh->nh_soa, NULL) < 0) {
-      SU_DEBUG_5(("nua(%p): %s: error processing SDP answer in %u %s\n",
-		  nh, method,
-		  sip->sip_status->st_status,
-		  sip->sip_status->st_phrase));
-      sdp = NULL;
-    }
-    else {
-      /* note: case 2: answer to our offer */
-      if (soa_activate(nh->nh_soa, NULL) < 0) {
-	SU_DEBUG_3(("nua(%p): %s: error activating media after %u %s\n",
-		    nh, method,
-		    sip->sip_status->st_status,
-		    sip->sip_status->st_phrase));
-	/* XXX */
-      }
-      else {
-	SU_DEBUG_5(("nua(%p): %s: processed SDP answer in %u %s\n",
-		    nh, method,
-		    sip->sip_status->st_status,
-		    sip->sip_status->st_phrase));
-      }
-
-      assert(!cr->cr_offer_recv);
-    }
-  }
-
-  msg_destroy(msg);		/* unref */
-
-  nua_stack_process_response(nh, cr, orq, sip,
-			     NH_REMOTE_MEDIA_TAGS(sdp != NULL, nh->nh_soa),
-			     TAG_END());
-
-  return retval;
-}
-
-#if 0
-/** Parse and store SDP from incoming request */
-static
-int session_process_request(nua_handle_t *nh,
-			    nta_incoming_t *irq,
-			    sip_t const *sip)
-{
-  char const *sdp = NULL;
-  isize_t len;
-
-  if (nh->nh_soa) {
-    msg_t *msg = nta_outgoing_getresponse(irq);
-
-    if (session_get_description(msg, sip, &sdp, &len)) {
-      if (soa_is_complete(nh->nh_soa)) {
-	/* Ignore spurious answers after completing O/A */
-	SU_DEBUG_5(("nua: ignoring duplicate SDP in %u %s\n",
-		    sip->sip_status->st_status, sip->sip_status->st_phrase));
-	sdp = NULL;
-      }
-      else if (soa_parse_sdp(nh->nh_soa, sdp, len) < 0) {
-	SU_DEBUG_5(("nua: error parsing SDP in %u %s\n",
-		    sip->sip_status->st_status,
-		    sip->sip_status->st_phrase));
-	sdp = NULL;
-      }
-    }
-
-    msg_destroy(msg);
-  }
-
-  return
-    nua_stack_process_response(nh, cr, orq, sip,
-			       NH_REMOTE_MEDIA_TAGS(sdp != NULL, nh->nh_soa),
-			       TAG_END());
-}
-#endif
-
-static int respond_to_options(nua_server_request_t *sr, tagi_t const *tags);
+/* ====================================================================== */
 
 /** @NUA_EVENT nua_i_options
  *
@@ -3924,50 +4234,38 @@
  * @END_NUA_EVENT
  */
 
-int nua_stack_process_options(nua_t *nua,
-			      nua_handle_t *nh,
-			      nta_incoming_t *irq,
-			      sip_t const *sip)
-{
-  nua_server_request_t *sr, sr0[1];
-  int done;
-
-  /* Hook to outbound */
-  done = nua_registration_process_request(nua->nua_registrations, irq, sip);
-  if (done)
-    return done;
+int nua_options_server_respond(nua_server_request_t *sr, tagi_t const *tags);
 
-  sr = nua_server_request(nua, nh, irq, sip, SR_INIT(sr0), sizeof *sr,
-			  respond_to_options, 0);
-
-  SR_STATUS1(sr, SIP_200_OK);
-
-  return nua_stack_server_event(nua, sr, nua_i_options, TAG_END());
-}
+nua_server_methods_t const nua_options_server_methods = 
+  {
+    SIP_METHOD_OPTIONS,
+    nua_i_options,		/* Event */
+    { 
+      0,			/* Do not create dialog */
+      0,			/* Initial request */
+      0,			/* Not a target refresh request  */
+      1,			/* Add Contact */
+    },
+    nua_base_server_init,
+    nua_base_server_preprocess,
+    nua_base_server_params,
+    nua_options_server_respond,
+    nua_base_server_report,
+  };
 
 /** @internal Respond to an OPTIONS request.
  *
  */
-static int respond_to_options(nua_server_request_t *sr, tagi_t const *tags)
+int nua_options_server_respond(nua_server_request_t *sr, tagi_t const *tags)
 {
   nua_handle_t *nh = sr->sr_owner;
   nua_t *nua = nh->nh_nua;
-  msg_t *msg;
-  int final;
 
-  msg = nua_server_response(sr,
-			    sr->sr_status, sr->sr_phrase,
-			    SIPTAG_ALLOW(NH_PGET(nh, allow)),
-			    SIPTAG_SUPPORTED(NH_PGET(nh, supported)),
-			    TAG_IF(NH_PGET(nh, path_enable),
-				   SIPTAG_SUPPORTED_STR("path")),
-			    SIPTAG_ACCEPT_STR(SDP_MIME_TYPE),
-			    TAG_NEXT(tags));
+  if (200 <= sr->sr_status && sr->sr_status < 300) {
+    msg_t *msg = sr->sr_response.msg;
+    sip_t *sip = sr->sr_response.sip;
 
-  final = sr->sr_status >= 200;
-
-  if (msg) {
-    sip_t *sip = sip_object(msg);
+    sip_add_tl(msg, sip, SIPTAG_ACCEPT(nua->nua_invite_accept), TAG_END());
 
     if (!sip->sip_payload) {	/* XXX - do MIME multipart? */
       soa_session_t *soa = nh->nh_soa;
@@ -3977,10 +4275,7 @@
 
       session_include_description(soa, 0, msg, sip);
     }
-
-    if (nta_incoming_mreply(sr->sr_irq, msg) < 0)
-      final = 1;
   }
 
-  return final;
+  return nua_base_server_respond(sr, tags);
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_stack.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_stack.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_stack.c	Tue Apr 24 10:14:28 2007
@@ -37,7 +37,7 @@
 #include "config.h"
 
 #include <sofia-sip/su_tag_class.h>
-#include <sofia-sip/su_tag_class.h>
+#include <sofia-sip/su_tag_inline.h>
 #include <sofia-sip/su_tagarg.h>
 #include <sofia-sip/su_strlst.h>
 #include <sofia-sip/su_uniqueid.h>
@@ -51,8 +51,7 @@
 
 #define NTA_AGENT_MAGIC_T    struct nua_s
 #define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
-#define NTA_INCOMING_MAGIC_T struct nua_handle_s
+#define NTA_OUTGOING_MAGIC_T struct nua_client_request
 
 #include <sofia-sip/sip.h>
 #include <sofia-sip/sip_header.h>
@@ -91,8 +90,6 @@
 static int nh_authorize(nua_handle_t *nh,
 			tag_type_t tag, tag_value_t value, ...);
 
-static int nh_challenge(nua_handle_t *nh, sip_t const *sip);
-
 static void nua_stack_timer(nua_t *nua, su_timer_t *t, su_timer_arg_t *a);
 
 /* ---------------------------------------------------------------------- */
@@ -147,7 +144,7 @@
     return -1;
 
   dnh->nh_prefs = (void *)(dnh + 1);
-  dnh->nh_valid = nua_handle;
+  dnh->nh_valid = nua_valid_handle_cookie;
   dnh->nh_nua = nua;
   nua_handle_ref(dnh); dnh->nh_ref_by_stack = 1; 
   nua_handle_ref(dnh); dnh->nh_ref_by_user = 1;
@@ -226,29 +223,40 @@
 int nh_notifier_shutdown(nua_handle_t *nh, nea_event_t *ev,
 			 tag_type_t t, tag_value_t v, ...);
 
+int nua_stack_tevent(nua_t *nua, nua_handle_t *nh, msg_t *msg,
+		     nua_event_t event, int status, char const *phrase,
+		     tag_type_t tag, tag_value_t value, ...)
+{
+  ta_list ta;
+  int retval;
+  ta_start(ta, tag, value);
+  retval = nua_stack_event(nua, nh, msg, event, status, phrase, ta_args(ta));
+  ta_end(ta);
+  return retval;
+}
+
 /** @internal Send an event to the application. */
 int nua_stack_event(nua_t *nua, nua_handle_t *nh, msg_t *msg,
 		    nua_event_t event, int status, char const *phrase,
-		    tag_type_t tag, tag_value_t value, ...)
+		    tagi_t const *tags)
 {
   su_msg_r sumsg = SU_MSG_R_INIT;
-
-  ta_list ta;
   size_t e_len, len, xtra, p_len;
 
   if (event == nua_r_ack || event == nua_i_none)
     return event;
 
-  enter;
+  if (nh == nua->nua_dhandle)
+    nh = NULL;
 
   if (nua_log->log_level >= 5) {
     char const *name = nua_event_name(event) + 4;
     char const *p = phrase ? phrase : "";
 
     if (status == 0)
-      SU_DEBUG_5(("nua(%p): %s %s\n", nh, name, p));
+      SU_DEBUG_5(("nua(%p): event %s %s\n", (void *)nh, name, p));
     else
-      SU_DEBUG_5(("nua(%p): %s %u %s\n", nh, name, status, p));
+      SU_DEBUG_5(("nua(%p): event %s %u %s\n", (void *)nh, name, status, p));
   }
 
   if (event == nua_r_destroy) {
@@ -269,36 +277,42 @@
     return event;
   }
 
-  ta_start(ta, tag, value);
-
-  e_len = offsetof(event_t, e_tags);
-  len = tl_len(ta_args(ta));
-  xtra = tl_xtra(ta_args(ta), len);
+  if (tags) {
+    e_len = offsetof(event_t, e_tags);
+    len = tl_len(tags);
+    xtra = tl_xtra(tags, len);
+  }
+  else {
+    e_len = sizeof(event_t), len = 0, xtra = 0;
+  }
   p_len = phrase ? strlen(phrase) + 1 : 1;
 
   if (su_msg_create(sumsg, nua->nua_client, su_task_null,
 		    nua_event, e_len + len + xtra + p_len) == 0) {
     event_t *e = su_msg_data(sumsg);
+    void *p;
 
-    tagi_t *t = e->e_tags, *t_end = (tagi_t *)((char *)t + len);
-    void *b = t_end, *end = (char *)b + xtra;
+    if (tags) {
+      tagi_t *t = e->e_tags, *t_end = (tagi_t *)((char *)t + len);
+      void *b = t_end, *end = (char *)b + xtra;
 
-    t = tl_dup(t, ta_args(ta), &b);
-    assert(t == t_end); assert(b == end);
+      t = tl_dup(t, tags, &b); p = b;
+      assert(t == t_end); assert(b == end); (void)end;
+    }
+    else
+      p = e + 1;
 
     e->e_event = event;
     e->e_nh = nh ? nua_handle_ref(nh) : nua->nua_dhandle;
     e->e_status = status;
-    e->e_phrase = strcpy(end, phrase ? phrase : "");
+    e->e_phrase = strcpy(p, phrase ? phrase : "");
     if (msg)
       e->e_msg = msg, su_home_threadsafe(msg_home(msg));
 
-    if (su_msg_send(sumsg) != 0)
+    if (su_msg_send(sumsg) != 0 && nh)
       nua_handle_unref(nh);
   }
 
-  ta_end(ta);
-
   return event;
 }
 
@@ -322,9 +336,16 @@
 {
   nua_handle_t *nh = e->e_nh;
   tagi_t *tags = e->e_tags;
+  nua_event_t event;
+  int error = 0;
 
   assert(tags);
 
+  if (nua_log->log_level >= 7) {
+    char const *name = nua_event_name(e->e_event) + 4;
+    SU_DEBUG_7(("nua(%p): recv %s\n", (void *)nh, name));
+  }
+
   if (nh) {
     if (!nh->nh_prev)
       nh_append(nua, nh);
@@ -338,98 +359,105 @@
   if (nua_log->log_level >= 5) {
     char const *name = nua_event_name(e->e_event);
     if (e->e_status == 0)
-      SU_DEBUG_5(("nua(%p): signal %s\n", nh, name + 4));
+      SU_DEBUG_5(("nua(%p): signal %s\n", (void *)nh, name + 4));
     else
       SU_DEBUG_5(("nua(%p): signal %s %u %s\n",
-		  nh, name + 4, e->e_status, e->e_phrase ? e->e_phrase : ""));
+		  (void *)nh, name + 4,
+		  e->e_status, e->e_phrase ? e->e_phrase : ""));
   }
 
   su_msg_save(nua->nua_signal, msg);
 
+  event = e->e_event;
+
   if (nua->nua_shutdown && !e->e_always) {
     /* Shutting down */
-    nua_stack_event(nua, nh, NULL, e->e_event,
+    nua_stack_event(nua, nh, NULL, event,
 		    901, "Stack is going down",
-		    TAG_END());
+		    NULL);
   }
-
-  else switch (e->e_event) {
+  else switch (event) {
   case nua_r_get_params:
-    nua_stack_get_params(nua, nh ? nh : nua->nua_dhandle, e->e_event, tags);
+    nua_stack_get_params(nua, nh ? nh : nua->nua_dhandle, event, tags);
     break;
   case nua_r_set_params:
-    nua_stack_set_params(nua, nh ? nh : nua->nua_dhandle, e->e_event, tags);
+    nua_stack_set_params(nua, nh ? nh : nua->nua_dhandle, event, tags);
     break;
   case nua_r_shutdown:
     nua_stack_shutdown(nua);
     break;
   case nua_r_register:
   case nua_r_unregister:
-    nua_stack_register(nua, nh, e->e_event, tags);
+    nua_stack_register(nua, nh, event, tags);
     break;
   case nua_r_invite:
-    nua_stack_invite(nua, nh, e->e_event, tags);
+    error = nua_stack_invite(nua, nh, event, tags);
     break;
   case nua_r_cancel:
-    nua_stack_cancel(nua, nh, e->e_event, tags);
+    error = nua_stack_cancel(nua, nh, event, tags);
     break;
   case nua_r_bye:
-    nua_stack_bye(nua, nh, e->e_event, tags);
+    error = nua_stack_bye(nua, nh, event, tags);
     break;
   case nua_r_options:
-    nua_stack_options(nua, nh, e->e_event, tags);
+    error = nua_stack_options(nua, nh, event, tags);
     break;
   case nua_r_refer:
-    nua_stack_refer(nua, nh, e->e_event, tags);
+    error = nua_stack_refer(nua, nh, event, tags);
     break;
   case nua_r_publish:
   case nua_r_unpublish:
-    nua_stack_publish(nua, nh, e->e_event, tags);
+    error = nua_stack_publish(nua, nh, event, tags);
     break;
   case nua_r_info:
-    nua_stack_info(nua, nh, e->e_event, tags);
+    error = nua_stack_info(nua, nh, event, tags);
     break;
   case nua_r_update:
-    nua_stack_update(nua, nh, e->e_event, tags);
+    error = nua_stack_update(nua, nh, event, tags);
     break;
   case nua_r_message:
-    nua_stack_message(nua, nh, e->e_event, tags);
+    error = nua_stack_message(nua, nh, event, tags);
     break;
   case nua_r_subscribe:
   case nua_r_unsubscribe:
-    nua_stack_subscribe(nua, nh, e->e_event, tags);
+    error = nua_stack_subscribe(nua, nh, event, tags);
     break;
   case nua_r_notify:
-    nua_stack_notify(nua, nh, e->e_event, tags);
+    error = nua_stack_notify(nua, nh, event, tags);
     break;
   case nua_r_notifier:
-    nua_stack_notifier(nua, nh, e->e_event, tags);
+    nua_stack_notifier(nua, nh, event, tags);
     break;
   case nua_r_terminate:
-    nua_stack_terminate(nua, nh, e->e_event, tags);
+    nua_stack_terminate(nua, nh, event, tags);
     break;
   case nua_r_method:
-    nua_stack_method(nua, nh, e->e_event, tags);
+    error = nua_stack_method(nua, nh, event, tags);
     break;
   case nua_r_authenticate:
-    nua_stack_authenticate(nua, nh, e->e_event, tags);
+    nua_stack_authenticate(nua, nh, event, tags);
     break;
   case nua_r_authorize:
-    nua_stack_authorize(nua, nh, e->e_event, tags);
+    nua_stack_authorize(nua, nh, event, tags);
     break;
   case nua_r_ack:
-    nua_stack_ack(nua, nh, e->e_event, tags);
+    error = nua_stack_ack(nua, nh, event, tags);
     break;
   case nua_r_respond:
     nua_stack_respond(nua, nh, e->e_status, e->e_phrase, tags);
     break;
-  case nua_r_destroy:
+  case nua_r_destroy: 
     nua_stack_destroy_handle(nua, nh, tags);
-    break;
+    su_msg_destroy(nua->nua_signal);
+    return;
   default:
     break;
   }
 
+  if (error < 0) {
+    nua_stack_event(nh->nh_nua, nh, NULL, event, NUA_INTERNAL_ERROR, NULL);
+  }
+
   if (su_msg_is_non_null(nua->nua_signal))
     su_msg_destroy(nua->nua_signal);
 
@@ -512,6 +540,7 @@
 }
 
 
+
 /* ====================================================================== */
 
 /**Shutdown a @nua stack.
@@ -581,15 +610,11 @@
     for (sr = ds->ds_sr; sr; sr = sr_next) {
       sr_next = sr->sr_next;
 
-      if (sr->sr_respond) {
-	SR_STATUS1(sr, SIP_410_GONE);
-	sr->sr_usage = NULL;
-	sr->sr_respond(sr, NULL);
-	sr->sr_respond = NULL;
-	busy++;
+      if (nua_server_request_is_pending(sr)) {
+	SR_STATUS1(sr, SIP_410_GONE); /* 410 terminates dialog */
+	nua_server_respond(sr, NULL);
+	nua_server_report(sr);
       }
-	
-      nua_server_request_destroy(sr);
     }
 
     busy += nh_call_pending(nh, 0);
@@ -625,7 +650,7 @@
     nta_agent_destroy(nua->nua_nta), nua->nua_nta = NULL;
   }
 
-  nua_stack_event(nua, NULL, NULL, nua_r_shutdown, status, phrase, TAG_END());
+  nua_stack_event(nua, NULL, NULL, nua_r_shutdown, status, phrase, NULL);
 }
 
 /* ---------------------------------------------------------------------- */
@@ -650,7 +675,7 @@
   return nh;
 }
 
-/** @internal Append an handle to the list of handles */
+/** @internal Append a handle to the list of handles */
 void nh_append(nua_t *nua, nua_handle_t *nh)
 {
   nh->nh_next = NULL;
@@ -673,17 +698,15 @@
 
 void nua_stack_destroy_handle(nua_t *nua, nua_handle_t *nh, tagi_t const *tags)
 {
-  nh_call_pending(nh, 0);	/* Call pending operations with 0 */
-
   if (nh->nh_notifier)
     nua_stack_terminate(nua, nh, 0, NULL);
 
-#if 0
+  nua_dialog_shutdown(nh, nh->nh_ds);
+
   if (nh->nh_ref_by_user) {
     nh->nh_ref_by_user = 0;
     nua_handle_unref(nh);
   }
-#endif
 
   nh_destroy(nua, nh);
 }
@@ -712,12 +735,14 @@
 {
   assert(nh); assert(nh != nua->nua_dhandle);
 
-  nh_enter;
-
   if (nh->nh_notifier)
     nea_server_destroy(nh->nh_notifier), nh->nh_notifier = NULL;
 
-  nua_creq_deinit(nh->nh_ds->ds_cr, NULL);
+  while (nh->nh_ds->ds_cr)
+    nua_client_request_destroy(nh->nh_ds->ds_cr);
+
+  while (nh->nh_ds->ds_sr)
+    nua_server_request_destroy(nh->nh_ds->ds_sr);
 
   nua_dialog_deinit(nh, nh->nh_ds);
 
@@ -733,7 +758,7 @@
 /* ======================================================================== */
 
 /**@internal
- * Initialize handle Allow and authentication info, save parameters.
+ * Save handle parameters and initial authentication info.
  *
  * @retval -1 upon an error
  * @retval 0 when successful
@@ -912,1202 +937,1856 @@
   return retval;
 }
 
-/**@internal
- * Collect challenges from response.
- *
- * @return Number of updated challenges, 0 if no updates found.
- * @retval -1 upon error.
- */
-static
-int nh_challenge(nua_handle_t *nh, sip_t const *sip)
-{
-  int server = 0, proxy = 0;
-
-  if (sip->sip_www_authenticate)
-    server = auc_challenge(&nh->nh_auth, nh->nh_home,
-			   sip->sip_www_authenticate,
-			   sip_authorization_class);
-
-  if (sip->sip_proxy_authenticate)
-    proxy = auc_challenge(&nh->nh_auth, nh->nh_home,
-			  sip->sip_proxy_authenticate,
-			  sip_proxy_authorization_class);
-
-  if (server < 0 || proxy < 0)
-    return -1;
-
-  return server + proxy;
-}
-
-#include <sofia-sip/su_tag_inline.h>
-
-/** Check if tag list has contact */
-int nua_tagis_have_contact_tag(tagi_t const *t)
+static inline
+int can_redirect(sip_contact_t const *m, sip_method_t method)
 {
-  for (; t && t->t_tag; t = t_next(t))
-    if (t->t_tag == siptag_contact ||
-	t->t_tag == siptag_contact_str)
-      return 1;
+  if (m && m->m_url->url_host) {
+    enum url_type_e type = m->m_url->url_type;
+    return
+      type == url_sip ||
+      type == url_sips ||
+      (type == url_tel &&
+       (method == sip_method_invite || method == sip_method_message)) ||
+      (type == url_im && method == sip_method_message) ||
+      (type == url_pres && method == sip_method_subscribe);
+  }
   return 0;
 }
 
-/**@internal
- * Create a request message.
+/* ======================================================================== */
+/* Authentication */
+
+/** @NUA_EVENT nua_r_authenticate
+ *
+ * Response to nua_authenticate(). Under normal operation, this event is
+ * never sent but rather the unauthenticated operation is completed. 
+ * However, if there is no operation to authentication or if there is an
+ * authentication error the #nua_r_authenticate event is sent to the
+ * application with the status code as follows:
+ * - <i>202 No operation to restart</i>:\n
+ *   The authenticator associated with the handle was updated, but there was
+ *   no operation to retry with the new credentials.
+ * - <i>900 Cannot add credentials</i>:\n
+ *   There was internal problem updating authenticator.
+ * - <i>904 No matching challenge</i>:\n
+ *   There was no challenge matching with the credentials provided by
+ *   nua_authenticate(), e.g., their realm did not match with the one 
+ *   received with the challenge.
+ * 
+ * @param status status code from authentication 
+ * @param phrase a short textual description of @a status code
+ * @param nh     operation handle authenticated
+ * @param hmagic application context associated with the handle
+ * @param sip    NULL
+ * @param tags   empty
+ * 
+ * @sa nua_terminate(), nua_handle_destroy()
  *
- * @param nua
- * @param nh
- * @param cr
- * @param restart
- * @param method
- * @param name
- * @param tag, value, ... list of tag-value pairs
- */
-msg_t *nua_creq_msg(nua_t *nua,
-		    nua_handle_t *nh,
-		    nua_client_request_t *cr,
-		    int restart,
-		    sip_method_t method, char const *name,
-		    tag_type_t tag, tag_value_t value, ...)
+ * @END_NUA_EVENT
+ */
+
+void
+nua_stack_authenticate(nua_t *nua, nua_handle_t *nh, nua_event_t e,
+		       tagi_t const *tags)
 {
-  struct nua_dialog_state *ds = nh->nh_ds;
-  msg_t *msg = NULL;
-  sip_t *sip;
-  ta_list ta;
-  url_string_t const *url = NULL;
-  long seq = -1;
-  int copy = 1;
+  nua_client_request_t *cr = nh->nh_ds->ds_cr;
+  int status = nh_authorize(nh, TAG_NEXT(tags));
 
-  /* If restarting, use existing message */
-  if (restart) {
-    msg = cr->cr_msg; sip = sip_object(msg);
-
-    /* Trying to restart different method? */
-    if (sip && method && sip->sip_request->rq_method != method) {
-      SU_DEBUG_3(("nua(%p): trying to %s "
-		  "but there is already %s waiting to restart\n",
-		  nh, name, sip->sip_request->rq_method_name));
-      restart = 0, msg = NULL; sip = NULL;
-    }
-
-    /* Remove CSeq */
-    if (sip && sip->sip_cseq)
-      sip_header_remove(msg, sip, (sip_header_t *)sip->sip_cseq);
-    if (sip && sip->sip_request)
-      method = sip->sip_request->rq_method,
-	name = sip->sip_request->rq_method_name;
-  }
-
-  if (!restart) {
-    if (cr->cr_msg) {
-      /* If method is ACK or CANCEL, use existing CSeq */
-      if (method == sip_method_ack || method == sip_method_cancel) {
-	sip_t *nh_sip = sip_object(cr->cr_msg);
-	if (nh_sip && nh_sip->sip_cseq)
-	  seq = nh_sip->sip_cseq->cs_seq;
-	/* ACK/CANCEL cannot be restarted so we do not copy message */
-	copy = 0;
-      }
-      else
-	msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
+  if (status > 0) {
+    if (cr && cr->cr_wait_for_cred) {
+      nua_client_restart_request(cr, cr->cr_terminating, tags);
     }
-    msg = nta_msg_create(nua->nua_nta, 0);
+    else {
+      nua_stack_event(nua, nh, NULL, e, 
+		      202, "No operation to restart",
+		      NULL);
+    }
+  }
+  else if (cr && cr->cr_wait_for_cred) {
+    cr->cr_wait_for_cred = 0;
 
-    /**@par Populating SIP Request Message with Tagged Arguments
-     *
-     * The tagged arguments can be used to pass values for any SIP headers
-     * to the stack. When the INVITE message (or any other SIP message) is
-     * created, the tagged values saved with nua_handle() are used first,
-     * next the tagged values given with the operation (nua_invite()) are
-     * added.
-     *
-     * When multiple tags for the same header are specified, the behaviour
-     * depends on the header type. If only a single header field can be
-     * included in a SIP message, the latest non-NULL value is used, e.g.,
-     * @Subject. However, if the SIP header can consist of multiple lines or
-     * header fields separated by comma, e.g., @Accept, all the tagged
-     * values are concatenated.
-     *
-     * However, if a tag value is #SIP_NONE (-1 casted as a void pointer),
-     * the values from previous tags are ignored.
-     */
-    tl_gets(nh->nh_tags, NUTAG_URL_REF(url), TAG_END());
-    sip_add_tl(msg, sip_object(msg), TAG_NEXT(nh->nh_tags));
+    if (status < 0)
+      nua_client_response(cr, 900, "Cannot add credentials", NULL);
+    else
+      nua_client_response(cr, 904, "No matching challenge", NULL);
+  }
+  else if (status < 0) {
+    nua_stack_event(nua, nh, NULL, e, 900, "Cannot add credentials", NULL);
+  }
+  else {
+    nua_stack_event(nua, nh, NULL, e, 904, "No matching challenge", NULL);
   }
+}
 
-  ta_start(ta, tag, value);
 
-  sip = sip_object(msg);
-  if (!sip)
-    goto error;
-  if (sip_add_tl(msg, sip, ta_tags(ta)) < 0)
-    goto error;
+/* ======================================================================== */
+/*
+ * Process incoming requests
+ */
 
-  if (method != sip_method_ack) {
-    /**
-     * Next, values previously set with nua_set_params() or nua_set_hparams()
-     * are used: @Allow, @Supported, @Organization, and @UserAgent headers are
-     * added to the request if they are not already set. 
-     */
-    if (!sip->sip_allow && !ds->ds_remote_tag)
-      sip_add_dup(msg, sip, (sip_header_t*)NH_PGET(nh, allow));
+nua_server_methods_t const *nua_server_methods[] = {
+  /* These must be in same order as in sip_method_t */
+  &nua_extension_server_methods,
+  &nua_invite_server_methods,	/**< INVITE */
+  NULL,				/**< ACK */
+  NULL,				/**< CANCEL */
+  &nua_bye_server_methods,	/**< BYE */
+  &nua_options_server_methods,	/**< OPTIONS */
+  &nua_register_server_methods,	/**< REGISTER */
+  &nua_info_server_methods,	/**< INFO */
+  &nua_prack_server_methods,	/**< PRACK */
+  &nua_update_server_methods,	/**< UPDATE */
+  &nua_message_server_methods,	/**< MESSAGE */
+  &nua_subscribe_server_methods,/**< SUBSCRIBE */
+  &nua_notify_server_methods,	/**< NOTIFY */
+  &nua_refer_server_methods,	/**< REFER */
+  &nua_publish_server_methods,	/**< PUBLISH */
+  NULL
+};
 
-    if (!sip->sip_supported && NH_PGET(nh, supported))
-      sip_add_dup(msg, sip, (sip_header_t *)NH_PGET(nh, supported));
-    
-    if (method == sip_method_register && NH_PGET(nh, path_enable) &&
-	!sip_has_feature(sip->sip_supported, "path") &&
-	!sip_has_feature(sip->sip_require, "path"))
-      sip_add_make(msg, sip, sip_supported_class, "path");
-
-    if (!sip->sip_organization && NH_PGET(nh, organization))
-      sip_add_dup(msg, sip, (sip_header_t *)NH_PGET(nh, organization));
-
-    if (!sip->sip_user_agent && NH_PGET(nh, user_agent))
-      sip_add_make(msg, sip, sip_user_agent_class, NH_PGET(nh, user_agent));
-  }
-	  
-  {
-    int add_contact = 0, use_dialog = 0, add_service_route, has_contact = 0;
-    tagi_t const *t;
 
-    for (t = ta_args(ta); t; t = t_next(t)) {
-      if (t->t_tag == siptag_contact ||
-	  t->t_tag == siptag_contact_str)
-	has_contact = 1;
-      else if (t->t_tag == nutag_url)
-	url = (url_string_t const *)t->t_value;
-      else if (t->t_tag == nutag_method && method == sip_method_unknown)
-	name = (char const *)t->t_value;
-      else if (t->t_tag == nutag_use_dialog)
-	use_dialog = t->t_value != 0;
-      else if (t->t_tag == _nutag_add_contact)
-	add_contact = t->t_value != 0;
-    }
-
-    if (!restart)
-      cr->cr_has_contact = has_contact;
-
-    if (has_contact) add_contact = 0;
-
-    if (method == sip_method_register && url == NULL)
-      url = (url_string_t const *)NH_PGET(nh, registrar);
-
-    if (seq != -1) {
-      sip_cseq_t *cseq;
-     
-      assert(method != sip_method_unknown || name || sip->sip_request);
-      
-      if (method || name)
-	cseq = sip_cseq_create(msg_home(msg), seq, method, name);
-      else 
-	cseq = sip_cseq_create(msg_home(msg), seq, 
-			       sip->sip_request->rq_method, 
-			       sip->sip_request->rq_method_name);
-
-      sip_header_insert(msg, sip, (sip_header_t *)cseq);
-    }
-
-    /**
-     * Now, the target URI for the request needs to be determined.
-     *
-     * For initial requests, values from tags are used. If NUTAG_URL() is
-     * given, it is used as target URI. Otherwise, if SIPTAG_TO() is given,
-     * it is used as target URI. If neither is given, the complete request
-     * line already specified using SIPTAG_REQUEST() or SIPTAG_REQUEST_STR()
-     * is used. At this point, the target URI is stored in the request line,
-     * together with method name and protocol version ("SIP/2.0"). The
-     * initial dialog information is also created: @CallID, @CSeq headers
-     * are generated, if they do not exist, and a tag is added to the @From
-     * header.
-     */
-    if (!ds->ds_leg) {
-      nta_leg_t *leg = nua->nua_dhandle->nh_ds->ds_leg;
-
-      if ((ds->ds_remote_tag && ds->ds_remote_tag[0] && 
-	   sip_to_tag(nh->nh_home, sip->sip_to, ds->ds_remote_tag) < 0)
-	  || 
-	  (sip->sip_from == NULL &&
-	   sip_add_dup(msg, sip, (sip_header_t *)nua->nua_from) < 0))
-	goto error;
+int nua_stack_process_request(nua_handle_t *nh,
+			      nta_leg_t *leg,
+			      nta_incoming_t *irq,
+			      sip_t const *sip)
+{
+  nua_t *nua = nh->nh_nua;
+  sip_method_t method = sip->sip_request->rq_method;
+  char const *name = sip->sip_request->rq_method_name;
+  nua_server_methods_t const *sm;
+  nua_server_request_t *sr, sr0[1];
+  int status, initial = 1;
+  int create_dialog;
 
-      if (use_dialog) {
-	ds->ds_leg = nta_leg_tcreate(nua->nua_nta,
-				     nua_stack_process_request, nh,
-				     SIPTAG_CALL_ID(sip->sip_call_id),
-				     SIPTAG_FROM(sip->sip_from),
-				     SIPTAG_TO(sip->sip_to),
-				     SIPTAG_CSEQ(sip->sip_cseq),
-				     TAG_END());
-	if (!ds->ds_leg)
-	  goto error;
-
-	leg = ds->ds_leg;
-
-	if (!sip->sip_from->a_tag &&
-	    sip_from_tag(msg_home(msg), sip->sip_from,
-			 nta_leg_tag(ds->ds_leg, NULL)) < 0)
-	  goto error;
-      }
+  char const *user_agent = NH_PGET(nh, user_agent);
+  sip_supported_t const *supported = NH_PGET(nh, supported);
+  sip_allow_t const *allow = NH_PGET(nh, allow);
 
-      if (nta_msg_request_complete(msg, leg, method, name, url) < 0)
-	goto error;
+  enter;
 
-      add_service_route = !restart;
-    }
-    else {
-      /**
-       * For in-dialog requests, the request URI is taken from the @Contact
-       * header received from the remote party during dialog establishment, 
-       * and the NUTAG_URL() is ignored.
-       */
-      if (ds->ds_route)
-	url = NULL;
-
-      /**Also, the @CallID and @CSeq headers and @From and @To tags are
-       * generated based on the dialog information and added to the request. 
-       * If the dialog has a route, it is added to the request, too.
-       */
-      if (nta_msg_request_complete(msg, ds->ds_leg, method, name, url) < 0)
-	goto error;
-      add_service_route = 0;
-    }
-    /***
-     * @MaxForwards header (with default value set by NTATAG_MAX_FORWARDS()) is
-     * also added now, if it does not exist.
-     */
-
-    /**
-     * Next, the stack generates a @Contact header for the request (unless
-     * the application already gave a @Contact header or it does not want to
-     * use @Contact and indicates that by including SIPTAG_CONTACT(NULL) or
-     * SIPTAG_CONTACT(SIP_NONE) in the tagged parameters.) If the
-     * application has registered the URI in @From header, the @Contact
-     * header used with registration is used. Otherwise, the @Contact header
-     * is generated from the local IP address and port number.
-     */
-    if (!add_contact ||
-	sip->sip_contact ||
-	nua_tagis_have_contact_tag(nh->nh_tags) ||
-	nua_tagis_have_contact_tag(ta_args(ta)))
-      add_contact = 0;
-
-    /**For the initial requests, @ServiceRoute set received from the registrar
-     * is also added to the request message.
-     */
-    if (add_contact || add_service_route) {
-      if (nua_registration_add_contact_to_request(nh, msg, sip, 
-						  add_contact, 
-						  add_service_route) < 0)
-	goto error;
-    }
+  nta_incoming_tag(irq, NULL);
 
-    if (method != sip_method_ack) {
-      if (nh->nh_auth) {
-	nh_authorize(nh, ta_tags(ta));
-
-	if (method != sip_method_invite &&
-	    method != sip_method_update &&
-	    method != sip_method_prack &&
-	    /* auc_authorize() removes existing authentication headers */
-	    auc_authorize(&nh->nh_auth, msg, sip) < 0)
-	  goto error;
-      }
-    }
-    else /* ACK */ {
-      while (sip->sip_allow)
-	sip_header_remove(msg, sip, (sip_header_t*)sip->sip_allow);
-      while (sip->sip_priority)
-	sip_header_remove(msg, sip, (sip_header_t*)sip->sip_priority);
-      while (sip->sip_proxy_require)
-	sip_header_remove(msg, sip, (sip_header_t*)sip->sip_proxy_require);
-      while (sip->sip_require)
-	sip_header_remove(msg, sip, (sip_header_t*)sip->sip_require);
-      while (sip->sip_subject)
-	sip_header_remove(msg, sip, (sip_header_t*)sip->sip_subject);
-      while (sip->sip_supported)
-	sip_header_remove(msg, sip, (sip_header_t*)sip->sip_supported);
-    }
-
-    ta_end(ta);
-
-    if (!ds->ds_remote)
-      ds->ds_remote = sip_to_dup(nh->nh_home, sip->sip_to);
-    if (!ds->ds_local)
-      ds->ds_local = sip_from_dup(nh->nh_home, sip->sip_from);
-
-    if (copy) {
-      cr->cr_msg = msg;
-      msg = msg_copy(msg);
-    }
+  if (method == sip_method_cancel)
+    return 481;
+
+  /* Hook to outbound */
+  if (method == sip_method_options) {
+    status = nua_registration_process_request(nua->nua_registrations,
+					      irq, sip);
+    if (status)
+      return status;
   }
 
-  return msg;
+  if (nta_check_method(irq, sip, allow,
+		       SIPTAG_SUPPORTED(supported),
+		       SIPTAG_USER_AGENT_STR(user_agent),
+		       TAG_END()))
+    return 405;
 
- error:
-  ta_end(ta);
-  msg_destroy(msg);
-  return NULL;
-}
+  switch (sip->sip_request->rq_url->url_type) {
+  case url_sip:
+  case url_sips:
+  case url_im:
+  case url_pres:
+  case url_tel:
+    break;
+  default:
+    nta_incoming_treply(irq, status = SIP_416_UNSUPPORTED_URI,
+			SIPTAG_ALLOW(allow),
+			SIPTAG_SUPPORTED(supported),
+			SIPTAG_USER_AGENT_STR(user_agent),
+			TAG_END());
+    return status;
+  }
 
-/* ---------------------------------------------------------------------- */
-nua_client_request_t *
-nua_client_request_pending(nua_client_request_t const *cr)
-{
-  for (;cr;cr = cr->cr_next)
-    if (cr->cr_orq)
-      return (nua_client_request_t *)cr;
+  if (nta_check_required(irq, sip, supported,
+			 SIPTAG_ALLOW(allow),
+			 SIPTAG_USER_AGENT_STR(user_agent),
+			 TAG_END()))
+    return 420;
 
-  return NULL;
-}
+  if (method > sip_method_unknown && method <= sip_method_publish)
+    sm = nua_server_methods[method];
+  else
+    sm = nua_server_methods[0];
 
-nua_client_request_t *
-nua_client_request_restarting(nua_client_request_t const *cr)
-{
-  for (;cr;cr = cr->cr_next)
-    if (cr->cr_restart)
-      return (nua_client_request_t *)cr;
+  initial = nh == nua->nua_dhandle;
 
-  return NULL;
-}
+  if (sm == NULL) {
+    SU_DEBUG_1(("nua(%p): strange %s from <" URL_PRINT_FORMAT ">\n",
+		(void *)nh, sip->sip_request->rq_method_name,
+		URL_PRINT_ARGS(sip->sip_from->a_url)));
+  }
+  else if (initial && sm->sm_flags.in_dialog) {
+    /* These must be in-dialog */
+    sm = NULL;
+  }
+  else if (initial && sip->sip_to->a_tag) {
+    /* RFC 3261 section 12.2.2:
+       
+       If the UAS wishes to reject the request because it does not wish to
+       recreate the dialog, it MUST respond to the request with a 481
+       (Call/Transaction Does Not Exist) status code and pass that to the
+       server transaction.
+    */
+    if (method != sip_method_message || !NH_PGET(nh, win_messenger_enable))
+      sm = NULL;
+  }
 
-nua_client_request_t *
-nua_client_request_by_orq(nua_client_request_t const *cr,
-			  nta_outgoing_t const *orq)
-{
-  for (;cr;cr = cr->cr_next)
-    if (cr->cr_orq == orq)
-      return (nua_client_request_t *)cr;
+  if (!sm) {
+    nta_incoming_treply(irq,
+			status = 481, "Call Does Not Exist",
+			SIPTAG_ALLOW(allow),
+			SIPTAG_SUPPORTED(supported),
+			SIPTAG_USER_AGENT_STR(user_agent),
+			TAG_END());
+    return 481;
+  }
 
-  return NULL;
-}
+  create_dialog = sm->sm_flags.create_dialog;
+  if (method == sip_method_message && NH_PGET(nh, win_messenger_enable))
+    create_dialog = 1;
+  sr = memset(sr0, 0, (sizeof sr0));
+
+  sr->sr_methods = sm;
+  sr->sr_method = method = sip->sip_request->rq_method;
+  sr->sr_add_contact = sm->sm_flags.add_contact;
+  sr->sr_target_refresh = sm->sm_flags.target_refresh;
 
-void nua_creq_deinit(nua_client_request_t *cr, nta_outgoing_t *orq)
-{
-  if (orq == NULL || orq == cr->cr_orq) {
-    cr->cr_retry_count = 0;
-    cr->cr_offer_sent = cr->cr_answer_recv = 0;
+  sr->sr_owner = nh;
+  sr->sr_initial = initial;
+
+  sr->sr_irq = irq;
 
-    if (cr->cr_msg)
-      msg_destroy(cr->cr_msg);
-    cr->cr_msg = NULL;
+  SR_STATUS1(sr, SIP_100_TRYING);
 
-    if (cr->cr_orq)
-      nta_outgoing_destroy(cr->cr_orq);
-    cr->cr_orq = NULL;
+  sr->sr_request.msg = nta_incoming_getrequest(irq);
+  sr->sr_request.sip = sip;
+  assert(sr->sr_request.msg);
+
+  sr->sr_response.msg = nta_incoming_create_response(irq, 0, NULL);
+  sr->sr_response.sip = sip_object(sr->sr_response.msg);
+
+  if (sr->sr_response.msg == NULL) {
+    SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
   }
-  else {
-    nta_outgoing_destroy(orq);
+  else if (sm->sm_init && sm->sm_init(sr)) {
+    if (sr->sr_status < 200)    /* Init may have set response status */
+      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+  }
+  /* Create handle if request does not fail */
+  else if (initial && sr->sr_status < 300) {
+    if ((nh = nua_stack_incoming_handle(nua, irq, sip, create_dialog)))
+      sr->sr_owner = nh;
+    else
+      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
   }
-}
 
+  if (sr->sr_status < 300 && sm->sm_preprocess && sm->sm_preprocess(sr)) {
+    if (sr->sr_status < 200)    /* Set response status if preprocess did not */
+      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+  }
 
-/**@internal
- * Get remote contact header for @a irq */
-static inline
-sip_contact_t const *incoming_contact(nta_incoming_t *irq)
-{
-  sip_contact_t const *retval = NULL;
-  msg_t *request;
-  sip_t *sip;
+  if (sr->sr_status < 300) {
+    if (sr->sr_target_refresh)
+      nua_dialog_uas_route(nh, nh->nh_ds, sip, 1); /* Set route and tags */
+    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
+  }
 
-  request = nta_incoming_getrequest(irq);
-  sip = sip_object(request);
-  if (sip)
-    retval = sip->sip_contact;
-  msg_destroy(request);
+  if (sr->sr_status == 100 && method != sip_method_unknown &&
+      !sip_is_allowed(NH_PGET(sr->sr_owner, appl_method), method, name)) {
+    if (method == sip_method_refer || method == sip_method_subscribe)
+      SR_STATUS1(sr, SIP_202_ACCEPTED);
+    else
+      SR_STATUS1(sr, SIP_200_OK);
+  }
 
-  return retval;
-}
+  /* INVITE server request is not finalized after 2XX response */
+  if (sr->sr_status < (method == sip_method_invite ? 300 : 200)) {
+    sr = su_alloc(nh->nh_home, (sizeof *sr));
 
-/**@internal
- * Create a response message.
- */
-msg_t *nh_make_response(nua_t *nua,
-			nua_handle_t *nh,
-			nta_incoming_t *irq,
-			int status, char const *phrase,
-			tag_type_t tag, tag_value_t value, ...)
-{
-  ta_list ta;
-  msg_t *msg = nta_msg_create(nua->nua_nta, 0);
-  sip_t *sip = sip_object(msg);
-  msg_t *retval = NULL;
+    if (sr) {
+      *sr = *sr0;
+
+      if ((sr->sr_next = nh->nh_ds->ds_sr))
+	*(sr->sr_prev = sr->sr_next->sr_prev) = sr,
+	  sr->sr_next->sr_prev = &sr->sr_next;
+      else
+	*(sr->sr_prev = &nh->nh_ds->ds_sr) = sr;
+    }
+    else {
+      sr = sr0;
+      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+    }
+  }
+
+  if (sr->sr_status <= 100) {
+    SR_STATUS1(sr, SIP_100_TRYING);
+    if (method == sip_method_invite || sip->sip_timestamp) {
+      nta_incoming_treply(irq, SIP_100_TRYING,
+			  SIPTAG_USER_AGENT_STR(user_agent),
+			  TAG_END());
+    }
+  }
+  else {
+    /* Note that this may change the sr->sr_status */
+    nua_server_respond(sr, NULL);
+  }
+
+  if (nua_server_report(sr) == 0)
+    return 0;
+
+  return 501;
+}		 
+
+#undef nua_base_server_init
+#undef nua_base_server_preprocess
+
+int nua_base_server_init(nua_server_request_t *sr)
+{
+  return 0;
+}
+
+int nua_base_server_preprocess(nua_server_request_t *sr)
+{
+  return 0;
+}
+
+void nua_server_request_destroy(nua_server_request_t *sr)
+{
+  if (sr == NULL)
+    return;
+
+  if (sr->sr_irq)
+    nta_incoming_destroy(sr->sr_irq), sr->sr_irq = NULL;
+
+  su_msg_destroy(sr->sr_signal);
+
+  if (sr->sr_request.msg)
+    msg_destroy(sr->sr_request.msg), sr->sr_request.msg = NULL;
+
+  if (sr->sr_response.msg)
+    msg_destroy(sr->sr_response.msg), sr->sr_response.msg = NULL;
+
+  if (sr->sr_prev) {
+    /* Allocated from heap */
+    if ((*sr->sr_prev = sr->sr_next))
+      sr->sr_next->sr_prev = sr->sr_prev;
+    su_free(sr->sr_owner->nh_home, sr);
+  }
+}
+
+/**@fn void nua_respond(nua_handle_t *nh, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...);
+ * 
+ * Respond to a request with given status code and phrase.
+ *
+ * The stack returns a SIP response message with given status code and
+ * phrase to the client. The tagged parameter list can specify extra headers
+ * to include with the response message and other stack parameters. The SIP
+ * session or other protocol state associated with the handle is updated
+ * accordingly (for instance, if an initial INVITE is responded with 200, a
+ * SIP session is established.)
+ *
+ * When responding to an incoming INVITE request, the nua_respond() can be
+ * called without NUTAG_WITH() (or NUTAG_WITH_CURRENT() or
+ * NUTAG_WITH_SAVED()). Otherwise, NUTAG_WITH() will contain an indication
+ * of the request being responded.
+ *
+ * @param nh              Pointer to operation handle
+ * @param status          SIP response status code (see RFCs of SIP)
+ * @param phrase          free text (default response phrase is used if NULL)
+ * @param tag, value, ... List of tagged parameters
+ *
+ * @return 
+ *    nothing
+ *
+ * @par Responses by Protocol Engine
+ *
+ * When nua protocol engine receives an incoming SIP request, it can either
+ * respond to the request automatically or let application to respond to the
+ * request. The automatic response is returned to the client if the request
+ * fails syntax check, or the method, SIP extension or content negotiation
+ * fails.
+ *
+ * When the @ref nua_handlingevents "request event" is delivered to the
+ * application, the application should examine the @a status parameter. The
+ * @a status parameter is 200 or greater if the request has been already
+ * responded automatically by the stack.
+ *
+ * The application can add methods that it likes to handle by itself with
+ * NUTAG_APPL_METHOD(). The default set of NUTAG_APPL_METHOD() includes
+ * INVITE, PUBLISH, REGISTER and SUBSCRIBE. Note that unless the method is
+ * also included in the set of allowed methods with NUTAG_ALLOW(), the stack
+ * will respond to the incoming methods with <i>405 Not Allowed</i>.
+ *
+ * In order to simplify the simple applications, most requests are responded
+ * automatically. The BYE and CANCEL requests are always responded by the
+ * stack. Likewise, the NOTIFY requests associated with an event
+ * subscription are responded by the stack.
+ *
+ * Note that certain methods are rejected outside a SIP session (created
+ * with INVITE transaction). They include BYE, UPDATE, PRACK and INFO. Also
+ * the auxiliary methods ACK and CANCEL are rejected by the stack if there
+ * is no ongoing INVITE transaction corresponding to them.
+ *
+ * @par Related Tags:
+ *    NUTAG_WITH(), NUTAG_WITH_THIS(), NUTAG_WITH_SAVED() \n
+ *    NUTAG_EARLY_ANSWER() \n
+ *    SOATAG_ADDRESS() \n
+ *    SOATAG_AF() \n
+ *    SOATAG_HOLD() \n
+ *    Tags used with nua_set_hparams() \n
+ *    Tags in <sip_tag.h>.
+ *
+ * @par Events:
+ *    #nua_i_state \n
+ *    #nua_i_media_error \n
+ *    #nua_i_error \n
+ *    #nua_i_active \n
+ *    #nua_i_terminated \n
+ *
+ * @sa #nua_i_invite, #nua_i_register, #nua_i_subscribe, #nua_i_publish
+ */
+
+void
+nua_stack_respond(nua_t *nua, nua_handle_t *nh,
+		  int status, char const *phrase, tagi_t const *tags)
+{
+  nua_server_request_t *sr;
   tagi_t const *t;
+  msg_t const *request = NULL;
+
+  t = tl_find_last(tags, nutag_with);
+
+  if (t)
+    request = (msg_t const *)t->t_value;
+
+  for (sr = nh->nh_ds->ds_sr; sr; sr = sr->sr_next) {
+    if (request && sr->sr_request.msg == request)
+      break;
+    /* nua_respond() to INVITE can be used without NUTAG_WITH() */
+    if (!t && sr->sr_method == sip_method_invite)
+      break;
+  }
 
+  if (sr == NULL) {
+    nua_stack_event(nua, nh, NULL, nua_i_error,
+		    500, "Responding to a Non-Existing Request", NULL);
+    return;
+  }
+  else if (!nua_server_request_is_pending(sr)) {
+    nua_stack_event(nua, nh, NULL, nua_i_error,
+		    500, "Already Sent Final Response", NULL);
+    return;
+  }
+  else if (sr->sr_100rel && !sr->sr_pracked && 200 <= status && status < 300) {
+    /* Save signal until we have received PRACK */
+    if (tags && nua_stack_set_params(nua, nh, nua_i_none, tags) < 0) {
+      sr->sr_application = status;
+      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+    }
+    else {
+      su_msg_save(sr->sr_signal, nh->nh_nua->nua_signal);
+      return;
+    }
+  }
+  else {
+    sr->sr_application = status;
+    if (tags && nua_stack_set_params(nua, nh, nua_i_none, tags) < 0)
+      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+    else
+      sr->sr_status = status, sr->sr_phrase = phrase;
+  }
+
+  nua_server_params(sr, tags);
+  nua_server_respond(sr, tags);
+  nua_server_report(sr);
+}
+
+int nua_server_params(nua_server_request_t *sr, tagi_t const *tags)
+{
+  if (sr->sr_methods->sm_params)
+    return sr->sr_methods->sm_params(sr, tags);
+  return 0;
+}
+
+#undef nua_base_server_params
+
+int nua_base_server_params(nua_server_request_t *sr, tagi_t const *tags) 
+{
+  return 0;
+}
+
+/** Return the response to the client.
+ *
+ * @retval 0 when successfully sent
+ * @retval -1 upon an error
+ */
+int nua_server_trespond(nua_server_request_t *sr,
+			tag_type_t tag, tag_value_t value, ...)
+{
+  int retval;
+  ta_list ta;
   ta_start(ta, tag, value);
+  retval = nua_server_respond(sr, ta_args(ta));
+  ta_end(ta);
+  return retval;
+}
+
+/** Return the response to the client.
+ *
+ * @retval 0 when successfully sent
+ * @retval -1 upon an error
+ */
+int nua_server_respond(nua_server_request_t *sr, tagi_t const *tags)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  sip_method_t method = sr->sr_method;
+  struct { msg_t *msg; sip_t *sip; } next = { NULL, NULL };
+  tagi_t next_tags[2] = {{ SIPTAG_END() }, { TAG_NEXT(tags) }};
+  int retval;
+
+  msg_t *msg = sr->sr_response.msg;
+  sip_t *sip = sr->sr_response.sip;
+  sip_contact_t *m = sr->sr_request.sip->sip_contact;
+
+  if (sr->sr_response.msg == NULL) {
+    assert(sr->sr_status == 500);
+    goto internal_error;
+  }
+
+  if (sr->sr_status < 200) {
+    next.msg = nta_incoming_create_response(sr->sr_irq, 0, NULL);
+    next.sip = sip_object(next.msg);
+    if (next.sip == NULL)
+      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+  }
 
-  if (!msg)
-    /* retval is NULL */;
-  else if (nta_msg_response_complete(msg, irq, status, phrase) < 0)
-    msg_destroy(msg);
-  else if (sip_add_tl(msg, sip, ta_tags(ta)) < 0)
-    msg_destroy(msg);
-  else if (sip_complete_message(msg) < 0)
-    msg_destroy(msg);
+  if (nta_incoming_complete_response(sr->sr_irq, msg,
+				     sr->sr_status,
+				     sr->sr_phrase,
+				     TAG_NEXT(tags)) < 0)
+    ;
   else if (!sip->sip_supported && NH_PGET(nh, supported) &&
 	   sip_add_dup(msg, sip, (sip_header_t *)NH_PGET(nh, supported)) < 0)
-    msg_destroy(msg);
+    ;
   else if (!sip->sip_user_agent && NH_PGET(nh, user_agent) &&
 	   sip_add_make(msg, sip, sip_user_agent_class, 
 			NH_PGET(nh, user_agent)) < 0)
-    msg_destroy(msg);
+    ;
   else if (!sip->sip_organization && NH_PGET(nh, organization) &&
-	   sip_add_dup(msg, sip, (sip_header_t *)NH_PGET(nh, organization)) < 0)
-    msg_destroy(msg);
+	   sip_add_dup(msg, sip, (void *)NH_PGET(nh, organization)) < 0)
+    ;
   else if (!sip->sip_allow && NH_PGET(nh, allow) &&
-	   sip_add_dup(msg, sip, (sip_header_t*)NH_PGET(nh, allow)) < 0)
-    msg_destroy(msg);
+	   sip_add_dup(msg, sip, (void *)NH_PGET(nh, allow)) < 0)
+    ;
   else if (!sip->sip_allow_events && 
-	   (sip->sip_cseq && 
-	    (sip->sip_cseq->cs_method == sip_method_publish ||
-	     sip->sip_cseq->cs_method == sip_method_subscribe)) &&
+	   (method == sip_method_publish || method == sip_method_subscribe) &&
 	   NH_PGET(nh, allow_events) &&
-	   sip_add_dup(msg, sip, (sip_header_t*)NH_PGET(nh, allow_events)) < 0)
-    msg_destroy(msg);
-  else if (!sip->sip_contact &&
-	   (t = tl_find(ta_args(ta), _nutag_add_contact)) &&
-	   t->t_value && 
-	   nua_registration_add_contact_to_response(nh, msg, sip, NULL, 
-						    incoming_contact(irq)) < 0)
-    msg_destroy(msg);
-  else
-    retval = msg;
+	   sip_add_dup(msg, sip, (void *)NH_PGET(nh, allow_events)) < 0)
+    ;
+  else if (!sip->sip_contact && sr->sr_status < 300 && sr->sr_add_contact &&
+	   nua_registration_add_contact_to_response(nh, msg, sip, NULL, m) < 0)
+    ;
+  else {
+    int term;
+    
+    term = sip_response_terminates_dialog(sr->sr_status, sr->sr_method, NULL);
 
-  ta_end(ta);
+    sr->sr_terminating = (term < 0) ? -1 : (term > 0 || sr->sr_terminating);
 
-  return retval;
+    retval = sr->sr_methods->sm_respond(sr, next_tags);
+
+    if (sr->sr_status < 200) 
+      sr->sr_response.msg = next.msg, sr->sr_response.sip = next.sip;
+    else if (next.msg)
+      msg_destroy(next.msg);
+
+    assert(sr->sr_status >= 200 || sr->sr_response.msg);
+
+    return retval;
+  }
+
+  if (next.msg)
+    msg_destroy(next.msg);
+
+  SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+
+  msg_destroy(msg);
+
+ internal_error:
+  sr->sr_response.msg = NULL, sr->sr_response.sip = NULL;
+  nta_incoming_treply(sr->sr_irq, sr->sr_status, sr->sr_phrase, TAG_END());
+
+  return 0;
 }
 
+/** Return the response to the client.
+ *
+ * @retval 0 when successfully sent
+ * @retval -1 upon an error
+ */
+int nua_base_server_respond(nua_server_request_t *sr, tagi_t const *tags)
+{
+  msg_t *response = sr->sr_response.msg;
+  sip_t *sip = sr->sr_response.sip;
 
-/* ======================================================================== */
-/* Generic processing */
+  sr->sr_response.msg = NULL, sr->sr_response.sip = NULL;
 
-int nua_stack_process_unknown(nua_t *nua,
-			      nua_handle_t *nh,
-			      nta_incoming_t *irq,
-			      sip_t const *sip)
+  if (sr->sr_status != sip->sip_status->st_status) {
+    msg_header_remove(response, (msg_pub_t *)sip,
+		      (msg_header_t *)sip->sip_status);
+    nta_incoming_complete_response(sr->sr_irq, response,
+				   sr->sr_status,
+				   sr->sr_phrase,    
+				   TAG_END());
+  }
+
+  if (sr->sr_status != sip->sip_status->st_status) {
+    msg_destroy(response);
+    SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+    nta_incoming_treply(sr->sr_irq, sr->sr_status, sr->sr_phrase, TAG_END());
+    return 0;
+  }
+
+  return nta_incoming_mreply(sr->sr_irq, response);
+}
+
+int nua_server_report(nua_server_request_t *sr)
 {
-  return 501;
+  if (sr)
+    return sr->sr_methods->sm_report(sr, NULL);
+  else
+    return 1;
 }
 
-/**@internal
- * Relay response message to the application.
+int nua_base_server_treport(nua_server_request_t *sr,
+			    tag_type_t tag, tag_value_t value,
+			    ...)
+{
+  int retval;
+  ta_list ta;
+  ta_start(ta, tag, value);
+  retval = nua_base_server_report(sr, ta_args(ta));
+  ta_end(ta);
+  return retval;
+}
+
+/**Report request event to the application.
  *
- * If handle has already been marked as destroyed by nua_handle_destroy(),
- * release the handle with nh_destroy().
+ * @retval 0 request lives
+ * @retval 1 request was destroyed
+ * @retval 2 request and its usage was destroyed
+ * @retval 3 request, all usages and dialog was destroyed
+ * @retval 4 request, all usages, dialog, and handle was destroyed
  */
-int nua_stack_process_response(nua_handle_t *nh,
-			       nua_client_request_t *cr,
-			       nta_outgoing_t *orq,
-			       sip_t const *sip,
-			       tag_type_t tag, tag_value_t value, ...)
-{
-  msg_t *msg = nta_outgoing_getresponse(orq);
-  int status = sip->sip_status->st_status;
-  char const *phrase = sip->sip_status->st_phrase;
-  ta_list ta;
-  int final;
+int nua_base_server_report(nua_server_request_t *sr, tagi_t const *tags)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_t *nua = nh->nh_nua;
+  nua_dialog_usage_t *usage = sr->sr_usage;
+  int initial = sr->sr_initial;
+  int status = sr->sr_status;
+  char const *phrase = sr->sr_phrase;
+
+  int terminated;
+  int handle_can_be_terminated = initial && !sr->sr_event;
+
+  assert(nh);
+
+  if (sr->sr_application) {
+    /* There was an error sending response */
+    if (sr->sr_application != sr->sr_status)
+      nua_stack_event(nua, nh, NULL, nua_i_error, status, phrase, tags);
+    sr->sr_application = 0;
+  }
+  else if (status < 300 && !sr->sr_event) {
+    msg_t *msg = msg_ref_create(sr->sr_request.msg);
+    nua_event_t e = sr->sr_methods->sm_event;
+    sr->sr_event = 1;
+    nua_stack_event(nua, nh, msg, e, status, phrase, tags);
+  }
+
+  if (status < 200)
+    return 0;			/* sr lives on until final response is sent */
+
+  if (sr->sr_method == sip_method_invite && status < 300)
+    return 0;			/* INVITE lives on until ACK is received */
+
+  if (initial && 300 <= status)
+    terminated = 1;
+  else if (sr->sr_terminating && status < 300)
+    terminated = 1;
+  else
+    terminated = sip_response_terminates_dialog(status, sr->sr_method, NULL);
 
-  if (status >= 200 && status < 300)
-    nh_challenge(nh, sip);  /* Collect nextnonce */
+  nua_server_request_destroy(sr);
 
-  if (nta_outgoing_method(orq) == sip_method_invite)
-    final = status >= 300;
-  else
-    final = status >= 200;
+  if (!terminated)
+    return 1;
 
-  if (final && cr) {
-    nua_creq_deinit(cr, orq);
+  if (usage)
+    nua_dialog_usage_remove(nh, nh->nh_ds, usage);
 
-    if (cr->cr_usage && nh->nh_ds->ds_cr == cr) {
-      if ((status >= 300 && !cr->cr_usage->du_ready) ||
-	  cr->cr_usage->du_terminating)
-	nua_dialog_usage_remove(nh, nh->nh_ds, cr->cr_usage);
-    }
+  if (!initial) {
+    if (terminated > 0)
+      return 2;
 
-    cr->cr_usage = NULL;
+    /* Remove all usages of the dialog */
+    nua_dialog_deinit(nh, nh->nh_ds);
+
+    return 3;
   }
+  else if (!handle_can_be_terminated) {
+    return 3;
+  }
+  else {
+    if (nh != nh->nh_nua->nua_dhandle)
+      nh_destroy(nh->nh_nua, nh);
 
-  ta_start(ta, tag, value);
+    return 4;
+  }
+}
+
+/* ---------------------------------------------------------------------- */
 
-  nua_stack_event(nh->nh_nua, nh, msg, cr->cr_event, status, phrase,
-		  ta_tags(ta));
+/** @class nua_client_request
+ *
+ * Each handle has a queue of client-side requests; if a request is pending,
+ * a new request from API is added to the queue. After the request is
+ * complete, it is removed from the queue and destroyed by the default. The
+ * exception is the client requests bound to a dialog usage: they are saved
+ * and re-used when the dialog usage is refreshed (and sometimes when the
+ * usage is terminated).
+ * 
+ * The client request is subclassed and its behaviour modified using virtual
+ * function table in #nua_client_methods_t.
+ * 
+ * The first three methods (crm_template(), crm_init(), crm_send()) are
+ * called when the request is sent first time.
+ * 
+ * The crm_template() is called if a template request message is needed (for
+ * example, in case of unregister, unsubscribe and unpublish, the template
+ * message is taken from the request establishing the usage).
+ * 
+ * The crm_init() is called when the template message and dialog leg has
+ * been created and populated by the tags procided by the application. Its
+ * parameters msg and sip are pointer to the template request message that
+ * is saved in the nua_client_request::cr_msg field.
+ *
+ * The crm_send() is called with a copy of the template message that has
+ * been populated with all the fields included in the request, including
+ * @CSeq and @MaxForwards. The crm_send() function, such as
+ * nua_publish_client_request(), usually calls nua_base_client_trequest() that
+ * then creates the nta-level transaction.
+ *
+ * The response to the request is processed by crm_check_restart(), which
+ * modifies and restarts the request when needed (e.g., when negotiating
+ * expiration time). After the request has been suitably modified, e.g., the
+ * expiration time has been increased, the restart function calls
+ * nua_client_restart(), which restarts the request and relays the
+ * intermediate response to the application with nua_client_restart() and
+ * crm_report().
+ *
+ * The final responses are processed by crm_recv() and and preliminary ones
+ * by crm_preliminary(). Both functions call nua_base_client_response() after
+ * method-specific processing.
+ *
+ * The nua_base_client_response() relays the response to the application with
+ * nua_client_restart() and crm_report().
+ *
+ * @par Terminating Dialog Usages and Dialogs
+ *
+ * The response can be marked as terminating with nua_client_terminating(). 
+ * When a terminating request completes the dialog usage is removed and the
+ * dialog is destroyed (unless there is an another active usage).
+ */
+static int nua_client_request_try(nua_client_request_t *cr);
+static int nua_client_request_sendmsg(nua_client_request_t *cr,
+  				      msg_t *msg, sip_t *sip);
+
+/**Create a client request.
+ *
+ * @retval 0 if request is pending
+ * @retval > 0 if error event has been sent
+ * @retval < 0 upon an error
+ */
+int nua_client_create(nua_handle_t *nh, 
+		      int event,
+		      nua_client_methods_t const *methods,
+		      tagi_t const * const tags)
+{
+  su_home_t *home = nh->nh_home;
+  nua_client_request_t *cr;
+  sip_method_t method;
+  char const *name;
+
+  method = methods->crm_method, name = methods->crm_method_name;
+  if (!name) {
+    tagi_t const *t = tl_find_last(tags, nutag_method);
+    if (t)
+      name = (char const *)t->t_value;
+  }
+
+  cr = su_zalloc(home, sizeof *cr + methods->crm_extra);
+  if (!cr) {
+    return nua_stack_event(nh->nh_nua, nh, 
+			   NULL,
+			   event,
+			   NUA_INTERNAL_ERROR,
+			   NULL);
+  }
+
+  cr->cr_owner = nh;
+  cr->cr_methods = methods;
+  cr->cr_event = event;
+  cr->cr_method = method;
+  cr->cr_method_name = name;
+  cr->cr_contactize = methods->crm_flags.target_refresh;
+  cr->cr_dialog = methods->crm_flags.create_dialog;
+  cr->cr_auto = 1;
+
+  if (su_msg_is_non_null(nh->nh_nua->nua_signal)) {
+    nua_event_data_t const *e = su_msg_data(nh->nh_nua->nua_signal);
+
+    if (tags == e->e_tags && event == e->e_event) {
+      cr->cr_auto = 0;
+      if (tags) {
+	su_msg_save(cr->cr_signal, nh->nh_nua->nua_signal);
+	cr->cr_tags = tags;
+      }
+    }
+  }
 
-  if (final)
-    cr->cr_event = nua_i_error;
+  if (tags && cr->cr_tags == NULL)
+    cr->cr_tags = tl_tlist(nh->nh_home, TAG_NEXT(tags));
 
-  ta_end(ta);
+  if (nua_client_request_queue(cr))
+    return 0;
 
-  return 0;
+  return nua_client_init_request(cr);
 }
 
-static inline
-int can_redirect(sip_contact_t const *m, sip_method_t method)
+int nua_client_tcreate(nua_handle_t *nh, 
+		       int event,
+		       nua_client_methods_t const *methods,
+		       tag_type_t tag, tag_value_t value, ...)
 {
-  if (m && m->m_url->url_host) {
-    enum url_type_e type = m->m_url->url_type;
-    return
-      type == url_sip ||
-      type == url_sips ||
-      (type == url_tel &&
-       (method == sip_method_invite || method == sip_method_message)) ||
-      (type == url_im && method == sip_method_message) ||
-      (type == url_pres && method == sip_method_subscribe);
-  }
-  return 0;
+  int retval;
+  ta_list ta;
+  ta_start(ta, tag, value);
+  retval = nua_client_create(nh, event, methods, ta_args(ta));
+  ta_end(ta);
+  return retval;
 }
 
-int nua_creq_restart_with(nua_handle_t *nh,
-			  nua_client_request_t *cr,
-			  nta_outgoing_t *orq,
-			  int status, char const *phrase,
-			  nua_creq_restart_f *f,
-			  TAG_LIST)
+int nua_client_request_queue(nua_client_request_t *cr)
 {
-  ta_list ta;
-  msg_t *msg = nta_outgoing_getresponse(orq);
+  int queued = 0;
+  nua_client_request_t **queue = &cr->cr_owner->nh_ds->ds_cr;
 
-  nua_stack_event(nh->nh_nua, nh, msg, cr->cr_event, status, phrase,
-		  TAG_END());
+  assert(cr->cr_prev == NULL && cr->cr_next == NULL);
 
-  nta_outgoing_destroy(orq);
+  cr->cr_status = 0;
 
-  if (f) {
-    ta_start(ta, tag, value);
-    f(nh, ta_args(ta));
-    ta_end(ta);
+  if (cr->cr_method != sip_method_invite &&
+      cr->cr_method != sip_method_cancel) {
+    while (*queue) {
+      if ((*queue)->cr_method == sip_method_invite ||
+	  (*queue)->cr_method == sip_method_cancel)
+	break;
+      queue = &(*queue)->cr_next;
+      queued = 1;
+    }
+  }
+  else {
+    while (*queue) {
+      queue = &(*queue)->cr_next;
+      if (cr->cr_method == sip_method_invite)
+	queued = 1;
+    }
   }
 
-  return 1;
+  if ((cr->cr_next = *queue))
+    cr->cr_next->cr_prev = &cr->cr_next;
+
+  cr->cr_prev = queue, *queue = cr;
+
+  return queued;
 }
 
+nua_client_request_t *nua_client_request_remove(nua_client_request_t *cr)
+{
+  if (cr->cr_prev)
+    if ((*cr->cr_prev = cr->cr_next))
+      cr->cr_next->cr_prev = cr->cr_prev;
+  cr->cr_prev = NULL, cr->cr_next = NULL;
+  return cr;
+}
 
-/** @internal Save operation until it can be restarted */
-int nua_creq_save_restart(nua_handle_t *nh,
-			  nua_client_request_t *cr,
-			  nta_outgoing_t *orq,
-			  int status, char const *phrase,
-			  nua_creq_restart_f *restart_function)
+void nua_client_request_destroy(nua_client_request_t *cr)
 {
-  nua_dialog_usage_t *du = cr->cr_usage;
-  msg_t *msg = nta_outgoing_getresponse(orq);
+  nua_handle_t *nh;
+  
+  if (cr == NULL)
+    return;
 
-  nua_stack_event(nh->nh_nua, nh, msg, cr->cr_event,
-		  status, phrase, 
-		  TAG_END());
-  nta_outgoing_destroy(orq);
+  if (cr->cr_methods->crm_deinit)
+    cr->cr_methods->crm_deinit(cr);
 
-  if (du)
-    du->du_refresh = 0;
+  nh = cr->cr_owner;
 
-  cr->cr_restart = restart_function;
-  return 1;
+  su_msg_destroy(cr->cr_signal);
+
+  nua_client_request_remove(cr);
+  nua_client_bind(cr, NULL);
+  
+  if (cr->cr_msg)
+    msg_destroy(cr->cr_msg);
+  cr->cr_msg = NULL, cr->cr_sip = NULL;
+
+  if (cr->cr_orq)
+    nta_outgoing_destroy(cr->cr_orq);
+
+  cr->cr_orq = NULL;
+
+  if (cr->cr_target)
+    su_free(nh->nh_home, cr->cr_target);
+
+  su_free(nh->nh_home, cr);
 }
 
+/** Bind client request to a dialog usage */ 
+int nua_client_bind(nua_client_request_t *cr, nua_dialog_usage_t *du)
+{
+  assert(cr);
+  if (cr == NULL)
+    return -1;
 
-/**@internal
- * Check response, return true if we can restart the request.
+  if (du == NULL) {
+    if (cr->cr_usage && cr->cr_usage->du_cr == cr)
+      cr->cr_usage->du_cr = NULL;
+    cr->cr_usage = NULL;
+    return 0;
+  }
+
+  if (du->du_cr && cr != du->du_cr) {
+    assert(!nua_client_is_queued(du->du_cr));
+    if (nua_client_is_queued(du->du_cr))
+      return -1;
+    if (nua_client_is_reporting(du->du_cr)) {
+      du->du_cr->cr_usage = NULL;
+      du->du_cr = NULL;
+    }
+    else
+      nua_client_request_destroy(du->du_cr);
+  }
+
+  du->du_cr = cr, cr->cr_usage = du;
+
+  return 0;
+}
+
+/**Initialize client request for sending.
+ *
+ * This function is called only first time the request is sent.
  *
+ * @retval 0 if request is pending
+ * @retval >=1 if error event has been sent
  */
-int nua_creq_check_restart(nua_handle_t *nh,
-			   nua_client_request_t *cr,
-			   nta_outgoing_t *orq,
-			   sip_t const *sip,
-			   nua_creq_restart_f *restart_function)
+int nua_client_init_request(nua_client_request_t *cr)
 {
-  int status = sip->sip_status->st_status;
-  sip_method_t method = nta_outgoing_method(orq);
-
-  nua_dialog_usage_t *du = cr->cr_usage;
+  nua_handle_t *nh = cr->cr_owner;
+  nua_t *nua = nh->nh_nua;
+  nua_dialog_state_t *ds = nh->nh_ds;
+  msg_t *msg = NULL;
+  sip_t *sip;
+  url_string_t const *url = NULL;
+  tagi_t const *t;
+  int has_contact = 0;
+  int error = 0;
+  
+  if (!cr->cr_method_name)
+    return nua_client_return(cr, NUA_INTERNAL_ERROR, NULL);
 
-  assert(restart_function);
+  if (cr->cr_msg)
+    return nua_client_request_try(cr);
 
-  if (orq != cr->cr_orq)
-    return 0;
+  cr->cr_answer_recv = 0, cr->cr_offer_sent = 0;
+  cr->cr_offer_recv = 0, cr->cr_answer_sent = 0;
+  cr->cr_terminated = 0, cr->cr_graceful = 0;
 
-  cr->cr_orq = NULL;
-  cr->cr_restart = NULL;
+  nua_stack_init_handle(nua, nh, TAG_NEXT(cr->cr_tags));
 
-  if (cr->cr_msg == NULL || status < 200)
-    ;
-  else if (++cr->cr_retry_count > NH_PGET(nh, retry_count))
-    ;
-  else if (status == 302) {
-    if (can_redirect(sip->sip_contact, method)) {
-      return
-	nua_creq_restart_with(nh, cr, orq, 100, "Redirected",
-			      restart_function,
-			      NUTAG_URL(sip->sip_contact->m_url),
-			      TAG_END());
+  if (cr->cr_method == sip_method_cancel) {
+    if (cr->cr_methods->crm_init) {
+      error = cr->cr_methods->crm_init(cr, NULL, NULL, cr->cr_tags);
+      if (error)
+	return error;
     }
+
+    if (cr->cr_methods->crm_send)
+      return cr->cr_methods->crm_send(cr, NULL, NULL, cr->cr_tags);
+    else
+      return nua_base_client_request(cr, NULL, NULL, cr->cr_tags);
   }
-  else if (status == 423) {
-    sip_t *req = sip_object(cr->cr_msg);
-    unsigned my_expires = 0;
 
-    if (req->sip_expires)
-      my_expires = req->sip_expires->ex_delta;
+  if (!cr->cr_methods->crm_template ||
+      !cr->cr_methods->crm_template(cr, &msg, cr->cr_tags))
+    msg = nta_msg_create(nua->nua_nta, 0);
 
-    if (sip->sip_min_expires &&
-	sip->sip_min_expires->me_delta > my_expires) {
-      sip_expires_t ex[1];
-      sip_expires_init(ex);
-      ex->ex_delta = sip->sip_min_expires->me_delta;
+  sip = sip_object(msg);
+  if (!sip)
+    return nua_client_return(cr, NUA_INTERNAL_ERROR, msg);
 
-      return
-	nua_creq_restart_with(nh, cr, orq,
-			      100, "Re-Negotiating Expiration",
-			      restart_function, 
-			      SIPTAG_EXPIRES(ex),
-			      TAG_END());
-    }
-  }
-  else if (method != sip_method_ack && method != sip_method_cancel &&
-	   ((status == 401 && sip->sip_www_authenticate) ||
-	    (status == 407 && sip->sip_proxy_authenticate)) &&
-	   nh_challenge(nh, sip) > 0) {
-    msg_t *request = nta_outgoing_getrequest(orq);
-    sip_t *rsip = sip_object(request);
-    int done;
-
-    /* XXX - check for instant restart */
-    done = auc_authorization(&nh->nh_auth, cr->cr_msg, (msg_pub_t*)NULL,
-			     rsip->sip_request->rq_method_name,
-			     rsip->sip_request->rq_url,
-			     rsip->sip_payload);
-
-    msg_destroy(request);
-
-    if (done > 0) {
-      return
-	nua_creq_restart_with(nh, cr, orq,
-			      100, "Request Authorized by Cache",
-			      restart_function, TAG_END());
-    }
-    else if (done == 0) {
-      /* Operation waits for application to call nua_authenticate() */
-      return nua_creq_save_restart(nh, cr, orq, 
-				   status, sip->sip_status->st_phrase, 
-				   restart_function);
+  /**@par Populating SIP Request Message with Tagged Arguments
+   *
+   * The tagged arguments can be used to pass values for any SIP headers
+   * to the stack. When the INVITE message (or any other SIP message) is
+   * created, the tagged values saved with nua_handle() are used first,
+   * next the tagged values given with the operation (nua_invite()) are
+   * added.
+   *
+   * When multiple tags for the same header are specified, the behaviour
+   * depends on the header type. If only a single header field can be
+   * included in a SIP message, the latest non-NULL value is used, e.g.,
+   * @Subject. However, if the SIP header can consist of multiple lines or
+   * header fields separated by comma, e.g., @Accept, all the tagged
+   * values are concatenated.
+   *
+   * However, if a tag value is #SIP_NONE (-1 casted as a void pointer),
+   * the values from previous tags are ignored.
+   */
+  if (nh->nh_tags) {
+    for (t = nh->nh_tags; t; t = t_next(t)) {
+      if (t->t_tag == siptag_contact ||
+	  t->t_tag == siptag_contact_str)
+	has_contact = 1;
+      else if (t->t_tag == nutag_url)
+	url = (url_string_t const *)t->t_value;
     }
-    else {
-      SU_DEBUG_5(("nua(%p): auc_authorization failed\n", nh));
+
+    t = nh->nh_tags, sip_add_tagis(msg, sip, &t);
+  }
+
+  for (t = cr->cr_tags; t; t = t_next(t)) {
+    if (t->t_tag == siptag_contact ||
+	t->t_tag == siptag_contact_str)
+      has_contact = 1;
+    else if (t->t_tag == nutag_url)
+      url = (url_string_t const *)t->t_value;
+    else if (t->t_tag == nutag_dialog) {
+      cr->cr_dialog = t->t_value > 1;
+      cr->cr_contactize = t->t_value >= 1;
+    }
+    else if (t->t_tag == nutag_auth && t->t_value) {
+      /* XXX ignoring errors */
+      if (nh->nh_auth)
+	auc_credentials(&nh->nh_auth, nh->nh_home, (char *)t->t_value);
+    }
+  }
+
+  if (cr->cr_method == sip_method_register && url == NULL)
+    url = (url_string_t const *)NH_PGET(nh, registrar);
+  
+  if ((t = cr->cr_tags)) {
+    if (sip_add_tagis(msg, sip, &t) < 0)
+      goto error;
+  }
+
+  /**
+   * Now, the target URI for the request needs to be determined.
+   *
+   * For initial requests, values from tags are used. If NUTAG_URL() is
+   * given, it is used as target URI. Otherwise, if SIPTAG_TO() is given,
+   * it is used as target URI. If neither is given, the complete request
+   * line already specified using SIPTAG_REQUEST() or SIPTAG_REQUEST_STR()
+   * is used. At this point, the target URI is stored in the request line,
+   * together with method name and protocol version ("SIP/2.0"). The
+   * initial dialog information is also created: @CallID, @CSeq headers
+   * are generated, if they do not exist, and a tag is added to the @From
+   * header.
+   */
+
+  if (!ds->ds_leg) {
+    if (ds->ds_remote_tag && ds->ds_remote_tag[0] && 
+	sip_to_tag(nh->nh_home, sip->sip_to, ds->ds_remote_tag) < 0)
+      goto error;
+
+    if (sip->sip_from == NULL && 
+	sip_add_dup(msg, sip, (sip_header_t *)nua->nua_from) < 0)
+      goto error;
+
+    if (cr->cr_dialog) {
+      ds->ds_leg = nta_leg_tcreate(nua->nua_nta,
+				   nua_stack_process_request, nh,
+				   SIPTAG_CALL_ID(sip->sip_call_id),
+				   SIPTAG_FROM(sip->sip_from),
+				   SIPTAG_TO(sip->sip_to),
+				   SIPTAG_CSEQ(sip->sip_cseq),
+				   TAG_END());
+      if (!ds->ds_leg)
+	goto error;
+
+      if (!sip->sip_from->a_tag &&
+	  sip_from_tag(msg_home(msg), sip->sip_from,
+		       nta_leg_tag(ds->ds_leg, NULL)) < 0)
+	goto error;
     }
   }
+  else {
+    if (ds->ds_route)
+      url = NULL;
+  }
 
-  /* This was final response that cannot be restarted. */
-  cr->cr_orq = orq;
+  if (url && nua_client_set_target(cr, (url_t *)url) < 0)
+    goto error;
 
-  if (du)
-    du->du_refresh = 0;
-  cr->cr_retry_count = 0;
+  cr->cr_has_contact = has_contact;
 
-  if (cr->cr_msg)
-    msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
+  if (cr->cr_methods->crm_init) {
+    error = cr->cr_methods->crm_init(cr, msg, sip, cr->cr_tags);
+    if (error < -1)
+      msg = NULL;
+    if (error < 0)
+      goto error;
+    if (error != 0)
+      return error;
+  }
 
-  return 0;
+  cr->cr_msg = msg;
+  cr->cr_sip = sip;
+
+  return nua_client_request_try(cr);
+
+ error:
+  return nua_client_return(cr, NUA_INTERNAL_ERROR, msg);
 }
 
-/** @internal Restart a request */
-int nua_creq_restart(nua_handle_t *nh,
-		     nua_client_request_t *cr,
-		     nta_response_f *cb,
-		     tagi_t *tags)
+
+/** Restart the request message.
+ *
+ * A restarted request has not completed successfully.
+ *
+ * @retval 0 if request is pending
+ * @retval >=1 if error event has been sent
+ */
+int nua_client_restart_request(nua_client_request_t *cr,
+			      int terminating,
+			      tagi_t const *tags)
 {
-  msg_t *msg;
+  if (cr) {
+    assert(nua_client_is_queued(cr));
 
-  cr->cr_restart = NULL;
+    if (tags && cr->cr_msg)
+      if (sip_add_tagis(cr->cr_msg, NULL, &tags) < 0)
+	/* XXX */;
 
-  if (!cr->cr_msg)
-    return 0;
+    cr->cr_terminating = terminating;
 
-  msg = nua_creq_msg(nh->nh_nua, nh, cr, 1, SIP_METHOD_UNKNOWN,
-		     TAG_NEXT(tags));
+    return nua_client_request_try(cr);
+  }
+  return 0;
+}
 
-  cr->cr_orq = nta_outgoing_mcreate(nh->nh_nua->nua_nta, cb, nh, NULL, msg,
-				    SIPTAG_END(), TAG_NEXT(tags));
+/** Resend the request message.
+ *
+ * A resent request has completed once successfully - restarted has not.
+ *
+ * @retval 0 if request is pending
+ * @retval >=1 if error event has been sent
+ */
+int nua_client_resend_request(nua_client_request_t *cr,
+			      int terminating)
+{
+  if (cr) {
+    cr->cr_retry_count = 0;
+    cr->cr_challenged = 0;
 
-  if (!cr->cr_orq) {
-    msg_destroy(msg);
-    return 0;
+    if (nua_client_is_queued(cr)) {
+      if (terminating)
+	cr->cr_graceful = 1;
+      return 0;
+    }
+
+    if (terminating)
+      cr->cr_terminating = terminating;
+
+    if (nua_client_request_queue(cr))
+      return 0;
+    if (nua_dialog_is_reporting(cr->cr_owner->nh_ds))
+      return 0;
+    return nua_client_request_try(cr);
   }
-
-  return 1;
+  return 0;
 }
 
-/* ======================================================================== */
-/* Authentication */
 
-/** @NUA_EVENT nua_r_authenticate
+/** Create a request message and send it.
  *
- * Response to nua_authenticate(). Under normal operation, this event is
- * never sent but rather the unauthenticated operation is completed. 
- * However, if there is no operation to authentication or if there is an
- * authentication error the #nua_r_authenticate event is sent to the
- * application with the status code as follows:
- * - <i>202 No operation to restart</i>:\n
- *   The authenticator associated with the handle was updated, but there was
- *   no operation to retry with the new credentials.
- * - <i>900 Cannot add credentials</i>:\n
- *   There was internal problem updating authenticator.
- * - <i>904 No matching challenge</i>:\n
- *   There was no challenge matching with the credentials provided by
- *   nua_authenticate(), e.g., their realm did not match with the one 
- *   received with the challenge.
- * 
- * @param status status code from authentication 
- * @param phrase a short textual description of @a status code
- * @param nh     operation handle authenticated
- * @param hmagic application context associated with the handle
- * @param sip    NULL
- * @param tags   empty
- * 
- * @sa nua_terminate(), nua_handle_destroy()
+ * If an error occurs, send error event to the application.
  *
- * @END_NUA_EVENT
+ * @retval 0 if request is pending
+ * @retval >=1 if error event has been sent
  */
-
-void
-nua_stack_authenticate(nua_t *nua, nua_handle_t *nh, nua_event_t e,
-		       tagi_t const *tags)
+static
+int nua_client_request_try(nua_client_request_t *cr)
 {
-  int status = nh_authorize(nh, TAG_NEXT(tags));
-
-  if (status > 0) {
-    nua_client_request_t *cr;
-    nua_creq_restart_f *restart = NULL;
+  int error = -1;
+  msg_t *msg = msg_copy(cr->cr_msg);
+  sip_t *sip = sip_object(msg);
 
-    cr = nua_client_request_restarting(nh->nh_ds->ds_cr);
+  cr->cr_answer_recv = 0, cr->cr_offer_sent = 0;
+  cr->cr_offer_recv = 0, cr->cr_answer_sent = 0;
 
-    if (cr) 
-      restart = cr->cr_restart, cr->cr_restart = NULL;
+  if (msg && sip) {
+    error = nua_client_request_sendmsg(cr, msg, sip);
+    if (!error)
+      return 0;
 
-    if (restart) {
-      /* nua_stack_event(nua, nh, NULL, e, SIP_200_OK, TAG_END()); */
-      restart(nh, (tagi_t *)tags);	/* Restart operation */
-    }
-    else {
-      nua_stack_event(nua, nh, NULL, e, 
-		      202, "No operation to restart",
-		      TAG_END());
-    }
-  }
-  else if (status < 0) {
-    nua_stack_event(nua, nh, NULL, e, 900, "Cannot add credentials", TAG_END());
-  }
-  else {
-    nua_stack_event(nua, nh, NULL, e, 904, "No matching challenge", TAG_END());
+    if (error == -1)
+      msg_destroy(msg);
   }
+
+  if (error < 0)
+    error = nua_client_response(cr, NUA_INTERNAL_ERROR, NULL);
+
+  assert(error > 0);
+  return error;
 }
 
-/* ======================================================================== */
-/*
- * Process incoming requests
+/**Send a request message.
+ *
+ * @retval 0 if request is pending
+ * @retval >=1 if error event has been sent
+ * @retval -1 if error occurred but event has not been sent,
+               and @a msg has not been destroyed
+ * @retval -2 if error occurred, event has not been sent,
+ *            but @a msg has been destroyed
  */
-
-int nua_stack_process_request(nua_handle_t *nh,
-			      nta_leg_t *leg,
-			      nta_incoming_t *irq,
-			      sip_t const *sip)
+static
+int nua_client_request_sendmsg(nua_client_request_t *cr, msg_t *msg, sip_t *sip)
 {
-  nua_t *nua = nh->nh_nua;
-  sip_method_t method = sip->sip_request->rq_method;
-  char const *user_agent = NH_PGET(nh, user_agent);
-  sip_supported_t const *supported = NH_PGET(nh, supported);
-  sip_allow_t const *allow = NH_PGET(nh, allow);
-  enter;
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_state_t *ds = nh->nh_ds;
+  sip_method_t method = cr->cr_method;
+  char const *name = cr->cr_method_name;
+  url_string_t const *url = (url_string_t *)cr->cr_target;
+  nta_leg_t *leg;
 
-  nta_incoming_tag(irq, NULL);
+  assert(cr->cr_orq == NULL);
 
-  if (nta_check_method(irq, sip, allow,
-		       SIPTAG_SUPPORTED(supported),
-		       SIPTAG_USER_AGENT_STR(user_agent),
-		       TAG_END()))
-    return 405;
+  cr->cr_retry_count++;
 
-  switch (sip->sip_request->rq_url->url_type) {
-  case url_sip:
-  case url_sips:
-  case url_im:
-  case url_pres:
-  case url_tel:
-    break;
-  default:
-    nta_incoming_treply(irq, SIP_416_UNSUPPORTED_URI,
-			SIPTAG_ALLOW(allow),
-			SIPTAG_SUPPORTED(supported),
-			SIPTAG_USER_AGENT_STR(user_agent),
-			TAG_END());
+  if (ds->ds_leg)
+    leg = ds->ds_leg;
+  else
+    leg = nh->nh_nua->nua_dhandle->nh_ds->ds_leg; /* Default leg */
+
+  if (nua_dialog_is_established(ds)) {
+    while (sip->sip_route)
+      sip_route_remove(msg, sip);
   }
+  
+  /**
+   * For in-dialog requests, the request URI is taken from the @Contact
+   * header received from the remote party during dialog establishment, 
+   * and the NUTAG_URL() is ignored.
+   *
+   * Also, the @CallID and @CSeq headers and @From and @To tags are
+   * generated based on the dialog information and added to the request. 
+   * If the dialog has a route, it is added to the request, too.
+   */
+  if (nta_msg_request_complete(msg, leg, method, name, url) < 0)
+    return -1;
+
+  /**@MaxForwards header (with default value set by NTATAG_MAX_FORWARDS()) is
+   * also added now, if it does not exist.
+   */
+
+  if (!ds->ds_remote)
+    ds->ds_remote = sip_to_dup(nh->nh_home, sip->sip_to);
+  if (!ds->ds_local)
+    ds->ds_local = sip_from_dup(nh->nh_home, sip->sip_from);
+
+  /**
+   * Next, values previously set with nua_set_params() or nua_set_hparams()
+   * are used: @Allow, @Supported, @Organization, and @UserAgent headers are
+   * added to the request if they are not already set. 
+   */
+  if (!sip->sip_allow)
+    sip_add_dup(msg, sip, (sip_header_t*)NH_PGET(nh, allow));
+  
+  if (!sip->sip_supported && NH_PGET(nh, supported))
+    sip_add_dup(msg, sip, (sip_header_t *)NH_PGET(nh, supported));
+  
+  if (method == sip_method_register && NH_PGET(nh, path_enable) &&
+      !sip_has_feature(sip->sip_supported, "path") &&
+      !sip_has_feature(sip->sip_require, "path"))
+    sip_add_make(msg, sip, sip_supported_class, "path");
+  
+  if (!sip->sip_organization && NH_PGET(nh, organization))
+    sip_add_dup(msg, sip, (sip_header_t *)NH_PGET(nh, organization));
+
+  if (!sip->sip_user_agent && NH_PGET(nh, user_agent))
+    sip_add_make(msg, sip, sip_user_agent_class, NH_PGET(nh, user_agent));
+
+  /**
+   * Next, the stack generates a @Contact header for the request (unless
+   * the application already gave a @Contact header or it does not want to
+   * use @Contact and indicates that by including SIPTAG_CONTACT(NULL) or
+   * SIPTAG_CONTACT(SIP_NONE) in the tagged parameters.) If the
+   * application has registered the URI in @From header, the @Contact
+   * header used with registration is used. Otherwise, the @Contact header
+   * is generated from the local IP address and port number.
+   */
+
+  /**For the initial requests, @ServiceRoute set that was received from the
+   * registrar is also added to the request message.
+   */
+  if (cr->cr_method != sip_method_register) {
+    if (nua_registration_add_contact_to_request(nh, msg, sip,
+						cr->cr_contactize &&
+						!cr->cr_has_contact,
+						!ds->ds_route) < 0)
+      return -1;
+  }
+
+  cr->cr_wait_for_cred = 0;
+
+  if (cr->cr_methods->crm_send)
+    return cr->cr_methods->crm_send(cr, msg, sip, NULL);
+
+  return nua_base_client_request(cr, msg, sip, NULL);
+}
+
+/**Add tags to request message and send it, 
+ *
+ * @retval 0 success
+ * @retval -1 if error occurred, but event has not been sent
+ * @retval -2 if error occurred, event has not been sent,
+ *            and @a msg has been destroyed
+ * @retval >=1 if error event has been sent
+ */
+int nua_base_client_trequest(nua_client_request_t *cr,
+			     msg_t *msg, sip_t *sip,
+			     tag_type_t tag, tag_value_t value, ...)
+{
+  int retval;
+  ta_list ta;
+  ta_start(ta, tag, value);
+  retval = nua_base_client_request(cr, msg, sip, ta_args(ta));
+  ta_end(ta);
+  return retval;
+}
 
-  if (nta_check_required(irq, sip, supported,
-			 SIPTAG_ALLOW(allow),
-			 SIPTAG_USER_AGENT_STR(user_agent),
-			 TAG_END()))
-    return 420;
+/** Send request.
+ *
+ * @retval 0 success
+ * @retval -1 if error occurred, but event has not been sent
+ * @retval -2 if error occurred, event has not been sent,
+ *            and @a msg has been destroyed
+ * @retval >=1 if error event has been sent
+ */
+int nua_base_client_request(nua_client_request_t *cr, msg_t *msg, sip_t *sip,
+			    tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
 
-  if (nh == nua->nua_dhandle) {
-    if (!sip->sip_to->a_tag)
-      ;
-    else if (method == sip_method_message && NH_PGET(nh, win_messenger_enable))
-      ;
-    else {
-      nta_incoming_treply(irq, 481, "Initial transaction with a To tag",
-			  TAG_END());
-      return 481;
+  if (nh->nh_auth) {
+    if (cr->cr_challenged || 
+	NH_PGET(nh, auth_cache) == nua_auth_cache_dialog) {
+      if (auc_authorize(&nh->nh_auth, msg, sip) < 0)
+	return nua_client_return(cr, 900, "Cannot add credentials", msg);
     }
-    nh = NULL;
   }
 
-  if (sip->sip_timestamp)
-    nta_incoming_treply(irq, SIP_100_TRYING, TAG_END());
+  cr->cr_seq = sip->sip_cseq->cs_seq; /* Save last sequence number */
 
-  switch (method) {
-  case sip_method_invite:
-    return nua_stack_process_invite(nua, nh, irq, sip);
-
-  case sip_method_info:
-    if (nh) return nua_stack_process_info(nua, nh, irq, sip);
-    /*FALLTHROUGH*/
-
-  case sip_method_update:
-    if (nh) return nua_stack_process_update(nua, nh, irq, sip);
-    /*FALLTHROUGH*/
+  cr->cr_orq = nta_outgoing_mcreate(nh->nh_nua->nua_nta,
+				    nua_client_orq_response, cr,
+				    NULL, 
+				    msg,
+				    TAG_NEXT(tags));
 
-  case sip_method_bye:
-    if (nh) return nua_stack_process_bye(nua, nh, irq, sip);
+  return cr->cr_orq ? 0 : -1;
+}
 
-    nta_incoming_treply(irq,
-			481, "Call Does Not Exist",
-			SIPTAG_ALLOW(allow),
-			SIPTAG_SUPPORTED(supported),
-			SIPTAG_USER_AGENT_STR(user_agent),
-			TAG_END());
-    return 481;
+/** Callback for nta client transaction */
+int nua_client_orq_response(nua_client_request_t *cr,
+			    nta_outgoing_t *orq,
+			    sip_t const *sip)
+{
+  int status;
+  char const *phrase;
+
+  if (sip && sip->sip_status) {
+    status = sip->sip_status->st_status;
+    phrase = sip->sip_status->st_phrase;
+  }
+  else {
+    status = nta_outgoing_status(orq);
+    phrase = "";
+  }
 
-  case sip_method_message:
-    return nua_stack_process_message(nua, nh, irq, sip);
+  nua_client_response(cr, status, phrase, sip);
 
-  case sip_method_notify:
-    return nua_stack_process_notify(nua, nh, irq, sip);
+  return 0;
+}
 
-  case sip_method_subscribe:
-    return nua_stack_process_subscribe(nua, nh, irq, sip);
+/**Return response to the client request.
+ *
+ * Return a response generated by the stack. This function is used to return
+ * a error response within @a nua_client_methods_t#crm_init or @a
+ * nua_client_methods_t#crm_send functions. It takes care of disposing the @a
+ * to_be_destroyed that cannot be sent.
+ *
+ * @retval 0 if response event was preliminary
+ * @retval 1 if response event was final
+ * @retval 2 if response event destroyed the handle, too.
+ */
+int nua_client_return(nua_client_request_t *cr,
+		      int status,
+		      char const *phrase,
+		      msg_t *to_be_destroyed)
+{
+  if (to_be_destroyed)
+    msg_destroy(to_be_destroyed);
+  nua_client_response(cr, status, phrase, NULL);
+  return 1;
+}
 
-  case sip_method_register:
-    return nua_stack_process_register(nua, nh, irq, sip);
+/** Process response to the client request.
+ *
+ * The response can be generated by the stack (@a sip is NULL) or
+ * returned by the remote server.
+ *
+ * @retval 0 if response event was preliminary
+ * @retval 1 if response event was final
+ * @retval 2 if response event destroyed the handle, too.
+ */
+int nua_client_response(nua_client_request_t *cr,
+			int status,
+			char const *phrase,
+			sip_t const *sip)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
 
-  case sip_method_options:
-    return nua_stack_process_options(nua, nh, irq, sip);
+  if (cr->cr_restarting)
+    return 0;
 
-  case sip_method_refer:
-    return nua_stack_process_refer(nua, nh, irq, sip);
+  cr->cr_status = status;
 
-  case sip_method_publish:
-    return nua_stack_process_publish(nua, nh, irq, sip);
+  if (status < 200) {
+    /* Xyzzy */
+  }
+  else if (sip && nua_client_check_restart(cr, status, phrase, sip)) {
+    return 0;
+  }
+  else if (status < 300) {
+    if (cr->cr_terminating) {
+      cr->cr_terminated = 1;
+    }
+    else {
+      if (sip) {
+	if (cr->cr_contactize)
+	  nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
+	nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
+      }
 
-  case sip_method_ack:
-  case sip_method_cancel:
-    SU_DEBUG_1(("nua(%p): strange %s from <" URL_PRINT_FORMAT ">\n", nh,
-		sip->sip_request->rq_method_name,
-		URL_PRINT_ARGS(sip->sip_from->a_url)));
-    /* Send nua_i_error ? */
-    return 481;
+      if (du && du->du_cr == cr)
+	du->du_ready = 1;
+    }
+  }
+  else {
+    sip_method_t method = cr->cr_method;
+    int terminated, graceful = 1;
 
-  case sip_method_unknown:
-    return nua_stack_process_method(nua, nh, irq, sip);
+    if (status < 700)
+      terminated = sip_response_terminates_dialog(status, method, &graceful);
+    else
+      /* XXX - terminate usage by all internal error responses */
+      terminated = 0, graceful = 1;
 
-  default:
-    return nua_stack_process_unknown(nua, nh, irq, sip);
+    if (terminated < 0)
+      cr->cr_terminated = terminated;      
+    else if (cr->cr_terminating || terminated)
+      cr->cr_terminated = 1;
+    else if (graceful)
+      cr->cr_graceful = 1;
   }
+  
+  if (status < 200) {
+    if (cr->cr_methods->crm_preliminary)
+      cr->cr_methods->crm_preliminary(cr, status, phrase, sip);
+    else
+      nua_base_client_response(cr, status, phrase, sip, NULL);
+    return 0;
+  }  
+
+  if (cr->cr_methods->crm_recv)
+    return cr->cr_methods->crm_recv(cr, status, phrase, sip);
+  else
+    return nua_base_client_response(cr, status, phrase, sip, NULL);
 }
 
-nua_server_request_t *nua_server_request(nua_t *nua,
-					 nua_handle_t *nh,
-					 nta_incoming_t *irq,
-					 sip_t const *sip,
-					 nua_server_request_t *sr,
-					 size_t size,
-					 nua_server_respond_f *respond,
-					 int create_dialog)
+/** Check if request should be restarted.
+ *
+ * @retval 1 if restarted or waring for restart
+ * @retval 0 otherwise
+ */
+int nua_client_check_restart(nua_client_request_t *cr,
+			     int status,
+			     char const *phrase,
+			     sip_t const *sip)
 {
-  int initial = 1, final = 200;
+  nua_handle_t *nh = cr->cr_owner;
 
-  assert(nua && irq && sip && sr);
+  assert(cr && status >= 200 && phrase && sip);
 
-  initial = nh == NULL || nh == nua->nua_dhandle;
+  if (cr->cr_retry_count > NH_PGET(nh, retry_count))
+    return 0;
 
-  /* INVITE server request is not finalized after 2XX response */
-  if (sip->sip_request->rq_method == sip_method_invite)
-    final = 300;
+  if (cr->cr_methods->crm_check_restart)
+    return cr->cr_methods->crm_check_restart(cr, status, phrase, sip);
+  else
+    return nua_base_client_check_restart(cr, status, phrase, sip);
+}
 
-  /* Create handle if request does not fail */
-  if (sr->sr_status >= 300)
-    ;
-  else if (initial) {
-    if (!(nh = nua_stack_incoming_handle(nua, irq, sip, create_dialog)))
-      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
-  }
-  else if (create_dialog) {
-    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
-    nua_dialog_uas_route(nh, nh->nh_ds, sip, 1);
-  }
+int nua_base_client_check_restart(nua_client_request_t *cr,
+				  int status,
+				  char const *phrase,
+				  sip_t const *sip)
+{
+  nua_handle_t *nh = cr->cr_owner; 
 
-  if (nh == NULL)
-    nh = nua->nua_dhandle;
+  /* XXX - handle Retry-After */
+
+  if (status == 302 || status == 305) {
+    sip_route_t r[1];
 
-  if (sr->sr_status < final) {
-    nua_server_request_t *sr0 = sr;
+    if (!can_redirect(sip->sip_contact, cr->cr_method))
+      return 0;
 
-    if (size < (sizeof *sr))
-      size = sizeof *sr;
+    switch (status) {
+    case 302:
+      if (nua_client_set_target(cr, sip->sip_contact->m_url) >= 0)
+	return nua_client_restart(cr, 100, "Redirected");
+      break;
 
-    sr = su_zalloc(nh->nh_home, size);
+    case 305:
+      sip_route_init(r);
+      *r->r_url = *sip->sip_contact->m_url;
+      if (sip_add_dup(cr->cr_msg, cr->cr_sip, (sip_header_t *)r) >= 0)
+	return nua_client_restart(cr, 100, "Redirected via a proxy");
+      break;
 
-    if (sr) {
-      if ((sr->sr_next = nh->nh_ds->ds_sr))
-	*(sr->sr_prev = sr->sr_next->sr_prev) = sr,
-	  sr->sr_next->sr_prev = &sr->sr_next;
-      else
-	*(sr->sr_prev = &nh->nh_ds->ds_sr) = sr;
-      SR_STATUS(sr, sr0->sr_status, sr0->sr_phrase);
+    default:
+      break;
     }
-    else {
-      sr = sr0;
-      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+  }
+
+
+  if (status == 423) {
+    unsigned my_expires = 0;
+    
+    if (cr->cr_sip->sip_expires)
+      my_expires = cr->cr_sip->sip_expires->ex_delta;
+
+    if (sip->sip_min_expires &&
+	sip->sip_min_expires->me_delta > my_expires) {
+      sip_expires_t ex[1];
+      sip_expires_init(ex);
+      ex->ex_delta = sip->sip_min_expires->me_delta;
+
+      if (sip_add_dup(cr->cr_msg, NULL, (sip_header_t *)ex) < 0)
+	return 0;
+
+      return nua_client_restart(cr, 100, "Re-Negotiating Expiration");
     }
   }
 
-  sr->sr_owner = nh;
-  sr->sr_method = sip->sip_request->rq_method;
-  sr->sr_respond = respond;
-  sr->sr_irq = irq;
-  sr->sr_initial = initial;
+  if ((status == 401 && sip->sip_www_authenticate) ||
+      (status == 407 && sip->sip_proxy_authenticate)) {
+    int server = 0, proxy = 0;
+    nta_outgoing_t *orq;
 
-  return sr;
-}		 
+    if (sip->sip_www_authenticate)
+      server = auc_challenge(&nh->nh_auth, nh->nh_home,
+			     sip->sip_www_authenticate,
+			     sip_authorization_class);
 
-void nua_server_request_destroy(nua_server_request_t *sr)
-{
-  if (sr->sr_irq)
-    nta_incoming_destroy(sr->sr_irq), sr->sr_irq = NULL;
+    if (sip->sip_proxy_authenticate)
+      proxy = auc_challenge(&nh->nh_auth, nh->nh_home,
+			    sip->sip_proxy_authenticate,
+			    sip_proxy_authorization_class);
 
-  sr->sr_msg = NULL;
+    if (server >= 0 && proxy >= 0) {
+      int invalid = cr->cr_challenged && server + proxy == 0;
 
-  if (sr->sr_prev) {
-    if ((*sr->sr_prev = sr->sr_next))
-      sr->sr_next->sr_prev = sr->sr_prev;
+      cr->cr_challenged = 1;
+
+      if (invalid)
+	/* Bad username/password */
+	auc_clear_credentials(&nh->nh_auth, NULL, NULL);
+      else if (auc_has_authorization(&nh->nh_auth)) 
+	return nua_client_restart(cr, 100, "Request Authorized by Cache");
 
-    if (sr->sr_owner)
-      su_free(sr->sr_owner->nh_home, sr);
+      orq = cr->cr_orq, cr->cr_orq = NULL;
+      cr->cr_wait_for_cred = 1;
+      nua_client_report(cr, status, phrase, NULL, orq, NULL);
+      nta_outgoing_destroy(orq);
+
+      return 1;
+    }
   }
+
+  return 0;  /* This was a final response that cannot be restarted. */
 }
 
-/** Send server event (nua_i_*) to the application. */
-int nua_stack_server_event(nua_t *nua,
-			   nua_server_request_t *sr,
-			   nua_event_t event,
-			   tag_type_t tag, tag_value_t value, ...)
+/** Restart request.
+ *
+ * @retval 1 if restarted
+ * @retval 0 otherwise
+ */
+int nua_client_restart(nua_client_request_t *cr,
+		       int status, char const *phrase)
 {
-  nua_handle_t *nh = sr->sr_owner; 
-  int status, final = 0;
+  nua_handle_t *nh = cr->cr_owner;
+  nta_outgoing_t *orq;
+  int error = -1, terminated, graceful;
+  msg_t *msg;
+  sip_t *sip;
 
-  if (nh == NULL) nh = nua->nua_dhandle;
+  if (cr->cr_retry_count > NH_PGET(nh, retry_count))
+    return 0;
 
-  if (sr->sr_status > 100)
-    /* Note that this may change the sr->sr_status */
-    final = sr->sr_respond(sr, NULL);
+  orq = cr->cr_orq, cr->cr_orq = NULL;  assert(orq);
+  terminated = cr->cr_terminated, cr->cr_terminated = 0;
+  graceful = cr->cr_graceful, cr->cr_graceful = 0;
 
-  status = sr->sr_status;
+  msg = msg_copy(cr->cr_msg);
+  sip = sip_object(msg);
 
-  if (status >= 200)
-    sr->sr_respond = NULL;
-  
-  if (status < 300 || !sr->sr_initial) {
-    ta_list ta;
-    msg_t *request;
-
-    ta_start(ta, tag, value);
-
-    assert(sr->sr_owner);
-    request = nta_incoming_getrequest(sr->sr_irq);
-    nua_stack_event(nua, sr->sr_owner, request, event, 
-		    sr->sr_status, sr->sr_phrase, 
-		    ta_tags(ta));
-    ta_end(ta);
-
-    if (final)
-      nua_server_request_destroy(sr);
-    else if (sr->sr_status < 200)
-      sr->sr_msg = request;
+  if (msg && sip) {
+    cr->cr_restarting = 1;
+    error = nua_client_request_sendmsg(cr, msg, sip);
+    cr->cr_restarting = 0;
+    if (error !=0 && error != -2)
+      msg_destroy(msg);
   }
-  else {
-    nh = sr->sr_owner;
 
-    nua_server_request_destroy(sr);
 
-    if (nh && nh != nua->nua_dhandle)
-      nh_destroy(nua, nh);
+  if (error) {
+    cr->cr_graceful = graceful;
+    cr->cr_terminated = terminated;
+    assert(cr->cr_orq == NULL);
+    cr->cr_orq = orq;
+    return 0;
   }
 
+  nua_client_report(cr, status, phrase, NULL, orq, NULL);
+
+  nta_outgoing_destroy(orq);
+
+  return 1;
+}
+
+int nua_client_set_target(nua_client_request_t *cr, url_t const *target)
+{
+  url_t *new_target, *old_target = cr->cr_target;
+
+  if (!target || target == old_target)
+    return 0;
+
+  new_target = url_hdup(cr->cr_owner->nh_home, (url_t *)target);
+  if (!new_target)
+    return -1;
+  cr->cr_target = new_target;
+  if (old_target)
+    su_free(cr->cr_owner->nh_home, old_target);
+
   return 0;
 }
 
-/** Respond to a request. */
-int nua_server_respond(nua_server_request_t *sr,
-		       int status, char const *phrase,
-		       tag_type_t tag, tag_value_t value, ...)
+/**@internal
+ * Relay response event to the application.
+ *
+ * @todo 
+ * If handle has already been marked as destroyed by nua_handle_destroy(),
+ * release the handle with nh_destroy().
+ *
+ * @retval 0 if event was preliminary
+ * @retval 1 if event was final
+ * @retval 2 if event destroyed the handle, too.
+ */
+int nua_base_client_tresponse(nua_client_request_t *cr,
+			      int status, char const *phrase,
+			      sip_t const *sip,
+			      tag_type_t tag, tag_value_t value, ...)
 {
   ta_list ta;
-  int final;
+  int retval;
 
-  assert(sr && sr->sr_respond);
-  SR_STATUS(sr, status, phrase);
+  if (cr->cr_event == nua_r_destroy)
+    return nua_base_client_response(cr, status, phrase, sip, NULL);
 
   ta_start(ta, tag, value);
-  final = sr->sr_respond(sr, ta_args(ta));
+  retval = nua_base_client_response(cr, status, phrase, sip, ta_args(ta));
   ta_end(ta);
 
-  if (final) {
-    nua_server_request_destroy(sr);    
-    return final;
+  return retval;
+}
+
+/**@internal
+ * Relay response event to the application.
+ *
+ * @todo 
+ * If handle has already been marked as destroyed by nua_handle_destroy(),
+ * release the handle with nh_destroy().
+ *
+ * @retval 0 if event was preliminary
+ * @retval 1 if event was final
+ * @retval 2 if event destroyed the handle, too.
+ */
+int nua_base_client_response(nua_client_request_t *cr,
+			     int status, char const *phrase,
+			     sip_t const *sip,
+			     tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  sip_method_t method = cr->cr_method;
+  nua_dialog_usage_t *du;
+
+  cr->cr_reporting = 1, nh->nh_ds->ds_reporting = 1;
+
+  if (nh->nh_auth && sip &&
+      (sip->sip_authentication_info || sip->sip_proxy_authentication_info)) {
+    /* Collect nextnonce */
+    if (sip->sip_authentication_info)
+      auc_info(&nh->nh_auth,
+	       sip->sip_authentication_info,
+	       sip_authorization_class);
+    if (sip->sip_proxy_authentication_info) 
+      auc_info(&nh->nh_auth,
+	       sip->sip_proxy_authentication_info,
+	       sip_proxy_authorization_class);
   }
 
-  if (sr->sr_status >= 200)
-    sr->sr_respond = NULL;
+  if ((method != sip_method_invite && status >= 200) || status >= 300)
+    nua_client_request_remove(cr);
 
-  return 0;
-}
+  nua_client_report(cr, status, phrase, sip, cr->cr_orq, tags);
 
-msg_t *nua_server_response(nua_server_request_t *sr,
-			   int status, char const *phrase,
-			   tag_type_t tag, tag_value_t value, ...)
-{
-  msg_t *msg;
-  ta_list(ta);
+  if (status < 200 ||
+      /* Un-ACKed 2XX response to INVITE */
+      (method == sip_method_invite && status < 300 && cr->cr_orq)) {
+    cr->cr_reporting = 0, nh->nh_ds->ds_reporting = 0;
+    return 1;
+  }
 
-  assert(sr && sr->sr_owner && sr->sr_owner->nh_nua);
+  if (cr->cr_orq)
+    nta_outgoing_destroy(cr->cr_orq), cr->cr_orq = NULL;
 
-  ta_start(ta, tag, value);
+  du = cr->cr_usage;
 
-  msg = nh_make_response(sr->sr_owner->nh_nua, sr->sr_owner, sr->sr_irq,
-			 sr->sr_status, sr->sr_phrase,
-			 ta_tags(ta));
-  
-  ta_end(ta);
+  if (cr->cr_terminated < 0) {
+    /* XXX - dialog has been terminated */;
+    nua_dialog_deinit(nh, nh->nh_ds), cr->cr_usage = NULL;
+  }
+  else if (du) {
+    if (cr->cr_terminated ||
+	(!du->du_ready && status >= 300 && nua_client_is_bound(cr))) {
+      /* Usage has been destroyed */
+      nua_dialog_usage_remove(nh, nh->nh_ds, du), cr->cr_usage = NULL;
+    }
+    else if (cr->cr_graceful) {
+      /* Terminate usage gracefully */
+      if (nua_dialog_usage_shutdown(nh, nh->nh_ds, du) > 0)
+	cr->cr_usage = NULL;
+    }
+  }
+  else if (cr->cr_terminated) {
+    if (nh->nh_ds->ds_usage == NULL)
+      nua_dialog_remove(nh, nh->nh_ds, NULL), cr->cr_usage = NULL;
+  }
+
+  cr->cr_reporting = 0, nh->nh_ds->ds_reporting = 0;
+
+  if (!nua_client_is_queued(cr) && !nua_client_is_bound(cr))
+    nua_client_request_destroy(cr);
 
-  return msg;
+  if (method == sip_method_cancel)
+    return 1;
+
+  return
+    nua_client_next_request(nh->nh_ds->ds_cr, method == sip_method_invite);
 }
 
-int nua_default_respond(nua_server_request_t *sr,
-			tagi_t const *tags)
+/** Send event, zap transaction but leave cr in list */
+int nua_client_report(nua_client_request_t *cr,
+		      int status, char const *phrase,
+		      sip_t const *sip,
+		      nta_outgoing_t *orq,
+		      tagi_t const *tags)
 {
-  msg_t *m;
+  nua_handle_t *nh;
 
-  assert(sr && sr->sr_owner && sr->sr_owner->nh_nua);
+  if (cr->cr_event == nua_r_destroy)
+    return 1;
 
-  m = nh_make_response(sr->sr_owner->nh_nua, sr->sr_owner, 
-		       sr->sr_irq,
-		       sr->sr_status, sr->sr_phrase,
-		       TAG_NEXT(tags));
+  if (cr->cr_methods->crm_report)
+    return cr->cr_methods->crm_report(cr, status, phrase, sip, orq, tags);
 
-  if (m) {
-    if (nta_incoming_mreply(sr->sr_irq, m) < 0)
-      SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);      
-  }
+  nh = cr->cr_owner;
   
-  return sr->sr_status >= 200 ? sr->sr_status : 0;
+  nua_stack_event(nh->nh_nua, nh, 
+		  nta_outgoing_getresponse(orq),
+		  cr->cr_event,
+		  status, phrase,
+		  tags);
+  return 1;
 }
 
-/** Respond to an request with given status. 
- *
- * When nua protocol engine receives an incoming SIP request, it can either
- * respond to the request automatically or let it up to application to
- * respond to the request. The automatic answer is sent if the request fails
- * because of method, SIP extension or, in some times, MIME content
- * negotiation fails.
- *
- * When responding to an incoming INVITE request, the nua_respond() can be
- * called without NUTAG_WITH() (or NUTAG_WITH_CURRENT() or
- * NUTAG_WITH_SAVED()). Otherwise, NUTAG_WITH() will contain an indication
- * of the request being responded.
- *
- * In order to simplify the simple applications, most requests are responded
- * automatically. The set of requests always responded by the stack include
- * BYE, CANCEL and NOTIFY. The application can add methods that it likes to
- * handle by itself with NUTAG_APPL_METHOD(). The default set of
- * NUTAG_APPL_METHOD() includes INVITE, PUBLISH, REGISTER and SUBSCRIBE. 
- * Note that unless the method is also included in the set of allowed
- * methods with NUTAG_ALLOW(), the stack will respond to the incoming
- * methods with <i>405 Not Allowed</i>.
- *
- * Note that certain methods are rejected outside a SIP session (created
- * with INVITE transaction). They include BYE, UPDATE, PRACK and INFO. Also
- * the auxiliary methods ACK and CANCEL are rejected by stack if there is no
- * ongoing INVITE transaction corresponding to them.
- *
- * @param nh              Pointer to operation handle
- * @param status          SIP response status (see RFCs of SIP)
- * @param phrase          free text (default response phrase used if NULL)
- * @param tag, value, ... List of tagged parameters
- *
- * @return 
- *    nothing
- *
- * @par Related Tags:
- *    NUTAG_WITH(), NUTAG_WITH_CURRENT(), NUTAG_WITH_SAVED() \n
- *    NUTAG_EARLY_ANSWER() \n
- *    SOATAG_ADDRESS() \n
- *    SOATAG_AF() \n
- *    SOATAG_HOLD() \n
- *    Tags in <sip_tag.h>.
- *
- * @par Events:
- *    #nua_i_state \n
- *    #nua_i_media_error \n
- *    #nua_i_error \n
- *    #nua_i_active \n
- *    #nua_i_terminated \n
- *
- * @sa #nua_i_invite, #nua_i_register, #nua_i_subscribe, #nua_i_publish
- */
-void
-nua_stack_respond(nua_t *nua, nua_handle_t *nh,
-		  int status, char const *phrase, tagi_t const *tags)
+int nua_client_treport(nua_client_request_t *cr,
+		       int status, char const *phrase,
+		       sip_t const *sip,
+		       nta_outgoing_t *orq,
+		       tag_type_t tag, tag_value_t value, ...)
 {
-  nua_server_request_t *sr;
-  tagi_t const *t;
-  msg_t const *request = NULL;
-
-  t = tl_find_last(tags, nutag_with);
-
-  if (t)
-    request = (msg_t const *)t->t_value;
+  int retval;
+  ta_list ta;
+  ta_start(ta, tag, value);
+  retval = nua_client_report(cr, status, phrase, sip, orq, ta_args(ta));
+  ta_end(ta);
+  return retval;
+}
 
-  for (sr = nh->nh_ds->ds_sr; sr; sr = sr->sr_next) {
-    if (request && sr->sr_msg == request)
-      break;
-    /* nua_respond() to INVITE can be used without NUTAG_WITH() */
-    if (!t && sr->sr_method == sip_method_invite && sr->sr_respond)
+int nua_client_next_request(nua_client_request_t *cr, int invite)
+{
+  for (; cr; cr = cr->cr_next) {
+    if (cr->cr_method == sip_method_cancel)
+      continue;
+    
+    if (invite 
+	? cr->cr_method == sip_method_invite
+	: cr->cr_method != sip_method_invite)
       break;
   }
-  
-  if (sr && sr->sr_respond) {
-    int final;
-    SR_STATUS(sr, status, phrase);
-    final = sr->sr_respond(sr, tags);
-    if (final)
-      nua_server_request_destroy(sr);    
-    else if (sr->sr_status >= 200)
-      sr->sr_respond = NULL;
-    return;
-  }
-  else if (sr) {
-    nua_stack_event(nua, nh, NULL, nua_i_error,
-		    500, "Already Sent Final Response", TAG_END());
-    return;
-  }
 
-  nua_stack_event(nua, nh, NULL, nua_i_error,
-		  500, "Responding to a Non-Existing Request", TAG_END());
+  if (cr && cr->cr_orq == NULL) 
+    nua_client_init_request(cr);
+
+  return 1;
+}
+
+nua_client_request_t *
+nua_client_request_pending(nua_client_request_t const *cr)
+{
+  for (;cr;cr = cr->cr_next)
+    if (cr->cr_orq)
+      return (nua_client_request_t *)cr;
+
+  return NULL;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_stack.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_stack.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_stack.h	Tue Apr 24 10:14:28 2007
@@ -103,6 +103,32 @@
   TAG_IF((include) && (soa) && soa_is_remote_chat_active(soa) >= 0,	\
 	 SOATAG_ACTIVE_CHAT(soa_is_remote_chat_active(soa)))
 
+#if HAVE_NUA_HANDLE_DEBUG
+
+#define nua_handle_ref(nh) nua_handle_ref_by((nh), __func__)
+#define nua_handle_unref(nh) nua_handle_unref_by((nh), __func__)
+
+static inline nua_handle_t *nua_handle_ref_by(nua_handle_t *nh,
+					      char const *by)
+{
+  if (nh)
+    SU_DEBUG_0(("nua_handle_ref(%p) => "MOD_ZU" by %s\n", nh, 
+		su_home_refcount((su_home_t *)nh) + 1,
+		by));
+  return (nua_handle_t *)su_home_ref((su_home_t *)nh);
+}
+
+static inline int nua_handle_unref_by(nua_handle_t *nh, char const *by)
+{
+  if (nh)
+    SU_DEBUG_0(("nua_handle_unref(%p) => "MOD_ZU" by %s\n", nh, 
+		su_home_refcount((su_home_t *)nh) - 1,
+		by));
+  return su_home_unref((su_home_t *)nh);
+}
+
+#endif
+
 /** NUA handle. 
  *
  */
@@ -113,7 +139,8 @@
   nua_handle_t  **nh_prev;
 
   nua_t        	 *nh_nua;	/**< Pointer to NUA object  */
-  void           *nh_valid;
+  void           *nh_valid;	/**< Cookie */
+#define nua_valid_handle_cookie ((void *)(intptr_t)nua_handle)
   nua_hmagic_t 	 *nh_magic;	/**< Application context */
 
   tagi_t         *nh_tags;	/**< Initial tags */
@@ -154,7 +181,8 @@
   nea_server_t   *nh_notifier;	/**< SIP notifier */
 };
 
-#define NH_IS_VALID(nh) ((nh) && (nh)->nh_valid)
+#define NH_IS_VALID(nh) \
+  ((nh) && (nh)->nh_valid == nua_valid_handle_cookie)
 
 #define NH_STATUS(nh) \
   (nh)->nh_status, \
@@ -285,28 +313,29 @@
   nua_stack_method;
 
 #define UA_EVENT1(e, statusphrase) \
-  nua_stack_event(nua, nh, NULL, e, statusphrase, TAG_END())
+  nua_stack_event(nua, nh, NULL, e, statusphrase, NULL)
 
 #define UA_EVENT2(e, status, phrase)			\
-  nua_stack_event(nua, nh, NULL, e, status, phrase, TAG_END())
+  nua_stack_event(nua, nh, NULL, e, status, phrase, NULL)
 
 #define UA_EVENT3(e, status, phrase, tag)			\
-  nua_stack_event(nua, nh, NULL, e, status, phrase, tag, TAG_END())
+  nua_stack_event(nua, nh, NULL, e, status, phrase, tag, NULL)
+
+int nua_stack_tevent(nua_t *nua, nua_handle_t *nh, msg_t *msg,
+		     nua_event_t event, int status, char const *phrase,
+		     tag_type_t tag, tag_value_t value, ...);
 
 int nua_stack_event(nua_t *nua, nua_handle_t *nh, msg_t *msg,
 		    nua_event_t event, int status, char const *phrase,
-		    tag_type_t tag, tag_value_t value, ...);
+		    tagi_t const *tags);
 
-nua_handle_t *nh_create_handle(nua_t *nua, nua_hmagic_t *hmagic,
-			       tagi_t *tags);
+nua_handle_t *nh_create_handle(nua_t *nua, nua_hmagic_t *hmagic, tagi_t *tags);
 
 nua_handle_t *nua_stack_incoming_handle(nua_t *nua,
 					nta_incoming_t *irq,
 					sip_t const *sip,
 					int create_dialog);
 
-enum { create_dialog = 1 };
-
 int nua_stack_init_handle(nua_t *nua, nua_handle_t *nh, 
 			  tag_type_t tag, tag_value_t value, ...);
 
@@ -349,48 +378,8 @@
 			      nta_incoming_t *irq,
 			      sip_t const *sip);
 
-int nua_stack_process_response(nua_handle_t *nh,
-			       nua_client_request_t *cr,
-			       nta_outgoing_t *orq,
-			       sip_t const *sip,
-			       tag_type_t tag, tag_value_t value, ...);
-
 int nua_stack_launch_network_change_detector(nua_t *nua);
 
-msg_t *nua_creq_msg(nua_t *nua, nua_handle_t *nh,
-		    nua_client_request_t *cr,
-		    int restart, 
-		    sip_method_t method, char const *name,
-		    tag_type_t tag, tag_value_t value, ...);
-
-int nua_tagis_have_contact_tag(tagi_t const *t);
-
-int nua_creq_check_restart(nua_handle_t *nh,
-			   nua_client_request_t *cr,
-			   nta_outgoing_t *orq,
-			   sip_t const *sip,
-			   nua_creq_restart_f *f);
-
-int nua_creq_restart_with(nua_handle_t *nh,
-			  nua_client_request_t *cr,
-			  nta_outgoing_t *orq,
-			  int status, char const *phrase,
-			  nua_creq_restart_f *f, 
-			  tag_type_t tag, tag_value_t value, ...);
-
-int nua_creq_save_restart(nua_handle_t *nh,
-			  nua_client_request_t *cr,
-			  nta_outgoing_t *orq,
-			  int status, char const *phrase,
-			  nua_creq_restart_f *f);
-
-int nua_creq_restart(nua_handle_t *nh,
-		     nua_client_request_t *cr,
-		     nta_response_f *cb,
-		     tagi_t *tags);
-
-void nua_creq_deinit(nua_client_request_t *cr, nta_outgoing_t *orq);
-
 sip_contact_t const *nua_stack_get_contact(nua_registration_t const *nr);
 
 int nua_registration_add_contact_to_request(nua_handle_t *nh,
@@ -405,51 +394,6 @@
 					     sip_record_route_t const *,
 					     sip_contact_t const *remote);
 
-msg_t *nh_make_response(nua_t *nua, nua_handle_t *nh, 
-			nta_incoming_t *irq,
-			int status, char const *phrase,
-			tag_type_t tag, tag_value_t value, ...);
-
-
-typedef int nua_stack_process_request_t(nua_t *nua,
-					nua_handle_t *nh,
-					nta_incoming_t *irq,
-					sip_t const *sip);
-
-nua_stack_process_request_t nua_stack_process_invite;
-nua_stack_process_request_t nua_stack_process_info;
-nua_stack_process_request_t nua_stack_process_update;
-nua_stack_process_request_t nua_stack_process_bye;
-nua_stack_process_request_t nua_stack_process_message;
-nua_stack_process_request_t nua_stack_process_options;
-nua_stack_process_request_t nua_stack_process_publish;
-nua_stack_process_request_t nua_stack_process_subscribe;
-nua_stack_process_request_t nua_stack_process_notify;
-nua_stack_process_request_t nua_stack_process_refer;
-nua_stack_process_request_t nua_stack_process_unknown;
-nua_stack_process_request_t nua_stack_process_register;
-nua_stack_process_request_t nua_stack_process_method;
-
-nua_client_request_t
-  *nua_client_request_pending(nua_client_request_t const *),
-  *nua_client_request_restarting(nua_client_request_t const *),
-  *nua_client_request_by_orq(nua_client_request_t const *cr,
-			     nta_outgoing_t const *orq);
-
-nua_server_request_t *nua_server_request(nua_t *nua,
-					 nua_handle_t *nh,
-					 nta_incoming_t *irq,
-					 sip_t const *sip,
-					 nua_server_request_t *sr,
-					 size_t size,
-					 nua_server_respond_f *respond,
-					 int create_dialog);
-
-int nua_stack_server_event(nua_t *nua,
-			   nua_server_request_t *sr,
-			   nua_event_t event,
-			   tag_type_t tag, tag_value_t value, ...);
-
 /* ---------------------------------------------------------------------- */
 
 #ifndef SDP_MIME_TYPE
@@ -466,15 +410,6 @@
 #define NUTAG_ADD_CONTACT(v) _nutag_add_contact, tag_bool_v(v)
 extern tag_typedef_t _nutag_add_contact;
 
-#define NUTAG_ADD_CONTACT_REF(v) _nutag_add_contact_ref, tag_bool_vr(&v)
-extern tag_typedef_t _nutag_add_contact_ref;
-
-#define NUTAG_COPY(v) _nutag_copy, tag_bool_v(v)
-extern tag_typedef_t _nutag_copy;
-
-#define NUTAG_COPY_REF(v) _nutag_copy_ref, tag_bool_vr(&v)
-extern tag_typedef_t _nutag_copy_ref;
-
 /* ---------------------------------------------------------------------- */
 
 typedef unsigned longlong ull;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_subnotref.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_subnotref.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_subnotref.c	Tue Apr 24 10:14:28 2007
@@ -47,12 +47,10 @@
 #include <sofia-sip/string0.h>
 #include <sofia-sip/sip_protos.h>
 #include <sofia-sip/sip_status.h>
+#include <sofia-sip/sip_extra.h>
 #include <sofia-sip/sip_util.h>
 #include <sofia-sip/su_uniqueid.h>
 
-#define NTA_LEG_MAGIC_T      struct nua_handle_s
-#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
-
 #include "nua_stack.h"
 
 /* ---------------------------------------------------------------------- */
@@ -60,9 +58,11 @@
 
 struct event_usage
 {
-  enum nua_substate  eu_substate;	/**< Subscription state */
+  enum nua_substate eu_substate;	/**< Subscription state */
   sip_time_t eu_expires;	        /**< Proposed expiration time */
   unsigned eu_notified;		        /**< Number of NOTIFYs received */
+  unsigned eu_unsolicited:1;	        /**< Not SUBSCRIBEd or REFERed */
+  unsigned eu_refer:1;		        /**< Implied subscription by refer */
   unsigned eu_final_wait:1;	        /**< Waiting for final NOTIFY */
   unsigned eu_no_id:1;		        /**< Do not use "id" (even if we have one) */
 };
@@ -105,6 +105,7 @@
 {
   ds->ds_has_events++;
   ds->ds_has_subscribes++;
+
   return 0;
 }
 
@@ -167,134 +168,128 @@
  * @sa NUTAG_SUBSTATE(), @RFC3265
  */
 
-static int process_response_to_subscribe(nua_handle_t *nh,
-					 nta_outgoing_t *orq,
+static int nua_subscribe_client_init(nua_client_request_t *cr, 
+				     msg_t *, sip_t *,
+				     tagi_t const *tags);
+static int nua_subscribe_client_request(nua_client_request_t *cr,
+					msg_t *, sip_t *,
+					tagi_t const *tags);
+static int nua_subscribe_client_response(nua_client_request_t *cr,
+					 int status, char const *phrase,
 					 sip_t const *sip);
 
+static nua_client_methods_t const nua_subscribe_client_methods = {
+  SIP_METHOD_SUBSCRIBE,
+  0,
+  { 
+    /* create_dialog */ 1,
+    /* in_dialog */ 1,
+    /* target refresh */ 1
+  },
+  NULL,
+  nua_subscribe_client_init,
+  nua_subscribe_client_request,
+  /* nua_subscribe_client_check_restart */ NULL,
+  nua_subscribe_client_response
+};
 
 int
 nua_stack_subscribe(nua_t *nua, nua_handle_t *nh, nua_event_t e,
 		    tagi_t const *tags)
 {
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  nua_dialog_usage_t *du = NULL;
-  struct event_usage *eu;
-  msg_t *msg;
-  sip_t *sip;
+  return nua_client_create(nh, e, &nua_subscribe_client_methods, tags);
+}
 
-  if (nua_stack_set_handle_special(nh, nh_has_subscribe, nua_r_subscribe) < 0)
-    return UA_EVENT3(e, 500, "Invalid handle for SUBSCRIBE", 
-		     NUTAG_SUBSTATE(nua_substate_terminated));
-  else if (cr->cr_orq)
-    return UA_EVENT2(e, 900, "Request already in progress");
-
-  /* Initialize allow and auth */
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
-
-  msg = nua_creq_msg(nua, nh, cr, 0,
-		     SIP_METHOD_SUBSCRIBE,
-		     NUTAG_USE_DIALOG(1),
-		     NUTAG_ADD_CONTACT(1),
-		     TAG_NEXT(tags));
-  sip = sip_object(msg);
+static int nua_subscribe_client_init(nua_client_request_t *cr,
+				     msg_t *msg, sip_t *sip,
+				     tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du;
+  sip_event_t *o = sip->sip_event;
 
-  if (sip) {
-    sip_event_t *o = sip->sip_event;
+  du = nua_dialog_usage_get(nh->nh_ds, nua_subscribe_usage, o);
 
-    du = nua_dialog_usage_get(nh->nh_ds, nua_subscribe_usage, o);
+  if (du == NULL && o == NULL)
+    du = nua_dialog_usage_get(nh->nh_ds, nua_subscribe_usage, NONE);
 
-    if (du == NULL && o == NULL)
-      du = nua_dialog_usage_get(nh->nh_ds, nua_subscribe_usage, NONE);
+  if (du) {
+    if (du->du_event && o == NULL)
+      /* Add Event header */
+      sip_add_dup(msg, sip, (sip_header_t *)du->du_event);
+  }
+  else if (cr->cr_event == nua_r_subscribe) {	
+    /* Create dialog usage */
+    du = nua_dialog_usage_add(nh, nh->nh_ds, nua_subscribe_usage, o);
+    /* Note that we allow SUBSCRIBE without event */
+  }
 
-    eu = nua_dialog_usage_private(du);
+  cr->cr_usage = du;
 
-    if (du && du->du_event && (o == NULL || (o->o_id && eu->eu_no_id))) {
-      if (eu->eu_no_id)		/* No id (XXX - nor other parameters) */
-	sip_add_make(msg, sip, sip_event_class, du->du_event->o_type);
-      else
-	sip_add_dup(msg, sip, (sip_header_t *)du->du_event);
-    }
+  return 0;
+}
 
-    if (e == nua_r_subscribe) {	
-      if (du == NULL)		/* Create dialog usage */
-	/* We allow here SUBSCRIBE without event */
-	du = nua_dialog_usage_add(nh, nh->nh_ds, nua_subscribe_usage, o);
+static int nua_subscribe_client_request(nua_client_request_t *cr,
+					msg_t *msg, sip_t *sip,
+					tagi_t const *tags)
+{
+  nua_dialog_usage_t *du = cr->cr_usage; 
+  sip_time_t expires = 0;
+
+  if (cr->cr_event != nua_r_subscribe ||
+      (du && du->du_shutdown) ||
+      (sip->sip_expires && sip->sip_expires->ex_delta == 0))
+    cr->cr_terminating = 1;
+
+  if (du) {
+    struct event_usage *eu = nua_dialog_usage_private(du);
+    sip_event_t *o = sip->sip_event;
+
+    if (nua_client_bind(cr, du) < 0)
+      return -1;
+
+    if (eu->eu_no_id && o && o->o_id) {
+      /* Notifier does not handle id properly, remove it */
+      msg_header_remove_param(o->o_common, "id");
     }
-    else if (du) { /* Unsubscribe */
-      /* Embryonic subscription is just a placeholder */
+
+#if 0
+    if (cr->cr_terminating) {
+      /* Already terminated subscription? */
       if (eu->eu_substate == nua_substate_terminated ||
 	  eu->eu_substate == nua_substate_embryonic) {
-	nua_dialog_usage_remove(nh, nh->nh_ds, du);
-	msg_destroy(msg);
-	return UA_EVENT3(e, SIP_200_OK, 
-			 NUTAG_SUBSTATE(nua_substate_terminated),
-			 TAG_END());
+	return nua_client_return(cr, SIP_200_OK, msg);
       }
     }
-  }
-
-  /* Store message template with supported features (eventlist) */
-  if (du && sip) {
-    if (du->du_msg)
-      msg_destroy(du->du_msg);
-    du->du_msg = msg_ref_create(cr->cr_msg);
-  }
+#endif
 
-  if (du)
-    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				      process_response_to_subscribe, nh, NULL,
-				      msg,
-				      TAG_IF(e != nua_r_subscribe,
-					     SIPTAG_EXPIRES_STR("0")),
-				      SIPTAG_END(), TAG_NEXT(tags));
-
-  eu = nua_dialog_usage_private(du);
-
-  if (!cr->cr_orq) {
-    int substate = nua_substate_terminated;
-
-    if (du == NULL)
-      ;
-    else if (du->du_ready)
-      substate = eu->eu_substate; /* No change in subscription state  */
+    nua_dialog_usage_reset_refresh(du); /* during SUBSCRIBE transaction */
+    
+    if (cr->cr_terminating)
+      expires = eu->eu_expires = 0;
+    else if (sip->sip_expires)
+      /* Use value specified by application or negotiated with Min-Expires */
+      expires = eu->eu_expires = sip->sip_expires->ex_delta;
     else
-      nua_dialog_usage_remove(nh, nh->nh_ds, du);
-
-    msg_destroy(msg);
-
-    return UA_EVENT3(e, NUA_INTERNAL_ERROR, 
-		     NUTAG_SUBSTATE(substate), TAG_END());
-  }
-
-  nua_dialog_usage_reset_refresh(du); /* during SUBSCRIBE transaction */
-  du->du_terminating = e != nua_r_subscribe; /* Unsubscribe or destroy */
-
-  if (du->du_terminating)
-    eu->eu_expires = 0;
-  else if (sip->sip_expires)
-    eu->eu_expires = sip->sip_expires->ex_delta;
-  else
     /* We just use common default value, but the default is actually
        package-specific according to the RFC 3265 section 4.4.4:
        [Event] packages MUST also define a
        default "Expires" value to be used if none is specified. */
-    eu->eu_expires = 3600;
+      expires = eu->eu_expires = 3600;
 
-  eu->eu_final_wait = 0;
-    
-  if (sip->sip_expires && sip->sip_expires->ex_delta == 0)
-    du->du_terminating = 1;
+    eu->eu_final_wait = 0;
 
-  if (eu->eu_substate == nua_substate_terminated)
-    eu->eu_substate = nua_substate_embryonic;
+    if (eu->eu_substate == nua_substate_terminated)
+      eu->eu_substate = nua_substate_embryonic;
+  }
 
-  cr->cr_usage = du;
-  return cr->cr_event = e;
-}
+  if (!sip->sip_expires || sip->sip_expires->ex_delta != expires) {
+    sip_expires_t ex[1];
+    sip_expires_init(ex)->ex_delta = expires;
+    sip_add_dup(msg, sip, (sip_header_t *)ex);
+  }
 
-static void restart_subscribe(nua_handle_t *nh, tagi_t *tags)
-{
-  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_subscribe, tags);
+  return nua_base_client_request(cr, msg, sip, tags);
 }
 
 /** @NUA_EVENT nua_r_subscribe
@@ -342,51 +337,41 @@
  * @END_NUA_EVENT
  */
 
-static int process_response_to_subscribe(nua_handle_t *nh,
-					 nta_outgoing_t *orq,
+static int nua_subscribe_client_response(nua_client_request_t *cr,
+					 int status, char const *phrase,
 					 sip_t const *sip)
 {
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
+  nua_handle_t *nh = cr->cr_owner;
   nua_dialog_usage_t *du = cr->cr_usage; 
   struct event_usage *eu = nua_dialog_usage_private(du);
-  int status = sip ? sip->sip_status->st_status : 408;
-  int gracefully = 0;
-  int substate = nua_substate_embryonic;
-
-  assert(du); assert(du->du_class == nua_subscribe_usage);
-
-  if (status < 200)
-    ;
-  else if (du == NULL) {
-    /* NOTIFY already removed du */
-  }
-  /* We have not received NOTIFY. */
-  else if (status < 300) {
+  enum nua_substate substate;
+
+  if (eu == NULL || cr->cr_terminated)
+    substate = nua_substate_terminated;
+  else if (status >= 300)
+    substate = eu->eu_substate;
+  else {
     int win_messenger_enable = NH_PGET(nh, win_messenger_enable);
     sip_time_t delta, now = sip_now();
 
     du->du_ready = 1;
-    substate = eu->eu_substate;
-    
-    if (du->du_terminating)
-      delta = 0;
-    else
-      /* If there is no expires header,
+
+    if (eu->eu_substate != nua_substate_terminated)
+      /* If there is no @Expires header, 
 	 use default value stored in eu_expires */
       delta = sip_contact_expires(NULL, sip->sip_expires, sip->sip_date, 
 				  eu->eu_expires, now);
+    else
+      delta = 0;
 
     if (win_messenger_enable && !nua_dialog_is_established(nh->nh_ds)) {
       /* Notify from messanger does not match with dialog tag */ 
       nh->nh_ds->ds_remote_tag = su_strdup(nh->nh_home, "");
     }
 
-    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
-    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
-
     if (delta > 0) {
       nua_dialog_usage_set_refresh(du, delta);
-    }
+    } 
     else if (!eu->eu_notified) {
       /* This is a fetch: subscription was really terminated
 	 but we wait 32 seconds for NOTIFY. */
@@ -396,51 +381,26 @@
 	delta = 4 * 60; 	/* Wait 4 minutes for NOTIFY from Messenger */
 
       eu->eu_final_wait = 1;
-
-      /* Do not remove usage in nua_stack_process_response  */
-      cr->cr_usage = NULL;	
+	
+      if (eu->eu_substate == nua_substate_terminated)
+	eu->eu_substate = nua_substate_embryonic;
 
       nua_dialog_usage_refresh_range(du, delta, delta);
     }
     else {
-      eu->eu_substate = substate = nua_substate_terminated;
+      eu->eu_substate = nua_substate_terminated;
     }
-  }
-  else /* if (status >= 300) */ {
-    int terminated;
-
-    if (nua_creq_check_restart(nh, cr, orq, sip, restart_subscribe))
-      return 0;
-
-    cr->cr_usage = NULL; /* We take care of removing/not removing usage */
 
     substate = eu->eu_substate;
 
-    if (!sip || !sip->sip_retry_after)
-      gracefully = 1;
-
-    terminated = 
-      sip_response_terminates_dialog(status, sip_method_subscribe, 
-				     &gracefully);
-
-    /* XXX - zap dialog if terminated < 0 ? */
-
-    if (terminated || !du->du_ready || du->du_terminating) {
-      substate = nua_substate_terminated;
-      nua_dialog_usage_remove(nh, nh->nh_ds, du);
-    }
-    else if (gracefully && substate != nua_substate_terminated) 
-      /* Post un-subscribe event */
-      nua_stack_post_signal(nh, nua_r_unsubscribe, 
-			    SIPTAG_EVENT(du->du_event), 
-			    SIPTAG_EXPIRES_STR("0"),
-			    TAG_END());
+    if (substate == nua_substate_terminated)
+      /* let nua_base_client_tresponse to remove usage */
+      cr->cr_terminated = 1;	
   }
-
-  nua_stack_process_response(nh, cr, orq, sip, 
-			     TAG_IF(substate >= 0, NUTAG_SUBSTATE(substate)),
-			     TAG_END());
-  return 0;
+  
+  return nua_base_client_tresponse(cr, status, phrase, sip, 
+				   NUTAG_SUBSTATE(substate),
+				   TAG_END());
 }
 
 /** Refresh subscription */
@@ -449,120 +409,72 @@
 					nua_dialog_usage_t *du,
 					sip_time_t now)
 {
-  nua_t *nua = nh->nh_nua;
-  nua_client_request_t *cr = ds->ds_cr;
+  nua_client_request_t *cr = du->du_cr;
   struct event_usage *eu = nua_dialog_usage_private(du);
-  msg_t *msg;
-
+  
   assert(eu);
   
   if (eu->eu_final_wait) {
-    /* Did not receive NOTIFY for fetch... */
+    /* Did not receive NOTIFY for fetch */
     sip_event_t const *o = du->du_event;
     char const *id = o ? o->o_id : NULL;
 
-    SU_DEBUG_3(("nua(%p): fetch event %s%s%s timeouts\n",
-		nh, o ? o->o_type : "(empty)",
+    SU_DEBUG_3(("nua(%p): event %s%s%s fetch timeouts\n",
+		(void *)nh, o ? o->o_type : "(empty)",
 		id ? "; id=" : "", id ? id : ""));
 
-    nua_stack_event(nh->nh_nua, nh,  NULL,
-		    nua_i_notify, 408, "Fetch Timeouts without NOTIFY", 
-		    NUTAG_SUBSTATE(nua_substate_terminated),
-		    SIPTAG_EVENT(o),
-		    TAG_END());
-
+    nua_stack_tevent(nh->nh_nua, nh,  NULL,
+		     nua_i_notify, 408, "Fetch Timeouts without NOTIFY", 
+		     NUTAG_SUBSTATE(nua_substate_terminated),
+		     SIPTAG_EVENT(du->du_event),
+		     TAG_END());
     nua_dialog_usage_remove(nh, ds, du);
 
     return;
   }
 
-  if (du->du_terminating)	/* No need to refresh. */
-    return;
-
-  if (cr->cr_msg) {
-    /* Already doing something, delay 5..15 seconds? */
-    if (cr->cr_usage != du)
-      nua_dialog_usage_refresh_range(du, 5, 15);
-    return;
-  }
-
-  cr->cr_msg = msg_copy(du->du_msg);
-
-  msg = nua_creq_msg(nua, nh, cr, 1,
-		     SIP_METHOD_SUBSCRIBE,
-		     NUTAG_USE_DIALOG(1),
-		     NUTAG_ADD_CONTACT(1),
-		     /* If dialog is established, remove initial route */
-		     TAG_IF(nua_dialog_is_established(nh->nh_ds),
-			    SIPTAG_ROUTE(NONE)),
+  if (cr) {
+    if (nua_client_resend_request(cr, 0) >= 0)
+      return;
+  }
+  else if (eu->eu_refer) {
+    /*
+     * XXX - If we have received a NOTIFY, we should try to terminate
+     * subscription
+     */
+  }
+
+  if (!eu->eu_unsolicited)
+    nua_stack_tevent(nh->nh_nua, nh, NULL,
+		     nua_i_notify, NUA_INTERNAL_ERROR,
+		     NUTAG_SUBSTATE(nua_substate_terminated),
+		     SIPTAG_EVENT(du->du_event),
 		     TAG_END());
 
-  cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				    process_response_to_subscribe, nh, NULL,
-				    msg,
-				    SIPTAG_END(), TAG_NEXT(NULL));
-  if (cr->cr_orq) {
-    cr->cr_usage = du;
-    cr->cr_event = nua_r_subscribe;
-    return;
-  }
-
-  if (du->du_terminating)
-    nua_dialog_usage_remove(nh, nh->nh_ds, du);
-  else   /* Try again later? */
-    nua_dialog_usage_refresh_range(du, 5, 15);
-
-  msg_destroy(msg);
-  UA_EVENT3(nua_r_subscribe, NUA_INTERNAL_ERROR, 
-	    NUTAG_SUBSTATE(eu->eu_substate),
-	    TAG_END());
+  nua_dialog_usage_remove(nh, ds, du);
 }
 
-
-/** Terminate subscription */
+/** Terminate subscription.
+ *
+ * @retval >0  shutdown done
+ * @retval 0   shutdown in progress
+ * @retval <0  try again later
+ */
 static int nua_subscribe_usage_shutdown(nua_handle_t *nh,
 					nua_dialog_state_t *ds,
 					nua_dialog_usage_t *du)
 {
-  nua_t *nua = nh->nh_nua;
-  nua_client_request_t *cr = ds->ds_cr;
   struct event_usage *eu = nua_dialog_usage_private(du);
-  msg_t *msg;
+  nua_client_request_t *cr = du->du_cr;
 
   assert(eu); (void)eu;
 
-  if (du->du_terminating)
-    return 100;			/* ...in progress */
-  
-  if (cr->cr_msg)
-    /* XXX - already doing something else? */
-    return 100;
-
-  cr->cr_msg = msg_copy(du->du_msg);
-
-  msg = nua_creq_msg(nua, nh, cr, 1,
-		     SIP_METHOD_SUBSCRIBE,
-		     NUTAG_USE_DIALOG(1),
-		     NUTAG_ADD_CONTACT(1),
-		     SIPTAG_EXPIRES_STR("0"),
-		     /* If dialog is established, remove initial route */
-		     TAG_IF(nua_dialog_is_established(nh->nh_ds),
-			    SIPTAG_ROUTE(NONE)),
-		     TAG_END());
-
-  cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				    process_response_to_subscribe, nh, NULL,
-				    msg,
-				    SIPTAG_END(), TAG_NEXT(NULL));
-  if (cr->cr_orq) {
-    cr->cr_usage = du;
-    cr->cr_event = nua_r_destroy;
-    return 100;
+  if (cr) {
+    if (nua_client_resend_request(cr, 1) >= 0)
+      return 0;
   }
-
-  /* Too bad. */
+  
   nua_dialog_usage_remove(nh, ds, du);
-  msg_destroy(msg);
   return 200;
 }
 
@@ -585,178 +497,195 @@
  * @END_NUA_EVENT
  */
 
-/** @internal Process incoming NOTIFY. */
-int nua_stack_process_notify(nua_t *nua,
-			     nua_handle_t *nh,
-			     nta_incoming_t *irq,
-			     sip_t const *sip)
-{
-  nua_dialog_state_t *ds = nh->nh_ds;
-  nua_dialog_usage_t *du;
-  struct event_usage *eu;
-  sip_subscription_state_t *subs = sip ? sip->sip_subscription_state : NULL;
-  sip_subscription_state_t ss0[1];
-  msg_t *response;
-  char expires[32];
-  int retry = -1;
-  char const *what = NULL, *why = NULL;
+int nua_notify_server_init(nua_server_request_t *sr);
+int nua_notify_server_preprocess(nua_server_request_t *sr);
+int nua_notify_server_report(nua_server_request_t *, tagi_t const *);
 
-  enter;
+nua_server_methods_t const nua_notify_server_methods = 
+  {
+    SIP_METHOD_NOTIFY,
+    nua_i_notify,		/* Event */
+    { 
+      /* create_dialog: */ 1,	/* Do create dialog */
+      /* in_dialog: */ 0,	/* Not always in-dialog request */
+      /* target_refresh: */ 1,	/* Target refresh request  */
+      /* add_contact: */ 1,	/* Add Contact to response */
+    },
+    nua_notify_server_init,
+    nua_notify_server_preprocess,
+    nua_base_server_params,
+    nua_base_server_respond,
+    nua_notify_server_report,
+  };
+
+
+int nua_notify_server_init(nua_server_request_t *sr)
+{
+  if (!sr->sr_initial) {
+    nua_dialog_state_t *ds = sr->sr_owner->nh_ds;
+
+    /* Check for forked subscription. */
+    if (ds->ds_remote_tag && ds->ds_remote_tag[0] && 
+	str0cmp(ds->ds_remote_tag, sr->sr_request.sip->sip_from->a_tag)) {
+      sip_contact_t const *m = NULL;
+
+      m = nua_stack_get_contact(sr->sr_owner->nh_nua->nua_registrations);
+      
+      if (m) {
+	sip_warning_t w[1];
+	
+	sip_warning_init(w)->w_code = 399;
+	w->w_host = m->m_url->url_host;
+	w->w_port = m->m_url->url_port;
+	w->w_text = "Forking SUBSCRIBEs are not supported";
 
-  if (nh == NULL) {
-    nta_incoming_treply(irq, 481, "Subscription Does Not Exist", 
-			TAG_END());
-    return 481;
-  }
-  assert(nh);
-
-  if (/* XXX - support forking of subscriptions?... */
-      ds->ds_remote_tag && ds->ds_remote_tag[0] && 
-      sip && sip->sip_from->a_tag &&
-      strcmp(ds->ds_remote_tag, sip->sip_from->a_tag)) {
-    sip_contact_t const *m = NULL;
-    sip_warning_t *w = NULL, w0[1];
-
-    m = nua_stack_get_contact(nua->nua_registrations);
-    if (m) {
-      w = sip_warning_init(w0);
-      w->w_code = 399;
-      w->w_host = m->m_url->url_host;
-      w->w_port = m->m_url->url_port;
-      w->w_text = "Forking SUBSCRIBEs are not supported";
-    }
+	sip_add_dup(sr->sr_response.msg, NULL, (sip_header_t*)w);
+      }
 
-    nta_incoming_treply(irq, 481, "Subscription Does Not Exist", 
-			SIPTAG_WARNING(w),
-			TAG_END());
-    return 481;
+      return SR_STATUS(sr, 481, "Subscription Does Not Exist");
+    }
   }
 
-  du = nua_dialog_usage_get(nh->nh_ds, nua_subscribe_usage, sip->sip_event);
+  return 0;
+}
+
+int nua_notify_server_preprocess(nua_server_request_t *sr)
+{
+  nua_dialog_state_t *ds = sr->sr_owner->nh_ds;
+  nua_dialog_usage_t *du;
+  struct event_usage *eu;
+  sip_t const *sip = sr->sr_request.sip;
+  sip_event_t *o = sip->sip_event;
+  enum nua_substate substate = nua_substate_terminated;
+  sip_subscription_state_t *subs = sip->sip_subscription_state;
+  char const *what = "", *reason = NULL;
+  int solicited = 1;
+
+  du = nua_dialog_usage_get(ds, nua_subscribe_usage, o);
 
   if (du == NULL) {
-    nta_incoming_treply(irq, 481, "Subscription Does Not Exist", TAG_END());
-    return 481;
-  }
+    if (!sip_is_allowed(NH_PGET(sr->sr_owner, appl_method), SIP_METHOD_NOTIFY))
+      return SR_STATUS(sr, 481, "Subscription Does Not Exist");
 
+    solicited = 0;    /* Let application to handle unsolicited NOTIFY */
+    du = nua_dialog_usage_add(sr->sr_owner, ds, nua_subscribe_usage, o);
+    if (!du)
+      return SR_STATUS1(sr, SIP_500_INTERNAL_SERVER_ERROR);
+  }
+  
+  sr->sr_usage = du;
   eu = nua_dialog_usage_private(du); assert(eu);
   eu->eu_notified++;
-
-  if (!sip->sip_event->o_id) {
+  if (!o->o_id) 
     eu->eu_no_id = 1;
-  }
 
   if (subs == NULL) {
-    /* Do some compatibility stuff here */
-    unsigned long delta;
-
-    sip_subscription_state_init(subs = ss0);
-
-    delta = sip->sip_expires ? sip->sip_expires->ex_delta : eu->eu_expires;
+    /* Compatibility */
+    unsigned long delta = eu->eu_expires;
+    if (sip->sip_expires) 
+      delta = sip->sip_expires->ex_delta;
 
     if (delta == 0)
-      subs->ss_substate = "terminated";
+      substate = nua_substate_terminated, what = "terminated";
     else
-      subs->ss_substate = "active";
-
-    if (delta > 0 && sip->sip_expires) {
-      snprintf(expires, sizeof expires, "%lu", delta);
-      subs->ss_expires = expires;
-    }
+      substate = nua_substate_active, what = "active";
   }
+  else if (strcasecmp(subs->ss_substate, what = "terminated") == 0) {
+    substate = nua_substate_terminated;
+    reason = subs->ss_reason;
 
-  nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
-  nua_dialog_uas_route(nh, nh->nh_ds, sip, 1);
-
-  if (strcasecmp(subs->ss_substate, what = "terminated") == 0) {
-    eu->eu_substate = nua_substate_terminated;
-
-    if (str0casecmp(subs->ss_reason, why = "deactivated") == 0) {
-      eu->eu_substate = nua_substate_embryonic;
-      retry = 0;		/* retry immediately */
-    } 
-    else if (str0casecmp(subs->ss_reason, why = "probation") == 0) {
-      eu->eu_substate = nua_substate_embryonic;
-      retry = 30;
-      if (subs->ss_retry_after)
-	retry = strtoul(subs->ss_retry_after, NULL, 10);
-      if (retry > 3600)
-	retry = 3600;
-    }
-    else
-      why = subs->ss_reason;
+    if (str0casecmp(reason, "deactivated") == 0 ||
+	str0casecmp(reason, "probation") == 0) 
+      substate = nua_substate_embryonic;
+  }
+  else if (strcasecmp(subs->ss_substate, what = "pending") == 0) {
+    substate = nua_substate_pending;
   }
-  else if (strcasecmp(subs->ss_substate, what = "pending") == 0)
-    eu->eu_substate = nua_substate_pending;
-  else /* if (strcasecmp(subs->ss_substate, "active") == 0) */ {
+  else /* if (strcasecmp(subs->ss_substate, what = "active") == 0) */ {
     /* Any extended state is considered as active */
-    what = subs->ss_substate ? subs->ss_substate : "active";
-    eu->eu_substate = nua_substate_active;
+    what = subs->ss_substate;
+    substate = nua_substate_active;
   }
 
-  if (du->du_terminating)
-    retry = -1;
-  
-  response = nh_make_response(nua, nh, irq, SIP_200_OK,
-			      SIPTAG_ALLOW(NH_PGET(nh, allow)),
-			      SIPTAG_SUPPORTED(NH_PGET(nh, supported)),
-			      TAG_END());
-
-  if (response && 
-      nua_registration_add_contact_to_response(nh, response, NULL, 
-					       sip->sip_record_route,
-					       sip->sip_contact) >= 0)
-    nta_incoming_mreply(irq, response);
-  else
-    nta_incoming_treply(irq, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
-
-  if (eu->eu_substate == nua_substate_terminated && retry > 0)
-    eu->eu_substate = nua_substate_embryonic;
-
-  nua_stack_event(nh->nh_nua, nh, nta_incoming_getrequest(irq),
-		  nua_i_notify, SIP_200_OK, 
-		  NUTAG_SUBSTATE(eu->eu_substate),
-		  TAG_END());
-
-  nta_incoming_destroy(irq), irq = NULL;
-
-  SU_DEBUG_5(("nua(%p): nua_stack_process_notify: %s (%s)\n", 
-	      nh, what, why ? why : ""));
-
-  if (eu->eu_substate == nua_substate_terminated) {
-    if (du != nh->nh_ds->ds_cr->cr_usage)
-      nua_dialog_usage_remove(nh, nh->nh_ds, du);
-    else
-      nua_dialog_usage_reset_refresh(du);
-  }
-  else if (eu->eu_substate == nua_substate_embryonic) {
-    if (retry >= 0) {
-      /* Try to subscribe again */
-      nua_dialog_remove(nh, nh->nh_ds, du); /* tear down */
-      nua_dialog_usage_refresh_range(du, retry, retry + 5);
+  eu->eu_substate = substate;
+  if (!solicited)
+    eu->eu_unsolicited = 1;
+
+  SU_DEBUG_5(("nua(%p): %s: %s (%s)\n", 
+	      (void *)sr->sr_owner, "nua_notify_server_preprocess",
+	      what, reason ? reason : ""));
+
+  if (solicited)
+    return SR_STATUS1(sr, SIP_200_OK);
+
+  return 0;
+}
+
+
+int nua_notify_server_report(nua_server_request_t *sr, tagi_t const *tags)
+{
+  nua_handle_t *nh = sr->sr_owner;
+  nua_dialog_usage_t *du = sr->sr_usage;
+  struct event_usage *eu = nua_dialog_usage_private(du);
+  sip_t const *sip = sr->sr_request.sip;
+  enum nua_substate substate = nua_substate_terminated;
+  sip_time_t delta = SIP_TIME_MAX;
+  int retry = -1;
+  int retval;
+
+  if (eu) {
+    sip_subscription_state_t *subs = sip->sip_subscription_state;
+
+    substate = eu->eu_substate;
+
+    if (substate == nua_substate_active || substate == nua_substate_pending) {
+      if (subs && subs->ss_expires)
+	delta = strtoul(subs->ss_expires, NULL, 10);
+      else
+	delta = eu->eu_expires;
+    }
+    else if (substate == nua_substate_embryonic) {
+      if (subs && subs->ss_reason) {
+	if (str0casecmp(subs->ss_reason, "deactivated") == 0) {
+	  retry = 0;		/* retry immediately */
+	} 
+	else if (str0casecmp(subs->ss_reason, "probation") == 0) {
+	  retry = 30;
+	  if (subs->ss_retry_after)
+	    retry = strtoul(subs->ss_retry_after, NULL, 10);
+	  if (retry > 3600)
+	    retry = 3600;
+	}
+      }
+    }
+    else if (substate == nua_substate_terminated) {
+      sr->sr_terminating = 1;
     }
-    else if (du != nh->nh_ds->ds_cr->cr_usage)
-      nua_dialog_usage_remove(nh, nh->nh_ds, du);
-    else
-      nua_dialog_usage_reset_refresh(du);
   }
-  else if (du->du_terminating) {
-    nua_dialog_usage_reset_refresh(du);
+  
+  retval = nua_base_server_treport(sr, /* can destroy sr */
+				   NUTAG_SUBSTATE(substate),
+				   TAG_NEXT(tags)); 
+
+  if (retval != 1 || du == NULL)
+    return retval;
+
+  if (eu->eu_unsolicited) {
+    /* Xyzzy */;
+  }
+  else if (retry >= 0) {		/* Try to subscribe again */
+    /* XXX - this needs through testing */
+    nua_dialog_remove(nh, nh->nh_ds, du); /* tear down */
+    nua_dialog_usage_refresh_range(du, retry, retry + 5);
   }
   else {
-    sip_time_t delta;
-
-    if (subs->ss_expires)
-      delta = strtoul(subs->ss_expires, NULL, 10);
-    else
-      delta = eu->eu_expires;
-    
     nua_dialog_usage_set_refresh(du, delta);
   }
 
-  return 0;
+  return retval;
 }
 
+
 /* ======================================================================== */
 /* REFER */
 
@@ -802,81 +731,6 @@
  * @RFC3515, @ReferTo, @RFC3892, @ReferredBy
  */
 
-static int process_response_to_refer(nua_handle_t *nh,
-				     nta_outgoing_t *orq,
-				     sip_t const *sip);
-
-int
-nua_stack_refer(nua_t *nua, nua_handle_t *nh, nua_event_t e, tagi_t const *tags)
-{
-  nua_dialog_usage_t *du = NULL;
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  msg_t *msg;
-  sip_t *sip;
-  sip_referred_by_t by[1];
-  sip_event_t *event = NULL;
-
-  if (nua_stack_set_handle_special(nh, nh_has_subscribe, nua_r_subscribe) < 0)
-    return UA_EVENT2(e, 900, "Invalid handle for REFER");
-  else if (cr->cr_orq)
-    return UA_EVENT2(e, 900, "Request already in progress");
-
-  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
-
-  sip_referred_by_init(by);
-  by->b_display = nua->nua_from->a_display;
-  *by->b_url = *nua->nua_from->a_url;
-
-  /* Now we create a REFER request message */
-  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
-			 SIP_METHOD_REFER,
-			 NUTAG_USE_DIALOG(1),
-			 SIPTAG_EVENT(SIP_NONE), /* remove event */
-			 SIPTAG_REFERRED_BY(by), /* Overriden by user tags */
-			 NUTAG_ADD_CONTACT(1),
-			 TAG_NEXT(tags));
-  sip = sip_object(msg);
-
-  if (sip && sip->sip_cseq)
-    event = sip_event_format(nh->nh_home, "refer;id=%u", 
-			     sip->sip_cseq->cs_seq);
-
-  if (event)
-    du = nua_dialog_usage_add(nh, nh->nh_ds, nua_subscribe_usage, event);
-  
-  if (du)
-    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
-				      process_response_to_refer, nh, NULL,
-				      msg,
-				      SIPTAG_END(), TAG_NEXT(tags));
-  
-  if (!cr->cr_orq) {
-    if (du)
-      nua_dialog_usage_remove(nh, nh->nh_ds, du);
-    su_free(nh->nh_home, event);
-    msg_destroy(msg);
-    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
-  }
-
-  /*
-   * We send a 100 trying event so that application gets a event 
-   * it can use to match NOTIFYs with its REFER
-   */
-  nua_stack_event(nua, nh, NULL, e, SIP_100_TRYING, 
-	   NUTAG_REFER_EVENT(event),
-	   TAG_END());
-  su_free(nh->nh_home, event);
-
-  cr->cr_usage = du;
-
-  return cr->cr_event = e;
-}
-
-void restart_refer(nua_handle_t *nh, tagi_t *tags)
-{
-  nua_stack_refer(nh->nh_nua, nh, nh->nh_ds->ds_cr->cr_event, tags);
-}
-
 /**@NUA_EVENT nua_r_refer
  *
  * @brief Response to outgoing REFER.
@@ -900,27 +754,130 @@
  * @END_NUA_EVENT
  */
 
-static int process_response_to_refer(nua_handle_t *nh,
-				     nta_outgoing_t *orq,
-				     sip_t const *sip)
+static int nua_refer_client_init(nua_client_request_t *cr, 
+				 msg_t *, sip_t *,
+				 tagi_t const *tags);
+static int nua_refer_client_request(nua_client_request_t *cr,
+				    msg_t *, sip_t *,
+				    tagi_t const *tags);
+static int nua_refer_client_response(nua_client_request_t *cr,
+				     int status, char const *phrase,
+				     sip_t const *sip);
+
+static nua_client_methods_t const nua_refer_client_methods = {
+  SIP_METHOD_REFER,
+  0,
+  { 
+    /* create_dialog */ 1,
+    /* in_dialog */ 1,
+    /* target refresh */ 1
+  },
+  /*nua_refer_client_template*/ NULL,
+  nua_refer_client_init,
+  nua_refer_client_request,
+  /* nua_refer_client_check_restart */ NULL,
+  nua_refer_client_response,
+  nua_refer_client_response,	/* Preliminary */
+  NULL
+};
+
+int
+nua_stack_refer(nua_t *nua, nua_handle_t *nh, nua_event_t e,
+		    tagi_t const *tags)
 {
-  nua_client_request_t *cr = nh->nh_ds->ds_cr;
-  int status = sip ? sip->sip_status->st_status : 408;
+  return nua_client_create(nh, e, &nua_refer_client_methods, tags);
+}
 
-  if (status < 200)
-    ;
-  else if (status < 300) {
-    if (cr->cr_usage)
-      cr->cr_usage->du_ready = 1;
-    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
-    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
-  }
-  else /* if (status >= 300) */ {
-    if (cr->cr_usage)
-      nua_dialog_usage_remove(nh, nh->nh_ds, cr->cr_usage), cr->cr_usage = NULL;
-    if (nua_creq_check_restart(nh, cr, orq, sip, restart_refer))
-      return 0;
+static int nua_refer_client_init(nua_client_request_t *cr,
+				 msg_t *msg, sip_t *sip,
+				 tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+
+  if (sip->sip_referred_by == NULL) {
+    sip_from_t *a = sip->sip_from;
+    sip_referred_by_t by[1];
+
+    sip_referred_by_init(by);
+
+    if (a == NULL)
+      a = nh->nh_nua->nua_from;
+    by->b_display = a->a_display;
+    *by->b_url = *a->a_url;
+
+    sip_add_dup(msg, sip, (sip_header_t *)by);
+  }
+
+  if (sip->sip_event)
+    sip_header_remove(msg, sip, (sip_header_t *)sip->sip_event);
+
+  return 0;
+}
+
+static int nua_refer_client_request(nua_client_request_t *cr,
+				    msg_t *msg, sip_t *sip,
+				    tagi_t const *tags)
+{
+  nua_handle_t *nh = cr->cr_owner;
+  nua_dialog_usage_t *du = cr->cr_usage;
+  struct event_usage *eu;
+  sip_event_t *event;
+  int error;
+
+  cr->cr_usage = NULL;
+
+  if (du)
+    nua_dialog_usage_remove(nh, nh->nh_ds, du);
+
+  event = sip_event_format(nh->nh_home, "refer;id=%u", sip->sip_cseq->cs_seq);
+  if (!event)
+    return -1;
+  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_subscribe_usage, event);
+  if (!du)
+    return -1;
+
+  eu = nua_dialog_usage_private(cr->cr_usage = du);
+  eu ->eu_refer = 1;
+
+  error = nua_base_client_request(cr, msg, sip, tags);
+
+  if (!error) {
+    /* Give application an Event header for matching NOTIFYs with REFER */
+    nua_stack_tevent(nh->nh_nua, nh, NULL,
+		     cr->cr_event, SIP_100_TRYING,
+		     NUTAG_REFER_EVENT(event),
+		     TAG_END());
+    su_free(nh->nh_home, event);
   }
 
-  return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
+  return error;
+}
+
+static int nua_refer_client_response(nua_client_request_t *cr,
+				     int status, char const *phrase,
+				     sip_t const *sip)
+{
+  nua_dialog_usage_t *du = cr->cr_usage; 
+  enum nua_substate substate = nua_substate_terminated;
+
+  if (du) {
+    struct event_usage *eu = nua_dialog_usage_private(du);
+
+    if (status < 200) {
+      substate = eu->eu_substate;      
+    } 
+    else if (status < 300) {
+      sip_refer_sub_t const *rs = sip_refer_sub(sip);
+
+      if (rs && strcasecmp("false", rs->rs_value) == 0)
+	cr->cr_terminated = 1;
+
+      if (!cr->cr_terminated)
+	substate = eu->eu_substate;
+    }
+  }
+  
+  return nua_base_client_tresponse(cr, status, phrase, sip, 
+				   NUTAG_SUBSTATE(substate),
+				   TAG_END());
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_tag.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_tag.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/nua_tag.c	Tue Apr 24 10:14:28 2007
@@ -68,6 +68,7 @@
 tag_typedef_t nutag_offer_sent = BOOLTAG_TYPEDEF(offer_sent);
 tag_typedef_t nutag_answer_sent = BOOLTAG_TYPEDEF(answer_sent);
 tag_typedef_t nutag_substate = INTTAG_TYPEDEF(substate);
+tag_typedef_t nutag_newsub = BOOLTAG_TYPEDEF(newsub);
 tag_typedef_t nutag_invite_timer = UINTTAG_TYPEDEF(invite_timer);
 tag_typedef_t nutag_session_timer = UINTTAG_TYPEDEF(session_timer);
 tag_typedef_t nutag_min_se = UINTTAG_TYPEDEF(min_se);
@@ -143,10 +144,9 @@
 tag_typedef_t nutag_path_enable = BOOLTAG_TYPEDEF(path_enable);
 tag_typedef_t nutag_service_route_enable = 
   BOOLTAG_TYPEDEF(service_route_enable);
+tag_typedef_t nutag_auth_cache = INTTAG_TYPEDEF(auth_cache);
 
 tag_typedef_t nutag_detect_network_updates = UINTTAG_TYPEDEF(detect_network_updates);
 
 tag_typedef_t nutag_with = PTRTAG_TYPEDEF(with);
-
-tag_typedef_t _nutag_add_contact = BOOLTAG_TYPEDEF(add_contact);
-tag_typedef_t _nutag_copy = BOOLTAG_TYPEDEF(copy);
+tag_typedef_t nutag_dialog = UINTTAG_TYPEDEF(dialog);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/outbound.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/outbound.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/outbound.c	Tue Apr 24 10:14:28 2007
@@ -117,7 +117,6 @@
 
   char const *ob_instance;	/**< Our instance ID */
   int32_t ob_reg_id;		/**< Flow-id */
-  char const *ob_features;	/**< Feature parameters for rcontact */
   sip_contact_t *ob_rcontact;	/**< Our contact */
   sip_contact_t *ob_dcontact;	/**< Contact for dialogs */
   sip_contact_t *ob_previous;	/**< Stale contact */
@@ -294,7 +293,8 @@
     else if (MATCH(use-upnp) || MATCH(use_upnp)) prefs->use_upnp = value;
     else if (MATCH(use-stun) || MATCH(use_stun)) prefs->use_stun = value;
     else
-      SU_DEBUG_1(("outbound_t: unknown option \"%.*s\"\n", (int)len, s));
+      SU_DEBUG_1(("outbound(%p): unknown option \"%.*s\"\n",
+		  (void *)ob->ob_owner, (int)len, s));
 
     s += len;
     len = strspn(s, " \t\n\r,;");
@@ -304,7 +304,8 @@
   }
 
   if (s && s[0]) {
-    SU_DEBUG_1(("outbound_t: invalid options \"%s\"\n", options));
+    SU_DEBUG_1(("outbound(%p): invalid options \"%s\"\n", 
+		(void *)ob->ob_owner, options));
     return -1;
   }
 
@@ -315,7 +316,8 @@
 	prefs->use_socks ||
 	prefs->use_upnp ||
 	prefs->use_stun)) {
-    SU_DEBUG_1(("outbound(%p): no nat traversal method given\n", ob->ob_owner));
+    SU_DEBUG_1(("outbound(%p): no nat traversal method given\n",
+		(void *)ob->ob_owner));
   }
 
   ob->ob_prefs = *prefs;
@@ -324,60 +326,27 @@
   return 0;
 }
 
-/** Set the feature string (added to the Contact header when registering). */
-int outbound_set_features(outbound_t *ob, char *features)
-{
-  char *old_features = (char *)ob->ob_features;
-  char *new_features = su_strdup(ob->ob_home, features);
-
-  if (features && !new_features)
-    return -1;
-
-  ob->ob_features = new_features;
-  su_free(ob->ob_home, old_features);
-  return 0;
-}
-
 /* ---------------------------------------------------------------------- */
 
-/** Hook for sending register request with extra outbound-ish headers. */
-nta_outgoing_t *outbound_register_request(outbound_t *ob, int terminating, 
-					  sip_contact_t *stack_contact,
-					  nta_agent_t *nta,
-					  nta_response_f *callback,
-					  nta_outgoing_magic_t *magic,
-					  url_string_t *next_hop,
-					  msg_t *msg,
-					  tag_type_t tag, tag_value_t value,
-					  ...)
-{
-  sip_contact_t *previous_contact = NULL;
-  ta_list ta;
-  nta_outgoing_t *orq;
-
-  if (stack_contact) {
-    if (ob) {
-      if (ob->ob_contacts)
-	stack_contact = ob->ob_rcontact;
-      previous_contact = ob->ob_previous;
-    }
+/** Obtain contacts for REGISTER */
+int outbound_get_contacts(outbound_t *ob, 
+			  sip_contact_t **return_current_contact, 
+			  sip_contact_t **return_previous_contact)
+{
+  if (ob) {
+    if (ob->ob_contacts)
+      *return_current_contact = ob->ob_rcontact;
+    *return_previous_contact = ob->ob_previous;
   }
+  return 0;
+}
 
-  ta_start(ta, tag, value);
-
-  orq = nta_outgoing_mcreate(nta, callback, magic, next_hop, msg,
-			     TAG_IF(previous_contact,
-				    SIPTAG_CONTACT(previous_contact)),
-			     TAG_IF(stack_contact,
-				    SIPTAG_CONTACT(stack_contact)),
-			     ta_tags(ta));
-
-  ta_end(ta);
-
-  if (orq && ob)
+/** REGISTER request has been sent */
+int outbound_start_registering(outbound_t *ob)
+{
+  if (ob)
     ob->ob_registering = 1;
-
-  return orq;
+  return 0;
 }
 
 /** Process response to REGISTER request */
@@ -391,17 +360,16 @@
   if (!ob)
     return 0;
 
-  assert(!request || request->sip_request);
-  assert(!response || response->sip_status);
-  
-  if (!response || !request)
-    return 0;
-
   if (terminating) {
-    ob->ob_registered = ob->ob_registering = 0;
+    ob->ob_registering = ob->ob_registered = 0;
     return 0;			/* Cleanup is done separately */
   }  
 
+  if (!response || !request)
+    return 0;
+
+  assert(request->sip_request); assert(response->sip_status);
+  
   reregister = outbound_check_for_nat(ob, request, response);
   if (reregister)
     return reregister;
@@ -423,7 +391,13 @@
 }
 
 
-/** @internal Check if there is a NAT between us and registrar */
+/** @internal Check if there is a NAT between us and registrar.
+ *
+ * @retval -1 upon an error
+ * @retval #ob_register_ok (0) if the registration was OK
+ * @retval #ob_reregister (1) if client needs to re-register
+ * @retval #ob_reregister_now (2) if client needs to re-register immediately
+ */
 static
 int outbound_check_for_nat(outbound_t *ob,
 			   sip_t const *request,
@@ -457,18 +431,18 @@
   if (!m || binding_changed >= ob_nat_changed) {
     if (ob->ob_stun) {
       /* Use STUN? */
-      return 1;
+      return ob_reregister;
     }
     else if (ob->ob_upnp) {
       /* Use UPnP */
-      return 1;
+      return ob_reregister;
     }
     else {
       if (outbound_contacts_from_via(ob, response->sip_via) < 0)
         return -1;
     }
 
-    return 2;
+    return ob_reregister_now;
   }
 
   return 0;
@@ -512,7 +486,7 @@
   if (!host_is_ip_address(received)) {
     if (received[0])
       SU_DEBUG_3(("outbound(%p): Via with invalid received=%s\n",
-		  ob->ob_owner, received));
+		  (void *)ob->ob_owner, received));
     return 0;
   }
 
@@ -530,14 +504,14 @@
 
   if (!nat_detected) {
     SU_DEBUG_1(("outbound(%p): detected NAT: %s != %s\n",
-		ob->ob_owner, v->v_host, received));
+		(void *)ob->ob_owner, v->v_host, received));
     if (ob->ob_oo && ob->ob_oo->oo_status)
       ob->ob_oo->oo_status(ob->ob_owner, ob, 101, "NAT detected", TAG_END());
   }
   else {
     SU_DEBUG_1(("outbound(%p): NAT binding changed: "
 		"[%s]:%s != [%s]:%s\n",
-		ob->ob_owner, nat_detected, nat_port, received, rport));
+		(void *)ob->ob_owner, nat_detected, nat_port, received, rport));
     if (ob->ob_oo && ob->ob_oo->oo_status)
       ob->ob_oo->oo_status(ob->ob_owner, ob, 102, "NAT binding changed", TAG_END());
   }
@@ -709,21 +683,32 @@
 {
   msg_t *msg = nta_msg_create(ob->ob_nta, MSG_FLG_COMPACT), *previous;
   sip_t *osip = sip_object(msg);
-  sip_accept_contact_t *ac;
-
-  char const *p1 = ob->ob_instance;
-  char const *p2 = ob->ob_features;
+  sip_contact_t *m = ob->ob_rcontact;
 
   unsigned d = ob->ob_keepalive.interval;
 
   assert(regsip); assert(regsip->sip_request);
 
-  if (p1 || p2) {
-    ac = sip_accept_contact_format(msg_home(msg), "*;require;explicit;%s%s%s",
-				   p1 ? p1 : "",
-				   p2 && p2 ? ";" : "",
-				   p2 ? p2 : "");
-    msg_header_insert(msg, NULL, (void *)ac);
+  if (m && m->m_params) {
+    sip_accept_contact_t *ac;
+    size_t i;
+    int features = 0;
+
+    ac = sip_accept_contact_make(msg_home(msg), "*;require;explicit");
+
+    for (i = 0; m->m_params[i]; i++) {
+      char const *s = m->m_params[i];
+      if (!sip_is_callerpref(s))
+	continue;
+      features++;
+      s = su_strdup(msg_home(msg), s);
+      msg_header_add_param(msg_home(msg), ac->cp_common, s);
+    }
+    
+    if (features)
+      msg_header_insert(msg, NULL, (void *)ac);
+    else
+      msg_header_free(msg_home(msg), (void *)ac);
   }
 
   if (0 >
@@ -877,18 +862,19 @@
     if (loglevel >= SU_LOG->log_level) {
       su_llog(SU_LOG, loglevel,       
 	      "outbound(%p): %s <" URL_PRINT_FORMAT ">\n",
-	      ob->ob_owner, failed ? "FAILED to validate" : "validated", 
+	      (void *)ob->ob_owner,
+	      failed ? "FAILED to validate" : "validated",
 	      URL_PRINT_ARGS(ob->ob_rcontact->m_url));
       if (failed)
 	su_llog(SU_LOG, loglevel, "outbound(%p): FAILED with %u %s\n", 
-		ob->ob_owner, status, phrase);
+		(void *)ob->ob_owner, status, phrase);
     }
 
     if (failed) 
       ob->ob_oo->oo_probe_error(ob->ob_owner, ob, status, phrase, TAG_END());
   }
   else if (status == 408) {
-    SU_DEBUG_1(("outbound(%p): keepalive timeout\n", ob->ob_owner));
+    SU_DEBUG_1(("outbound(%p): keepalive timeout\n", (void *)ob->ob_owner));
     ob->ob_oo->oo_keepalive_error(ob->ob_owner, ob, status, phrase, TAG_END());
     return 0;
   }
@@ -982,7 +968,7 @@
 
   if (ob->ob_keepalive.validating) {
     SU_DEBUG_1(("outbound(%p): registration check OPTIONS received\n", 
-		ob->ob_owner));
+		(void *)ob->ob_owner));
     ob->ob_keepalive.validated = 1;
   }
 
@@ -1018,48 +1004,16 @@
 
   v = v0; *v0 = *via; v0->v_next = NULL;
 
-  dcontact = ob->ob_oo->oo_contact(ob->ob_owner, home,
+  dcontact = ob->ob_oo->oo_contact(ob->ob_owner, home, 1,
 				   NULL, v, v->v_protocol, NULL);
 
   if (ob->ob_instance && ob->ob_reg_id != 0)
     snprintf(reg_id_param, sizeof reg_id_param, ";reg-id=%u", ob->ob_reg_id);
 
-  rcontact = ob->ob_oo->oo_contact(ob->ob_owner, home,
+  rcontact = ob->ob_oo->oo_contact(ob->ob_owner, home, 0,
 				   NULL, v, v->v_protocol, 
-				   ob->ob_features ? ob->ob_features : "",
 				   ob->ob_instance, reg_id_param, NULL);
     
-#if 0
-  char *uri;
-
-  /* uri contains < > */
-  uri = sip_contact_string_from_via(NULL, via, NULL, v->v_protocol);
-
-  dcontact = sip_contact_make(home, uri);
-
-
-
-  if (ob->ob_instance) {
-    char reg_id[20];
-
-    if (ob->ob_instance && ob->ob_reg_id)
-      snprintf(reg_id, sizeof reg_id, ";reg-id=%u", ob->ob_reg_id);
-    else
-      strcpy(reg_id, "");
-
-    rcontact = sip_contact_format(home, "%s;%s%s%s%s",
-				  uri, ob->ob_instance, reg_id,
-				  ob->ob_features ? ";" : "",
-				  ob->ob_features ? ob->ob_features : "");
-  }
-  else if (ob->ob_features)
-    rcontact = sip_contact_format(home, "%s;%s", uri, ob->ob_features);
-  else
-    rcontact = dcontact;
-
-  free(uri);
-#endif
-
   v = sip_via_dup(home, v);
 
   if (!rcontact || !dcontact || !v) {
@@ -1137,6 +1091,9 @@
   m3 = ob->ob_previous;
 
   if (terminating) {
+    if (ob->ob_by_stack && application_contact == NULL)
+      return 0;
+    
     if (ob->ob_contacts)
       previous = ob->ob_rcontact;
   }
@@ -1147,11 +1104,14 @@
       previous = ob->ob_contacts ? ob->ob_rcontact : NULL;
     }
   }
+  else if (ob->ob_by_stack) {
+    return 0;    /* Xyzzy - nothing happens */
+  }
   else if (v) {
     char const *tport = !v->v_next ? v->v_protocol : NULL; 
     char reg_id_param[20];
 
-    dcontact = ob->ob_oo->oo_contact(ob->ob_owner, home,
+    dcontact = ob->ob_oo->oo_contact(ob->ob_owner, home, 1, 
 				     NULL, v, tport, NULL);
     if (!dcontact)
       return -1;
@@ -1159,9 +1119,8 @@
     if (ob->ob_instance && ob->ob_reg_id != 0)
       snprintf(reg_id_param, sizeof reg_id_param, ";reg-id=%u", ob->ob_reg_id);
 
-    rcontact = ob->ob_oo->oo_contact(ob->ob_owner, home,
+    rcontact = ob->ob_oo->oo_contact(ob->ob_owner, home, 0,
 				     NULL, v, v->v_protocol, 
-				     ob->ob_features ? ob->ob_features : "",
 				     ob->ob_instance, reg_id_param, NULL);
     if (!rcontact)
       return -1;
@@ -1172,9 +1131,11 @@
       previous = ob->ob_contacts ? ob->ob_rcontact : NULL;
     }
   }
-
+    
   ob->ob_by_stack = application_contact == NULL;
 
+  ob->ob_contacts = rcontact != NULL;
+
   ob->ob_rcontact = rcontact;
   ob->ob_dcontact = dcontact;
   ob->ob_previous = previous;
@@ -1205,6 +1166,11 @@
     return ob->ob_dcontact;
 }
 
+sip_contact_t const *outbound_dialog_gruu(outbound_t const *ob)
+{
+  return ob ? ob->ob_gruu : NULL;
+}
+
 /* ---------------------------------------------------------------------- */
 
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/outbound.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/outbound.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/outbound.h	Tue Apr 24 10:14:28 2007
@@ -70,17 +70,11 @@
 			 unsigned dgram_interval,
 			 unsigned stream_interval);
 
-int outbound_set_features(outbound_t *ob, char *features);
+int outbound_get_contacts(outbound_t *ob, 
+			  sip_contact_t **return_current_contact, 
+			  sip_contact_t **return_previous_contact);
 
-nta_outgoing_t *outbound_register_request(outbound_t *ob, int terminating, 
-					  sip_contact_t *stack_contact,
-					  nta_agent_t *nta,
-					  nta_response_f *callback,
-					  nta_outgoing_magic_t *magic,
-					  url_string_t *next_hop,
-					  msg_t *msg,
-					  tag_type_t tag, tag_value_t value,
-					  ...);
+int outbound_start_registering(outbound_t *ob);
 
 int outbound_register_response(outbound_t *ob,
 			       int terminating,
@@ -102,6 +96,8 @@
 
 sip_contact_t const *outbound_dialog_contact(outbound_t const *ob);
 
+sip_contact_t const *outbound_dialog_gruu(outbound_t const *ob);
+
 int outbound_gruuize(outbound_t *ob, sip_t const *sip);
 
 void outbound_start_keepalive(outbound_t *ob,
@@ -122,6 +118,7 @@
   int oo_size;
   sip_contact_t *(*oo_contact)(outbound_owner_t *,
 			       su_home_t *home,
+			       int used_in_dialog,
 			       char const *extra_username,
 			       sip_via_t const *v,
 			       char const *transport,

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua.h	Tue Apr 24 10:14:28 2007
@@ -262,6 +262,12 @@
 /** Get name for NUA callstate. */
 SOFIAPUBFUN char const *nua_callstate_name(enum nua_callstate state);
 
+/** Return name of subscription state. @NEW_1_12_5. */
+SOFIAPUBFUN char const *nua_substate_name(enum nua_substate substate);
+
+/** Convert string to enum nua_substate. @NEW_1_12_5. */
+SOFIAPUBFUN enum nua_substate nua_substate_make(char const *sip_substate);
+
 /** Send SIP REGISTER request to the registrar. */ 
 SOFIAPUBFUN void nua_register(nua_handle_t *nh, tag_type_t, tag_value_t, ...);
 
@@ -331,15 +337,18 @@
 /*# Redirect an operation. @deprecated */
 SOFIAPUBFUN void nua_redirect(nua_handle_t *, tag_type_t, tag_value_t, ...);
 
-/** Extension request method. */
+/** Send a request message with an extension method. */
 SOFIAPUBFUN void nua_method(nua_handle_t *, tag_type_t, tag_value_t, ...);
 
-/** Respond with given status. */
+/** Respond to a request with given status code and phrase. */
 SOFIAPUBFUN void nua_respond(nua_handle_t *nh, 
 			     int status, char const *phrase,
 			     tag_type_t, tag_value_t, 
 			     ...);
 
+/** Check if event can be responded with nua_respond() */
+SOFIAPUBFUN int nua_event_is_incoming_request(nua_event_t e);
+
 #define nua_handle_home(nh) ((su_home_t *)(nh))
 
 /** Generate an instance identifier */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua_tag.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua_tag.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua_tag.h	Tue Apr 24 10:14:28 2007
@@ -157,6 +157,9 @@
  */
 #define NUTAG_WITH_THIS(nua) nutag_with, tag_ptr_v(nua_current_request((nua)))
 
+#define NUTAG_WITH_CURRENT(nua) \
+   nutag_with, tag_ptr_v(nua_current_request((nua)))
+
 /**Specify request to respond to.
  *
  * @par Used with
@@ -174,6 +177,26 @@
  */
 #define NUTAG_WITH_SAVED(e) nutag_with, tag_ptr_v(nua_saved_event_request((e)))
 
+/**An (extension) method is used to create dialog or refresh target.
+ *
+ * @par Used with
+ *    nua_method()
+ *
+ * @par Parameter type
+ *    unsigned int (0, 1, 2) 
+ *
+ * @par Values
+ *   - 0 if dialog target is not refreshed
+ *   - 1 if dialog target is refreshed
+ *   - > 1 if dialog is to be created 
+ *
+ * @NEW_1_12_6.
+ *
+ * @sa nua_method(), #nua_i_method
+ */
+#define NUTAG_DIALOG(b) nutag_dialog, tag_uint_v((b))
+SOFIAPUBVAR tag_typedef_t nutag_dialog;
+
 /**Set request retry count.
  *
  * Retry count determines how many times stack will automatically retry
@@ -451,8 +474,8 @@
  *
  * @par Used with
  *    nua_invite() \n
- *    nua_set_params() \n
- *    nua_get_params()
+ *    nua_set_params(), nua_set_hparams(),
+ *    nua_get_params(), nua_get_hparams()
  *
  * @par Parameter type
  *    int (enum nua_af)
@@ -471,40 +494,48 @@
 
 /**Default session timer in seconds.
  *
- * Set default session timer in seconds when using session timer extension. 
- * The value given here is the proposed session expiration time in seconds.
- * Note that the session timer extension is ponly used 
+ * Set default value for session timer in seconds when the session timer
+ * extension is used. The tag value is the proposed session expiration time
+ * in seconds, the session is refreshed twice during the expiration time.
  *
  * @par Sending INVITE and UPDATE Requests 
  *
- * If NUTAG_SESSION_TIMER() is used with non-zero value, the value is
- * used in the @SessionExpires header included in the INVITE or UPDATE
- * requests. The intermediate proxies or the ultimate destination can lower
- * the interval in @SessionExpires header. If the value is too low, they can
+ * If NUTAG_SESSION_TIMER() is used with non-zero value, the value is used
+ * in the @SessionExpires header included in the INVITE or UPDATE requests. 
+ * The intermediate proxies or the ultimate destination can lower the
+ * interval in @SessionExpires header. If the value is too low, they can
  * reject the request with the status code <i>422 Session Timer Too
- * Small</i>. When Re-INVITE will be sent in given intervals. In that case,
- * @b nua retries the request automatically.
- * 
- * @par Returning Response to the INVITE and UPDATE Requests 
+ * Small</i>. In that case, @b nua increases the value of @SessionExpires
+ * header and retries the request automatically.
+ *
+ * @par Returning a Response to the INVITE and UPDATE Requests 
  *
  * The NUTAG_SESSION_TIMER() value is also used when sending the final
  * response to the INVITE or UPDATE requests. If the NUTAG_SESSION_TIMER()
- * value is 0 or the value in the @SessionExpires header of the requeast is
+ * value is 0 or the value in the @SessionExpires header of the request is
  * lower than the value in NUTAG_SESSION_TIMER(), the value from the
  * incoming @SessionExpires header is used. However, if the value in
  * @SessionExpires is lower than the minimal acceptable session expiration
  * interval specified with the tag NUTAG_MIN_SE() the request is
  * automatically rejected with <i>422 Session Timer Too Small</i>.
  *
+ * @par Refreshes
+ *
+ * After the initial INVITE request, the SIP session is refreshed at the
+ * intervals indicated by the @SessionExpires header returned in the 2XX
+ * response. The party indicated with the "refresher" parameter of the
+ * @SessionExpires header sends a re-INVITE requests (or an UPDATE
+ * request if NUTAG_UPDATE_REFRESH(1) parameter tag has been set).
+ * 
  * @par When to Use NUTAG_SESSION_TIMER()?
  *
  * The session time extension is enabled ("timer" feature tag is included in
  * @Supported header) but not activated by default (no @SessionExpires
  * header is included in the requests or responses by default). Using
- * non-zero value with NUTAG_SESSION_TIMER() activates it. When the
- * extension is activated, @nua refreshes the call state by sending periodic
- * re-INVITE or UPDATE requests unless the remote end indicated that it will
- * take care of refreshes.
+ * non-zero value with NUTAG_SESSION_TIMER() or NUTAG_SESSION_REFRESHER()
+ * activates it. When the extension is activated, @nua refreshes the call
+ * state by sending periodic re-INVITE or UPDATE requests unless the remote
+ * end indicated that it will take care of refreshes.
  *
  * The session timer extension is mainly useful for proxies or back-to-back
  * user agents that keep call state. The call state is "soft" meaning that
@@ -512,6 +543,10 @@
  * will be destroyed. An ordinary user-agent can also make use of session
  * timer if it cannot get any activity feedback from RTP or other media.
  *
+ * @note The session timer extension is used only if the feature
+ * tag "timer" is listed in the @Supported header, set by NUTAG_SUPPORTED(),
+ * SIPTAG_SUPPORTED(), or SIPTAG_SUPPORTED_STR() tags.
+ *
  * @par Used with
  *    nua_invite(), nua_update(), nua_respond() \n
  *    nua_set_params() or nua_set_hparams() \n
@@ -530,8 +565,8 @@
  * Corresponding tag taking reference parameter is NUTAG_SESSION_TIMER_REF()
  *
  * @sa NUTAG_SUPPORTED(), NUTAG_MIN_SE(), NUTAG_SESSION_REFRESHER(),
- * nua_invite(), #nua_r_invite, #nua_i_invite, nua_update(), #nua_r_update,
- * #nua_i_update, 
+ * nua_invite(), #nua_r_invite, #nua_i_invite, nua_respond(), 
+ * nua_update(), #nua_r_update, #nua_i_update, 
  * NUTAG_UPDATE_REFRESH(), @RFC4028, @SessionExpires, @MinSE
  */
 #define NUTAG_SESSION_TIMER(x)  nutag_session_timer, tag_uint_v((x))
@@ -571,6 +606,7 @@
 #define NUTAG_MIN_SE_REF(x)     nutag_min_se_ref, tag_uint_vr((&(x)))
 SOFIAPUBVAR tag_typedef_t nutag_min_se_ref;
 
+/** Enumeration type of NUTAG_SESSION_REFRESHER(). */
 enum nua_session_refresher {
   nua_no_refresher,		/**< Disable session timer. */
   nua_local_refresher,		/**< Session refresh by local end. */
@@ -1074,7 +1110,7 @@
  *
  * The outbound option string can specify how the NAT traversal is handled.
  * The option tokens are as follows:
- * - "gruuize": try to generate a GRUU
+ * - "gruuize": try to generate a GRUU contact from REGISTER response
  * - "outbound": use SIP outbound extension (off by default)
  * - "validate": validate registration behind a NAT by sending OPTIONS to self
  * - "natify": try to traverse NAT
@@ -1084,6 +1120,10 @@
  * An option token with "no-" or "not-" prefix turns the option off. For
  * example, if you want to try to traverse NATs but not to use OPTIONS
  * keepalive, use NUTAG_OUTBOUND("natify no-options-keepalive").
+ * 
+ * An empty string can be passed to let the stack choose the
+ * default values for outbound usage (in the 1.12.5 release, the
+ * defaults are: "gruuize no-outbound validate use-port options-keepalive").
  *
  * @note
  * Options string is used so that no new tags need to be added when the
@@ -1207,7 +1247,7 @@
  *    nua_create()
  *
  * @par Parameter type
- *    msg_mclass_t *
+ *    msg_mclass_t const *
  *
  * @par Values
  *    Pointer to an extended SIP parser.
@@ -1242,8 +1282,45 @@
 #define NUTAG_AUTH_REF(x)	    nutag_auth_ref, tag_str_vr(&(x))
 SOFIAPUBVAR tag_typedef_t nutag_auth_ref;
 
+/** Authentication caching policy
+ *
+ * @par Used with
+ *    nua_set_params(), nua_set_hparams() \n
+ *    nua_get_params(), nua_get_hparams() \n
+ *    @NUA_HPARAM_CALLS 
+ *
+ * @par Parameter type
+ *    enum nua_auth_cache
+ *
+ * @par Values
+ *    - nua_auth_cache_dialog (0) - include credentials within dialog
+ *    - nua_auth_cache_challenged (1) - include credentials only when 
+ *                                      challenged
+ *    
+ * Corresponding tag taking reference parameter is NUTAG_AUTH_CACHE_REF().
+ *
+ * @NEW_1_12_6
+ */
+#define NUTAG_AUTH_CACHE(x)   nutag_auth_cache, tag_int_v(x)
+SOFIAPUBVAR tag_typedef_t nutag_auth_cache;
+
+#define NUTAG_AUTH_CACHE_REF(x) nutag_auth_cache_ref, tag_int_vr(&(x))
+SOFIAPUBVAR tag_typedef_t nutag_auth_cache_ref;
+
+/** Authentication caching policy. @NEW_1_12_6 */
+enum nua_auth_cache {
+  /** Include credentials within dialog (default) */
+  nua_auth_cache_dialog = 0,
+  /** Include credentials only when challenged */
+  nua_auth_cache_challenged = 1,
+  _nua_auth_cache_invalid
+};
+
 /** Keepalive interval in milliseconds.
  *
+ * This setting applies to OPTIONS/STUN keepalives. See documentation 
+ * for nua_register() for more detailed information.
+ *
  * @par Used with
  *    nua_register()   \n
  *    nua_set_params() \n
@@ -1269,6 +1346,8 @@
 
 /** Transport-level keepalive interval for streams.
  *
+ * See documentation for nua_register() for more detailed information.
+ *
  * @par Used with
  *    nua_register()   \n
  *    nua_set_params() \n
@@ -1327,6 +1406,7 @@
  *
  * @par Used with
  *    nua_register(), nua_set_hparams(), nua_set_params().
+ *    nua_invite(), nua_respond(), nua_subscribe(), nua_notify()
  *
  * @par Parameter type
  *    string (char *)
@@ -1358,6 +1438,7 @@
  *
  * @par Used with
  *    nua_register(), nua_set_hparams(), nua_set_params().
+ *    nua_invite(), nua_respond(), nua_subscribe(), nua_notify()
  *
  * @par Parameter type
  *    string (char *)
@@ -1388,7 +1469,8 @@
  * user-agent.
  *
  * @par Used with
- *    nua_register(), nua_set_hparams(), nua_set_params().
+ *    nua_register(), nua_set_hparams(), nua_set_params(), 
+ *    nua_invite(), nua_respond(), nua_subscribe(), nua_notify()
  *
  * @par Parameter type
  *    string (char *)
@@ -1735,7 +1817,8 @@
  *
  * Corresponding tag taking reference parameter is NUTAG_APPL_METHOD_REF()
  *
- * @since Working since @VERSION_1_12_5. 
+ * @since Working since @VERSION_1_12_5. Handling of client-side PRACK and
+ * UPDATE was fixed in @VERSION_1_12_6.
  */
 #define NUTAG_APPL_METHOD(x)     nutag_appl_method, tag_str_v(x)
 SOFIAPUBVAR tag_typedef_t nutag_appl_method;
@@ -1859,26 +1942,39 @@
 /** Get name for NUA call state */
 SOFIAPUBFUN char const *nua_callstate_name(enum nua_callstate state);
 
-/** Subscription state
+/**Subscription state.
  *
  * @par Used with
+ *    #nua_notify() \n
  *    #nua_r_subscribe \n
- *    #nua_i_notify
+ *    #nua_i_notify \n
+ *    #nua_i_subscribe \n
+ *    #nua_r_notify \n
+ *    nua_notify() \n
+ *    nua_respond() to SUBSCRIBE
  *
  * @par Parameter type
  *    int
  *
  * @par Values
- *   @c nua_substate_embryonic (0) \n
- *   @c nua_substate_pending (1) \n
- *   @c nua_substate_active (2) \n
- *   @c nua_substate_terminated	(3) \n
- *
- * see
- * <a href="http://www.ietf.org/rfc/rfc3265.txt">RFC 3265</a>
+ *   - #nua_substate_embryonic (0)
+ *   - #nua_substate_pending (1)
+ *   - #nua_substate_active (2)
+ *   - #nua_substate_terminated (3)
+ *
+ * Note that the @SubscriptionState or @Expires headers specified by
+ * application overrides the subscription state specified by
+ * NUTAG_SUBSTATE(). Application can terminate subscription by including
+ * NUTAG_SUBSTATE(nua_substate_terminated), @SubscriptionState with value
+ * "terminated" or @Expires header with value 0 in the NOTIFY request sent
+ * by nua_notify().
+ *
+ * @sa @RFC3265, @SubscriptionState, SIPTAG_SUBSCRIPTION_STATE(),
+ * SIPTAG_SUBSCRIPTION_STATE_STR(), #nua_r_subscribe, #nua_i_subscribe,
+ * #nua_i_refer, #nua_r_notify, #nua_i_notify.
  *
  * Corresponding tag taking reference parameter is NUTAG_SUBSTATE_REF()
-*/
+ */
 #define NUTAG_SUBSTATE(x) nutag_substate, tag_int_v(x)
 SOFIAPUBVAR tag_typedef_t nutag_substate;
 
@@ -1896,6 +1992,46 @@
   nua_substate_terminated = nea_terminated /**< Terminated subscription */
 };
 
+/** Return name of subscription state. @NEW_1_12_5. */
+SOFIAPUBFUN char const *nua_substate_name(enum nua_substate substate);
+
+/** Convert string to enum nua_substate. @NEW_1_12_5. */
+SOFIAPUBFUN enum nua_substate nua_substate_make(char const *sip_substate);
+
+/**Send unsolicited NOTIFY request.
+ *
+ * Some applications may require sending unsolicited NOTIFY requests, that
+ * is, NOTIFY without SUBSCRIBE or REFER request sent by event watcher. 
+ * However, sending NOTIFY request requires an existing dialog usage by
+ * default. If NUTAG_NEWSUB(1) is included in the nua_notify() the usage
+ * is create the usage by itself.
+ *
+ * If you want to create a subscription that does not terminate immediately
+ * include SIPTAG_SUBSCRIPTION_STATE_STR() with an "expires" parameter in
+ * the argument list, too.
+ *
+ * @par Used with
+ *    nua_notify()
+ *
+ * @par Parameter type
+ *    int (boolean)
+ *
+ * @par Values
+ *   - 0 - false (default) - do not create new subscription 
+ *         but reject NOTIFY with 481 locally \n
+ *   - 1 - true - create a subscription if it does not exist \n
+ *
+ * Corresponding tag taking reference parameter is NUTAG_NEWSUB().
+ *
+ * @since @NEW_1_12_5.
+ */
+#define NUTAG_NEWSUB(x)   nutag_newsub, tag_bool_v(x)
+SOFIAPUBVAR tag_typedef_t nutag_newsub;
+
+#define NUTAG_NEWSUB_REF(x) nutag_newsub_ref, tag_bool_vr(&(x))
+SOFIAPUBVAR tag_typedef_t nutag_newsub_ref;
+
+
 /**Default lifetime for implicit subscriptions created by REFER.
  *
  * Default expiration time in seconds for implicit subscriptions created by

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_100rel.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_100rel.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_100rel.c	Tue Apr 24 10:14:28 2007
@@ -101,24 +101,17 @@
 
   save_event_in_list(ctx, event, ep, call);
 
-  switch (event) {
-  case nua_i_prack:
-    if (200 <= status && status < 300) {
-      RESPOND(ep, call, nh, SIP_200_OK, 
-	      NUTAG_INCLUDE_EXTRA_SDP(1),
-	      TAG_END());
-      ep->next_condition = until_ready;
-    }
-  default:
-    break;
-  }
-
   switch (callstate(tags)) {
   case nua_callstate_received:
     RESPOND(ep, call, nh, SIP_180_RINGING,
 	    TAG_IF(call->sdp, SOATAG_USER_SDP_STR(call->sdp)),
 	    TAG_END());
+    RESPOND(ep, call, nh, SIP_200_OK, 
+	    NUTAG_INCLUDE_EXTRA_SDP(1),
+	    TAG_END());
     return 0;
+  case nua_callstate_ready:
+    return 1;
   case nua_callstate_terminated:
     if (call)
       nua_handle_destroy(call->nh), call->nh = NULL;
@@ -170,6 +163,7 @@
 
   nua_set_params(ctx->b.nua,
 		 NUTAG_EARLY_MEDIA(1),
+		 NUTAG_SESSION_TIMER(180),
 		 TAG_END());
   run_b_until(ctx, nua_r_set_params, until_final_response);
 
@@ -411,17 +405,21 @@
   TEST_1(is_answer_recv(e->data->e_tags));
   TEST_1(!is_offer_sent(e->data->e_tags));
 
-  if (md5 && !md5sess) {
-    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_prack);
-    TEST(e->data->e_status, 407);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_prack);
+
+  if (e->data->e_status != 200 && md5 && !md5sess) {
+    if (e->data->e_status != 100) {
+      TEST(e->data->e_status, 407);
+    }
 
     TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
     TEST(callstate(e->data->e_tags), nua_callstate_proceeding);
     TEST_1(!is_answer_recv(e->data->e_tags));
     TEST_1(!is_offer_sent(e->data->e_tags));
+
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_prack);
   }
 
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_prack);
   TEST(e->data->e_status, 200);
 
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
@@ -552,6 +550,8 @@
   }
 }
 
+int respond_483_to_prack(CONDITION_PARAMS);
+
 int test_183rel(struct context *ctx)
 {
   BEGIN();
@@ -661,30 +661,110 @@
   if (print_headings)
     printf("TEST NUA-10.2.1: PASSED\n");
 
+  /* Test for graceful termination by client because 483 sent to PRACK */
   if (print_headings)
-    printf("TEST NUA-10.2.2: terminate call\n");
+    printf("TEST NUA-10.2.2: graceful termination because PRACK fails\n");
 
-  BYE(b, b_call, b_call->nh, TAG_END());
-  run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+  nua_set_hparams(b_call->nh, NUTAG_APPL_METHOD("PRACK"),
+		  NUTAG_AUTOANSWER(0), TAG_END());
+  run_b_until(ctx, nua_r_set_params, NULL);
 
-  /* B transitions:
-   READY --(T2)--> TERMINATING: nua_bye()
-   TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
+  INVITE(a, a_call, a_call->nh, TAG_END());
+
+  run_ab_until(ctx, -1, until_terminated, -1, respond_483_to_prack);
+
+  /* Client transitions:
+     INIT -(C1)-> CALLING: nua_invite(), nua_i_state
+     CALLING -(C2)-> TERMINATING: nua_r_invite, nua_i_state, 
+                                  nua_r_prack, nua_i_state
+     TERMINATING -(T1)-> TERMINATED: nua_r_invite, nua_i_state
   */
-  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_r_bye);
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(is_offer_sent(e->data->e_tags));
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 183);
+
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
-  TEST_1(!e->next);
-  free_events_in_list(ctx, b->events);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding);
+  TEST_1(is_answer_recv(e->data->e_tags));
+  TEST_1(!is_offer_sent(e->data->e_tags));
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_prack);
+  TEST(e->data->e_status, 483);
 
-  /* A: READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state */
-  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_bye);
-  TEST(e->data->e_status, 200);
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST(callstate(e->data->e_tags), nua_callstate_terminating);
+
+  {
+    int bye = 1, cancel = 1, invite = 1;
+
+    while (bye || cancel || invite) {
+      TEST_1(e = e->next); 
+      if (e->data->e_event == nua_r_bye) {
+	TEST_E(e->data->e_event, nua_r_bye);
+	TEST(e->data->e_status, 200);
+	TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+	TEST(callstate(e->data->e_tags), nua_callstate_terminated);
+	bye = 0;
+      }
+      else if (e->data->e_event == nua_r_invite) {
+	TEST_E(e->data->e_event, nua_r_invite);
+	TEST(e->data->e_status, 487);
+	invite = 0;
+      }
+      else if (e->data->e_event == nua_r_cancel) {
+	TEST_E(e->data->e_event, nua_r_cancel);
+	TEST_1(e->data->e_status == 200 || e->data->e_status == 481);
+	cancel = 0;
+      }
+    }
+  }
   TEST_1(!e->next);
+
   free_events_in_list(ctx, a->events);
 
+  /*
+   Server transitions:
+   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
+   RECEIVED -(S2a)-> EARLY: nua_respond(), nua_i_state, nua_respond(to PRACK)
+   EARLY -(S3b)-> TERMINATED: nua_i_bye, nua_i_state
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+
+  /* Responded with 183 Session Progress */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(e->data->e_status, 183);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(is_answer_sent(e->data->e_tags));
+
+  /* 183 is PRACKed, PRACK is responded with 483 */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_prack);
+
+  /* Client terminates the call 
+     - we may (it is received before BYE) or may not (received after BYE) 
+       get CANCEL request 
+  */
+  TEST_1(e = e->next);
+  if (e->data->e_event == nua_i_cancel) {
+    TEST_E(e->data->e_event, nua_i_cancel);
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+    TEST(callstate(e->data->e_tags), nua_callstate_ready);
+    TEST_1(e = e->next);
+  }
+
+  TEST_E(e->data->e_event, nua_i_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, b->events);
+
   nua_handle_destroy(a_call->nh), a_call->nh = NULL;
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
@@ -694,6 +774,39 @@
   END();
 }
 
+int respond_483_to_prack(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  switch (event) {
+  case nua_i_prack:
+    if (status <= 200) {
+      RESPOND(ep, call, nh, 483, "Foo",
+	      NUTAG_WITH_THIS(nua),
+	      TAG_END());
+    }
+  default:
+    break;
+  }
+
+  save_event_in_list(ctx, event, ep, call);
+
+  switch (callstate(tags)) {
+  case nua_callstate_received:
+    RESPOND(ep, call, nh, SIP_183_SESSION_PROGRESS,
+	    TAG_IF(call->sdp, SOATAG_USER_SDP_STR(call->sdp)),
+	    TAG_END());
+    return 0;
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
+    return 1;
+  default:
+    return 0;
+  }
+}
+
 /*
  X  ringing_updated   ep
  |-------INVITE------>|
@@ -858,6 +971,8 @@
 
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_update);
   TEST(e->data->e_status, 200);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_session_expires);
 
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_proceeding);
@@ -1085,14 +1200,14 @@
 
   nua_set_params(ctx->a.nua,
 		 NUTAG_EARLY_MEDIA(1),
-		 SIPTAG_SUPPORTED_STR("100rel, precondition"),
+		 SIPTAG_SUPPORTED_STR("100rel, precondition, timer"),
 		 TAG_END());
   run_a_until(ctx, nua_r_set_params, until_final_response);
 
   nua_set_params(ctx->b.nua,
 		 NUTAG_EARLY_MEDIA(1),
 		 NUTAG_ONLY183_100REL(1),
-		 SIPTAG_SUPPORTED_STR("100rel, precondition"),
+		 SIPTAG_SUPPORTED_STR("100rel, precondition, timer"),
 		 TAG_END());
   run_b_until(ctx, nua_r_set_params, until_final_response);
 
@@ -1578,6 +1693,310 @@
   END();
 }
  
+int cancel_when_pracked(CONDITION_PARAMS);
+int alert_call(CONDITION_PARAMS);
+
+int test_180rel_cancel1(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+
+  if (print_headings)
+    printf("TEST NUA-10.6: CANCEL after PRACK\n");
+
+/* Test for 100rel:
+
+   A			B
+   |-------INVITE------>|
+   |<----100 Trying-----|
+   |			|
+   |<-------180---------|
+   |-------PRACK------->|
+   |<-------200---------|
+   |			|
+   |------CANCEL------->|
+   |<------200 OK-------|
+   |			|
+   |<-------487---------|
+   |--------ACK-------->|
+   |			|
+
+*/
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
+
+  nua_set_params(ctx->a.nua,
+		 NUTAG_EARLY_MEDIA(1),
+		 NUTAG_ONLY183_100REL(0),
+		 TAG_END());
+  run_a_until(ctx, nua_r_set_params, until_final_response);
+
+  nua_set_params(ctx->b.nua,
+		 NUTAG_EARLY_MEDIA(1),
+		 NUTAG_ONLY183_100REL(0),
+		 TAG_END());
+  run_b_until(ctx, nua_r_set_params, until_final_response);
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, cancel_when_pracked, -1, alert_call);
+
+  /* Client transitions:
+     INIT -(C1)-> CALLING: nua_invite(), nua_i_state
+     CALLING -(C2)-> PROCEEDING: nua_r_invite, nua_i_state, nua_r_prack
+     PROCEEDING -(C3+C4)-> TERMINATED: nua_r_invite, nua_i_state
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(is_offer_sent(e->data->e_tags));
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding);
+  TEST_1(is_answer_recv(e->data->e_tags));
+  TEST_1(!is_offer_sent(e->data->e_tags));
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_prack);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_cancel);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 487);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+
+  /*
+   Server transitions:
+   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
+   RECEIVED -(S2a)-> EARLY: nua_respond(), nua_i_state
+   Option A:
+   EARLY -(S10)-> TERMINATED: nua_i_cancel, nua_i_state
+   Option B:
+   EARLY -(S3b)-> COMPLETED: nua_respond(), nua_i_state
+   COMPLETED -(S4)-> READY: nua_i_ack, nua_i_state
+   READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state   
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+
+  /* Responded with 180 Ringing */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(is_answer_sent(e->data->e_tags));
+
+  /* 180 is PRACKed */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_prack);
+  /* Does not have effect on call state */
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_cancel);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+
+  free_events_in_list(ctx, b->events);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-10.6: PASSED\n");
+  
+  END();
+}
+
+int cancel_when_pracked(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  if (event == nua_r_prack)
+    CANCEL(ep, call, nh, TAG_END());
+
+  switch (callstate(tags)) {
+  case nua_callstate_proceeding:
+    return 0;
+  case nua_callstate_ready:
+    return 1;
+  case nua_callstate_terminated:
+    return 1;
+  default:
+    return 0;
+  }
+}
+
+int test_180rel_cancel2(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+
+  if (print_headings)
+    printf("TEST NUA-10.7: CANCEL after 100rel 180\n");
+
+/* Test for 100rel:
+
+   A			B
+   |-------INVITE------>|
+   |<----100 Trying-----|
+   |			|
+   |<-------180---------|
+   |-------PRACK------->|
+   |<-------200---------|
+   |			|
+   |------CANCEL------->|
+   |<------200 OK-------|
+   |			|
+   |<-------487---------|
+   |--------ACK-------->|
+   |			|
+
+*/
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
+
+  nua_set_params(ctx->a.nua,
+		 NUTAG_EARLY_MEDIA(1),
+		 NUTAG_ONLY183_100REL(0),
+		 TAG_END());
+  run_a_until(ctx, nua_r_set_params, until_final_response);
+
+  nua_set_params(ctx->b.nua,
+		 NUTAG_EARLY_MEDIA(1),
+		 NUTAG_ONLY183_100REL(0),
+		 TAG_END());
+  run_b_until(ctx, nua_r_set_params, until_final_response);
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, cancel_when_ringing, -1, accept_pracked2);
+
+  /* Client transitions:
+     INIT -(C1)-> CALLING: nua_invite(), nua_i_state
+     CALLING -(C2)-> PROCEEDING: nua_r_invite, nua_i_state, nua_r_prack
+     PROCEEDING -(C3+C4)-> TERMINATED: nua_r_invite, nua_i_state
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(is_offer_sent(e->data->e_tags));
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding);
+  TEST_1(is_answer_recv(e->data->e_tags));
+  TEST_1(!is_offer_sent(e->data->e_tags));
+
+#define NEXT_SKIP_PRACK_CANCEL() \
+  do { TEST_1(e = e->next); } \
+  while (e->data->e_event == nua_r_prack || e->data->e_event == nua_r_cancel)
+
+  NEXT_SKIP_PRACK_CANCEL();
+
+  TEST_E(e->data->e_event, nua_r_invite);
+  if (e->data->e_status == 487) {
+    TEST(e->data->e_status, 487);
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+    TEST(callstate(e->data->e_tags), nua_callstate_terminated);
+    TEST_1(!e->next);
+  }
+  else {
+    TEST(e->data->e_status, 200);
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+    TEST(callstate(e->data->e_tags), nua_callstate_ready);
+
+    BYE(a, a_call, a_call->nh, TAG_END());
+    run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+
+    NEXT_SKIP_PRACK_CANCEL(); TEST_E(e->data->e_event, nua_r_bye);
+    TEST(e->data->e_status, 200);
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+    TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+    TEST_1(!e->next);
+  }
+
+  free_events_in_list(ctx, a->events);
+
+  /*
+   Server transitions:
+   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
+   RECEIVED -(S2a)-> EARLY: nua_respond(), nua_i_state
+   Option A:
+   EARLY -(S10)-> TERMINATED: nua_i_cancel, nua_i_state
+   Option B:
+   EARLY -(S3b)-> COMPLETED: nua_respond(), nua_i_state
+   COMPLETED -(S4)-> READY: nua_i_ack, nua_i_state
+   READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state   
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+
+  /* Responded with 180 Ringing */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(is_answer_sent(e->data->e_tags));
+
+  /* 180 is PRACKed */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_prack);
+  /* Does not have effect on call state */
+
+  if (e->next->data->e_event == nua_i_cancel) {
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_cancel);
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+    TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  }
+  else {
+    /* Respond with 200 OK */
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+    TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
+    TEST_1(!is_offer_answer_done(e->data->e_tags));
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_ack);
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+    TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
+    TEST_1(!is_offer_answer_done(e->data->e_tags));
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_bye);
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+    TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  }
+
+  free_events_in_list(ctx, b->events);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-10.7: PASSED\n");
+  
+  END();
+}
+
 
 int test_100rel(struct context *ctx)
 {
@@ -1589,6 +2008,28 @@
   retval = test_preconditions(ctx); RETURN_ON_SINGLE_FAILURE(retval);
   retval = test_preconditions2(ctx); RETURN_ON_SINGLE_FAILURE(retval);
   retval = test_update_by_uas(ctx); RETURN_ON_SINGLE_FAILURE(retval);
+  retval = test_180rel_cancel1(ctx); RETURN_ON_SINGLE_FAILURE(retval);
+  retval = test_180rel_cancel2(ctx); RETURN_ON_SINGLE_FAILURE(retval);
+
+  nua_set_params(ctx->a.nua,
+		 NUTAG_EARLY_MEDIA(0),
+		 SIPTAG_SUPPORTED(ctx->a.supported),
+		 TAG_END());
+  run_a_until(ctx, nua_r_set_params, until_final_response);
+
+  nua_set_params(ctx->b.nua,
+		 NUTAG_EARLY_MEDIA(0),
+		 NUTAG_ONLY183_100REL(0),
+		 SIPTAG_SUPPORTED(ctx->b.supported),
+		 TAG_END());
+  run_b_until(ctx, nua_r_set_params, until_final_response);
+
+  nua_set_params(ctx->c.nua,
+		 NUTAG_EARLY_MEDIA(0),
+		 NUTAG_ONLY183_100REL(0),
+		 SIPTAG_SUPPORTED(ctx->c.supported),
+		 TAG_END());
+  run_c_until(ctx, nua_r_set_params, until_final_response);
 
   return retval;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_basic_call.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_basic_call.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_basic_call.c	Tue Apr 24 10:14:28 2007
@@ -117,6 +117,8 @@
   case nua_callstate_received:
     RESPOND(ep, call, nh, SIP_180_RINGING, 
 	    TAG_IF(call->sdp, SOATAG_USER_SDP_STR(call->sdp)),
+	    NUTAG_M_DISPLAY("Bob"),
+	    NUTAG_M_USERNAME("b+b"),
 	    TAG_END());
     return 0;
   case nua_callstate_early:
@@ -203,9 +205,16 @@
   sip_replaces_t *repa, *repb;
   nua_handle_t *nh;
 
+  static int once = 0;
+  sip_time_t se, min_se;
+
   if (print_headings)
     printf("TEST NUA-3.1: Basic call\n");
 
+  /* Disable session timer from proxy */
+  test_proxy_get_session_timer(ctx->p, &se, &min_se); 
+  test_proxy_set_session_timer(ctx->p, 0, 0); 
+
   a_call->sdp = "m=audio 5008 RTP/AVP 8";
   b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
 
@@ -217,6 +226,8 @@
   INVITE(a, a_call, a_call->nh,
 	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
 	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 NUTAG_M_USERNAME("a+a"),
+	 NUTAG_M_DISPLAY("Alice"),
 	 TAG_END());
 
   run_ab_until(ctx, -1, until_ready, -1, accept_call_with_early_sdp);
@@ -263,8 +274,15 @@
   TEST_1(is_answer_recv(e->data->e_tags));
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
   TEST(e->data->e_status, 200);
-  TEST_1(sip->sip_payload);
   TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_payload);
+  TEST_1(sip->sip_contact);
+  TEST_S(sip->sip_contact->m_display, "Bob");
+  TEST_S(sip->sip_contact->m_url->url_user, "b+b");
+  if (!once) {
+    /* The session expiration is not used by default. */
+    TEST_1(sip->sip_session_expires == NULL);
+  }
   /* Test that B uses application-specific contact */
   if (ctx->proxy_tests)
     TEST_1(sip->sip_contact->m_url->url_user);
@@ -282,6 +300,14 @@
   */
   TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
   TEST(e->data->e_status, 100);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_contact);
+  TEST_S(sip->sip_contact->m_display, "Alice");
+  TEST_S(sip->sip_contact->m_url->url_user, "a+a");
+  if (!once++) {
+    /* The Session-Expires header is not used by default. */
+    TEST_1(sip->sip_session_expires == NULL);
+  }
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
   TEST_1(is_offer_recv(e->data->e_tags));
@@ -331,6 +357,8 @@
   nua_handle_destroy(a_call->nh), a_call->nh = NULL;
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
+  test_proxy_set_session_timer(ctx->p, se, min_se); 
+
   if (print_headings)
     printf("TEST NUA-3.1: PASSED\n");
 
@@ -404,6 +432,7 @@
   INVITE(a, a_call, a_call->nh,
 	 NUTAG_URL(b->contact->m_url),
 	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 NUTAG_ALLOW("INFO"),
 	 TAG_END());
 
   run_ab_until(ctx, -1, until_ready, -1, accept_early_answer);
@@ -466,32 +495,96 @@
   TEST_1(nua_handle_has_active_call(b_call->nh));
   TEST_1(!nua_handle_has_call_on_hold(b_call->nh));
 
+  /* Send a NOTIFY from B to A */
+  if (print_headings)
+    printf("TEST NUA-3.2.2: send a NOTIFY within a dialog\n");
+
+  /* Make A to accept NOTIFY */
+  nua_set_params(a->nua, NUTAG_APPL_METHOD("NOTIFY"), TAG_END());
+  run_a_until(ctx, nua_r_set_params, until_final_response);
+
+  NOTIFY(b, b_call, b_call->nh,
+	 NUTAG_NEWSUB(1),
+	 SIPTAG_SUBJECT_STR("NUA-3.2.2"),
+	 SIPTAG_EVENT_STR("message-summary"),
+	 SIPTAG_CONTENT_TYPE_STR("application/simple-message-summary"),
+	 SIPTAG_PAYLOAD_STR("Messages-Waiting: no"),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, accept_notify, -1, save_until_final_response);
+
+  /* Notifier events: nua_r_notify */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_r_notify);
+  TEST(e->data->e_status, 200);
+  TEST_1(tl_find(e->data->e_tags, nutag_substate));
+  TEST(tl_find(e->data->e_tags, nutag_substate)->t_value,
+       nua_substate_terminated);
+
+  /* watcher events: nua_i_notify */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_notify);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_subscription_state);
+  TEST_S(sip->sip_subscription_state->ss_substate, "terminated");
+  TEST_1(tl_find(e->data->e_tags, nutag_substate));
+  TEST(tl_find(e->data->e_tags, nutag_substate)->t_value, 
+       nua_substate_terminated);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  if (print_headings)
+    printf("TEST NUA-3.2.2: PASSED\n");
+
+  INFO(b, b_call, b_call->nh, TAG_END());
   BYE(b, b_call, b_call->nh, TAG_END());
+  INFO(b, b_call, b_call->nh, TAG_END());
+
   run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
 
+  while (!b->events->head || /* r_info */
+	 !b->events->head->next || /* r_bye */
+	 !b->events->head->next->next || /* i_state */
+	 !b->events->head->next->next->next) /* r_info */
+    run_ab_until(ctx, -1, save_events, -1, save_until_final_response);
+
   /* B transitions:
+   nua_info()
    READY --(T2)--> TERMINATING: nua_bye()
+   nua_r_info with 200
    TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
+   nua_r_info with 481/900
   */
-  TEST_1(e = b->events->head);  TEST_E(e->data->e_event, nua_r_bye);
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_r_info);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_bye);
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_info);
+  TEST_1(e->data->e_status >= 900 || e->data->e_status == 481);
   TEST_1(!e->next);
   free_events_in_list(ctx, b->events);
 
   TEST_1(!nua_handle_has_active_call(b_call->nh));
 
   /* A transitions:
+     nua_i_info
      READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state
   */
-  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_bye);
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_info);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_bye);
   TEST(e->data->e_status, 200);
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
   TEST_1(!e->next);
   free_events_in_list(ctx, a->events);
 
-  TEST_1(!nua_handle_has_active_call(a_call->nh));
+  BYE(a, a_call, a_call->nh, TAG_END());
+  run_a_until(ctx, -1, save_until_final_response);
+
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_bye);
+  TEST_1(e->data->e_status >= 900);
+  TEST_1(!e->next);
+  free_events_in_list(ctx, a->events);
 
   nua_handle_destroy(a_call->nh), a_call->nh = NULL;
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
@@ -502,8 +595,376 @@
   END();
 }
 
+/* ====================================================================== */
+
+/* Basic calls with soa disabled */
+
+int accept_call_no_media(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  switch (callstate(tags)) {
+  case nua_callstate_received:
+    RESPOND(ep, call, nh, SIP_180_RINGING, 
+	    NUTAG_MEDIA_ENABLE(0),
+	    TAG_END());
+    return 0;
+  case nua_callstate_early:
+    RESPOND(ep, call, nh, SIP_200_OK,
+	    TAG_IF(call->sdp, SIPTAG_CONTENT_TYPE_STR("application/sdp")),
+	    TAG_IF(call->sdp, SIPTAG_PAYLOAD_STR(call->sdp)),
+	    TAG_END());
+    return 0;
+  case nua_callstate_ready:
+    return 1;
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
+    return 1;
+  default:
+    return 0;
+  }
+}
+
+int test_basic_call_3(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+  sip_t const *sip;
+
+  if (print_headings)
+    printf("TEST NUA-3.3: Basic call with media disabled\n");
+
+  a_call->sdp = "v=0\r\n"
+    "o=- 1 1 IN IP4 127.0.0.1\r\n"
+    "s=-\r\n"
+    "c=IN IP4 127.0.0.1\r\n"
+    "t=0 0\r\n"
+    "m=audio 5008 RTP/AVP 8\r\n";
+
+  b_call->sdp = 
+    "v=0\r\n"
+    "o=- 2 1 IN IP4 127.0.0.1\r\n"
+    "s=-\r\n"
+    "c=IN IP4 127.0.0.1\r\n"
+    "t=0 0\r\n"
+    "m=audio 5010 RTP/AVP 0 8\r\n";
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, 
+				 SIPTAG_TO_STR("<sip:b at x.org>"),
+				 TAG_END()));
+
+  TEST_1(!nua_handle_has_active_call(a_call->nh));
+  TEST_1(!nua_handle_has_call_on_hold(a_call->nh));
+
+  INVITE(a, a_call, a_call->nh,
+	 NUTAG_MEDIA_ENABLE(0),
+	 NUTAG_URL(b->contact->m_url),
+	 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
+	 SIPTAG_PAYLOAD_STR(a_call->sdp),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, until_ready, -1, accept_call_no_media);
+
+  /* Client transitions:
+     INIT -(C1)-> CALLING: nua_invite(), nua_i_state
+     CALLING -(C2)-> PROCEEDING: nua_r_invite, nua_i_state
+     PROCEEDING -(C3+C4)-> READY: nua_r_invite, nua_i_state
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(is_offer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); /* PROCEEDING */
+  TEST_1(!is_answer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 200);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_content_type); 
+  TEST_S(sip->sip_content_type->c_type, "application/sdp");
+  TEST_1(sip->sip_payload);	/* there is sdp in 200 OK */
+  TEST_1(sip->sip_contact);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
+  TEST_1(is_answer_recv(e->data->e_tags));
+  TEST_1(!e->next);
+  free_events_in_list(ctx, a->events);
+
+  TEST_1(nua_handle_has_active_call(a_call->nh));
+  TEST_1(!nua_handle_has_call_on_hold(a_call->nh));
+
+  /*
+   Server transitions:
+   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
+   RECEIVED -(S2a)-> EARLY: nua_respond(), nua_i_state
+   EARLY -(S3b)-> COMPLETED: nua_respond(), nua_i_state
+   COMPLETED -(S4)-> READY: nua_i_ack, nua_i_state
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(!is_answer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
+  TEST_1(is_answer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_ack);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
+  TEST_1(!e->next);
+  free_events_in_list(ctx, b->events);
+
+  TEST_1(nua_handle_has_active_call(b_call->nh));
+  TEST_1(!nua_handle_has_call_on_hold(b_call->nh));
+
+  BYE(b, b_call, b_call->nh, TAG_END());
+
+  run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+
+  /* B transitions:
+   READY --(T2)--> TERMINATING: nua_bye()
+   TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_r_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+  free_events_in_list(ctx, b->events);
+
+  TEST_1(!nua_handle_has_active_call(b_call->nh));
+
+  /* A transitions:
+     nua_i_info
+     READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_bye);
+  TEST(e->data->e_status, 200);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+  free_events_in_list(ctx, a->events);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-3.3: PASSED\n");
+
+  END();
+}
+
+int ack_when_completing_no_media(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  switch (callstate(tags)) {
+  case nua_callstate_completing:
+    ACK(ep, call, nh, 
+	TAG_IF(call->sdp, SIPTAG_CONTENT_TYPE_STR("application/sdp")),
+	TAG_IF(call->sdp, SIPTAG_PAYLOAD_STR(call->sdp)),
+	TAG_END());
+    return 0;
+  case nua_callstate_ready:
+    return 1;
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
+    return 1;
+  default:
+    return 0;
+  }
+}
+
+int accept_call_no_media2(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  switch (callstate(tags)) {
+  case nua_callstate_received:
+    RESPOND(ep, call, nh, SIP_180_RINGING, 
+	    NUTAG_MEDIA_ENABLE(0),
+	    TAG_IF(call->sdp, SIPTAG_CONTENT_TYPE_STR("application/sdp")),
+	    TAG_IF(call->sdp, SIPTAG_PAYLOAD_STR(call->sdp)),
+	    TAG_END());
+    return 0;
+  case nua_callstate_early:
+    RESPOND(ep, call, nh, SIP_200_OK,
+	    TAG_IF(call->sdp, SIPTAG_CONTENT_TYPE_STR("application/sdp")),
+	    TAG_IF(call->sdp, SIPTAG_PAYLOAD_STR(call->sdp)),
+	    TAG_END());
+    return 0;
+  case nua_callstate_ready:
+    return 1;
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
+    return 1;
+  default:
+    return 0;
+  }
+}
+
+/* Media disabled, offer/answer in 200 OK/ACK */
+int test_basic_call_4(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+  sip_t const *sip;
+
+  if (print_headings)
+    printf("TEST NUA-3.4: 3pcc call with media disabled\n");
+
+  a_call->sdp = "v=0\r\n"
+    "o=- 1 1 IN IP4 127.0.0.1\r\n"
+    "s=-\r\n"
+    "c=IN IP4 127.0.0.1\r\n"
+    "t=0 0\r\n"
+    "m=audio 5008 RTP/AVP 8\r\n";
+
+  b_call->sdp = 
+    "v=0\r\n"
+    "o=- 2 1 IN IP4 127.0.0.1\r\n"
+    "s=-\r\n"
+    "c=IN IP4 127.0.0.1\r\n"
+    "t=0 0\r\n"
+    "m=audio 5010 RTP/AVP 0 8\r\n";
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, 
+				 SIPTAG_TO_STR("<sip:b at x.org>"),
+				 TAG_END()));
+
+  TEST_1(!nua_handle_has_active_call(a_call->nh));
+  TEST_1(!nua_handle_has_call_on_hold(a_call->nh));
+
+  INVITE(a, a_call, a_call->nh,
+	 NUTAG_MEDIA_ENABLE(0),
+	 NUTAG_URL(b->contact->m_url),
+	 NUTAG_AUTOACK(0),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, ack_when_completing_no_media,
+	       -1, accept_call_no_media2);
+
+  /* Client transitions:
+     INIT -(C1)-> CALLING: nua_invite(), nua_i_state
+     CALLING -(C2)-> PROCEEDING: nua_r_invite, nua_i_state
+     PROCEEDING -(C3+C4)-> READY: nua_r_invite, nua_i_state
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(!is_offer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); /* PROCEEDING */
+  TEST_1(!is_answer_recv(e->data->e_tags));
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 200);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_content_type); 
+  TEST_S(sip->sip_content_type->c_type, "application/sdp");
+  TEST_1(sip->sip_payload);	/* there is sdp in 200 OK */
+  TEST_1(sip->sip_contact);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completing); /* COMPLETING */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
+  TEST_1(is_answer_sent(e->data->e_tags));
+  TEST_1(!e->next);
+  free_events_in_list(ctx, a->events);
+
+  TEST_1(nua_handle_has_active_call(a_call->nh));
+  TEST_1(!nua_handle_has_call_on_hold(a_call->nh));
+
+  /*
+   Server transitions:
+   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
+   RECEIVED -(S2a)-> EARLY: nua_respond(), nua_i_state
+   EARLY -(S3b)-> COMPLETED: nua_respond(), nua_i_state
+   COMPLETED -(S4)-> READY: nua_i_ack, nua_i_state
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(!is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(!is_answer_sent(e->data->e_tags));
+  TEST_1(is_offer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
+  TEST_1(is_offer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_ack);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
+  TEST_1(is_answer_recv(e->data->e_tags));
+  TEST_1(!e->next);
+  free_events_in_list(ctx, b->events);
+
+  TEST_1(nua_handle_has_active_call(b_call->nh));
+  TEST_1(!nua_handle_has_call_on_hold(b_call->nh));
+
+  BYE(b, b_call, b_call->nh, TAG_END());
+
+  run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+
+  /* B transitions:
+   READY --(T2)--> TERMINATING: nua_bye()
+   TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_r_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+  free_events_in_list(ctx, b->events);
+
+  TEST_1(!nua_handle_has_active_call(b_call->nh));
+
+  /* A transitions:
+     nua_i_info
+     READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_bye);
+  TEST(e->data->e_status, 200);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+  free_events_in_list(ctx, a->events);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-3.4: PASSED\n");
+
+  END();
+}
 
 int test_basic_call(struct context *ctx)
 {
-  return test_basic_call_1(ctx) || test_basic_call_2(ctx);
+  return test_basic_call_1(ctx) || test_basic_call_2(ctx) || 
+    test_basic_call_3(ctx) || test_basic_call_4(ctx);
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_call_hold.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_call_hold.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_call_hold.c	Tue Apr 24 10:14:28 2007
@@ -467,7 +467,7 @@
   */
 
   if (print_headings)
-    printf("TEST NUA-7.6: re-INVITE without auto-ack\n");
+    printf("TEST NUA-7.6.1: re-INVITE without auto-ack\n");
 
   /* Turn off auto-ack */
   nua_set_hparams(b_call->nh, NUTAG_AUTOACK(0), TAG_END());
@@ -517,7 +517,7 @@
   free_events_in_list(ctx, a->events);
 
   if (print_headings)
-    printf("TEST NUA-7.6: PASSED\n");
+    printf("TEST NUA-7.6.1: PASSED\n");
 
 
   /* ---------------------------------------------------------------------- */
@@ -528,7 +528,7 @@
    */
 
   if (print_headings)
-    printf("TEST NUA-7.6: terminate call\n");
+    printf("TEST NUA-7.6.2: terminate call\n");
 
   BYE(a, a_call, a_call->nh, TAG_END());
   run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
@@ -555,7 +555,7 @@
   free_events_in_list(ctx, b->events);
 
   if (print_headings)
-    printf("TEST NUA-7.6: PASSED\n");
+    printf("TEST NUA-7.6.2: PASSED\n");
 
   nua_handle_destroy(a_call->nh), a_call->nh = NULL;
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
@@ -725,9 +725,6 @@
   nua_handle_destroy(a_call->nh), a_call->nh = NULL;
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
-  if (print_headings)
-    printf("TEST NUA-7.8: PASSED\n");
-
   END();
 }
 
@@ -784,6 +781,211 @@
   }
 }
 
+/* ======================================================================== */
+
+int accept_and_attempt_reinvite(CONDITION_PARAMS);
+int until_ready2(CONDITION_PARAMS);
+
+/* test_reinvite2 message sequence looks like this:
+
+ A                    B
+ |                    |
+ |-------INVITE------>|
+ |<----100 Trying-----|
+ |                    |
+ |<----180 Ringing----|
+ |                    |
+ |           /-INVITE-|
+ |           \---900->|
+ |                    |
+ |<--------200--------|
+ |---------ACK------->|
+ :                    :
+ :   queue INVITE     :
+ :                    :
+ |-----re-INVITE----->|
+ |<--------200--------|
+ |---------ACK------->|
+ |-----re-INVITE----->|
+ |<--------200--------|
+ |---------ACK------->|
+ :                    :
+ :        glare       :
+ :                    :
+ |-----re-INVITE----->|
+ |<----re-INVITE------|
+ |<--------491--------|
+ |---------491------->|
+ |---------ACK------->|
+ |<--------ACK--------|
+ :                    :
+ |---------BYE------->|
+ |<--------200--------|
+*/
+
+int test_reinvite2(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a, *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+
+  if (print_headings)
+    printf("TEST NUA-7.8.1: Test re-INVITE glare\n");
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 0 8\n";
+  b_call->sdp = "m=audio 5010 RTP/AVP 8\n";
+
+  TEST_1(a_call->nh = 
+	 nua_handle(a->nua, a_call, 
+		    SIPTAG_FROM_STR("Alice <sip:alice at example.com>"),
+		    SIPTAG_TO(b->to),
+		    TAG_END()));
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, until_ready, -1, accept_and_attempt_reinvite);
+
+  TEST_1(nua_handle_has_active_call(a_call->nh));
+  TEST_1(nua_handle_has_active_call(b_call->nh));
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  /* Check that we can queue INVITEs */
+  INVITE(a, a_call, a_call->nh, TAG_END());
+  INVITE(a, a_call, a_call->nh, TAG_END());
+
+  run_ab_until(ctx, -1, until_ready2, -1, until_ready2);
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  /* Check that INVITE glare works */
+  INVITE(a, a_call, a_call->nh, TAG_END());
+  INVITE(b, b_call, b_call->nh, TAG_END());
+
+  a->flags.n = 0, b->flags.n = 0;
+  run_ab_until(ctx, -1, until_ready2, -1, until_ready2);
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  if (print_headings)
+    printf("TEST NUA-7.8.1: PASSED\n");
+
+
+
+  /* ---------------------------------------------------------------------- */
+  /*
+ A                    B
+ |---------BYE------->|
+ |<--------200--------|
+   */
+
+  if (print_headings)
+    printf("TEST NUA-7.8.2: terminate call\n");
+
+  BYE(a, a_call, a_call->nh, TAG_END());
+  run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+
+  /*
+   Transitions of A:
+   READY --(T2)--> TERMINATING: nua_bye()
+   TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+  free_events_in_list(ctx, a->events);
+
+  /* Transitions of B:
+     READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_bye);
+  TEST(e->data->e_status, 200);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+  free_events_in_list(ctx, b->events);
+
+  if (print_headings)
+    printf("TEST NUA-7.8.2: PASSED\n");
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  END();
+}
+
+int accept_and_attempt_reinvite(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  if (event == nua_i_prack) {
+    INVITE(ep, call, nh, TAG_END());
+    RESPOND(ep, call, nh, SIP_200_OK,
+	    TAG_IF(call->sdp, SOATAG_USER_SDP_STR(call->sdp)),
+	    TAG_END());
+  }
+  else switch (callstate(tags)) {
+  case nua_callstate_received:
+    RESPOND(ep, call, nh, SIP_180_RINGING, 
+	    SIPTAG_REQUIRE_STR("100rel"),
+	    TAG_END());
+    return 0;
+  case nua_callstate_early:
+    return 0;
+  case nua_callstate_ready:
+    return 1;
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
+    return 1;
+  default:
+    return 0;
+  }
+  return 0;
+}
+
+/*
+ X      INVITE
+ |                    |
+ |-------INVITE------>|
+ |<--------200--------|
+ |---------ACK------->|
+*/
+int until_ready2(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  if (event == nua_r_invite && status == 491) {
+    if (ep == &ctx->a && ++ctx->b.flags.n >= 2) ctx->b.running = 0;
+    if (ep == &ctx->b && ++ctx->a.flags.n >= 2) ctx->a.running = 0;
+  }
+
+  switch (callstate(tags)) {
+  case nua_callstate_ready:
+    return ++ep->flags.n >= 2;
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
+    return 1;
+  default:
+    return 0;
+  }
+}
+
 int test_reinvites(struct context *ctx)
 {
   int retval = 0;
@@ -794,7 +996,10 @@
   retval = test_call_hold(ctx);
   
   if (retval == 0)
-    retval |= test_reinvite(ctx);
+    retval = test_reinvite(ctx);
+
+  if (retval == 0)
+    retval = test_reinvite2(ctx);
 
   if (print_headings && retval == 0)
     printf("TEST NUA-7: PASSED\n");

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_call_reject.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_call_reject.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_call_reject.c	Tue Apr 24 10:14:28 2007
@@ -261,7 +261,8 @@
 
 /* ------------------------------------------------------------------------ */
 
-int reject_302(CONDITION_PARAMS);
+int reject_302(CONDITION_PARAMS), reject_305(CONDITION_PARAMS);
+int redirect_always(CONDITION_PARAMS);
 int reject_604(CONDITION_PARAMS);
 
 /*
@@ -281,6 +282,7 @@
  |<---604 Nowhere-----|
  |--------ACK-------->|
 */
+
 int reject_302(CONDITION_PARAMS)
 {
   if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
@@ -301,6 +303,33 @@
   case nua_callstate_terminated:
     if (call)
       nua_handle_destroy(call->nh), call->nh = NULL;
+    ep->next_condition = reject_305;
+    return 0;
+  default:
+    return 0;
+  }
+}
+
+int reject_305(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  switch (callstate(tags)) {
+  case nua_callstate_received:
+    {
+      sip_contact_t m[1];
+      *m = *ep->contact;
+      m->m_url->url_user = "305";
+      m->m_url->url_params = "lr=1";
+      RESPOND(ep, call, nh, SIP_305_USE_PROXY, SIPTAG_CONTACT(m), TAG_END());
+    }
+    return 0;
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
     ep->next_condition = reject_604;
     return 0;
   default:
@@ -308,6 +337,27 @@
   }
 }
 
+int redirect_always(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  if (event == nua_i_invite) {
+    char user[30];
+    sip_contact_t m[1];
+    *m = *ep->contact;
+    snprintf(user, sizeof user, "user-%u", ep->flags.n++);
+    m->m_url->url_user = user;
+    RESPOND(ep, call, nh, SIP_302_MOVED_TEMPORARILY,
+	    SIPTAG_CONTACT(m), TAG_END());
+    nua_handle_destroy(nh);
+    call->nh = NULL;
+    return 1;
+  }
+
+  return 0;
+}
+
 int reject_604(CONDITION_PARAMS)
 {
   if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
@@ -338,6 +388,7 @@
   struct endpoint *a = &ctx->a, *b = &ctx->b;
   struct call *a_call = a->call, *b_call = b->call;
   struct event *e;
+  sip_t const *sip;
 
   /* Make call reject-3 */
   if (print_headings)
@@ -388,6 +439,12 @@
   TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
   TEST_1(is_offer_sent(e->data->e_tags));
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 100);
+  TEST(sip_object(e->data->e_msg)->sip_status->st_status, 305);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(is_offer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
   TEST(e->data->e_status, 180);
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_proceeding); /* PROCEEDING */
@@ -415,6 +472,18 @@
   TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
   TEST_1(is_offer_recv(e->data->e_tags));
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_request);
+  TEST_S(sip->sip_request->rq_url->url_user, "302");
+  TEST_1(sip->sip_route);
+  TEST_S(sip->sip_route->r_url->url_user, "305");
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
@@ -428,6 +497,25 @@
   if (print_headings)
     printf("TEST NUA-4.3: PASSED\n");
 
+  if (print_headings)
+    printf("TEST NUA-4.3.1: redirect until retry count is exceeded\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SIPTAG_SUBJECT_STR("redirect always"),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 TAG_END());
+  run_ab_until(ctx, -1, until_terminated, -1, redirect_always);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-4.3: PASSED\n");
+
   END();
 }
 
@@ -638,11 +726,12 @@
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
   TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_proxy_authorization);
+  /* Ensure that nua_authenticate() tags get added to the request */
   TEST_1(sip->sip_subject);
   TEST_S(sip->sip_subject->g_value, "Got 407");
-  TEST_1(sip->sip_proxy_authorization);
-  TEST(e->data->e_status, 100);
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
   TEST_1(is_offer_recv(e->data->e_tags));
@@ -723,7 +812,7 @@
   sip_t const *sip;
 
   if (print_headings)
-    printf("TEST NUA-4.6: invalid challenge \n");
+    printf("TEST NUA-4.6.1: invalid challenge \n");
 
   a_call->sdp = "m=audio 5008 RTP/AVP 8";
   b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
@@ -772,7 +861,161 @@
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
   if (print_headings)
-    printf("TEST NUA-4.6: PASSED\n");
+    printf("TEST NUA-4.6.1: PASSED\n");
+
+  END();
+}
+
+
+/* ------------------------------------------------------------------------ */
+
+/* Reject call with 401, twice */
+
+/*
+ A   reject-401-bad   B
+ |                    |
+ |-------INVITE------>|
+ |<----100 Trying-----|
+ |<--------401--------|
+ |---------ACK------->|
+ |                    |
+ |-------INVITE------>|
+ |<----100 Trying-----|
+ |<--------401--------|
+ |---------ACK------->|
+*/
+
+int reject_401_bad(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  switch (callstate(tags)) {
+  case nua_callstate_received:
+    RESPOND(ep, call, nh, SIP_401_UNAUTHORIZED,
+	    /* Send a challenge that we do not grok */
+	    SIPTAG_WWW_AUTHENTICATE_STR("Digest realm=\"No hope\", "
+					"nonce=\"goO541ftNrw327aWpu2\", "
+					"algorithm=MD5, "
+					"qop=\"auth\""),
+	    TAG_END());
+    return 0;
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
+    if (ep->flags.bit0)		/* Terminate 2 calls */
+      return 1;
+    ep->flags.bit0 = 1;
+    return 0;
+  default:
+    return 0;
+  }
+}
+
+int authenticate_bad(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  if (event == nua_r_invite && status == 401) {
+    AUTHENTICATE(ep, call, nh, NUTAG_AUTH("Digest:\"No hope\":jaska:secret"),
+		 SIPTAG_SUBJECT_STR("Bad password"),
+		 TAG_END());
+    return 0;
+  }
+
+  switch (callstate(tags)) {
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
+    return 1;
+  default:
+    return 0;
+  }
+}
+
+
+int test_reject_401_bad(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a, *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event const *e;
+  sip_t const *sip;
+
+  if (print_headings)
+    printf("TEST NUA-4.6.2: bad username/password\n");
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SIPTAG_SUBJECT_STR("reject-401-bad"),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 TAG_END());
+
+
+  run_ab_until(ctx, -1, authenticate_bad, -1, reject_401_bad);
+
+  /*
+   Client transitions
+   INIT -(C1)-> CALLING -(C6a)-> TERMINATED/INIT
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(is_offer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(sip_object(e->data->e_msg)->sip_status->st_status, 401);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(is_offer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(sip_object(e->data->e_msg)->sip_status->st_status, 401);
+  /* nua_authenticate() fails and INVITE returns an internal error response */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 904);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next); 
+
+  free_events_in_list(ctx, a->events);
+
+  /*
+   Server transitions:
+   INIT -(S1)-> RECEIVED -(S6a)-> TERMINATED
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_invite);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, b->events);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-4.6.2: PASSED\n");
 
   END();
 }
@@ -911,7 +1154,7 @@
 
   /*
    Client transitions in reject-3:
-   INIT -(C1)-> PROCEEDING -(C6a)-> TERMINATED
+   INIT -(C1)-> CALLING -(C6a)-> TERMINATED
   */
 
   TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
@@ -927,7 +1170,7 @@
   /* No content-encoding is supported */
   TEST_S(sip->sip_accept_encoding->aa_value, "");
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* CALLING */
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
   TEST_1(!e->next);
 
   free_events_in_list(ctx, a->events);
@@ -944,3 +1187,340 @@
 
   END();
 }
+
+/* ---------------------------------------------------------------------- */
+
+size_t filter_200_OK(void *arg, void *message, size_t len)
+{
+  (void)arg;
+
+  if (len >= 11 && strncasecmp(message, "SIP/2.0 200", 11) == 0)
+    return 0;
+  return len;
+}
+
+size_t filter_ACK(void *arg, void *message, size_t len)
+{
+  (void)arg;
+
+  if (len >= 7 && strncasecmp(message, "ACK sip", 7) == 0) 
+    return 0;
+  return len;
+}
+
+int call_with_bad_ack(CONDITION_PARAMS);
+int accept_call_with_bad_contact(CONDITION_PARAMS);
+
+int test_call_timeouts(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a, *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+  struct nat_filter *f, *f2;
+
+  if (print_headings)
+    printf("TEST NUA-4.7: check for error and timeout handling\n");
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
+
+  if (!ctx->nat)
+    goto completed_4_7_1;
+
+  if (print_headings)
+    printf("TEST NUA-4.7.1: ACK timeout (200 OK filtered)\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  TEST_1(f = test_nat_add_filter(ctx->nat, filter_200_OK, NULL, nat_inbound));
+  TEST_1(f2 = test_nat_add_filter(ctx->nat, filter_200_OK,
+				  NULL, nat_outbound));
+  
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SIPTAG_SUBJECT_STR("NUA-4.7.1"),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 TAG_END());
+  run_ab_until(ctx, -1, until_terminated, -1, accept_call);
+
+  /*
+ A     accept_call    B
+ |                    |
+ |-------INVITE------>|
+ |<----100 Trying-----|
+ |                    |
+ |<----180 Ringing----|
+ |                    |
+ |   X-----200--------|
+ |   X-----200--------|
+ |   X-----200--------|
+ |                    |
+ |<--------BYE--------|
+ |--------200 OK---X  |
+
+  */
+
+  /*
+    Client transitions:
+  */
+
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); /* PROCEEDING */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+
+  /*
+   Server transitions:
+   -(S1)-> RECEIVED -(S2a)-> EARLY -(S3b)-> COMPLETED -(S5)-> TERMINATING
+   -(S10)-> TERMINATED -X
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
+  TEST_1(is_answer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_error);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminating); /* TERMINATING */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_bye);
+  TEST(e->data->e_status, 408);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  TEST_1(test_nat_remove_filter(ctx->nat, f) == 0);
+  TEST_1(test_nat_remove_filter(ctx->nat, f2) == 0);
+
+  if (print_headings)
+    printf("TEST NUA-4.7.1: PASSED\n");
+
+ completed_4_7_1:
+
+  if (!ctx->nat)
+    goto completed_4_7_2;
+
+  if (print_headings)
+    printf("TEST NUA-4.7.2: ACK timeout (ACK filtered)\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  TEST_1(f = test_nat_add_filter(ctx->nat, filter_ACK, NULL, nat_outbound));
+  
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SIPTAG_SUBJECT_STR("NUA-4.7.2"),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 TAG_END());
+  run_ab_until(ctx, -1, until_terminated, -1, accept_call);
+
+  /*
+ A     accept_call    B
+ |                    |
+ |-------INVITE------>|
+ |<----100 Trying-----|
+ |                    |
+ |<----180 Ringing----|
+ |                    |
+ |<--------200--------|
+ |--------ACK-----X   |
+ |                    |
+ |<--------200--------|
+ |--------ACK-----X   |
+ |                    |
+ |<--------200--------|
+ |--------ACK-----X   |
+ |                    |
+ |<--------BYE--------|
+ |--------200 OK----->|
+
+  */
+
+  /*
+  */
+
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); 
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 200);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); 
+  TEST_1(!e->next);
+
+  /*
+   Server transitions:
+   -(S1)-> RECEIVED -(S2a)-> EARLY -(S3b)-> COMPLETED -(S5)-> TERMINATING
+   -(S10)-> TERMINATED -X
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
+  TEST_1(is_answer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_error);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminating); /* TERMINATING */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  TEST_1(test_nat_remove_filter(ctx->nat, f) == 0);
+
+  if (print_headings)
+    printf("TEST NUA-4.7.2: PASSED\n");
+
+ completed_4_7_2:
+
+  if (print_headings)
+    printf("TEST NUA-4.7.3: sending ACK fails\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SIPTAG_SUBJECT_STR("NUA-4.7.3"),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 NUTAG_AUTOACK(0),
+	 TAG_END());
+  run_ab_until(ctx, -1, call_with_bad_ack, -1, accept_call);
+
+  /*
+ A     accept_call    B
+ |                    |
+ |-------INVITE------>|
+ |<----100 Trying-----|
+ |                    |
+ |<----180 Ringing----|
+ |                    |
+ |<--------200--------|
+ |--ACK-X             |
+ |                    |
+ |---------BYE------->|
+ |<-------200 OK------|
+
+  */
+
+  /*
+  */
+
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); 
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 200);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completing); /* COMPLETING */
+  /* try to send ACK */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminating);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); 
+  TEST_1(!e->next);
+
+  /*
+   Server transitions:
+   -(S1)-> RECEIVED -(S2a)-> EARLY -(S3b)-> COMPLETED -(S5)-> TERMINATING
+   -(S10)-> TERMINATED -X
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
+  TEST_1(is_answer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-4.7.3: PASSED\n");
+
+  /* XXX - PRACK timeout, PRACK failing, media failing, re-INVITEs */
+
+  if (print_headings)
+    printf("TEST NUA-4.7: PASSED\n");
+
+  END();
+}
+
+int call_with_bad_ack(CONDITION_PARAMS)
+{
+  if (!check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  if (event == nua_r_invite && 200 <= status && status < 300) {
+    ACK(ep, call, nh,
+	/* Syntax error - sending ACK fails, we send BYE */
+	SIPTAG_MAX_FORWARDS_STR("blue"),
+	TAG_END());
+  }
+
+  return event == nua_i_state && callstate(tags) == nua_callstate_terminated;
+}
+
+/* ---------------------------------------------------------------------- */
+
+int test_rejects(struct context *ctx)
+{
+  return
+    test_reject_401_bad(ctx) ||
+    test_reject_a(ctx) ||
+    test_reject_b(ctx) ||
+    test_reject_302(ctx) ||
+    test_reject_401(ctx) ||
+    test_mime_negotiation(ctx) ||
+    test_call_timeouts(ctx) ||
+    test_reject_401_aka(ctx) ||
+    0;
+}

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_cancel_bye.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_cancel_bye.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_cancel_bye.c	Tue Apr 24 10:14:28 2007
@@ -118,6 +118,8 @@
   case nua_callstate_proceeding:
     CANCEL(ep, call, nh, TAG_END());
     return 0;
+  case nua_callstate_ready:
+    return 1;
   case nua_callstate_terminated:
     return 1;
   default:
@@ -144,6 +146,7 @@
   }
 }
 
+int accept_after_183(CONDITION_PARAMS);
 
 int test_call_cancel(struct context *ctx)
 {
@@ -211,7 +214,7 @@
   /* ------------------------------------------------------------------------ */
 
   if (print_headings)
-    printf("TEST NUA-5.2: cancel call when ringing\n");
+    printf("TEST NUA-5.2.1: cancel call when ringing\n");
 
   TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
 
@@ -278,11 +281,56 @@
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
   if (print_headings)
-    printf("TEST NUA-5.2: PASSED\n");
+    printf("TEST NUA-5.2.1: PASSED\n");
+
+  /* ------------------------------------------------------------------------ */
+  if (print_headings)
+    printf("TEST NUA-5.2.2: CANCEL call when server waits for PRACK\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 NUTAG_APPL_METHOD("PRACK"),
+	 /*SIPTAG_REJECT_CONTACT_STR("*;audio=FALSE"),*/
+	 TAG_END());
+
+  run_ab_until(ctx, -1, cancel_when_ringing, -1, accept_after_183);
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-5.2.2: PASSED\n");
+
 
   END();
 }
 
+int accept_after_183(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  switch (callstate(tags)) {
+  case nua_callstate_received:
+    RESPOND(ep, call, nh, SIP_183_SESSION_PROGRESS, TAG_END());
+    RESPOND(ep, call, nh, SIP_200_OK, TAG_END());
+    return 0;
+  case nua_callstate_terminated:
+    return 1;
+  default:
+    return 0;
+  }
+}
+
+
 /* ======================================================================== */
 /* Destroy call handle */
 
@@ -496,13 +544,13 @@
     return 0;
   case nua_callstate_early:
     if (call)
-      nua_handle_destroy(call->nh), call->nh = NULL;
+      DESTROY(ep, call, nh), call->nh = NULL;
     return 1;
   case nua_callstate_completed:
   case nua_callstate_ready:
   case nua_callstate_terminated:
     if (call)
-      nua_handle_destroy(call->nh), call->nh = NULL;
+      DESTROY(ep, call, nh), call->nh = NULL;
     return 1;
   default:
     return 0;
@@ -594,7 +642,7 @@
   case nua_callstate_ready:
   case nua_callstate_terminated:
     if (call)
-      nua_handle_destroy(call->nh), call->nh = NULL;
+      DESTROY(ep, call, nh), call->nh = NULL;
     return 1;
   default:
     return 0;
@@ -673,6 +721,82 @@
   END();
 }
 
+/* Destroy when one INVITE is queued. */
+int test_call_destroy_5(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+
+  if (print_headings)
+    printf("TEST NUA-5.7: destroy when re-INVITE is queued\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 NUTAG_AUTOACK(0),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 TAG_END());
+
+  INVITE(a, a_call, a_call->nh, TAG_END());
+
+  run_ab_until(ctx, -1, until_terminated, -1, destroy_when_completed);
+
+  /* Client transitions:
+     INIT -(C1)-> CALLING: nua_invite(), ...
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
+  TEST_1(is_offer_sent(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); /* PROCEEDING */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 200);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completing); /* COMPLETING */
+  TEST_1(is_answer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 481);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+
+  /*
+   Server transitions:
+   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
+   RECEIVED -(S2a)-> EARLY: nua_respond(), nua_i_state
+   EARLY -(S3b)-> COMPLETED: nua_respond(), nua_i_state ... DESTROY
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
+  TEST_1(is_answer_sent(e->data->e_tags));
+  TEST_1(!e->next);  
+
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-5.7: PASSED\n");
+
+  END();
+}
+
 int test_call_destroy(struct context *ctx)
 {
   struct endpoint *a = &ctx->a,  *b = &ctx->b;
@@ -685,10 +809,12 @@
     test_call_destroy_1(ctx) ||
     test_call_destroy_2(ctx) ||
     test_call_destroy_3(ctx) ||
-    test_call_destroy_4(ctx);
+    test_call_destroy_4(ctx) ||
+    test_call_destroy_5(ctx);
 }
 
 /* ======================================================================== */
+
 /* Early BYE
 
    A			B
@@ -731,13 +857,30 @@
   }
 }
 
-int test_early_bye(struct context *ctx)
+int bye_when_completing(CONDITION_PARAMS);
+
+static int ack_sent = 0;
+
+size_t count_acks(void *arg, void *message, size_t len)
+{
+  (void)arg;
+
+  if (strncasecmp(message, "ACK sip:", 8) == 0)
+    ack_sent++;
+
+  return len;
+}
+
+int test_bye_before_200(struct context *ctx)
 {
   BEGIN();
   struct endpoint *a = &ctx->a,  *b = &ctx->b;
   struct call *a_call = a->call, *b_call = b->call;
   struct event *e;
 
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
+
   if (print_headings)
     printf("TEST NUA-6.1: BYE call when ringing\n");
 
@@ -809,3 +952,513 @@
   END();
 }
 
+
+int bye_when_completing(CONDITION_PARAMS)
+{
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  switch (callstate(tags)) {
+  case nua_callstate_completing:
+    ack_sent = 0;
+    BYE(ep, call, nh, TAG_END());
+    return 0;
+  case nua_callstate_terminated:
+    return 1;
+  default:
+    return 0;
+  }
+}
+
+
+int test_bye_before_ack(struct context *ctx)
+{
+  BEGIN();
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+  struct nat_filter *f = NULL;
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
+
+/* Early BYE 2
+
+   A			B
+   |-------INVITE------>|
+   |<----100 Trying-----|
+   |			|
+   |<----180 Ringing----|
+   |<-------200---------|
+   |			|
+   |--------BYE-------->|
+   |<------200 OK-------|
+   |--------ACK-------->|
+   |			|
+   |			|
+*/
+  if (print_headings)
+    printf("TEST NUA-6.2: BYE call when completing\n");
+
+  if (ctx->nat)
+    TEST_1(f = test_nat_add_filter(ctx->nat, count_acks, NULL, nat_outbound));
+  ack_sent = 0;
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 NUTAG_AUTOACK(0),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, bye_when_completing, -1, accept_until_terminated);
+
+  /* Client transitions:
+     INIT -(C1)-> CALLING: nua_invite(), nua_i_state
+     CALLING -(C2)-> PROCEEDING: nua_r_invite(180, nua_i_state, nua_cancel()
+     PROCEEDING -(C6b)-> TERMINATED: nua_r_invite(487), nua_i_state
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling);
+  TEST_1(is_offer_sent(e->data->e_tags));
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); 
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 200);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completing); 
+  TEST_1(e = e->next);
+
+  TEST_E(e->data->e_event, nua_r_bye); TEST(e->data->e_status, 200);
+  TEST_1(e->data->e_msg);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+
+  if (ctx->nat) {
+    while (ack_sent == 0)
+      su_root_step(ctx->root, 100);
+    TEST_1(ack_sent > 0);
+    TEST_1(test_nat_remove_filter(ctx->nat, f) == 0);
+  }
+
+  /*
+   Server transitions:
+   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
+   RECEIVED -(S2a)-> EARLY: nua_respond(180), nua_i_state
+   EARLY -(S6b)--> TERMINATED: nua_i_cancel, nua_i_state
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_bye);
+  TEST(e->data->e_status, 200);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-6.2: PASSED\n");
+
+  END();
+}
+
+int reject_reinvite_401(CONDITION_PARAMS);
+
+int test_bye_after_receiving_401(struct context *ctx)
+{
+  BEGIN();
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
+
+/* BYE after receiving 401
+
+   A			B
+   |-------INVITE------>|
+   |<----100 Trying-----|
+   |			|
+   |<----180 Ringing----|
+   |<-------200---------|
+   |--------ACK-------->|
+   |			|
+   |<------INVITE-------|
+   |--------401-------->|
+   |<--------ACK--------|
+   |			|
+   |<--------BYE--------|
+   |------200 OK------->|
+   |			|
+*/
+  if (print_headings)
+    printf("TEST NUA-6.3: BYE after receiving 401\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SIPTAG_SUBJECT_STR("NUA-6.3"),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 NUTAG_AUTOANSWER(0),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, until_ready, -1, accept_call);
+
+  free_events_in_list(ctx, a->events);
+
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  free_events_in_list(ctx, b->events);
+
+  /* re-INVITE A. */
+  INVITE(b, b_call, b_call->nh, 
+	 SIPTAG_SUBJECT_STR("NUA-6.3 re-INVITE"),
+	 TAG_END());
+  run_ab_until(ctx, -1, reject_reinvite_401, -1, save_until_final_response);
+
+  TEST_1(nua_handle_has_active_call(a_call->nh));
+  TEST_1(nua_handle_has_active_call(b_call->nh));
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  BYE(b, b_call, b_call->nh, TAG_END());
+  
+  run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-6.3: PASSED\n");
+
+  END();
+}
+
+int test_bye_after_sending_401(struct context *ctx)
+{
+  BEGIN();
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
+
+/* BYE after sending 401
+
+   A			B
+   |-------INVITE------>|
+   |<----100 Trying-----|
+   |			|
+   |<----180 Ringing----|
+   |<-------200---------|
+   |--------ACK-------->|
+   |			|
+   |<------INVITE-------|
+   |--------401-------->|
+   |<--------ACK--------|
+   |			|
+   |--------BYE-------->|
+   |<------200 OK-------|
+   |			|
+*/
+  if (print_headings)
+    printf("TEST NUA-6.4.1: BYE after sending 401\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SIPTAG_SUBJECT_STR("NUA-6.4.1"),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 NUTAG_AUTOANSWER(0),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, until_ready, -1, accept_call);
+
+  free_events_in_list(ctx, a->events);
+
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  free_events_in_list(ctx, b->events);
+
+  /* re-INVITE A. */
+  INVITE(b, b_call, b_call->nh, 
+	 SIPTAG_SUBJECT_STR("NUA-6.4.1 re-INVITE"),
+	 TAG_END());
+  run_ab_until(ctx, -1, reject_reinvite_401, -1, save_until_final_response);
+
+  TEST_1(nua_handle_has_active_call(a_call->nh));
+  TEST_1(nua_handle_has_active_call(b_call->nh));
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  BYE(a, a_call, a_call->nh, TAG_END());
+  
+  run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-6.4.1: PASSED\n");
+
+  END();
+}
+
+int test_bye_after_receiving_401_to_update(struct context *ctx)
+{
+  BEGIN();
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
+
+/* BYE after receiving 401
+
+   A			B
+   |-------INVITE------>|
+   |<----100 Trying-----|
+   |			|
+   |<----180 Ringing----|
+   |<-------200---------|
+   |--------ACK-------->|
+   |			|
+   |<------UPDATE-------|
+   |--------401-------->|
+   |			|
+   |<--------BYE--------|
+   |------200 OK------->|
+   |			|
+*/
+  if (print_headings)
+    printf("TEST NUA-6.4.2: BYE after receiving 401 to UPDATE\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SIPTAG_SUBJECT_STR("NUA-6.4.2"),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 NUTAG_AUTOANSWER(0),
+	 NUTAG_APPL_METHOD("UPDATE"),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, until_ready, -1, accept_call);
+
+  free_events_in_list(ctx, a->events);
+
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  free_events_in_list(ctx, b->events);
+
+  /* UPDATE A. */
+  UPDATE(b, b_call, b_call->nh, 
+	 SIPTAG_SUBJECT_STR("NUA-6.4.2 UPDATE"),
+	 TAG_END());
+  BYE(b, b_call, b_call->nh, TAG_END()); /* Queued until nua_authenticate */
+  run_ab_until(ctx, -1, reject_reinvite_401, -1, save_until_final_response);
+
+  TEST_1(nua_handle_has_active_call(a_call->nh));
+  TEST_1(nua_handle_has_active_call(b_call->nh));
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  AUTHENTICATE(b, b_call, b_call->nh, TAG_END());
+  
+  run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-6.4.2: PASSED\n");
+
+  END();
+}
+
+int reject_reinvite_401(CONDITION_PARAMS)
+{
+  void *request = nua_current_request(nua);
+
+  save_event_in_list(ctx, event, ep, call);
+
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  if (status < 200 && (event == nua_i_invite || event == nua_i_update)) {
+    RESPOND(ep, call, nh, SIP_401_UNAUTHORIZED,
+	    NUTAG_WITH(request),
+	    SIPTAG_WWW_AUTHENTICATE_STR("Digest realm=\"test_nua\", "
+					"nonce=\"nsdhfuds\", algorithm=MD5, "
+					"qop=\"auth\""),
+	    TAG_END());
+    return 0;
+  }
+
+  if (event == nua_i_state) switch (callstate(tags)) {
+  case nua_callstate_ready:
+    return 1;
+  case nua_callstate_terminated:
+    if (call)
+      nua_handle_destroy(call->nh), call->nh = NULL;
+    return 1;
+  default:
+    return 0;
+  }
+
+  return 0;
+}
+
+int test_bye_to_invalid_contact(struct context *ctx)
+{
+  BEGIN();
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+
+  a_call->sdp = "m=audio 5008 RTP/AVP 8";
+  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
+
+/* Early BYE 2
+
+   A			B
+   |-------INVITE------>|
+   |<----100 Trying-----|
+   |			|
+   |<----180 Ringing----|
+   |<-------200---------|
+   |			|
+   |--------BYE-------->|
+   |<------200 OK-------|
+   |--------ACK-------->|
+   |			|
+   |			|
+*/
+  if (print_headings)
+    printf("TEST NUA-6.4.3: BYE call when completing\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  INVITE(a, a_call, a_call->nh,
+	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	 SOATAG_USER_SDP_STR(a_call->sdp),
+	 SIPTAG_CONTACT(NULL),
+	 SIPTAG_HEADER_STR("Contact: <<sip:xyzzy at com.invalid>"),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, until_ready, -1, accept_call);
+
+  /* Client transitions:
+     INIT -(C1)-> CALLING: nua_invite(), nua_i_state
+     CALLING -(C2)-> PROCEEDING: nua_r_invite(180, nua_i_state, nua_cancel()
+     PROCEEDING -(C6b)-> TERMINATED: nua_r_invite(487), nua_i_state
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_calling);
+  TEST_1(is_offer_sent(e->data->e_tags));
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); 
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 200);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_ready); 
+  TEST_1(!e->next);
+
+  /*
+   Server transitions:
+   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
+   RECEIVED -(S2a)-> EARLY: nua_respond(180), nua_i_state
+   EARLY -(S6b)--> TERMINATED: nua_i_cancel, nua_i_state
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
+  TEST(e->data->e_status, 100);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
+  TEST_1(is_offer_recv(e->data->e_tags));
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_ack);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  BYE(b, b_call, b_call->nh, TAG_END());
+  
+  run_b_until(ctx, -1, until_terminated);
+
+  /* B transitions:
+   READY --(T2)--> TERMINATING: nua_bye()
+   TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
+  */
+  TEST_1(e = b->events->head);  TEST_E(e->data->e_event, nua_r_bye);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
+  TEST_1(!e->next);
+  free_events_in_list(ctx, b->events);
+
+  TEST_1(!nua_handle_has_active_call(b_call->nh));
+  TEST_1(nua_handle_has_active_call(a_call->nh));
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-6.4.3: PASSED\n");
+
+  END();
+}
+
+int test_early_bye(struct context *ctx)
+{
+  return 
+    test_bye_before_200(ctx) ||
+    test_bye_before_ack(ctx) ||
+    test_bye_after_receiving_401(ctx) ||
+    test_bye_after_sending_401(ctx) ||
+    test_bye_after_receiving_401_to_update(ctx) ||
+    test_bye_to_invalid_contact(ctx) ||
+    0;
+}

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_extension.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_extension.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_extension.c	Tue Apr 24 10:14:28 2007
@@ -167,6 +167,13 @@
   free_events_in_list(ctx, b->events);
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
+  nua_set_params(b->nua,
+		 SIPTAG_ALLOW(b->allow),
+		 NUTAG_APPL_METHOD(NULL),
+		 NUTAG_APPL_METHOD(b->appl_method),
+		 TAG_END());
+  run_b_until(ctx, nua_r_set_params, until_final_response);
+
   if (print_headings)
     printf("TEST NUA-13.1: PASSED\n");
   END();

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_init.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_init.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_init.c	Tue Apr 24 10:14:28 2007
@@ -35,6 +35,8 @@
 
 #include "test_nua.h"
 
+#include <sofia-sip/tport_tag.h>
+
 #if HAVE_FUNC
 #elif HAVE_FUNCTION
 #define __func__ __FUNCTION__
@@ -65,6 +67,9 @@
   struct event *e;
   sip_contact_t const *m = NULL;
   sip_from_t const *sipaddress = NULL;
+  sip_allow_t const *allow = NULL;
+  sip_supported_t const *supported = NULL;
+  char const *appl_method = NULL;
   url_t const *p_uri, *a_uri;		/* Proxy URI */
   char const *a_bind, *a_bind2;
 
@@ -105,7 +110,9 @@
 			       AUTHTAG_OPAQUE("kuik"),
 			       AUTHTAG_DB(passwd_name),
 			       AUTHTAG_QOP("auth-int"),
-			       AUTHTAG_ALGORITHM("md5-sess"),
+			       AUTHTAG_ALGORITHM("md5"),
+			       AUTHTAG_NEXT_EXPIRES(60),
+			       TAG_IF(ctx->proxy_logging, TPTAG_LOG(1)),
 			       TAG_END());
 
     ctx->proxy_tests = ctx->p != NULL;
@@ -218,22 +225,29 @@
 			  NUTAG_URL(a_bind),
 			  TAG_IF(a_bind != a_bind2, NUTAG_SIPS_URL(a_bind2)),
 			  SOATAG_USER_SDP_STR("m=audio 5004 RTP/AVP 0 8"),
-			  NTATAG_SIP_T1X64(4000),
+			  NTATAG_SIP_T1X64(2000),
 			  NUTAG_INSTANCE(ctx->a.instance),
+			  TAG_IF(ctx->a.logging, TPTAG_LOG(1)),
 			  TAG_END());
   TEST_1(ctx->a.nua);
 
   nua_get_params(ctx->a.nua, TAG_ANY(), TAG_END());
   run_a_until(ctx, nua_r_get_params, save_until_final_response);
-  TEST_1(e = ctx->a.events->head);
+  TEST_1(e = ctx->a.specials->head);
   TEST(tl_gets(e->data->e_tags,
 	       NTATAG_CONTACT_REF(m),
 	       SIPTAG_FROM_REF(sipaddress),
-	       TAG_END()), 2); TEST_1(m);
+	       SIPTAG_ALLOW_REF(allow),
+	       NUTAG_APPL_METHOD_REF(appl_method),
+	       SIPTAG_SUPPORTED_REF(supported),
+	       TAG_END()), 5); TEST_1(m);
   TEST_1(ctx->a.contact = sip_contact_dup(ctx->home, m));
   TEST_1(ctx->a.to = sip_to_dup(ctx->home, sipaddress));
+  TEST_1(ctx->a.allow = sip_allow_dup(ctx->home, allow));
+  TEST_1(ctx->a.appl_method = su_strdup(ctx->home, appl_method));
+  TEST_1(ctx->a.supported = sip_supported_dup(ctx->home, supported));
 
-  free_events_in_list(ctx, ctx->a.events);
+  free_events_in_list(ctx, ctx->a.specials);
 
   if (print_headings)
     printf("TEST NUA-2.2.1: PASSED\n");
@@ -249,19 +263,30 @@
 			  NUTAG_URL("sip:0.0.0.0:*"),
 			  SOATAG_USER_SDP_STR("m=audio 5006 RTP/AVP 8 0"),
 			  NUTAG_INSTANCE(ctx->b.instance),
+			  /* Quicker timeout */
+			  NTATAG_SIP_T1X64(2000),
+			  TAG_IF(ctx->b.logging, TPTAG_LOG(1)),
 			  TAG_END());
   TEST_1(ctx->b.nua);
 
   nua_get_params(ctx->b.nua, TAG_ANY(), TAG_END());
   run_b_until(ctx, nua_r_get_params, save_until_final_response);
-  TEST_1(e = ctx->b.events->head);
+  TEST_1(e = ctx->b.specials->head);
   TEST(tl_gets(e->data->e_tags,
 	       NTATAG_CONTACT_REF(m),
 	       SIPTAG_FROM_REF(sipaddress),
-	       TAG_END()), 2); TEST_1(m);
+	       SIPTAG_ALLOW_REF(allow),
+	       NUTAG_APPL_METHOD_REF(appl_method),
+	       SIPTAG_SUPPORTED_REF(supported),
+	       TAG_END()), 5); TEST_1(m);
+
   TEST_1(ctx->b.contact = sip_contact_dup(ctx->home, m));
   TEST_1(ctx->b.to = sip_to_dup(ctx->home, sipaddress));
-  free_events_in_list(ctx, ctx->b.events);
+  TEST_1(ctx->b.allow = sip_allow_dup(ctx->home, allow));
+  TEST_1(ctx->b.appl_method = su_strdup(ctx->home, appl_method));
+  TEST_1(ctx->b.supported = sip_supported_dup(ctx->home, supported));
+
+  free_events_in_list(ctx, ctx->b.specials);
 
   if (print_headings)
     printf("TEST NUA-2.2.2: PASSED\n");
@@ -277,19 +302,26 @@
 			  NUTAG_URL("sip:0.0.0.0:*"),
 			  SOATAG_USER_SDP_STR("m=audio 5400 RTP/AVP 8 0"),
 			  NUTAG_INSTANCE(ctx->c.instance),
+			  TAG_IF(ctx->c.logging, TPTAG_LOG(1)),
 			  TAG_END());
   TEST_1(ctx->c.nua);
 
   nua_get_params(ctx->c.nua, TAG_ANY(), TAG_END());
   run_c_until(ctx, nua_r_get_params, save_until_final_response);
-  TEST_1(e = ctx->c.events->head);
+  TEST_1(e = ctx->c.specials->head);
   TEST(tl_gets(e->data->e_tags,
 	       NTATAG_CONTACT_REF(m),
 	       SIPTAG_FROM_REF(sipaddress),
-	       TAG_END()), 2); TEST_1(m);
+	       SIPTAG_ALLOW_REF(allow),
+	       NUTAG_APPL_METHOD_REF(appl_method),
+	       SIPTAG_SUPPORTED_REF(supported),
+	       TAG_END()), 5); TEST_1(m);
   TEST_1(ctx->c.contact = sip_contact_dup(ctx->home, m));
   TEST_1(ctx->c.to = sip_to_dup(ctx->home, sipaddress));
-  free_events_in_list(ctx, ctx->c.events);
+  TEST_1(ctx->c.allow = sip_allow_dup(ctx->home, allow));
+  TEST_1(ctx->c.appl_method = su_strdup(ctx->home, appl_method));
+  TEST_1(ctx->c.supported = sip_supported_dup(ctx->home, supported));
+  free_events_in_list(ctx, ctx->c.specials);
 
   if (print_headings)
     printf("TEST NUA-2.2.3: PASSED\n");

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nat.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nat.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nat.c	Tue Apr 24 10:14:28 2007
@@ -91,6 +91,8 @@
 
   struct binding *bindings;
 
+  struct nat_filter *in_filters, *out_filters;
+
   /* True if we act in symmetric way */
   int symmetric;
   /* True if we do logging */
@@ -153,6 +155,15 @@
 
 static int invalidate_binding(struct binding *b);
 
+LIST_PROTOS(static, nat_filter, struct nat_filter);
+
+struct nat_filter
+{
+  struct nat_filter *next, **prev;
+  size_t (*condition)(void *arg, void *message, size_t len);
+  void *arg;
+};
+
 /* nat entry point */
 static int
 test_nat_init(su_root_t *root, struct nat *nat)
@@ -670,19 +681,35 @@
 {
   int events;
   ssize_t n, m;
+  size_t len, filtered;
+  struct nat_filter *f;
 
   events = su_wait_events(wait, b->in_socket);
 
   n = su_recv(b->in_socket, nat->buffer, sizeof nat->buffer, 0);
-  if (n < 0) {
+  if (n == -1) {
     su_perror("udp_in_to_out: recv");
     return 0;
   }
 
+  len = (size_t)n;
+
+  for (f = nat->out_filters; f; f = f->next) {
+    filtered = f->condition(f->arg, nat->buffer, len);
+    if (filtered != len) {
+      if (nat->logging)
+	printf("nat: udp filtered "MOD_ZU" from %s => "MOD_ZU" to %s\n",
+	       len, b->in_name, filtered, b->out_name);
+      if (filtered == 0)
+	return 0;
+      len = filtered;
+    }
+  }
+
   if (nat->symmetric)
-    m = su_send(b->out_socket, nat->buffer, n, 0);
+    m = su_send(b->out_socket, nat->buffer, len, 0);
   else
-    m = su_sendto(b->out_socket, nat->buffer, n, 0,
+    m = su_sendto(b->out_socket, nat->buffer, len, 0,
 		  nat->out_address, nat->out_addrlen);
 
   if (nat->logging)
@@ -696,6 +723,8 @@
 {
   int events;
   ssize_t n, m;
+  size_t len, filtered;
+  struct nat_filter *f;
 
   events = su_wait_events(wait, b->out_socket);
 
@@ -705,6 +734,20 @@
     return 0;
   }
 
+  len = (size_t)n;
+
+  for (f = nat->in_filters; f; f = f->next) {
+    filtered = f->condition(f->arg, nat->buffer, len);
+    if (filtered != len) {
+      if (nat->logging)
+	printf("nat: udp filtered "MOD_ZU" from %s => "MOD_ZU" to %s\n",
+	       len, b->out_name, filtered, b->in_name);
+      if (filtered == 0)
+	return 0;
+      len = filtered;
+    }
+  }
+
   m = su_send(b->in_socket, nat->buffer, n, 0);
 
   if (nat->logging)
@@ -882,3 +925,75 @@
 
   return 0;
 }
+
+LIST_BODIES(static, nat_filter, struct nat_filter, next, prev);
+
+struct args {
+  struct nat *nat;
+  struct nat_filter *f;
+  int outbound;
+};
+
+int execute_nat_filter_insert(void *_args)
+{
+  struct args *a = (struct args *)_args;
+  if (a->outbound)
+    nat_filter_insert(&a->nat->out_filters, a->f);
+  else
+    nat_filter_insert(&a->nat->in_filters, a->f);
+  return 0;
+}
+
+int execute_nat_filter_remove(void *_args)
+{
+  struct args *a = (struct args *)_args;
+  nat_filter_remove(a->f);
+  return 0;
+}
+
+struct nat_filter *test_nat_add_filter(struct nat *nat,
+				       size_t (*condition)(void *arg,
+							   void *message,
+							   size_t len),
+				       void *arg,
+				       int outbound)
+{
+  struct args a[1];
+
+  if (nat == NULL)
+    return su_seterrno(EFAULT), NULL;
+
+  a->nat = nat;
+  a->f = su_zalloc(nat->home, sizeof *a->f);
+  a->outbound = outbound;
+
+  if (a->f) {
+    a->f->condition = condition;
+    a->f->arg = arg;
+    if (su_task_execute(su_clone_task(nat->clone),
+			execute_nat_filter_insert, a, NULL) < 0)
+      su_free(nat->home, a->f), a->f = NULL;
+  }
+
+  return a->f;
+}
+
+
+int test_nat_remove_filter(struct nat *nat,
+			   struct nat_filter *filter)
+{
+  struct args a[1];
+
+  if (nat == NULL)
+    return su_seterrno(EFAULT);
+
+  a->nat = nat;
+  a->f = filter;
+  
+  if (su_task_execute(su_clone_task(nat->clone),
+		      execute_nat_filter_remove, a, NULL) < 0)
+    return -1;
+
+  su_free(nat->home, filter);
+  return 0;
+}

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nat.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nat.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nat.h	Tue Apr 24 10:14:28 2007
@@ -31,6 +31,7 @@
 SOFIA_BEGIN_DECLS
 
 struct nat;
+struct nat_filter;
 
 struct nat *test_nat_create(su_root_t *, int family, 
 			    tag_type_t, tag_value_t, ...);
@@ -42,6 +43,18 @@
 
 int test_nat_flush(struct nat *nat);
 
+struct nat_filter *test_nat_add_filter(struct nat *nat,
+				       size_t (*condition)(void *arg,
+							   void *message,
+							   size_t len),
+				       void *arg,
+				       int outbound);
+
+enum { nat_inbound, nat_outbound };
+
+int test_nat_remove_filter(struct nat *nat,
+			   struct nat_filter *filter);
+
 /* Tags */
 
 /** If true, act as symmetric nat. */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua.c	Tue Apr 24 10:14:28 2007
@@ -72,20 +72,29 @@
 static char const options_usage[] =
   "   -v | --verbose    be verbose\n"
   "   -q | --quiet      be quiet\n"
+  "   -a | --abort      abort on error\n" 
   "   -s                use only single thread\n"
   "   -l level          set logging level (0 by default)\n"
   "   -e | --events     print nua events\n"
   "   -A                print nua events for A\n"
   "   -B                print nua events for B\n"
   "   -C                print nua events for C\n"
+  "   --log=a           log messages for A\n"
+  "   --log=b           log messages for B\n"
+  "   --log=c           log messages for C\n"
+  "   --log=proxy       log messages for proxy\n"
   "   --attach          print pid, wait for a debugger to be attached\n"
   "   --no-proxy        do not use internal proxy\n"
   "   --no-nat          do not use internal \"nat\"\n"
   "   --symmetric       run internal \"nat\" in symmetric mode\n"
   "   -N                print events from internal \"nat\"\n"
+  "   --loop            loop main tests for ever\n"
   "   --no-alarm        don't ask for guard ALARM\n"
   "   -p uri            specify uri of outbound proxy (implies --no-proxy)\n"
   "   --proxy-tests     run tests involving proxy, too\n"
+#if SU_HAVE_OSX_CF_API /* If compiled with CoreFoundation events */
+  "   --osx-runloop     use OSX CoreFoundation runloop instead of poll() loop\n"
+#endif
   "   -k                do not exit after first error\n"
   ;
 
@@ -99,7 +108,7 @@
 int main(int argc, char *argv[])
 {
   int retval = 0;
-  int i, o_quiet = 0, o_attach = 0, o_alarm = 1;
+  int i, o_quiet = 0, o_attach = 0, o_alarm = 1, o_loop = 0;
   int o_events_init = 0, o_events_a = 0, o_events_b = 0, o_events_c = 0;
   int o_iproxy = 1, o_inat = 1;
   int o_inat_symmetric = 0, o_inat_logging = 0, o_expensive = 0;
@@ -199,6 +208,21 @@
     else if (strcmp(argv[i], "--no-alarm") == 0) {
       o_alarm = 0;
     }
+    else if (strcmp(argv[i], "--loop") == 0) {
+      o_alarm = 0, o_loop = 1;
+    }
+    else if (strcmp(argv[i], "--log=a") == 0) {
+      ctx->a.logging = 1;
+    }
+    else if (strcmp(argv[i], "--log=b") == 0) {
+      ctx->b.logging = 1;
+    }
+    else if (strcmp(argv[i], "--log=c") == 0) {
+      ctx->c.logging = 1;
+    }
+    else if (strcmp(argv[i], "--log=proxy") == 0) {
+      ctx->proxy_logging = 1;
+    }
 #if SU_HAVE_OSX_CF_API /* If compiled with CoreFoundation events */
     else if (strcmp(argv[i], "--osx-runloop") == 0) {
       ctx->osx_runloop = 1;
@@ -210,8 +234,10 @@
     else if (argv[i][0] != '-') {
       break;
     }
-    else
+    else {
+      fprintf(stderr, "test_nua: unknown argument \"%s\"\n\n", argv[i]);
       usage(1);
+    }
   }
 
   if (o_attach) {
@@ -222,8 +248,15 @@
   }
 #if HAVE_ALARM
   else if (o_alarm) {
-    alarm(o_expensive ? 60 : 120);
     signal(SIGALRM, sig_alarm);
+    if (o_expensive) {
+      printf("%s: extending timeout to %u because expensive tests\n",
+	     name, 240);
+      alarm(240);
+    }
+    else {
+      alarm(120);
+    }
   }
 #endif
 
@@ -279,17 +312,12 @@
     if (retval == 0 && o_inat)
       retval |= test_nat_timeout(ctx);
 
-    if (retval == 0) {
-      retval |= test_extension(ctx); SINGLE_FAILURE_CHECK();
+    while (retval == 0) {
       retval |= test_basic_call(ctx); SINGLE_FAILURE_CHECK();
-      retval |= test_reject_a(ctx); SINGLE_FAILURE_CHECK();
-      retval |= test_reject_b(ctx); SINGLE_FAILURE_CHECK();
-      retval |= test_reject_302(ctx); SINGLE_FAILURE_CHECK();
-      retval |= test_reject_401(ctx); SINGLE_FAILURE_CHECK();
-      retval |= test_mime_negotiation(ctx); SINGLE_FAILURE_CHECK();
-      retval |= test_reject_401_aka(ctx); SINGLE_FAILURE_CHECK();
+      retval |= test_rejects(ctx); SINGLE_FAILURE_CHECK();
       retval |= test_call_cancel(ctx); SINGLE_FAILURE_CHECK();
       retval |= test_call_destroy(ctx); SINGLE_FAILURE_CHECK();
+      retval |= test_offer_answer(ctx); SINGLE_FAILURE_CHECK();
       retval |= test_early_bye(ctx); SINGLE_FAILURE_CHECK();
       retval |= test_reinvites(ctx); SINGLE_FAILURE_CHECK();
       retval |= test_session_timer(ctx); SINGLE_FAILURE_CHECK();
@@ -297,6 +325,9 @@
       retval |= test_100rel(ctx); SINGLE_FAILURE_CHECK();
       retval |= test_simple(ctx); SINGLE_FAILURE_CHECK();
       retval |= test_events(ctx); SINGLE_FAILURE_CHECK();
+      retval |= test_extension(ctx); SINGLE_FAILURE_CHECK();
+      if (!o_loop)
+	break;
     }
 
     if (ctx->proxy_tests && (retval == 0 || !ctx->p))

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua.h	Tue Apr 24 10:14:28 2007
@@ -126,10 +126,14 @@
   int threading, proxy_tests, expensive, quit_on_single_failure, osx_runloop;
   char const *external_proxy;
 
+  int proxy_logging;
+
   struct endpoint {
     char name[4];
     struct context *ctx;	/* Backpointer */
 
+    int logging;
+
     int running;
 
     condition_function *next_condition;
@@ -138,6 +142,10 @@
     sip_contact_t *contact;
     sip_from_t *to;
 
+    sip_allow_t *allow;
+    char const *appl_method;
+    sip_supported_t *supported;
+
     printer_function *printer;
 
     char const *instance;
@@ -158,12 +166,11 @@
     struct eventlist specials[1];
 
     /* State flags for complex scenarios */
-    union {
-      struct {
-	unsigned bit0:1, bit1:1, bit2:1, bit3:1;
-	unsigned bit4:1, bit5:1, bit6:1, bit7:1;
-      } b;
+    struct {
       unsigned n;
+      unsigned bit0:1, bit1:1, bit2:1, bit3:1;
+      unsigned bit4:1, bit5:1, bit6:1, bit7:1;
+      unsigned :0;
     } flags;
 
   } a, b, c;
@@ -185,6 +192,9 @@
 		       struct call *);
 void free_events_in_list(struct context *,
 			 struct eventlist *);
+void free_event_in_list(struct context *ctx,
+			struct eventlist *list,
+			struct event *e);
 
 #define CONDITION_PARAMS			\
   nua_event_t event,				\
@@ -204,6 +214,9 @@
 int until_terminated(CONDITION_PARAMS);
 int until_ready(CONDITION_PARAMS);
 int accept_call(CONDITION_PARAMS);
+int cancel_when_ringing(CONDITION_PARAMS);
+
+int accept_notify(CONDITION_PARAMS);
 
 void a_callback(nua_event_t event,
 		int status, char const *phrase,
@@ -316,11 +329,10 @@
 int test_unregister(struct context *ctx);
 
 int test_basic_call(struct context *ctx);
-int test_reject_a(struct context *ctx);
-int test_reject_b(struct context *ctx);
-int test_reject_302(struct context *ctx);
-int test_reject_401(struct context *ctx);
+int test_offer_answer(struct context *ctx);
+int test_rejects(struct context *ctx);
 int test_mime_negotiation(struct context *ctx);
+int test_call_timeouts(struct context *ctx);
 int test_reject_401_aka(struct context *ctx);
 int test_call_cancel(struct context *ctx);
 int test_call_destroy(struct context *ctx);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua_api.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua_api.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua_api.c	Tue Apr 24 10:14:28 2007
@@ -210,7 +210,10 @@
   run_a_until(ctx, -1, save_until_final_response);
 
   TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_unregister);
-  TEST(e->data->e_status, 401);
+  if (e->data->e_status == 401)
+    TEST(e->data->e_status, 401);
+  else
+    TEST(e->data->e_status, 406);
   TEST_1(!e->next);
 
   free_events_in_list(ctx, a->events);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua_params.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua_params.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_nua_params.c	Tue Apr 24 10:14:28 2007
@@ -117,12 +117,12 @@
   nua_get_params(ctx->a.nua, TAG_ANY(), TAG_END());
   run_a_until(ctx, nua_r_get_params, save_until_final_response);
 
-  TEST_1(e = ctx->a.events->head);
+  TEST_1(e = ctx->a.specials->head);
   TEST_E(e->data->e_event, nua_r_get_params);
   for (n = 0, t = e->data->e_tags; t; n++, t = tl_next(t))
     ;
   TEST_1(n > 32);
-  free_events_in_list(ctx, ctx->a.events);
+  free_events_in_list(ctx, ctx->a.specials);
 
   nh = nua_handle(ctx->a.nua, NULL, TAG_END()); TEST_1(nh);
   nua_handle_unref(nh);
@@ -148,9 +148,12 @@
 
 		 SIPTAG_SUPPORTED_STR("test"),
 		 SIPTAG_ALLOW_STR("DWIM, OPTIONS, INFO"),
+		 NUTAG_APPL_METHOD(NULL),
+		 NUTAG_APPL_METHOD("INVITE, REGISTER, PUBLISH, SUBSCRIBE"),
 		 SIPTAG_ALLOW_EVENTS_STR("reg"),
 		 SIPTAG_USER_AGENT_STR("test_nua/1.0"),
 
+
 		 SIPTAG_ORGANIZATION_STR("Open Laboratory"),
 		 
 		 NUTAG_M_DISPLAY("XXX"),
@@ -190,6 +193,7 @@
 		 NUTAG_MEDIA_FEATURES(1),
 		 NUTAG_SERVICE_ROUTE_ENABLE(0),
 		 NUTAG_PATH_ENABLE(0),
+		 NUTAG_AUTH_CACHE(nua_auth_cache_challenged),
 		 NUTAG_REFER_EXPIRES(333),
 		 NUTAG_REFER_WITH_ID(0),
 		 NUTAG_SUBSTATE(nua_substate_pending),
@@ -211,10 +215,13 @@
 		 SIPTAG_ALLOW(sip_allow_make(tmphome, "INFO")),
 		 NUTAG_ALLOW("ACK, INFO"),
 
+		 NUTAG_APPL_METHOD("NOTIFY"),
+
 		 SIPTAG_ALLOW_EVENTS_STR("reg"),
 		 SIPTAG_ALLOW_EVENTS(sip_allow_events_make(tmphome, "presence")),
 		 NUTAG_ALLOW_EVENTS("presence.winfo"),
 
+
 		 SIPTAG_USER_AGENT(sip_user_agent_make(tmphome, "test_nua")),
 
 		 SIPTAG_ORGANIZATION(sip_organization_make(tmphome, "Pussy Galore's Flying Circus")),
@@ -262,12 +269,14 @@
     int media_features = -1;
     int service_route_enable = -1;
     int path_enable = -1;
+    int auth_cache = -1;
     unsigned refer_expires = (unsigned)-1;
     int refer_with_id = -1;
     int substate = -1;
 
     sip_allow_t const *allow = NONE;
     char const *allow_str = "NONE";
+    char const *appl_method = "NONE";
     sip_allow_events_t const *allow_events = NONE;
     char const *allow_events_str = "NONE";
     sip_supported_t const *supported = NONE;
@@ -291,7 +300,7 @@
     nua_get_params(ctx->a.nua, TAG_ANY(), TAG_END());
     run_a_until(ctx, nua_r_get_params, save_until_final_response);
 
-    TEST_1(e = ctx->a.events->head);
+    TEST_1(e = ctx->a.specials->head);
     TEST_E(e->data->e_event, nua_r_get_params);
 
     n = tl_gets(e->data->e_tags,
@@ -324,6 +333,7 @@
 	       	NUTAG_MEDIA_FEATURES_REF(media_features),
 	       	NUTAG_SERVICE_ROUTE_ENABLE_REF(service_route_enable),
 	       	NUTAG_PATH_ENABLE_REF(path_enable),
+	       	NUTAG_AUTH_CACHE_REF(auth_cache),
 	       	NUTAG_REFER_EXPIRES_REF(refer_expires),
 	       	NUTAG_REFER_WITH_ID_REF(refer_with_id),
 	       	NUTAG_SUBSTATE_REF(substate),
@@ -332,6 +342,7 @@
 	       	SIPTAG_SUPPORTED_STR_REF(supported_str),
 	       	SIPTAG_ALLOW_REF(allow),
 	       	SIPTAG_ALLOW_STR_REF(allow_str),
+		NUTAG_APPL_METHOD_REF(appl_method),
 		SIPTAG_ALLOW_EVENTS_REF(allow_events),
 		SIPTAG_ALLOW_EVENTS_STR_REF(allow_events_str),
 	       	SIPTAG_USER_AGENT_REF(user_agent),
@@ -353,7 +364,7 @@
 		NUTAG_INSTANCE_REF(instance),
 
 		TAG_END());
-    TEST(n, 46);
+    TEST(n, 48);
 
     TEST_S(sip_header_as_string(tmphome, (void *)from), Alice);
     TEST_S(from_str, Alice);
@@ -383,12 +394,14 @@
     TEST(media_features, 1);
     TEST(service_route_enable, 0);
     TEST(path_enable, 0);
+    TEST(auth_cache, nua_auth_cache_challenged);
     TEST(refer_expires, 333);
     TEST(refer_with_id, 0);
     TEST(substate, nua_substate_pending);
 
     TEST_S(sip_header_as_string(tmphome, (void *)allow), "OPTIONS, INFO, ACK");
     TEST_S(allow_str, "OPTIONS, INFO, ACK");
+    TEST_S(appl_method, "INVITE, REGISTER, PUBLISH, SUBSCRIBE, NOTIFY");
     TEST_S(sip_header_as_string(tmphome, (void *)allow_events), 
 	   "reg, presence, presence.winfo");
     TEST_S(allow_events_str, "reg, presence, presence.winfo");
@@ -414,7 +427,7 @@
     TEST_S(m_features, expect_m_features); }
     TEST_S(outbound, "foo");
 
-    free_events_in_list(ctx, ctx->a.events);
+    free_events_in_list(ctx, ctx->a.specials);
   }
 
   /* Test that only those tags that have been set per handle are returned by nua_get_hparams() */
@@ -446,6 +459,7 @@
     int media_features = -1;
     int service_route_enable = -1;
     int path_enable = -1;
+    int auth_cache = -1;
     unsigned refer_expires = (unsigned)-1;
     int refer_with_id = -1;
     int substate = -1;
@@ -504,6 +518,7 @@
 	       	NUTAG_MEDIA_FEATURES_REF(media_features),
 	       	NUTAG_SERVICE_ROUTE_ENABLE_REF(service_route_enable),
 	       	NUTAG_PATH_ENABLE_REF(path_enable),
+		NUTAG_AUTH_CACHE_REF(auth_cache),
 	       	NUTAG_SUBSTATE_REF(substate),
 
 	       	SIPTAG_SUPPORTED_REF(supported),
@@ -556,6 +571,7 @@
     TEST(media_features, -1);
     TEST(service_route_enable, -1);
     TEST(path_enable, -1);
+    TEST(auth_cache, -1);
     TEST(refer_expires, (unsigned)-1);
     TEST(refer_with_id, -1);
     TEST(substate, -1);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_ops.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_ops.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_ops.c	Tue Apr 24 10:14:28 2007
@@ -44,7 +44,7 @@
 
 int save_events(CONDITION_PARAMS)
 {
-  return save_event_in_list(ctx, event, ep, ep->call) == event_is_normal;
+  return save_event_in_list(ctx, event, ep, call) == event_is_normal;
 }
 
 int until_final_response(CONDITION_PARAMS)
@@ -54,8 +54,10 @@
 
 int save_until_final_response(CONDITION_PARAMS)
 {
-  save_event_in_list(ctx, event, ep, ep->call);
-  return event >= nua_r_set_params && status >= 200;
+  save_event_in_list(ctx, event, ep, call);
+  return
+    nua_r_set_params <= event && event < nua_i_network_changed
+    && status >= 200;
 }
 
 /** Save events.
@@ -64,13 +66,13 @@
  */
 int save_until_received(CONDITION_PARAMS)
 {
-  return save_event_in_list(ctx, event, ep, ep->call) == event_is_normal;
+  return save_event_in_list(ctx, event, ep, call) == event_is_normal;
 }
 
 /** Save events until nua_i_outbound is received.  */
 int save_until_special(CONDITION_PARAMS)
 {
-  return save_event_in_list(ctx, event, ep, ep->call) == event_is_special;
+  return save_event_in_list(ctx, event, ep, call) == event_is_special;
 }
 
 /* Return call state from event tag list */
@@ -143,34 +145,49 @@
 		 sip_t const *sip,
 		 tagi_t tags[])
 {
+  tagi_t const *t;
+
   if (event == nua_i_state) {
     fprintf(stderr, "%s.nua(%p): event %s %s\n",
-	    ep->name, nh, nua_event_name(event),
+	    ep->name, (void *)nh, nua_event_name(event),
 	    nua_callstate_name(callstate(tags)));
   }
   else if ((int)event >= nua_r_set_params) {
-    fprintf(stderr, "%s.nua(%p): event %s status %u %s\n",
-	    ep->name, nh, nua_event_name(event), status, phrase);
+    t = tl_find(tags, nutag_substate);
+    if (t) {
+      fprintf(stderr, "%s.nua(%p): event %s status %u %s (%s)\n",
+	      ep->name, (void*)nh, nua_event_name(event), status, phrase,
+	      nua_substate_name(t->t_value));
+    }
+    else {
+      fprintf(stderr, "%s.nua(%p): event %s status %u %s\n",
+	      ep->name, (void *)nh, nua_event_name(event), status, phrase);
+    }
+  }
+  else if (event == nua_i_notify) {
+    t = tl_find(tags, nutag_substate);
+    fprintf(stderr, "%s.nua(%p): event %s %s (%s)\n",
+	    ep->name, (void *)nh, nua_event_name(event), phrase,
+	    nua_substate_name(t ? t->t_value : 0));
   }
   else if ((int)event >= 0) {
     fprintf(stderr, "%s.nua(%p): event %s %s\n",
-	    ep->name, nh, nua_event_name(event), phrase);
+	    ep->name, (void *)nh, nua_event_name(event), phrase);
   }
   else if (status > 0) {
     fprintf(stderr, "%s.nua(%p): call %s() with status %u %s\n",
-	    ep->name, nh, operation, status, phrase);
+	    ep->name, (void *)nh, operation, status, phrase);
   }
   else {
-    tagi_t const *t;
     t = tl_find(tags, siptag_subject_str);
     if (t && t->t_value) {
       char const *subject = (char const *)t->t_value;
       fprintf(stderr, "%s.nua(%p): call %s() \"%s\"\n",
-	      ep->name, nh, operation, subject);
+	      ep->name, (void *)nh, operation, subject);
     }
     else
       fprintf(stderr, "%s.nua(%p): call %s()\n",
-	      ep->name, nh, operation);
+	      ep->name, (void *)nh, operation);
   }
 
   if ((tstflags & tst_verbatim) && tags)
@@ -202,10 +219,11 @@
     }
   }
 
-  if ((ep->next_event == -1 || ep->next_event == event) &&
-      (ep->next_condition == NULL ||
+  if ((ep->next_condition == NULL ||
        ep->next_condition(event, status, phrase,
-			  nua, ctx, ep, nh, call, sip, tags)))
+			  nua, ctx, ep, nh, call, sip, tags))
+      &&
+      (ep->next_event == -1 || ep->next_event == event))
     ep->running = 0;
 
   ep->last_event = event;
@@ -256,21 +274,21 @@
   a->last_event = -1;
   a->running = a_condition != NULL && a_condition != save_events;
   a->running |= a_event != -1;
-  a->flags.n = 0;
+  memset(&a->flags, 0, sizeof a->flags);
 
   b->next_event = b_event;
   b->next_condition = b_condition;
   b->last_event = -1;
   b->running = b_condition != NULL && b_condition != save_events;
   b->running |= b_event != -1;
-  b->flags.n = 0;
+  memset(&b->flags, 0, sizeof b->flags);
 
   c->next_event = c_event;
   c->next_condition = c_condition;
   c->last_event = -1;
   c->running = c_condition != NULL && c_condition != save_events;
   c->running |= c_event != -1;
-  c->flags.n = 0;
+  memset(&c->flags, 0, sizeof c->flags);
 
   for (; a->running || b->running || c->running;) {
     su_root_step(ctx->root, 1000);
@@ -379,7 +397,7 @@
   return 0;
 }
 
-/* Destroy an handle */
+/* Destroy a handle */
 int DESTROY(struct endpoint *ep,
 	    struct call *call,
 	    nua_handle_t *nh)
@@ -450,7 +468,7 @@
   return action;
 }
 
-/* Save nua event in endpoint list */
+/* Free nua events from endpoint list */
 void free_events_in_list(struct context *ctx,
 			 struct eventlist *list)
 {
@@ -466,6 +484,21 @@
   list->tail = &list->head;
 }
 
+void free_event_in_list(struct context *ctx,
+			struct eventlist *list,
+			struct event *e)
+{
+  if (e) {
+    if ((*e->prev = e->next))
+      e->next->prev = e->prev;
+    nua_destroy_event(e->saved_event);
+    su_free(ctx->home, e);
+
+    if (list->head == NULL)
+      list->tail = &list->head;
+  }
+}			      
+
 int is_special(nua_event_t e)
 {
   if (e == nua_i_active || e == nua_i_terminated)

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_proxy.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_proxy.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_proxy.c	Tue Apr 24 10:14:28 2007
@@ -52,6 +52,7 @@
 #include <sofia-sip/auth_module.h>
 #include <sofia-sip/su_tagarg.h>
 #include <sofia-sip/msg_addr.h>
+#include <sofia-sip/hostdomain.h>
 
 #include <stdlib.h>
 #include <assert.h>
@@ -228,9 +229,10 @@
 				  URL_STRING_MAKE("sip:0.0.0.0:*"),
 				  NULL, NULL,
 				  NTATAG_UA(0),
+				  NTATAG_CANCEL_487(0),
 				  NTATAG_SERVER_RPORT(1),
 				  NTATAG_CLIENT_RPORT(1),
-				  TAG_END());
+				  TAG_NEXT(proxy->tags));
 
   proxy->transport_contacts = create_transport_contacts(proxy);
 
@@ -308,7 +310,7 @@
   free(proxy->tags);
 }
 
-/* Create tst proxy object */
+/* Create test proxy object */
 struct proxy *test_proxy_create(su_root_t *root,
 				tag_type_t tag, tag_value_t value, ...)
 {
@@ -373,6 +375,27 @@
   }
 }
 
+void test_proxy_set_session_timer(struct proxy *p,
+				  sip_time_t session_expires, 
+				  sip_time_t min_se)
+{
+  if (p) {
+    p->prefs.session_expires = session_expires;
+    p->prefs.min_se = min_se;
+  }
+}
+
+void test_proxy_get_session_timer(struct proxy *p,
+				  sip_time_t *return_session_expires,
+				  sip_time_t *return_min_se)
+{
+  if (p) {
+    if (return_session_expires)
+      *return_session_expires = p->prefs.session_expires;
+    if (return_min_se) *return_min_se = p->prefs.min_se;
+  }
+}
+
 /* ---------------------------------------------------------------------- */
 
 static sip_contact_t *create_transport_contacts(struct proxy *p)
@@ -425,6 +448,7 @@
 
   sip_session_expires_t *x = NULL, x0[1];
   sip_min_se_t *min_se = NULL, min_se0[1];
+  char const *require = NULL;
 
   mf = sip->sip_max_forwards;
 
@@ -445,24 +469,33 @@
   }
 
   if (method == sip_method_invite) {
-    if (!sip->sip_min_se || 
-	sip->sip_min_se->min_delta < proxy->prefs.min_se) {
-      min_se = sip_min_se_init(min_se0);
-      min_se->min_delta = proxy->prefs.min_se;
-    }
-
-    if (!sip->sip_session_expires) {
-      x = sip_session_expires_init(x0);
-      x->x_delta = proxy->prefs.session_expires;
-    }
-    else if (sip->sip_session_expires->x_delta < proxy->prefs.min_se
-	     && sip_has_supported(sip->sip_supported, "timer")) {
-      if (min_se == NULL)
-	min_se = sip->sip_min_se; assert(min_se);
-      nta_incoming_treply(irq, SIP_422_SESSION_TIMER_TOO_SMALL,
-			  SIPTAG_MIN_SE(min_se),
-			  TAG_END());
-      return 422;
+    if (proxy->prefs.min_se) {
+      if (!sip->sip_min_se || 
+	  sip->sip_min_se->min_delta < proxy->prefs.min_se) {
+	min_se = sip_min_se_init(min_se0);
+	min_se->min_delta = proxy->prefs.min_se;
+      }
+
+      if (sip->sip_session_expires
+	  && sip->sip_session_expires->x_delta < proxy->prefs.min_se
+	  && sip_has_supported(sip->sip_supported, "timer")) {
+	if (min_se == NULL)
+	  min_se = sip->sip_min_se; assert(min_se);
+	nta_incoming_treply(irq, SIP_422_SESSION_TIMER_TOO_SMALL,
+			    SIPTAG_MIN_SE(min_se),
+			    TAG_END());
+	return 422;
+      }
+    }
+
+    if (proxy->prefs.session_expires) {
+      if (!sip->sip_session_expires ||
+	  sip->sip_session_expires->x_delta > proxy->prefs.session_expires) {
+	x = sip_session_expires_init(x0);
+	x->x_delta = proxy->prefs.session_expires;
+	if (!sip_has_supported(sip->sip_supported, "timer"))
+	  require = "timer";
+      }
     }
   }
 
@@ -526,6 +559,7 @@
 				   SIPTAG_REQUEST(rq),
 				   SIPTAG_SESSION_EXPIRES(x),
 				   SIPTAG_MIN_SE(min_se),
+				   SIPTAG_REQUIRE_STR(require),
 				   TAG_END());
   if (t->client == NULL) {
     proxy_transaction_destroy(t);
@@ -707,8 +741,8 @@
 sip_contact_t *binding_contacts(su_home_t *home, struct binding *bindings);
 
 int process_register(struct proxy *proxy,
-       	      nta_incoming_t *irq,
-       	      sip_t const *sip)
+		     nta_incoming_t *irq,
+		     sip_t const *sip)
 {
   auth_status_t *as;
   msg_t *msg;
@@ -751,6 +785,13 @@
 			     sip_t const *sip)
 {
   struct registration_entry *e = NULL;
+  sip_contact_t *m = sip->sip_contact;
+  sip_via_t *v = sip->sip_via;
+
+  if (m && v && v->v_received && m->m_url->url_host
+      && strcasecmp(v->v_received, m->m_url->url_host) 
+      && host_is_ip_address(m->m_url->url_host))
+    return set_status(as, 406, "Unacceptable Contact");
 
   auth_mod_check_client(p->auth, as, sip->sip_authorization,
 			registrar_challenger);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_proxy.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_proxy.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_proxy.h	Tue Apr 24 10:14:28 2007
@@ -48,6 +48,14 @@
 			       sip_time_t *return_expires, 
 			       sip_time_t *return_max_expires);
 
+void test_proxy_set_session_timer(struct proxy *p,
+				  sip_time_t session_expires, 
+				  sip_time_t min_se);
+
+void test_proxy_get_session_timer(struct proxy *p,
+				  sip_time_t *return_session_expires,
+				  sip_time_t *return_min_se);
+
 SOFIA_END_DECLS
 
 #endif

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_refer.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_refer.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_refer.c	Tue Apr 24 10:14:28 2007
@@ -43,21 +43,22 @@
 #define __func__ "test_call_hold"
 #endif
 
-int accept_call_immediately(CONDITION_PARAMS);
-
 /* ======================================================================== */
 /* NUA-9 tests: REFER */
 
-int test_refer0(struct context *ctx, int refer_with_id, char const *tests);
-int test_refer1(struct context *ctx, int refer_with_id, char const *tests);
+int test_refer0(struct context *ctx, char const *tests,
+		int refer_with_id, int notify_by_appl);
+
+int notify_until_terminated(CONDITION_PARAMS);
 
 int test_refer(struct context *ctx)
 {
   /* test twice, once without id and once with id */
   return
-    test_refer0(ctx, 0, "NUA-9.1") ||
-    test_refer0(ctx, 1, "NUA-9.2") ||
-    test_refer1(ctx, 0, "NUA-9.3");
+    test_refer0(ctx, "NUA-9.1", 0, 0) ||
+    test_refer0(ctx, "NUA-9.2", 1, 0) ||
+    test_refer0(ctx, "NUA-9.3", 0, 1) ||
+    test_refer0(ctx, "NUA-9.4", 1, 1);
 }
 
 /* Referred call:
@@ -103,13 +104,15 @@
 
 */
 
-int test_refer0(struct context *ctx, int refer_with_id, char const *tests)
+int test_refer0(struct context *ctx, char const *tests,
+		int refer_with_id, int notify_by_appl)
 {
   BEGIN();
 
   struct endpoint *a = &ctx->a,  *b = &ctx->b, *c = &ctx->c;
   struct call *a_call = a->call, *b_call = b->call, *c_call = c->call;
-  struct call *a_c2;
+  struct call *a_refer, *a_c2, *b_refer;
+  struct eventlist *a_revents, *b_revents;
   struct event *e;
   sip_t const *sip;
   sip_event_t const *a_event, *b_event;
@@ -124,7 +127,10 @@
   su_home_auto(tmphome, sizeof(tmphome));
 
   if (print_headings)
-    printf("TEST %s: REFER: refer A to C\n", tests);
+    printf("TEST %s: REFER: refer A to C%s%s%s\n", tests,
+	   refer_with_id ? " with Event id" : "",
+	   refer_with_id && !notify_by_appl ? " and" : "",
+	   !notify_by_appl ? " nua generating the NOTIFYs" : "");
 
   if (print_headings)
     printf("TEST %s.1: REFER: make a call between A and B\n", tests);
@@ -133,6 +139,28 @@
   nua_set_params(ctx->a.nua, NUTAG_REFER_WITH_ID(refer_with_id), TAG_END());
   run_a_until(ctx, nua_r_set_params, until_final_response);
 
+  if (refer_with_id) {
+    TEST_1(a_refer = calloc(1, (sizeof *a_refer) + (sizeof *a_refer->events)));
+    call_init(a_refer);
+    a_refer->events = (void *)(a_refer + 1);
+    eventlist_init(a_refer->events);
+
+    a_call->next = a_refer;
+    a_revents = a_refer->events;
+
+    TEST_1(b_refer = calloc(1, (sizeof *b_refer) + (sizeof *b_refer->events)));
+    call_init(b_refer);
+    b_refer->events = (void *)(b_refer + 1);
+    eventlist_init(b_refer->events);
+
+    b_call->next = b_refer;
+    b_revents = b_refer->events;
+  }
+  else {
+    a_refer = a_call, b_refer = b_call;
+    a_revents = a->events, b_revents = b->events;
+  }
+
   TEST_1(a_c2 = calloc(1, (sizeof *a_c2) + (sizeof *a_c2->events)));
   call_init(a_c2);
   a_c2->events = (void *)(a_c2 + 1);
@@ -198,7 +226,7 @@
     printf("TEST %s.1: PASSED\n", tests);
 
   /* ---------------------------------------------------------------------- */
-  /* REFER (initial NOTIFY is no more sent)
+  /* REFER (initial NOTIFY is no more sent unless REFER creates a new dialog)
    A                    B
    |<------REFER--------|
    |-------200 OK------>|
@@ -207,13 +235,20 @@
    */
 
   if (print_headings)
-    printf("TEST %s.2: refer A to C\n", tests);
+    printf("TEST %s.2: B refers A to C\n", tests);
+
+  if (b_refer != b_call)
+    TEST_1(b_refer->nh = 
+	   nua_handle(b->nua, b_refer, SIPTAG_TO(a->to), TAG_END()));
 
   *sip_refer_to_init(r0)->r_url = *c->contact->m_url;
   r0->r_url->url_headers = "subject=referred";
   r0->r_display = "C";
 
-  REFER(b, b_call, b_call->nh, SIPTAG_REFER_TO(r0), TAG_END());
+  REFER(b, b_refer, b_refer->nh, SIPTAG_REFER_TO(r0),
+	TAG_IF(!ctx->proxy_tests && b_refer != b_call,
+	       NUTAG_URL(a->contact->m_url)),
+	TAG_END());
   run_ab_until(ctx, -1, save_until_received,
 	       -1, save_until_final_response);
 
@@ -221,7 +256,7 @@
     Events in A:
     nua_i_refer
   */
-  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_refer);
+  TEST_1(e = a_revents->head); TEST_E(e->data->e_event, nua_i_refer);
   TEST(e->data->e_status, 202);
   a_event = NULL;
   TEST(tl_gets(e->data->e_tags,
@@ -233,17 +268,12 @@
   TEST_1(refer_to = sip_refer_to_dup(tmphome, sip->sip_refer_to));
   TEST_1(sip->sip_referred_by);
   TEST_1(referred_by = sip_referred_by_dup(tmphome, sip->sip_referred_by));
-  if (e->next) {
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_notify);
-  TEST_1(!e->next);
-  }
-  free_events_in_list(ctx, a->events);
 
   /*
      Events in B after nua_refer():
      nua_r_refer
   */
-  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_r_refer);
+  TEST_1(e = b_revents->head); TEST_E(e->data->e_event, nua_r_refer);
   TEST(e->data->e_status, 100);
   TEST(tl_gets(e->data->e_tags,
 	       NUTAG_REFER_EVENT_REF(b_event),
@@ -254,22 +284,32 @@
   TEST(e->data->e_status, 202);
   TEST_1(sip = sip_object(e->data->e_msg));
   TEST_SIZE(strtoul(b_event->o_id, NULL, 10), sip->sip_cseq->cs_seq);
-#if 0
-  if (!e->next)
-    run_b_until(ctx, -1, save_until_received);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_notify);
-  TEST(e->data->e_status, 200);
-  TEST_1(sip = sip_object(e->data->e_msg));
-  TEST_1(sip->sip_event);
-  if (refer_with_id)
-    TEST_S(sip->sip_event->o_id, b_event->o_id);
-  TEST_1(sip->sip_subscription_state);
-  TEST_S(sip->sip_subscription_state->ss_substate, "pending");
-  TEST_1(sip->sip_payload && sip->sip_payload->pl_data);
-  TEST_S(sip->sip_payload->pl_data, "SIP/2.0 100 Trying\r\n");
-  TEST_1(!e->next);
-#endif
-  free_events_in_list(ctx, b->events);
+
+  if (a_refer != a_call) {
+    if (b_revents->head->next->next == NULL)
+      run_ab_until(ctx, -1, save_until_received, nua_i_notify, save_events);
+    else if (a_revents->head->next == NULL)
+      run_a_until(ctx, -1, save_until_received);
+
+    TEST_1(e = a_revents->head->next); TEST_E(e->data->e_event, nua_r_notify);
+    TEST_1(!e->next);
+
+    TEST_1(e = b_revents->head->next->next);
+    TEST_E(e->data->e_event, nua_i_notify);
+    TEST(e->data->e_status, 200);
+    TEST_1(sip = sip_object(e->data->e_msg));
+    TEST_1(sip->sip_event);
+    if (refer_with_id)
+      TEST_S(sip->sip_event->o_id, b_event->o_id);
+    TEST_1(sip->sip_subscription_state);
+    TEST_S(sip->sip_subscription_state->ss_substate, "pending");
+    TEST_1(sip->sip_payload && sip->sip_payload->pl_data);
+    TEST_S(sip->sip_payload->pl_data, "SIP/2.0 100 Trying\r\n");
+    TEST_1(!e->next);
+  }
+
+  free_events_in_list(ctx, a_revents);
+  free_events_in_list(ctx, b_revents);
 
   if (print_headings)
     printf("TEST %s.2: PASSED\n", tests);
@@ -371,42 +411,43 @@
   *sip_to_init(to)->a_url = *refer_to->r_url;
   to->a_display = refer_to->r_display;
 
-  a->call->next = a_c2;
+  a_refer->next = a_c2;
 
   TEST_1(a_c2->nh = nua_handle(a->nua, a_c2, SIPTAG_TO(to), TAG_END()));
 
   INVITE(a, a_c2, a_c2->nh, /* NUTAG_URL(refer_to->r_url), */
-	 NUTAG_REFER_EVENT(a_event),
-	 NUTAG_NOTIFY_REFER(a_call->nh),
+	 TAG_IF(!notify_by_appl, NUTAG_REFER_EVENT(a_event)),
+	 TAG_IF(!notify_by_appl, NUTAG_NOTIFY_REFER(a_refer->nh)),
 	 SOATAG_USER_SDP_STR(a_c2->sdp),
 	 SIPTAG_REFERRED_BY(referred_by),
 	 TAG_END());
 
   run_abc_until(ctx,
-		-1, until_ready,
+		-1, notify_by_appl ? notify_until_terminated : until_ready,
 		-1, save_until_received,
-		-1, accept_call_immediately);
-  /* XXX - we should use accept_call instead of accept_call_immediately but
-     nua has a problem with automatically generated NOTIFYs:
-     3rd NOTIFY is not sent because 2nd is still in progress
-  */
+		-1, accept_call);
+
+  /* Wait until both NOTIFY has been responded */
+  while (a_revents->head == NULL || a_revents->head->next == NULL)
+    run_ab_until(ctx, -1, save_until_received, -1, save_events);
+  while (b_revents->head == NULL || b_revents->head->next == NULL)
+    run_ab_until(ctx, -1, save_events, -1, save_until_received);
 
   /* Client A transitions:
      INIT -(C1)-> CALLING: nua_invite(), nua_i_state
-     CALLING -(C2a+C4)-> READY: nua_r_invite, nua_i_state
-     nua_i_notify
-
-     XXX should be:
      CALLING -(C2+C4)-> PROCEEDING: nua_r_invite, nua_i_state
-     optional: nua_i_notify
+     nua_r_notify
      PROCEEDING -(C3+C4)-> READY: nua_r_invite, nua_i_state
-     nua_i_notify
-     optional: nua_i_notify
+     nua_r_notify
   */
   TEST_1(e = a_c2->events->head); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
   TEST_1(is_offer_sent(e->data->e_tags));
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
+  TEST(e->data->e_status, 180);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); /* PROCEEDING */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
   TEST(e->data->e_status, 200);
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
@@ -414,19 +455,32 @@
   TEST_1(!e->next);
   free_events_in_list(ctx, a_c2->events);
 
-  if (a->events->head == NULL)
-    run_a_until(ctx, -1, save_until_received);
-  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_notify);
-  TEST_1(!e->next);
-  free_events_in_list(ctx, a->events);
+  TEST_1(e = a_revents->head); TEST_E(e->data->e_event, nua_r_notify);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_notify);
+  if (a_refer == a_call && notify_by_appl) {
+    free_event_in_list(ctx, a_revents, a_revents->head);
+    free_event_in_list(ctx, a_revents, a_revents->head);
+  }
+  else {
+    TEST_1(!e->next);
+    free_events_in_list(ctx, a_revents);
+  }
 
   /*
      Events in B after nua_refer():
      nua_i_notify
   */
-  if (b->events->head == NULL)
-    run_b_until(ctx, -1, save_until_received);
-  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_notify);
+  TEST_1(e = b_revents->head); TEST_E(e->data->e_event, nua_i_notify);
+  TEST(e->data->e_status, 200);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_subscription_state);
+  TEST_S(sip->sip_subscription_state->ss_substate, "active");
+  TEST_1(sip->sip_payload && sip->sip_payload->pl_data);
+  TEST_S(sip->sip_payload->pl_data, "SIP/2.0 180 Ringing\r\n");
+  TEST_1(sip->sip_event);
+  if (refer_with_id)
+    TEST_S(sip->sip_event->o_id, b_event->o_id);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_notify);
   TEST(e->data->e_status, 200);
   TEST_1(sip = sip_object(e->data->e_msg));
   TEST_1(sip->sip_subscription_state);
@@ -436,13 +490,20 @@
   TEST_1(sip->sip_event);
   if (refer_with_id)
     TEST_S(sip->sip_event->o_id, b_event->o_id);
-  TEST_1(!e->next);
-  free_events_in_list(ctx, b->events);
+  if (b_refer == b_call && notify_by_appl) {
+    free_event_in_list(ctx, b_revents, b_revents->head);
+    free_event_in_list(ctx, b_revents, b_revents->head);
+  }
+  else {
+    TEST_1(!e->next);
+    free_events_in_list(ctx, b_revents);
+  }
 
   /*
    C transitions:
    INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
-   RECEIVED -(S3b)-> COMPLETED: nua_respond(), nua_i_state
+   RECEIVED -(S2a)-> EARLY: nua_respond(), nua_i_state
+   EARLY -(S3b)-> COMPLETED: nua_respond(), nua_i_state
    COMPLETED -(S4)-> READY: nua_i_ack, nua_i_state
   */
   TEST_1(e = c->events->head); TEST_E(e->data->e_event, nua_i_invite);
@@ -451,6 +512,8 @@
   TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
   TEST_1(is_offer_recv(e->data->e_tags));
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
+  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
   TEST_1(is_answer_sent(e->data->e_tags));
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_ack);
@@ -472,20 +535,28 @@
   if (print_headings)
     printf("TEST %s.5.1: terminate call between A and B\n", tests);
 
-  BYE(a, a_call, a_call->nh, TAG_END());
-  run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+  if (notify_by_appl) {
+    if (!a->events->head || !a->events->head->next)
+      run_ab_until(ctx, -1, until_terminated, -1, save_events);
+    if (!b->events->head || !b->events->head->next)
+      run_ab_until(ctx, -1, save_events, -1, until_terminated);
+  }
+  else {
+    BYE(a, a_call, a_call->nh, TAG_END());
+    run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+  }
 
   /*
-   Transitions of A:
-   READY --(T2)--> TERMINATING: nua_bye()
-   TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
+    Transitions of A:
+    READY --(T2)--> TERMINATING: nua_bye()
+    TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
   */
   TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_bye);
   TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
   TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
   TEST_1(!e->next);
   free_events_in_list(ctx, a->events);
-
+  
   /* Transitions of B:
      READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state
   */
@@ -540,10 +611,20 @@
   if (print_headings)
     printf("TEST %s.5.2: PASSED\n", tests);
 
+  nua_handle_destroy(c_call->nh), c_call->nh = NULL;
+
   nua_handle_destroy(a_c2->nh), a_c2->nh = NULL;
-  a->call->next = NULL; free(a_c2);
+  a_refer->next = NULL; free(a_c2);
 
-  nua_handle_destroy(c_call->nh), c_call->nh = NULL;
+  if (a_refer != a_call) {
+    nua_handle_destroy(a_refer->nh), a_refer->nh = NULL;
+    a_call->next = NULL; free(a_refer);
+  }
+
+  if (b_refer != b_call) {
+    nua_handle_destroy(b_refer->nh), b_refer->nh = NULL;
+    b_call->next = NULL; free(b_refer);
+  }
 
   if (print_headings)
     printf("TEST %s: PASSED\n", tests);
@@ -555,40 +636,6 @@
 
 
 /*
- accept_call_immediately
-                      X
- |                    |
- |-------INVITE------>|
- |<----100 Trying-----|
- |                    |
- |<--------200--------|
- |---------ACK------->|
-*/
-int accept_call_immediately(CONDITION_PARAMS)
-{
-  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
-    return 0;
-
-  save_event_in_list(ctx, event, ep, call);
-
-  switch (callstate(tags)) {
-  case nua_callstate_received:
-    RESPOND(ep, call, nh, SIP_200_OK,
-	    TAG_IF(call->sdp, SOATAG_USER_SDP_STR(call->sdp)),
-	    TAG_END());
-    return 0;
-  case nua_callstate_ready:
-    return 1;
-  case nua_callstate_terminated:
-    if (call)
-      nua_handle_destroy(call->nh), call->nh = NULL;
-    return 1;
-  default:
-    return 0;
-  }
-}
-
-/*
  X      INVITE
  |                    |
  |-----------------INVITE-------------------->|
@@ -610,18 +657,31 @@
   if (event == nua_r_invite) {
     sip_status_t *st = sip->sip_status;
     sip_payload_t *pl;
+    struct call *r_call;
+
+    if (!nua_handle_has_events(ep->call->nh))
+      r_call = ep->call->next;
+    else
+      r_call = ep->call;
+
+    assert(nua_handle_has_events(r_call->nh));
 
     pl = sip_payload_format(NULL, "SIP/2.0 %u %s\r\n", 
 			    st->st_status, st->st_phrase);
 
-    NOTIFY(ep, ep->call, ep->call->nh,
+    NOTIFY(ep, r_call, r_call->nh,
 	   SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
 	   SIPTAG_PAYLOAD(pl),
-	   TAG_IF(st->st_status >= 200,
-		  NUTAG_SUBSTATE(nua_substate_terminated)),
+	   NUTAG_SUBSTATE(st->st_status >= 200
+			  ? nua_substate_terminated
+			  : nua_substate_active),
 	   TAG_END());
 
-    BYE(ep, ep->call, ep->call->nh, TAG_END());
+    su_free(NULL, pl);
+
+    if (st->st_status >= 200)
+      BYE(ep, ep->call, ep->call->nh, TAG_END());
+
     return 0;
   }
 
@@ -635,392 +695,3 @@
     return 0;
   }
 }
-
-/* Referred call - NOTIFY and BYE are overlapped
-
-   A			B
-   |			|
-   |-------INVITE------>|
-   |<----100 Trying-----|
-   |			|
-   |<----180 Ringing----|
-   |			|
-   |<------200 OK-------|
-   |--------ACK-------->|
-   |			|
-   |<------REFER--------|
-   |-------200 OK------>|			C
-  [|-------NOTIFY------>|]			|
-  [|<------200 OK-------|]			|
-   |			|			|
-   |			|			|
-   |<-----SUBSCRIBE-----|                       |
-   |-------200 OK------>|			|
-   |			|			|
-   |			|			|
-   |-----------------INVITE-------------------->|
-   |			|			|
-   |			|			|
-   |<------------------200----------------------|
-   |-------NOTIFY------>|			|
-   |--------BYE-------->|			|
-   |-------------------ACK--------------------->|
-   |<------200 OK-------|			|
-   |<------200 OK-------|			|
-   |			X			|
-   |			 			|
-   |-------------------BYE--------------------->|
-   |<------------------200----------------------|
-   |						|
-
-*/
-
-int test_refer1(struct context *ctx, int refer_with_id, char const *tests)
-{
-  BEGIN();
-
-  struct endpoint *a = &ctx->a,  *b = &ctx->b, *c = &ctx->c;
-  struct call *a_call = a->call, *b_call = b->call, *c_call = c->call;
-  struct call *a_c2;
-  struct event *e;
-  sip_t const *sip;
-  sip_event_t const *a_event, *b_event;
-  sip_refer_to_t const *refer_to;
-  sip_referred_by_t const *referred_by;
-
-  sip_refer_to_t r0[1];
-  sip_to_t to[1];
-
-  su_home_t tmphome[SU_HOME_AUTO_SIZE(16384)];
-
-  su_home_auto(tmphome, sizeof(tmphome));
-
-  if (print_headings)
-    printf("TEST %s: REFER: refer A to C\n", tests);
-
-  if (print_headings)
-    printf("TEST %s.1: REFER: make a call between A and B\n", tests);
-
-  /* Do (not) include id with first implicit Event: refer */
-  nua_set_params(ctx->a.nua, NUTAG_REFER_WITH_ID(refer_with_id), TAG_END());
-  run_a_until(ctx, nua_r_set_params, until_final_response);
-
-  TEST_1(a_c2 = calloc(1, (sizeof *a_c2) + (sizeof *a_c2->events)));
-  call_init(a_c2);
-  a_c2->events = (void *)(a_c2 + 1);
-  eventlist_init(a_c2->events);
-
-  a_call->sdp = "m=audio 5008 RTP/AVP 8";
-  b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
-  a_c2->sdp   = "m=audio 5012 RTP/AVP 8";
-  c_call->sdp = "m=audio 5014 RTP/AVP 0 8";
-
-  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
-
-  INVITE(a, a_call, a_call->nh,
-	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
-	 SOATAG_USER_SDP_STR(a_call->sdp),
-	 TAG_END());
-
-  run_ab_until(ctx, -1, until_ready, -1, accept_call);
-
-  /* Client transitions:
-     INIT -(C1)-> CALLING: nua_invite(), nua_i_state
-     CALLING -(C2)-> PROCEEDING: nua_r_invite, nua_i_state
-     PROCEEDING -(C3+C4)-> READY: nua_r_invite, nua_i_state
-  */
-  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
-  TEST_1(is_offer_sent(e->data->e_tags));
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
-  TEST(e->data->e_status, 180);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_proceeding); /* PROCEEDING */
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
-  TEST_1(is_answer_recv(e->data->e_tags));
-  TEST_1(!e->next);
-  free_events_in_list(ctx, a->events);
-
-  /*
-   Server transitions:
-   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
-   RECEIVED -(S2a)-> EARLY: nua_respond(), nua_i_state
-   EARLY -(S3b)-> COMPLETED: nua_respond(), nua_i_state
-   COMPLETED -(S4)-> READY: nua_i_ack, nua_i_state
-  */
-  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_invite);
-  TEST(e->data->e_status, 100);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
-  TEST_1(is_offer_recv(e->data->e_tags));
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_early); /* EARLY */
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
-  TEST_1(is_answer_sent(e->data->e_tags));
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_ack);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
-  TEST_1(!e->next);
-  free_events_in_list(ctx, b->events);
-
-  if (print_headings)
-    printf("TEST %s.1: PASSED\n", tests);
-
-  /* ---------------------------------------------------------------------- */
-  /* REFER (initial NOTIFY is no more sent)
-   A                    B
-   |<------REFER--------|
-   |-------200 OK------>|
-  [|-------NOTIFY------>|]			|
-  [|<------200 OK-------|]			|
-   */
-
-  if (print_headings)
-    printf("TEST %s.2: refer A to C\n", tests);
-
-  *sip_refer_to_init(r0)->r_url = *c->contact->m_url;
-  r0->r_url->url_headers = "subject=referred";
-  r0->r_display = "C";
-
-  REFER(b, b_call, b_call->nh, SIPTAG_REFER_TO(r0), TAG_END());
-  run_ab_until(ctx, -1, save_until_received,
-	       -1, save_until_final_response);
-
-  /*
-    Events in A:
-    nua_i_refer
-  */
-  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_refer);
-  TEST(e->data->e_status, 202);
-  a_event = NULL;
-  TEST(tl_gets(e->data->e_tags,
-	       NUTAG_REFER_EVENT_REF(a_event),
-	       TAG_END()), 1);
-  TEST_1(a_event); TEST_1(a_event = sip_event_dup(tmphome, a_event));
-  TEST_1(sip = sip_object(e->data->e_msg));
-  TEST_1(sip->sip_refer_to);
-  TEST_1(refer_to = sip_refer_to_dup(tmphome, sip->sip_refer_to));
-  TEST_1(sip->sip_referred_by);
-  TEST_1(referred_by = sip_referred_by_dup(tmphome, sip->sip_referred_by));
-  if (e->next) {
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_notify);
-  TEST_1(!e->next);
-  }
-  free_events_in_list(ctx, a->events);
-
-  /*
-     Events in B after nua_refer():
-     nua_r_refer
-  */
-  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_r_refer);
-  TEST(e->data->e_status, 100);
-  TEST(tl_gets(e->data->e_tags,
-	       NUTAG_REFER_EVENT_REF(b_event),
-	       TAG_END()), 1);
-  TEST_1(b_event); TEST_1(b_event->o_id);
-  TEST_1(b_event = sip_event_dup(tmphome, b_event));
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_refer);
-  TEST(e->data->e_status, 202);
-  TEST_1(sip = sip_object(e->data->e_msg));
-  TEST_SIZE(strtoul(b_event->o_id, NULL, 10), sip->sip_cseq->cs_seq);
-#if 0
-  if (!e->next)
-    run_b_until(ctx, -1, save_until_received);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_notify);
-  TEST(e->data->e_status, 200);
-  TEST_1(sip = sip_object(e->data->e_msg));
-  TEST_1(sip->sip_event);
-  if (refer_with_id)
-    TEST_S(sip->sip_event->o_id, b_event->o_id);
-  TEST_1(sip->sip_subscription_state);
-  TEST_S(sip->sip_subscription_state->ss_substate, "pending");
-  TEST_1(sip->sip_payload && sip->sip_payload->pl_data);
-  TEST_S(sip->sip_payload->pl_data, "SIP/2.0 100 Trying\r\n");
-  TEST_1(!e->next);
-#endif
-  free_events_in_list(ctx, b->events);
-
-  if (print_headings)
-    printf("TEST %s.2: PASSED\n", tests);
-
-
-  /* ---------------------------------------------------------------------- */
-  /*
-   A                    B                       C
-   |			|			|
-   |-----------------INVITE-------------------->|
-   |			|			|
-  XXX			|			|
-   |			|			|
-   |<------------------200----------------------|
-   |-------NOTIFY------>|			|
-   |---------BYE------->|			|
-   |-------------------ACK--------------------->|
-   |<--------200--------|			|
-   |<------200 OK-------|			|
-   |                    X
-     */
-
-  if (print_headings)
-    printf("TEST %s.4: A invites C\n", tests);
-
-  *sip_to_init(to)->a_url = *refer_to->r_url;
-  to->a_display = refer_to->r_display;
-
-  a->call->next = a_c2;
-
-  TEST_1(a_c2->nh = nua_handle(a->nua, a_c2, SIPTAG_TO(to), TAG_END()));
-
-  INVITE(a, a_c2, a_c2->nh, /* NUTAG_URL(refer_to->r_url), */
-	 NUTAG_REFER_EVENT(a_event),
-	 /* NUTAG_NOTIFY_REFER(a_call->nh), */
-	 SOATAG_USER_SDP_STR(a_c2->sdp),
-	 SIPTAG_REFERRED_BY(referred_by),
-	 TAG_END());
-
-  run_abc_until(ctx,
-		-1, notify_until_terminated,
-		-1, until_terminated,
-		-1, accept_call_immediately);
-
-  /* XXX - we should use accept_call instead of accept_call_immediately but
-     nua has a problem with automatically generated NOTIFYs:
-     3rd NOTIFY is not sent because 2nd is still in progress
-  */
-
-  /* Client A transitions:
-     INIT -(C1)-> CALLING: nua_invite(), nua_i_state
-     CALLING -(C2a+C4)-> READY: nua_r_invite, nua_i_state
-     nua_r_notify
-
-     Transitions of first call:
-     READY --(T2)--> TERMINATING: nua_bye()
-     TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
-
-     XXX should be:
-     CALLING -(C2+C4)-> PROCEEDING: nua_r_invite, nua_i_state
-     optional: nua_i_notify
-     PROCEEDING -(C3+C4)-> READY: nua_r_invite, nua_i_state
-     nua_i_notify
-     optional: nua_i_notify
-  */
-  TEST_1(e = a_c2->events->head); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
-  TEST_1(is_offer_sent(e->data->e_tags));
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_invite);
-  TEST(e->data->e_status, 200);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
-  TEST_1(is_answer_recv(e->data->e_tags));
-  TEST_1(!e->next);
-  free_events_in_list(ctx, a_c2->events);
-
-  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_notify);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_bye);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
-  free_events_in_list(ctx, a->events);
-
-  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
-
-  /*
-     Events in B after nua_refer():
-     nua_i_notify
-     READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state
-  */
-  if (b->events->head == NULL)
-    run_b_until(ctx, -1, save_until_received);
-  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_notify);
-  TEST(e->data->e_status, 200);
-  TEST_1(sip = sip_object(e->data->e_msg));
-  TEST_1(sip->sip_subscription_state);
-  TEST_S(sip->sip_subscription_state->ss_substate, "terminated");
-  TEST_1(sip->sip_payload && sip->sip_payload->pl_data);
-  TEST_S(sip->sip_payload->pl_data, "SIP/2.0 200 OK\r\n");
-  TEST_1(sip->sip_event);
-  if (refer_with_id)
-    TEST_S(sip->sip_event->o_id, b_event->o_id);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_bye);
-  TEST(e->data->e_status, 200);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
-  TEST_1(!e->next);
-  free_events_in_list(ctx, b->events);
-
-  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
-
-  /*
-   C transitions:
-   INIT -(S1)-> RECEIVED: nua_i_invite, nua_i_state
-   RECEIVED -(S3b)-> COMPLETED: nua_respond(), nua_i_state
-   COMPLETED -(S4)-> READY: nua_i_ack, nua_i_state
-  */
-  TEST_1(e = c->events->head); TEST_E(e->data->e_event, nua_i_invite);
-  TEST(e->data->e_status, 100);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_received); /* RECEIVED */
-  TEST_1(is_offer_recv(e->data->e_tags));
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_completed); /* COMPLETED */
-  TEST_1(is_answer_sent(e->data->e_tags));
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_ack);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
-  TEST_1(!e->next);
-  free_events_in_list(ctx, c->events);
-
-  if (print_headings)
-    printf("TEST %s.4: PASSED\n", tests);
-
-  /* ---------------------------------------------------------------------- */
-  /*
-   A                                            C
-   |-------------------BYE--------------------->|
-   |<------------------200----------------------|
-   */
-
-  if (print_headings)
-    printf("TEST %s.5.2: terminate call between A and C\n", tests);
-
-  BYE(a, a_c2, a_c2->nh, TAG_END());
-  run_abc_until(ctx, -1, until_terminated, -1, NULL, -1, until_terminated);
-
-  /*
-   Transitions of A:
-   READY --(T2)--> TERMINATING: nua_bye()
-   TERMINATING --(T3)--> TERMINATED: nua_r_bye, nua_i_state
-  */
-  TEST_1(e = a_c2->events->head); TEST_E(e->data->e_event, nua_r_bye);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
-  TEST_1(!e->next);
-  free_events_in_list(ctx, a_c2->events);
-
-  /* Transitions of B:
-     READY -(T1)-> TERMINATED: nua_i_bye, nua_i_state
-  */
-  TEST_1(e = c->events->head); TEST_E(e->data->e_event, nua_i_bye);
-  TEST(e->data->e_status, 200);
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_terminated); /* TERMINATED */
-  TEST_1(!e->next);
-  free_events_in_list(ctx, c->events);
-
-  if (print_headings)
-    printf("TEST %s.5.2: PASSED\n", tests);
-
-  nua_handle_destroy(a_c2->nh), a_c2->nh = NULL;
-  a->call->next = NULL; free(a_c2);
-
-  nua_handle_destroy(c_call->nh), c_call->nh = NULL;
-
-  if (print_headings)
-    printf("TEST %s: PASSED\n", tests);
-
-  su_home_deinit(tmphome);
-
-  END();
-}

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_register.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_register.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_register.c	Tue Apr 24 10:14:28 2007
@@ -55,6 +55,7 @@
   struct event *e;
   sip_t const *sip;
   sip_cseq_t cseq[1];
+  int seen_401;
 
   if (ctx->p)
     test_proxy_set_expiration(ctx->p, 5, 5, 10);
@@ -133,16 +134,32 @@
 	   NUTAG_KEEPALIVE(1000),
 	   NUTAG_M_DISPLAY("A&A"),
 	   NUTAG_M_USERNAME("a"),
+	   NUTAG_M_PARAMS("foo=bar"),
+	   NUTAG_M_FEATURES("q=0.9"),
 	   SIPTAG_CSEQ(cseq),
 	   TAG_END());
   run_a_until(ctx, -1, save_until_final_response);
 
   TEST_1(e = a->events->head);
-  TEST_E(e->data->e_event, nua_r_register);
   TEST_1(sip = sip_object(e->data->e_msg));
+  if (ctx->nat) {
+    TEST_E(e->data->e_event, nua_r_register);
+    TEST(e->data->e_status, 100);
+    TEST(sip->sip_status->st_status, 406);
+    /* Check that CSeq included in tags is actually used in the request */
+    TEST(sip->sip_cseq->cs_seq, 13);
+    TEST_1(!sip->sip_contact);
+    TEST_1(e = e->next);
+    TEST_1(sip = sip_object(e->data->e_msg));
+    TEST(sip->sip_cseq->cs_seq, 14);
+  }
+  else {
+    /* Check that CSeq included in tags is actually used in the request */
+    TEST(sip->sip_cseq->cs_seq, 13);
+  }
+  TEST_E(e->data->e_event, nua_r_register);
   TEST(e->data->e_status, 401);
   TEST(sip->sip_status->st_status, 401);
-  TEST(sip->sip_cseq->cs_seq, 13);
   TEST_1(!sip->sip_contact);
   TEST_1(!e->next);
   free_events_in_list(ctx, a->events);
@@ -160,7 +177,8 @@
     /* VC does not dig \" with TEST_S() */
   TEST_S(sip->sip_contact->m_display, expect_m_display); }
   TEST_S(sip->sip_contact->m_url->url_user, "a");
-  TEST(sip->sip_cseq->cs_seq, 14);
+  TEST_1(strstr(sip->sip_contact->m_url->url_params, "foo=bar"));
+  TEST_S(sip->sip_contact->m_q, "0.9");
 
   if (ctx->nat) {
     TEST_1(e = a->specials->head);
@@ -184,6 +202,8 @@
 
     REGISTER(b, b_reg, b_reg->nh, SIPTAG_TO(b->to), 
 	     SIPTAG_CONTACT(m),
+	     /* Do not include credentials unless challenged */
+	     NUTAG_AUTH_CACHE(nua_auth_cache_challenged),
 	     TAG_END());
   }
   run_ab_until(ctx, -1, save_events, -1, save_until_final_response);
@@ -208,7 +228,7 @@
   TEST_1(sip->sip_contact);
   TEST_S(sip->sip_contact->m_display, "B");
   TEST_S(sip->sip_contact->m_url->url_user, "b");
-
+  free_events_in_list(ctx, b->events);
   if (print_headings)
     printf("TEST NUA-2.3.2: PASSED\n");
 
@@ -221,8 +241,12 @@
   TEST_1(c_reg->nh = nua_handle(c->nua, c_reg, TAG_END()));
 
   REGISTER(c, c_reg, c_reg->nh, SIPTAG_TO(c->to), 
+	   NUTAG_OUTBOUND(NULL),
 	   NUTAG_M_DISPLAY("C"),
 	   NUTAG_M_USERNAME("c"),
+	   NUTAG_M_PARAMS("c=1"),
+	   NUTAG_M_FEATURES("q=0.987;expires=5"),
+	   NUTAG_CALLEE_CAPS(1),
 	   SIPTAG_EXPIRES_STR("5"), /* Test 423 negotiation */
 	   TAG_END());
   run_abc_until(ctx, -1, save_events, -1, save_events, 
@@ -253,6 +277,9 @@
   TEST_1(sip->sip_contact);
   TEST_S(sip->sip_contact->m_display, "C");
   TEST_S(sip->sip_contact->m_url->url_user, "c");
+  TEST_1(strstr(sip->sip_contact->m_url->url_params, "c=1"));
+  TEST_S(sip->sip_contact->m_q, "0.987");
+  TEST_1(msg_header_find_param(sip->sip_contact->m_common, "methods="));
   TEST_1(!e->next);
   free_events_in_list(ctx, c->events);
 
@@ -306,11 +333,21 @@
   TEST_1(!e->next);
   free_events_in_list(ctx, a->events);
 
+  seen_401 = 0;
+
   for (e = b->events->head; e; e = e->next) {
     TEST_E(e->data->e_event, nua_r_register);
-    TEST(e->data->e_status, 200);
     TEST_1(sip = sip_object(e->data->e_msg));
-    TEST_1(sip->sip_contact);
+
+    if (e->data->e_status == 200) {
+      TEST(e->data->e_status, 200);
+      TEST_1(seen_401);
+      TEST_1(sip->sip_contact);
+    }
+    else if (sip->sip_status && sip->sip_status->st_status == 401) {
+      seen_401 = 1;
+    }
+
     if (!e->next)
       break;
   }
@@ -349,7 +386,7 @@
   sip_t const *sip;
 
   if (print_headings)
-    printf("TEST NUA-2.3.2: REGISTER b to c\n");
+    printf("TEST NUA-2.6.1: REGISTER b to c\n");
 
   nua_set_params(ctx->c.nua,
 		 NUTAG_ALLOW("REGISTER"),
@@ -372,9 +409,6 @@
   TEST_1(sip = sip_object(e->data->e_msg));
   TEST_1(!sip->sip_contact);
 
-  if (print_headings)
-    printf("TEST NUA-2.6.1: PASSED\n");
-
   free_events_in_list(ctx, b->events);
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
@@ -388,7 +422,7 @@
   nua_handle_destroy(c_call->nh), c_call->nh = NULL;
 
   if (print_headings)
-    printf("TEST NUA-2.3.4: PASSED\n");
+    printf("TEST NUA-2.6.1: PASSED\n");
 
   END();
 }
@@ -552,7 +586,8 @@
 
   BEGIN();
 
-  struct endpoint *a = &ctx->a,  *b = &ctx->b, *c = &ctx->c;
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
   struct event *e;
   sip_t const *sip;
 
@@ -586,7 +621,38 @@
   if (print_headings)
     printf("TEST NUA-2.5.1: PASSED\n");
   
-  (void)b; (void)c; (void)sip;
+  if (print_headings)
+    printf("TEST NUA-2.5.2: OPTIONS from B to A\n");
+
+  TEST_1(b_call->nh = nua_handle(b->nua, b_call, SIPTAG_TO(a->to), TAG_END()));
+
+  OPTIONS(b, b_call, b_call->nh, TAG_END());
+
+  run_ab_until(ctx, -1, save_until_received,
+	       -1, save_until_final_response);
+
+  /* Client events: nua_options(), nua_r_options */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_r_options);
+  TEST(e->data->e_status, 200);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_allow); TEST_1(sip->sip_accept); TEST_1(sip->sip_supported);
+  /* TEST_1(sip->sip_content_type); */
+  /* TEST_1(sip->sip_payload); */
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  /* Server events: nua_i_options */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_options);
+  TEST(e->data->e_status, 200);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-2.5.2: PASSED\n");
 
   END();
 }
@@ -619,6 +685,10 @@
     run_a_until(ctx, -1, save_until_final_response);
     TEST_1(e = a->events->head);
     TEST_E(e->data->e_event, nua_r_unregister);
+    if (e->data->e_status == 100) {
+      TEST_1(e = e->next);
+      TEST_E(e->data->e_event, nua_r_unregister);
+    }
     TEST(e->data->e_status, 200);
     TEST_1(sip = sip_object(e->data->e_msg));
     TEST_1(!sip->sip_contact);
@@ -639,6 +709,10 @@
     run_b_until(ctx, -1, save_until_final_response);
     TEST_1(e = b->events->head);
     TEST_E(e->data->e_event, nua_r_unregister);
+    if (e->data->e_status == 100) {
+      TEST_1(e = e->next);
+      TEST_E(e->data->e_event, nua_r_unregister);
+    }
     TEST(e->data->e_status, 200);
     TEST_1(sip = sip_object(e->data->e_msg));
     TEST_1(!sip->sip_contact);
@@ -658,6 +732,7 @@
   UNREGISTER(c, c->call, c->call->nh, SIPTAG_TO(c->to), 
 	     NUTAG_M_DISPLAY("C"),
 	     NUTAG_M_USERNAME("c"),
+	     NUTAG_M_PARAMS("c=1"),
 	     TAG_END());
   run_c_until(ctx, -1, save_until_final_response);
 
@@ -688,6 +763,10 @@
     run_c_until(ctx, -1, save_until_final_response);
     TEST_1(e = c->events->head);
     TEST_E(e->data->e_event, nua_r_unregister);
+    if (e->data->e_status == 100) {
+      TEST_1(e = e->next);
+      TEST_E(e->data->e_event, nua_r_unregister);
+    }
     TEST(e->data->e_status, 200);
     TEST_1(sip = sip_object(e->data->e_msg));
     TEST_1(!sip->sip_contact);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_session_timer.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_session_timer.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_session_timer.c	Tue Apr 24 10:14:28 2007
@@ -22,7 +22,7 @@
  *
  */
 
-/**@CFILE test_nua_re_invite.c
+/**@CFILE test_session_timer.c
  * @brief NUA-8 tests: Session timer, UPDATE
  *
  * @author Pekka Pessi <Pekka.Pessi at nokia.com>
@@ -40,11 +40,13 @@
 #elif HAVE_FUNCTION
 #define __func__ __FUNCTION__
 #else
-#define __func__ "test_call_hold"
+#define __func__ "test_session_timer"
 #endif
 
 /* ======================================================================== */
 
+static size_t remove_update(void *a, void *message, size_t len);
+
 int test_session_timer(struct context *ctx)
 {
   BEGIN();
@@ -69,22 +71,6 @@
    |--INVITE->| 	|
    |<--422----|		|
    |---ACK--->|		|
-   |			|
-   |-------INVITE------>|
-   |<-------422---------|
-   |--------ACK-------->|
-   |			|
-   |-------INVITE------>|
-   |<----100 Trying-----|
-   |			|
-   |<----180 Ringing----|
-   |			|
-   |<------200 OK-------|
-   |--------ACK-------->|
-   |			|
-   |<-------BYE---------|
-   |-------200 OK-------|
-   |			|
 
 */
 
@@ -94,8 +80,15 @@
   a_call->sdp = "m=audio 5008 RTP/AVP 8";
   b_call->sdp = "m=audio 5010 RTP/AVP 0 8";
 
+  /* We negotiate session timer of 6 second */
+  /* Disable session timer from proxy */
+  test_proxy_set_session_timer(ctx->p, 0, 0); 
+
   nua_set_params(ctx->b.nua,
 		 NUTAG_SESSION_REFRESHER(nua_any_refresher),
+		 NUTAG_MIN_SE(1),
+		 NUTAG_SESSION_TIMER(6),
+		 NTATAG_SIP_T1X64(8000),
 		 TAG_END());
 
   run_b_until(ctx, nua_r_set_params, until_final_response);
@@ -159,23 +152,132 @@
   if (print_headings)
     printf("TEST NUA-8.1.1: PASSED\n");
 
+  if (ctx->expensive) {
+    nua_set_hparams(a_call->nh,
+		    NUTAG_SUPPORTED("timer"),
+		    NUTAG_MIN_SE(1),
+		    NUTAG_SESSION_TIMER(5),
+		    TAG_END());
+    run_a_until(ctx, nua_r_set_params, until_final_response);
+
+    if (print_headings)
+      printf("TEST NUA-8.1.2: Wait for refresh using INVITE\n");
+
+    run_ab_until(ctx, -1, until_ready, -1, until_ready);
+
+    free_events_in_list(ctx, a->events);
+    free_events_in_list(ctx, b->events);
+
+    if (print_headings)
+      printf("TEST NUA-8.1.2: PASSED\n");
+
+    nua_set_hparams(b_call->nh,
+		    NUTAG_UPDATE_REFRESH(1),
+		    TAG_END());
+    run_b_until(ctx, nua_r_set_params, until_final_response);
+
+    if (print_headings)
+      printf("TEST NUA-8.1.3: Wait for refresh using UPDATE\n");
+
+    run_ab_until(ctx, -1, until_ready, -1, until_ready);
+
+    TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_update);
+
+    free_events_in_list(ctx, a->events);
+    free_events_in_list(ctx, b->events);
+
+    if (print_headings)
+      printf("TEST NUA-8.1.3: PASSED\n");
+
+    if (ctx->nat) {
+      struct nat_filter *f;
+
+      if (print_headings)
+	printf("TEST NUA-8.1.4: filter UPDATE, wait until session expires\n");
+
+      f = test_nat_add_filter(ctx->nat, remove_update, NULL, nat_inbound);
+      TEST_1(f);
+
+      run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+      
+      TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_bye);
+
+      free_events_in_list(ctx, a->events);
+      free_events_in_list(ctx, b->events);
+
+      nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+      nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+      test_nat_remove_filter(ctx->nat, f);
+
+      if (print_headings)
+	printf("TEST NUA-8.1.4: PASSED\n");
+    }
+  }
+
+  if (b_call->nh) {
+    if (print_headings)
+      printf("TEST NUA-8.1.9: Terminate first session timer call\n");
+
+    BYE(b, b_call, b_call->nh, TAG_END());
+    run_ab_until(ctx, -1, until_terminated, -1, until_terminated);
+    free_events_in_list(ctx, a->events);
+    free_events_in_list(ctx, b->events);
+
+    nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+    nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+    if (print_headings)
+      printf("TEST NUA-8.1.9: PASSED\n");
+  }
+
+  /*
+   |			|
+   |-------INVITE------>|
+   |<-------422---------|
+   |--------ACK-------->|
+   |			|
+   |-------INVITE------>|
+   |<----100 Trying-----|
+   |			|
+   |<----180 Ringing----|
+   |			|
+   |<------200 OK-------|
+   |--------ACK-------->|
+   |			|
+   |<-------BYE---------|
+   |-------200 OK-------|
+   |			|
+  */
+
   if (print_headings)
-    printf("TEST NUA-8.1.2: Session timers negotiation\n");
+    printf("TEST NUA-8.2: Session timers negotiation\n");
+
+  test_proxy_set_session_timer(ctx->p, 180, 90);
+
+  nua_set_params(a->nua,
+		 NUTAG_SUPPORTED("timer"),
+		 TAG_END());
+
+  run_a_until(ctx, nua_r_set_params, until_final_response);
 
-  nua_set_hparams(b_call->nh,
-		  NUTAG_AUTOANSWER(0),
-		  NUTAG_MIN_SE(120),
-		  TAG_END());
+  nua_set_params(b->nua,
+		 NUTAG_AUTOANSWER(0),
+		 NUTAG_MIN_SE(120),
+		 NTATAG_SIP_T1X64(2000),
+		 TAG_END());
 
   run_b_until(ctx, nua_r_set_params, until_final_response);
 
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to),
+				 TAG_END()));
 
   INVITE(a, a_call, a_call->nh,
 	 TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
 	 SOATAG_USER_SDP_STR(a_call->sdp),
 	 SIPTAG_SUPPORTED_STR("100rel, timer"),
-	 NUTAG_SESSION_TIMER(15),
-	 NUTAG_MIN_SE(5),
+	 NUTAG_SESSION_TIMER(4),
+	 NUTAG_MIN_SE(3),
 	 TAG_END());
 
   run_ab_until(ctx, -1, until_ready, -1, accept_call);
@@ -252,17 +354,17 @@
   free_events_in_list(ctx, b->events);
 
   if (print_headings)
-    printf("TEST NUA-8.1: PASSED\n");
+    printf("TEST NUA-8.2: PASSED\n");
 
   if (print_headings)
-    printf("TEST NUA-8.2: use UPDATE\n");
+    printf("TEST NUA-8.3: UPDATE with session timer headers\n");
 
   UPDATE(b, b_call, b_call->nh, TAG_END());
   run_ab_until(ctx, -1, until_ready, -1, until_ready);
 
   /* Events from B (who sent UPDATE) */
   TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_state);
-  TEST(callstate(e->data->e_tags), nua_callstate_ready); /* READY */
+  TEST(callstate(e->data->e_tags), nua_callstate_calling); /* CALLING */
   TEST_1(is_offer_sent(e->data->e_tags));
   if (!e->next)
     run_b_until(ctx, -1, until_ready);
@@ -313,7 +415,20 @@
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
   if (print_headings)
-    printf("TEST NUA-8.2: PASSED\n");
+    printf("TEST NUA-8.3: PASSED\n");
 
   END();
 }
+
+static
+size_t remove_update(void *a, void *message, size_t len)
+{
+  (void)a;
+
+  if (strncmp("UPDATE ", message, 7) == 0) {
+    return 0;
+  }
+
+  return len;
+}
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_simple.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_simple.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_simple.c	Tue Apr 24 10:14:28 2007
@@ -43,6 +43,8 @@
 #define __func__ "test_simple"
 #endif
 
+extern int accept_request(CONDITION_PARAMS);
+
 int test_message(struct context *ctx)
 {
   BEGIN();
@@ -62,7 +64,7 @@
 
 */
   if (print_headings)
-    printf("TEST NUA-11.1: MESSAGE\n");
+    printf("TEST NUA-11.1.1: MESSAGE\n");
 
   if (ctx->proxy_tests)
     *url = *b->to->a_url;
@@ -76,7 +78,7 @@
 
   MESSAGE(a, a_call, a_call->nh,
 	  NUTAG_URL(url),
-	  SIPTAG_SUBJECT_STR("NUA-11.1"),
+	  SIPTAG_SUBJECT_STR("NUA-11.1.1"),
 	  SIPTAG_CONTENT_TYPE_STR("text/plain"),
 	  SIPTAG_PAYLOAD_STR("Hello hellO!\n"),
 	  TAG_END());
@@ -98,7 +100,7 @@
   TEST(e->data->e_status, 200);
   TEST_1(sip = sip_object(e->data->e_msg));
   TEST_1(sip->sip_subject && sip->sip_subject->g_string);
-  TEST_S(sip->sip_subject->g_string, "NUA-11.1");
+  TEST_S(sip->sip_subject->g_string, "NUA-11.1.1");
   TEST_1(sip->sip_organization);
   TEST_S(sip->sip_organization->g_string, "United Testers");
   TEST_1(!e->next);
@@ -110,7 +112,64 @@
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
   if (print_headings)
-    printf("TEST NUA-11.1: PASSED\n");
+    printf("TEST NUA-11.1.1: PASSED\n");
+
+/* MESSAGE as application method
+
+   A			B
+   |-------MESSAGE----->|
+   |<-------202---------|
+   |			|
+*/
+
+  if (print_headings)
+    printf("TEST NUA-11.1.2: MESSAGE\n");
+
+  nua_set_params(b->nua, NUTAG_APPL_METHOD("MESSAGE"), TAG_END());
+  run_b_until(ctx, nua_r_set_params, until_final_response);
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, TAG_END()));
+
+  MESSAGE(a, a_call, a_call->nh,
+	  NUTAG_URL(url),
+	  SIPTAG_SUBJECT_STR("NUA-11.1.2"),
+	  SIPTAG_CONTENT_TYPE_STR("text/plain"),
+	  SIPTAG_PAYLOAD_STR("Hello hellO!\n"),
+	  TAG_END());
+
+  run_ab_until(ctx, -1, save_until_final_response, -1, accept_request);
+
+  /* Client events:
+     nua_message(), nua_r_message
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_message);
+  TEST(e->data->e_status, 202);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip_user_agent(sip)); 
+  TEST_S(sip_user_agent(sip)->g_value, "007");
+  TEST_1(!e->next);
+
+  /*
+   Server events:
+   nua_i_message
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_message);
+  TEST(e->data->e_status, 100);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_subject && sip->sip_subject->g_string);
+  TEST_S(sip->sip_subject->g_string, "NUA-11.1.2");
+  TEST_1(sip->sip_organization);
+  TEST_S(sip->sip_organization->g_string, "United Testers");
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-11.1.2: PASSED\n");
 
 
 /* Message test
@@ -131,7 +190,7 @@
   MESSAGE(a, a_call, a_call->nh,
 	  /* We cannot reach us by using our contact! */
 	  NUTAG_URL(!ctx->p && !ctx->proxy_tests ? a->contact->m_url : NULL),
-	  SIPTAG_SUBJECT_STR("NUA-11.1b"),
+	  SIPTAG_SUBJECT_STR("NUA-11.2"),
 	  SIPTAG_CONTENT_TYPE_STR("text/plain"),
 	  SIPTAG_PAYLOAD_STR("Hello hellO!\n"),
 	  TAG_END());
@@ -141,16 +200,21 @@
   /* Events:
      nua_message(), nua_i_message, nua_r_message
   */
-  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_i_message);
+  TEST_1(e = a->specials->head);
+  while (e->data->e_event == nua_i_outbound)
+    e = e->next;
+  TEST_E(e->data->e_event, nua_i_message);
   TEST(e->data->e_status, 200);
   TEST_1(sip = sip_object(e->data->e_msg));
   TEST_1(sip->sip_subject && sip->sip_subject->g_string);
-  TEST_S(sip->sip_subject->g_string, "NUA-11.1b");
-  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_message);
+  TEST_S(sip->sip_subject->g_string, "NUA-11.2");
+
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_message);
   TEST(e->data->e_status, 200);
   TEST_1(!e->next);
 
   free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, a->specials);
   nua_handle_destroy(a_call->nh), a_call->nh = NULL;
 
   if (print_headings)
@@ -159,12 +223,34 @@
   END();
 }
 
+int accept_request(CONDITION_PARAMS)
+{
+  msg_t *with = nua_current_request(nua);
+  
+  if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
+    return 0;
+
+  save_event_in_list(ctx, event, ep, call);
+
+  if (status < 200) {
+    RESPOND(ep, call, nh, SIP_202_ACCEPTED,
+	    NUTAG_WITH(with),
+	    SIPTAG_USER_AGENT_STR("007"),
+	    TAG_END());
+    return 1;
+  }
+
+  return 0;
+}
+
+char const *test_etag = "tagtag";
+
 int respond_with_etag(CONDITION_PARAMS)
 {
   msg_t *with = nua_current_request(nua);
 
   if (!(check_handle(ep, call, nh, SIP_500_INTERNAL_SERVER_ERROR)))
-    return 0;
+    return 1;
 
   save_event_in_list(ctx, event, ep, call);
 
@@ -172,18 +258,18 @@
     char const *etag;
   case nua_i_publish:
     etag = sip->sip_if_match ? sip->sip_if_match->g_value : NULL;
-    if (sip->sip_if_match && (etag == NULL || strcmp(etag, "tagtag"))) {
+    if (sip->sip_if_match && (etag == NULL || strcmp(etag, test_etag))) {
       RESPOND(ep, call, nh, SIP_412_PRECONDITION_FAILED,
 	      NUTAG_WITH(with),
 	      TAG_END());
     } 
     else {
-	RESPOND(ep, call, nh, SIP_200_OK,
-		NUTAG_WITH(with),
-		SIPTAG_ETAG_STR("tagtag"),
-		SIPTAG_EXPIRES_STR("3600"),
-		SIPTAG_EXPIRES(sip->sip_expires),	/* overrides 3600 */
-		TAG_END());
+      RESPOND(ep, call, nh, SIP_200_OK,
+	      NUTAG_WITH(with),
+	      SIPTAG_ETAG_STR(test_etag),
+	      SIPTAG_EXPIRES_STR("3600"),
+	      SIPTAG_EXPIRES(sip->sip_expires),	/* overrides 3600 */
+	      TAG_END());
     }
     return 1;
   default:
@@ -191,6 +277,14 @@
   }
 }
 
+static int close_handle(CONDITION_PARAMS)
+{
+  if (call->nh == nh)
+    call->nh = NULL;
+  nua_handle_destroy(nh);
+  return 1;
+}
+
 int test_publish(struct context *ctx)
 {
   BEGIN();
@@ -306,6 +400,7 @@
 	  SIPTAG_EVENT_STR("presence"),
 	  SIPTAG_CONTENT_TYPE_STR("text/urllist"),
 	  SIPTAG_PAYLOAD_STR("sip:example.com\n"),
+	  SIPTAG_EXPIRES_STR("5"),
 	  TAG_END());
 
   run_ab_until(ctx, -1, save_until_final_response, -1, respond_with_etag);
@@ -317,7 +412,7 @@
   TEST(e->data->e_status, 200);
   TEST_1(sip = sip_object(e->data->e_msg));
   TEST_1(sip->sip_etag);
-  TEST_S(sip->sip_etag->g_string, "tagtag");
+  TEST_S(sip->sip_etag->g_string, test_etag);
   TEST_1(!e->next);
 
   /*
@@ -332,6 +427,41 @@
   free_events_in_list(ctx, b->events);
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
+  if (!ctx->expensive && 0)
+    goto skip_republish;
+
+  run_ab_until(ctx, -1, save_until_final_response, -1, respond_with_etag); 
+
+  /* Client events: nua_r_publish
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_publish);
+  TEST(e->data->e_status, 200);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_etag);
+  TEST_S(sip->sip_etag->g_string, test_etag);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+ 
+  /*
+   Server events:
+   nua_i_publish
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_publish);
+  TEST(e->data->e_status, 100);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_if_match);
+  TEST_S(sip->sip_if_match->g_string, "tagtag");
+  TEST_1(!sip->sip_content_type);
+  TEST_1(!sip->sip_payload);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, b->events);
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+ skip_republish:
+
   UNPUBLISH(a, a_call, a_call->nh, TAG_END());
 
   run_ab_until(ctx, -1, save_until_final_response, -1, respond_with_etag);
@@ -357,8 +487,60 @@
   nua_handle_destroy(a_call->nh), a_call->nh = NULL;
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  /* Let server close handle without responding to PUBLISH */ 
+  PUBLISH(a, a_call, a_call->nh,
+	  TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	  SIPTAG_EVENT_STR("presence"),
+	  SIPTAG_CONTENT_TYPE_STR("text/urllist"),
+	  SIPTAG_PAYLOAD_STR("sip:example.com\n"),
+	  TAG_END());
+
+  run_ab_until(ctx, -1, save_until_final_response, -1, close_handle);
+
+  /* Client events:
+     nua_publish(), nua_r_publish
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_publish);
+  TEST(e->data->e_status, 500);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+
+  /* No Event header */
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  PUBLISH(a, a_call, a_call->nh,
+	  TAG_IF(!ctx->proxy_tests, NUTAG_URL(b->contact->m_url)),
+	  SIPTAG_CONTENT_TYPE_STR("text/urllist"),
+	  SIPTAG_PAYLOAD_STR("sip:example.com\n"),
+	  TAG_END());
+
+  run_ab_until(ctx, -1, save_until_final_response, -1, save_events);
+
+  /* Client events:
+     nua_publish(), nua_r_publish
+  */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_publish);
+  TEST(e->data->e_status, 489);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+
+  /*
+   Server events: nothing
+  */
+  TEST_1(!b->events->head);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+
   if (print_headings)
     printf("TEST NUA-11.3: PASSED\n");
+
   END();
 }
 
@@ -429,7 +611,10 @@
   tagi_t const *n_tags, *r_tags;
 
   if (print_headings)
-    printf("TEST NUA-11.4: establishing subscription without notifier\n");
+    printf("TEST NUA-11.4: notifier server using nua_notify()\n");
+
+  if (print_headings)
+    printf("TEST NUA-11.4.1: establishing subscription\n");
 
   TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
 
@@ -489,7 +674,7 @@
   free_events_in_list(ctx, b->events);
 
   if (print_headings)
-    printf("TEST NUA-11.4: PASSED\n");
+    printf("TEST NUA-11.4.1: PASSED\n");
 
   /* ---------------------------------------------------------------------- */
 
@@ -502,7 +687,7 @@
    |                    |
 */
   if (print_headings)
-    printf("TEST NUA-11.5: send NOTIFY\n");
+    printf("TEST NUA-11.4.2: send NOTIFY\n");
 
   /* Update presence data */
 
@@ -542,7 +727,7 @@
   free_events_in_list(ctx, b->events);
 
   if (print_headings)
-    printf("TEST NUA-11.5: PASSED\n");
+    printf("TEST NUA-11.4.2: PASSED\n");
 
   /* ---------------------------------------------------------------------- */
 
@@ -557,7 +742,7 @@
    |                    |
 */
   if (print_headings)
-    printf("TEST NUA-11.6: un-SUBSCRIBE\n");
+    printf("TEST NUA-11.4.3: un-SUBSCRIBE\n");
 
   UNSUBSCRIBE(a, a_call, a_call->nh, TAG_END());
 
@@ -614,11 +799,538 @@
   nua_handle_destroy(b_call->nh), b_call->nh = NULL;
 
   if (print_headings)
-    printf("TEST NUA-11.6: PASSED\n");
+    printf("TEST NUA-11.4.3: PASSED\n");
+
+  if (print_headings)
+    printf("TEST NUA-11.4: PASSED\n");
+
+  END();
+}
+
+/* ---------------------------------------------------------------------- */
+/* Subscriber gracefully terminates dialog upon 483 */
+
+static
+size_t change_status_to_483(void *a, void *message, size_t len);
+int save_until_notified_and_responded_twice(CONDITION_PARAMS);
+int save_until_notify_responded_twice(CONDITION_PARAMS);
+
+int test_subscribe_notify_graceful(struct context *ctx)
+{
+  if (!ctx->nat)
+    return 0;
+
+  BEGIN();
+
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+  sip_t const *sip;
+  tagi_t const *n_tags, *r_tags;
+  struct nat_filter *f;
+
+  if (print_headings)
+    printf("TEST NUA-11.5.1: establishing subscription\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  SUBSCRIBE(a, a_call, a_call->nh, NUTAG_URL(b->contact->m_url),
+	    SIPTAG_EVENT_STR("presence"),
+	    SIPTAG_ACCEPT_STR("application/xpidf, application/pidf+xml"),
+	    TAG_END());
+
+  run_ab_until(ctx, -1, save_until_notified_and_responded,
+	       -1, accept_and_notify);
+
+  /* Client events:
+     nua_subscribe(), nua_i_notify/nua_r_subscribe
+  */
+  TEST_1(e = a->events->head);
+  if (e->data->e_event == nua_i_notify) {
+    TEST_E(e->data->e_event, nua_i_notify);
+    TEST_1(sip = sip_object(e->data->e_msg));
+    n_tags = e->data->e_tags;
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_subscribe);
+    r_tags = e->data->e_tags;
+    TEST_1(tl_find(r_tags, nutag_substate));
+    TEST(tl_find(r_tags, nutag_substate)->t_value, nua_substate_pending);
+  }
+  else {
+    TEST_E(e->data->e_event, nua_r_subscribe);
+    TEST(e->data->e_status, 202);
+    r_tags = e->data->e_tags;
+    TEST_1(tl_find(r_tags, nutag_substate));
+    TEST(tl_find(r_tags, nutag_substate)->t_value, nua_substate_embryonic);
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_notify);
+    TEST_1(sip = sip_object(e->data->e_msg));
+    n_tags = e->data->e_tags;
+  }
+  TEST_1(sip->sip_event); TEST_S(sip->sip_event->o_type, "presence");
+  TEST_1(sip->sip_content_type);
+  TEST_S(sip->sip_content_type->c_type, "application/pidf+xml");
+  TEST_1(sip->sip_subscription_state);
+  TEST_S(sip->sip_subscription_state->ss_substate, "pending");
+  TEST_1(sip->sip_subscription_state->ss_expires);
+  TEST_1(tl_find(n_tags, nutag_substate));
+  TEST(tl_find(n_tags, nutag_substate)->t_value, nua_substate_pending);
+  TEST_1(!e->next);
+  free_events_in_list(ctx, a->events);
+
+  /* Server events: nua_i_subscribe, nua_r_notify */
+  TEST_1(e = b->events->head);
+  TEST_E(e->data->e_event, nua_i_subscribe);
+  TEST_E(e->data->e_status, 100);
+  TEST_1(sip = sip_object(e->data->e_msg));
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_notify);
+  r_tags = e->data->e_tags;
+  TEST_1(tl_find(r_tags, nutag_substate));
+  TEST(tl_find(r_tags, nutag_substate)->t_value, nua_substate_pending);
+
+  free_events_in_list(ctx, b->events);
+
+  if (print_headings)
+    printf("TEST NUA-11.5.1: PASSED\n");
+
+  if (print_headings)
+    printf("TEST NUA-11.5.2: terminate gracefully upon 483\n");
+
+  TEST_1(f = test_nat_add_filter(ctx->nat,
+				 change_status_to_483, NULL,
+				 nat_inbound));
+
+  SUBSCRIBE(a, a_call, a_call->nh, TAG_END());
+
+  run_ab_until(ctx, -1, save_until_notified_and_responded_twice, 
+	       -1, save_until_notify_responded_twice);
+
+#if 0
+  /* Client events:
+     nua_unsubscribe(), nua_i_notify/nua_r_unsubscribe
+  */
+  TEST_1(e = a->events->head);
+  if (e->data->e_event == nua_i_notify) {
+    TEST_E(e->data->e_event, nua_i_notify);
+    n_tags = e->data->e_tags;
+    TEST_1(sip = sip_object(e->data->e_msg));
+    TEST_1(sip->sip_event);
+    TEST_1(sip->sip_subscription_state);
+    TEST_S(sip->sip_subscription_state->ss_substate, "terminated");
+    TEST_1(!sip->sip_subscription_state->ss_expires);
+    TEST_1(tl_find(n_tags, nutag_substate));
+    TEST(tl_find(n_tags, nutag_substate)->t_value, nua_substate_terminated);
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_unsubscribe);
+    TEST(e->data->e_status, 200);
+    r_tags = e->data->e_tags;
+    TEST_1(tl_find(r_tags, nutag_substate));
+    TEST(tl_find(r_tags, nutag_substate)->t_value, nua_substate_terminated);
+  }
+  else {
+    TEST_E(e->data->e_event, nua_r_unsubscribe);
+    TEST(e->data->e_status, 200);
+    r_tags = e->data->e_tags;
+    TEST_1(tl_find(r_tags, nutag_substate));
+    TEST(tl_find(r_tags, nutag_substate)->t_value, nua_substate_terminated);
+  }
+  TEST_1(!e->next);
+
+  /* Notifier events: nua_r_notify */
+  TEST_1(e = b->events->head);
+  TEST_E(e->data->e_event, nua_i_subscribe);
+  TEST(e->data->e_status, 200);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(tl_find(e->data->e_tags, nutag_substate));
+  TEST(tl_find(e->data->e_tags, nutag_substate)->t_value, 
+       nua_substate_terminated);
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_notify);
+  TEST_1(e->data->e_status >= 200);
+  r_tags = e->data->e_tags;
+  TEST_1(tl_find(r_tags, nutag_substate));
+  TEST(tl_find(r_tags, nutag_substate)->t_value, nua_substate_terminated);
+#endif
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  test_nat_remove_filter(ctx->nat, f);
+
+  if (print_headings)
+    printf("TEST NUA-11.5.2: PASSED\n");
+
+  END();
+}
+
+static
+size_t change_status_to_483(void *a, void *message, size_t len)
+{
+  (void)a;
+
+  if (strncmp("SIP/2.0 2", message, 9) == 0) {
+    memcpy(message, "SIP/2.0 483", 11);
+  }
+  return len;
+}
+
+int save_until_notified_and_responded_twice(CONDITION_PARAMS)
+{
+  save_event_in_list(ctx, event, ep, call);
+
+  if (event == nua_i_notify) {
+    if (ep->flags.bit0)
+      ep->flags.bit1 = 1;
+    ep->flags.bit0 = 1;
+  }
+
+  if (event == nua_r_subscribe || event == nua_r_unsubscribe) {
+    if (status >= 300)
+      return 1;
+    else if (status >= 200) {
+      if (ep->flags.bit2)
+	ep->flags.bit3 = 1;
+      ep->flags.bit2 = 1;
+    }
+  }
+
+  return ep->flags.bit0 && ep->flags.bit1 && ep->flags.bit2 && ep->flags.bit3;
+}
+
+int save_until_notify_responded_twice(CONDITION_PARAMS)
+{
+  save_event_in_list(ctx, event, ep, call);
+
+  if (event == nua_r_notify) {
+    if (ep->flags.bit0)
+      ep->flags.bit1 = 1;
+    ep->flags.bit0 = 1;
+  }
+
+  return ep->flags.bit0 && ep->flags.bit1;
+}
+
+
+/* ---------------------------------------------------------------------- */
+/* Unsolicited NOTIFY */
+
+int accept_notify(CONDITION_PARAMS);
+
+int test_newsub_notify(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+  sip_t const *sip;
+  sip_call_id_t *i;
+  tagi_t const *n_tags, *r_tags;
+
+  if (print_headings)
+    printf("TEST NUA-11.7.1: rejecting NOTIFY without subscription locally\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  NOTIFY(a, a_call, a_call->nh, NUTAG_URL(b->contact->m_url),
+	 SIPTAG_SUBJECT_STR("NUA-11.7.1"),
+	 SIPTAG_EVENT_STR("message-summary"),
+	 SIPTAG_CONTENT_TYPE_STR("application/simple-message-summary"),
+	 SIPTAG_PAYLOAD_STR("Messages-Waiting: yes"),
+	 TAG_END());
+
+  run_a_until(ctx, -1, save_until_final_response);
+
+  /* Client events:
+     nua_notify(), nua_r_notify
+  */
+  TEST_1(e = a->events->head);
+  TEST_E(e->data->e_event, nua_r_notify);
+  TEST(e->data->e_status, 481);
+  TEST_1(!e->data->e_msg);
+  TEST_1(!e->next);
+  free_events_in_list(ctx, a->events);
+
+  if (print_headings)
+    printf("TEST NUA-11.7.1: PASSED\n");
+
+  if (print_headings)
+    printf("TEST NUA-11.7.2: rejecting NOTIFY without subscription\n");
+
+  TEST_1(i = sip_call_id_create(nua_handle_home(a_call->nh), NULL));
+
+  NOTIFY(a, a_call, a_call->nh, NUTAG_URL(b->contact->m_url),
+	 NUTAG_NEWSUB(1),
+	 SIPTAG_SUBJECT_STR("NUA-11.7.2 first"),
+	 SIPTAG_FROM_STR("<sip:alice at example.com>;tag=nua-11.7.2"),
+	 SIPTAG_CALL_ID(i),
+	 SIPTAG_CSEQ_STR("1 NOTIFY"),
+	 SIPTAG_EVENT_STR("message-summary"),
+	 SIPTAG_CONTENT_TYPE_STR("application/simple-message-summary"),
+	 SIPTAG_PAYLOAD_STR("Messages-Waiting: yes"),
+	 TAG_END());
+
+  run_a_until(ctx, -1, save_until_final_response);
+
+  /* Client events:
+     nua_notify(), nua_r_notify
+  */
+  TEST_1(e = a->events->head);
+  TEST_E(e->data->e_event, nua_r_notify);
+  TEST(e->data->e_status, 481);
+  TEST_1(e->data->e_msg);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  
+  /* 2nd NOTIFY using same dialog */
+  /* Check that server really discards the dialog */
+
+  NOTIFY(a, a_call, a_call->nh, NUTAG_URL(b->contact->m_url),
+	 NUTAG_NEWSUB(1),
+	 SIPTAG_SUBJECT_STR("NUA-11.7.2 second"),
+	 SIPTAG_FROM_STR("<sip:alice at example.com>;tag=nua-11.7.2"),
+	 SIPTAG_CALL_ID(i),
+	 SIPTAG_CSEQ_STR("2 NOTIFY"),
+	 SIPTAG_EVENT_STR("message-summary"),
+	 SIPTAG_CONTENT_TYPE_STR("application/simple-message-summary"),
+	 SIPTAG_PAYLOAD_STR("Messages-Waiting: yes"),
+	 TAG_END());
+
+  run_a_until(ctx, -1, save_until_final_response);
+
+  /* Client events:
+     nua_notify(), nua_r_notify
+  */
+  TEST_1(e = a->events->head);
+  TEST_E(e->data->e_event, nua_r_notify);
+  TEST(e->data->e_status, 481);
+  TEST_1(e->data->e_msg);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+
+  if (print_headings)
+    printf("TEST NUA-11.7.2: PASSED\n");
+
+  /* ---------------------------------------------------------------------- */
+
+  if (print_headings)
+    printf("TEST NUA-11.7.3: accept NOTIFY\n");
+
+  nua_set_params(b->nua, NUTAG_APPL_METHOD("NOTIFY"), TAG_END());
+  run_b_until(ctx, nua_r_set_params, until_final_response);
+
+  NOTIFY(a, a_call, a_call->nh,
+	 NUTAG_URL(b->contact->m_url),
+	 NUTAG_NEWSUB(1),
+	 SIPTAG_SUBJECT_STR("NUA-11.7.3"),
+	 SIPTAG_EVENT_STR("message-summary"),
+	 SIPTAG_CONTENT_TYPE_STR("application/simple-message-summary"),
+	 SIPTAG_PAYLOAD_STR("Messages-Waiting: yes"),
+	 TAG_END());
+
+  run_ab_until(ctx, -1, save_until_final_response, -1, accept_notify);
+
+  /* Notifier events: nua_r_notify */
+  TEST_1(e = a->events->head); TEST_E(e->data->e_event, nua_r_notify);
+  TEST(e->data->e_status, 200);
+  r_tags = e->data->e_tags;
+  TEST_1(tl_find(r_tags, nutag_substate));
+  TEST(tl_find(r_tags, nutag_substate)->t_value, nua_substate_terminated);
+
+  /* subscriber events:
+     nua_i_notify
+  */
+  TEST_1(e = b->events->head); TEST_E(e->data->e_event, nua_i_notify);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_subscription_state);
+  TEST_S(sip->sip_subscription_state->ss_substate, "terminated");
+  n_tags = e->data->e_tags;
+  TEST_1(tl_find(n_tags, nutag_substate));
+  TEST(tl_find(n_tags, nutag_substate)->t_value, nua_substate_terminated);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+  free_events_in_list(ctx, b->events);
+
+  if (print_headings)
+    printf("TEST NUA-11.7.3: PASSED\n");
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-11.7: PASSED\n");
+
+  END();
+}
+
+/**Terminate when received notify. 
+ * Respond to NOTIFY with 200 OK if it has not been responded.
+ * Save events (except nua_i_active or terminated).
+ */
+int accept_notify(CONDITION_PARAMS)
+{
+  if (event == nua_i_notify && status < 200)
+    RESPOND(ep, call, nh, SIP_200_OK, 
+	    NUTAG_WITH_THIS(ep->nua),
+	    TAG_END());
+
+  save_event_in_list(ctx, event, ep, call);
+
+  return event == nua_i_notify;
+}
+
+/* ======================================================================== */
+
+int save_until_subscription_terminated(CONDITION_PARAMS);
+int accept_subscription_until_terminated(CONDITION_PARAMS);
+
+/* Timeout subscription */
+int test_subscription_timeout(struct context *ctx)
+{
+  BEGIN();
+
+  struct endpoint *a = &ctx->a,  *b = &ctx->b;
+  struct call *a_call = a->call, *b_call = b->call;
+  struct event *e;
+  sip_t const *sip;
+  tagi_t const *n_tags, *r_tags;
+
+  if (print_headings)
+    printf("TEST NUA-11.8: subscribe and wait until subscription times out\n");
+
+  TEST_1(a_call->nh = nua_handle(a->nua, a_call, SIPTAG_TO(b->to), TAG_END()));
+
+  METHOD(a, a_call, a_call->nh,
+	 NUTAG_METHOD("SUBSCRIBE"),
+	 NUTAG_URL(b->contact->m_url),
+	 SIPTAG_EVENT_STR("presence"),
+	 SIPTAG_ACCEPT_STR("application/xpidf, application/pidf+xml"),
+	 SIPTAG_EXPIRES_STR("2"),
+	 NUTAG_APPL_METHOD("NOTIFY"),
+	 NUTAG_DIALOG(2),
+	 TAG_END());
+
+  run_ab_until(ctx,
+	       -1, save_until_subscription_terminated,
+	       -1, accept_subscription_until_terminated);
+
+  /* Client events:
+     nua_method(), nua_i_notify/nua_r_method, nua_i_notify
+  */
+  TEST_1(e = a->events->head);
+  if (e->data->e_event == nua_i_notify) {
+    TEST_E(e->data->e_event, nua_i_notify);
+    TEST_1(sip = sip_object(e->data->e_msg));
+    n_tags = e->data->e_tags;
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_subscribe);
+    r_tags = e->data->e_tags;
+  }
+  else {
+    TEST_E(e->data->e_event, nua_r_method);
+    TEST(e->data->e_status, 202);
+    r_tags = e->data->e_tags;
+    TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_notify);
+    TEST_1(sip = sip_object(e->data->e_msg));
+    n_tags = e->data->e_tags;
+  }
+  TEST_1(sip->sip_event); TEST_S(sip->sip_event->o_type, "presence");
+  TEST_1(sip->sip_content_type);
+  TEST_S(sip->sip_content_type->c_type, "application/pidf+xml");
+  TEST_1(sip->sip_subscription_state);
+  TEST_S(sip->sip_subscription_state->ss_substate, "pending");
+  TEST_1(sip->sip_subscription_state->ss_expires);
+  TEST_1(tl_find(n_tags, nutag_substate));
+  TEST(tl_find(n_tags, nutag_substate)->t_value, nua_substate_pending);
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_i_notify);
+  n_tags = e->data->e_tags;
+  TEST_1(tl_find(n_tags, nutag_substate));
+  TEST(tl_find(n_tags, nutag_substate)->t_value, nua_substate_terminated);
+  TEST_1(sip = sip_object(e->data->e_msg));
+  TEST_1(sip->sip_event);
+  TEST_1(sip->sip_subscription_state);
+  TEST_S(sip->sip_subscription_state->ss_substate, "terminated");
+  TEST_1(!sip->sip_subscription_state->ss_expires);
+  TEST_1(!e->next);
+
+  free_events_in_list(ctx, a->events);
+
+  /* Server events: nua_i_subscribe, nua_r_notify */
+  TEST_1(e = b->events->head);
+  TEST_E(e->data->e_event, nua_i_subscribe);
+  TEST_E(e->data->e_status, 100);
+  TEST_1(sip = sip_object(e->data->e_msg));
+
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_notify);
+  r_tags = e->data->e_tags;
+  TEST_1(tl_find(r_tags, nutag_substate));
+  TEST(tl_find(r_tags, nutag_substate)->t_value, nua_substate_pending);
+
+  /* Notifier events: 2nd nua_r_notify */
+  TEST_1(e = e->next); TEST_E(e->data->e_event, nua_r_notify);
+  TEST_1(e->data->e_status >= 200);
+  r_tags = e->data->e_tags;
+  TEST_1(tl_find(r_tags, nutag_substate));
+  TEST(tl_find(r_tags, nutag_substate)->t_value, nua_substate_terminated);
+
+  free_events_in_list(ctx, b->events);
+
+  nua_handle_destroy(a_call->nh), a_call->nh = NULL;
+  nua_handle_destroy(b_call->nh), b_call->nh = NULL;
+
+  if (print_headings)
+    printf("TEST NUA-11.8: PASSED\n");
 
   END();
 }
 
+int save_until_subscription_terminated(CONDITION_PARAMS)
+{
+  void *with = nua_current_request(nua);
+
+  save_event_in_list(ctx, event, ep, call);
+
+  if (event == nua_i_notify) {
+    if (status < 200)
+      RESPOND(ep, call, nh, SIP_200_OK, NUTAG_WITH(with), TAG_END());
+
+    tags = tl_find(tags, nutag_substate);
+    return tags && tags->t_value == nua_substate_terminated;
+  }
+
+  return 0;
+}
+
+int accept_subscription_until_terminated(CONDITION_PARAMS)
+{
+  void *with = nua_current_request(nua);
+
+  save_event_in_list(ctx, event, ep, call);
+
+  if (event == nua_i_subscribe && status < 200) {
+    RESPOND(ep, call, nh, SIP_202_ACCEPTED,
+	    NUTAG_WITH(with),
+	    SIPTAG_EXPIRES_STR("360"),
+	    TAG_END());
+    NOTIFY(ep, call, nh, 
+	   SIPTAG_EVENT(sip->sip_event),
+	   SIPTAG_CONTENT_TYPE_STR("application/pidf+xml"),
+	   SIPTAG_PAYLOAD_STR(presence_closed),
+	   NUTAG_SUBSTATE(nua_substate_pending),
+	   TAG_END());
+  }
+  else if (event == nua_r_notify) {
+    tags = tl_find(tags, nutag_substate);
+    return tags && tags->t_value == nua_substate_terminated;
+  }
+
+  return 0;
+}
+
+
 /* ======================================================================== */
 /* Test simple methods: MESSAGE, PUBLISH, SUBSCRIBE/NOTIFY */
 
@@ -628,5 +1340,8 @@
     test_message(ctx)
     || test_publish(ctx)
     || test_subscribe_notify(ctx)
+    || test_subscribe_notify_graceful(ctx)
+    || test_newsub_notify(ctx)
+    || test_subscription_timeout(ctx)
     ;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_sip_events.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_sip_events.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/nua/test_sip_events.c	Tue Apr 24 10:14:28 2007
@@ -64,15 +64,15 @@
 int save_until_notified_and_responded(CONDITION_PARAMS)
 {
   save_event_in_list(ctx, event, ep, call);
-  if (event == nua_i_notify) ep->flags.b.bit0 = 1;
+  if (event == nua_i_notify) ep->flags.bit0 = 1;
   if (event == nua_r_subscribe || event == nua_r_unsubscribe) {
     if (status >= 300)
       return 1;
     else if (status >= 200)
-      ep->flags.b.bit1 = 1;
+      ep->flags.bit1 = 1;
   }
 
-  return ep->flags.b.bit0 && ep->flags.b.bit1;
+  return ep->flags.bit0 && ep->flags.bit1;
 }
 
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -43,7 +43,7 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile sdp.docs $(BUILT_SOURCES) \
+EXTRA_DIST =		sdp.docs $(BUILT_SOURCES) \
 			tests/message-1.sdp \
 			tests/message-2.sdp \
 			tests/message-3.sdp \
@@ -58,4 +58,5 @@
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/run_test_sdp
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/run_test_sdp	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/run_test_sdp	Tue Apr 24 10:14:28 2007
@@ -6,7 +6,8 @@
 #
 
 test_sdp="${1:-./test_sdp}"
-tests="${2:-tests}"
+sdp_path=`dirname $0`
+tests="${2:-${sdp_path}/tests}"
 
 if test -r $tests/message-1.sdp ; then
 
@@ -17,6 +18,6 @@
 done
 
 else 
-    echo "sdp run-tests: no tests found, skipping."
+    echo "sdp run-tests: no tests found in $tests, skipping."
+    exit 77
 fi
-

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/sdp.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/sdp.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/sdp.c	Tue Apr 24 10:14:28 2007
@@ -1061,7 +1061,7 @@
   b += STRUCT_ALIGN(b);
   srcsdp = (sdp_session_t *)src->t_value;
 
-  sdp = session_dup(&b, srcsdp);
+  sdp = srcsdp ? session_dup(&b, srcsdp) : NULL;
 
   dst->t_tag = src->t_tag;
   dst->t_value = (tag_value_t)sdp;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/sdp_print.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/sdp_print.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/sdp_print.c	Tue Apr 24 10:14:28 2007
@@ -405,7 +405,13 @@
     return;
   }
 
-  sdp_printf(p, "%s%s%s", nettype, addrtype, c->c_address);
+  if (nettype && addrtype)
+    sdp_printf(p, "%s%s%s", nettype, addrtype, c->c_address);
+  else if (nettype)
+    sdp_printf(p, "%s%s%s", nettype, c->c_address);
+  else
+    sdp_printf(p, "%s", c->c_address);
+    
   if (c->c_mcast || c->c_ttl) {
     sdp_printf(p, "/%u", c->c_ttl);
     if (c->c_groups > 1)

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/torture_sdp.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/torture_sdp.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sdp/torture_sdp.c	Tue Apr 24 10:14:28 2007
@@ -460,7 +460,7 @@
 
   su_home_check(home); TEST_1(home);
 
-  TEST_1((parser = sdp_parse(home, s3_msg, sizeof(s1_msg), 0)));
+  TEST_1((parser = sdp_parse(home, s3_msg, sizeof(s3_msg) - 1, 0)));
   
   TEST_1(sdp_sanity_check(parser) == 0);
 
@@ -469,6 +469,59 @@
   END();
 }
 
+static char const pint_msg[] = 
+  "v=0\r\n"
+  "o=- 2353687640 2353687640 IN IP4 128.3.4.5\r\n"
+  "s=marketing\r\n"
+  "e=john.jones.3 at chinet.net\r\n"
+  "c=TN RFC2543 +1-201-406-4090\r\n"
+  "t=2353687640 0\r\n"
+  "m=audio 1 voice -\r\n"
+  ;
+
+static char const pint_torture_msg[] = 
+  "v=0\r\n"
+  "o=- 2353687640 2353687640 IN IP4 128.3.4.5\r\n"
+  "s=marketing\r\n"
+
+  "c= TN RFC2543 123\r\n"
+  "a=phone-context:+97252\r\n"
+  "t=2353687640 0\r\n"
+  "m= text 1  fax plain\r\n"
+  "a=fmtp:plain  spr:fi6MeoclEjaF3EDfYHlkqx1zn8A1lMoiJFUHpQ5Xo\r\n"
+  ;
+
+static int test_pint(void)
+{
+  su_home_t *home = su_home_create();
+  sdp_parser_t *parser;
+  sdp_session_t *sdp;
+  sdp_printer_t *printer;
+  char const *m;
+
+  BEGIN();
+
+  su_home_check(home); TEST_1(home);
+
+  TEST_1((parser = sdp_parse(home, pint_msg, sizeof(pint_msg) - 1, sdp_f_anynet)));
+  TEST_1((sdp = sdp_session(parser)));
+
+  TEST_1((printer = sdp_print(home, sdp, NULL, -1, 0)));
+  TEST_1((m = sdp_message(printer)));
+  TEST_S(m, pint_msg);
+  TEST(sdp_message_size(printer), sizeof(pint_msg) - 1);
+
+  TEST_1((parser = sdp_parse(home, pint_torture_msg, sizeof(pint_torture_msg) - 1,
+			     sdp_f_anynet)));
+  TEST_1((sdp = sdp_session(parser)));
+  
+  su_home_check(home);
+  su_home_unref(home);
+
+  END();
+}
+
+
 static sdp_list_t const l0[1] = {{ sizeof(l0), NULL, "foo" }};
 static sdp_list_t const l1[1] = {{ sizeof(l1), (sdp_list_t *)l0, "bar" }};
 
@@ -848,9 +901,10 @@
   END();
 }
 
-void usage(void)
+void usage(int exitcode)
 {
-  fprintf(stderr, "usage: %s [-v]\n", name);
+  fprintf(stderr, "usage: %s [-v] [-a]\n", name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -861,8 +915,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   null = fopen("/dev/null", "ab");
@@ -870,6 +926,7 @@
   retval |= test_error(); fflush(stdout);
   retval |= test_session(); fflush(stdout);
   retval |= test_session2(); fflush(stdout);
+  retval |= test_pint(); fflush(stdout);
   retval |= test_sanity(); fflush(stdout);
   retval |= test_list(); fflush(stdout);
   retval |= test_rtpmap(); fflush(stdout);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -25,6 +25,7 @@
 GENERATED_H = 		sofia-sip/sip_hclasses.h \
 			sofia-sip/sip_protos.h sofia-sip/sip_tag.h \
 			sofia-sip/sip_extra.h
+
 H_IN = 			sofia-sip/sip_hclasses.h.in \
 			sofia-sip/sip_protos.h.in sofia-sip/sip_tag.h.in \
 			sofia-sip/sip_extra.h.in
@@ -33,9 +34,9 @@
            sofia-sip/sip_header.h sofia-sip/sip_parser.h \
 	   sofia-sip/sip_tag_class.h sofia-sip/sip_status.h
 
-GENERATED_C = sip_tag.c sip_tag_ref.c sip_parser_table.c
+GENERATED_C = sip_tag.c sip_parser_table.c
 
-BUILT_SOURCES = 	$(GENERATED_H) $(GENERATED_C)
+BUILT_SOURCES = 	$(GENERATED_H) $(GENERATED_C) sip_tag_ref.c
 
 nobase_include_sofia_HEADERS = $(GENERATED_H) $(PUBLIC_H) $(H_IN)
 
@@ -46,8 +47,8 @@
 			sip_refer.c sip_session.c \
 			sip_caller_prefs.c sip_reason.c \
 			sip_status.c sip_time.c \
-			sip_tag_class.c \
-			$(GENERATED_C)
+			sip_tag_class.c sip_inlined.c \
+			$(BUILT_SOURCES)
 
 COVERAGE_INPUT = 	$(libsip_la_SOURCES) $(include_sofia_HEADERS)
 
@@ -55,6 +56,7 @@
 			../msg/libmsg.la \
 			../bnf/libbnf.la \
 			../url/liburl.la \
+			../ipt/libipt.la \
 			../su/libsu.la
 
 torture_sip_LDFLAGS = 	-static
@@ -67,7 +69,7 @@
 # note: srcdir needs to be specified, otherwise
 #       breaks make distcheck target
 
-EXTRA_DIST =		Doxyfile sip.docs sip_parser.docs sip.doxyaliases \
+EXTRA_DIST =		sip.docs sip_parser.docs sip.doxyaliases \
 			ADD-A-HEADER GRAMMAR sip_bad_mask \
 			sip_parser_table.c.in sip_tag.c.in \
 			sip_extra_headers.txt \
@@ -93,62 +95,57 @@
 # ----------------------------------------------------------------------
 # Tests
 
-#TESTS = torture_sip run_test_sip_msg run_test_date
+TESTS = torture_sip run_test_sip_msg run_test_date
 
-#dist_noinst_SCRIPTS = 	run_test_sip_msg run_test_date
+dist_noinst_SCRIPTS = 	run_test_sip_msg run_test_date
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
 
 MSG_PARSER_AWK = $(srcdir)/../msg/msg_parser.awk
 
-AWK_SIP_AWK = $(AWK) -f $(MSG_PARSER_AWK) module=sip
-
-#
-# Note: sip_bad_mask is used by nta to weed out bad messages
-#
-sip_parser_table.c: sip_bad_mask
+AWK_SIP_AWK = LC_ALL=C $(AWK) -f $(MSG_PARSER_AWK) module=sip
 
-sofia-sip/sip_hclasses.h: sofia-sip/sip_hclasses.h.in
-sofia-sip/sip_protos.h: sofia-sip/sip_protos.h.in
-sofia-sip/sip_tag.h: sofia-sip/sip_tag.h.in
+SS_SIP_H = ${srcdir}/sofia-sip/sip.h
 
-$(GENERATED_H): $(MSG_PARSER_AWK)
+EXTRA = ${srcdir}/sip_extra_headers.txt
 
-sip_parser_table.c: sip_parser_table.c.in $(MSG_PARSER_AWK)
-sip_tag.c: sip_tag.c.in $(MSG_PARSER_AWK)
+${GENERATED_H} ${GENERATED_C}: ${SS_SIP_H} ${MSG_PARSER_AWK}
 
-EXTRA = $(srcdir)/sip_extra_headers.txt
-
-sofia-sip/sip_hclasses.h: sofia-sip/sip.h
+sofia-sip/sip_hclasses.h: ${srcdir}/sofia-sip/sip_hclasses.h.in
 	@-mkdir sofia-sip 2>/dev/null || true
-	$(AWK_SIP_AWK) PR=$@ TEMPLATE=$(srcdir)/sofia-sip/sip_hclasses.h.in $<
+	${AWK_SIP_AWK} PR=$@ TEMPLATE=${srcdir}/sofia-sip/sip_hclasses.h.in \
+		${SS_SIP_H}
 
-sofia-sip/sip_protos.h: sofia-sip/sip.h
+sofia-sip/sip_protos.h: ${srcdir}/sofia-sip/sip_protos.h.in
 	@-mkdir sofia-sip 2>/dev/null || true
-	$(AWK_SIP_AWK) PR=$@ TEMPLATE=$(srcdir)/sofia-sip/sip_protos.h.in $<
+	${AWK_SIP_AWK} PR=$@ TEMPLATE=${srcdir}/sofia-sip/sip_protos.h.in \
+		 ${SS_SIP_H}
 
-sofia-sip/sip_tag.h: sofia-sip/sip.h
+sofia-sip/sip_tag.h: ${srcdir}/sofia-sip/sip_tag.h.in
 	@-mkdir sofia-sip 2>/dev/null || true
-	$(AWK_SIP_AWK) PR=$@ TEMPLATE=$(srcdir)/sofia-sip/sip_tag.h.in $<
+	${AWK_SIP_AWK} PR=$@ TEMPLATE=${srcdir}/sofia-sip/sip_tag.h.in \
+		${SS_SIP_H}
 
-sip_tag.c: sofia-sip/sip.h sip_extra_headers.txt
-	$(AWK_SIP_AWK) PR=$@ TEMPLATE=$(srcdir)/sip_tag.c.in $< $(EXTRA)
+sip_tag.c: ${srcdir}/sip_tag.c.in ${EXTRA}
+	${AWK_SIP_AWK} PR=$@ TEMPLATE=${srcdir}/sip_tag.c.in \
+		${SS_SIP_H} ${EXTRA}
 
-sip_parser_table.c: sip_extra_headers.txt
+# Note: sip_bad_mask is used by nta to weed out bad messages
 
-sip_parser_table.c: sofia-sip/sip.h
-	$(AWK_SIP_AWK) PT=$@ TEMPLATE=$(srcdir)/sip_parser_table.c.in \
-		FLAGFILE=$(srcdir)/sip_bad_mask \
-		MC_HASH_SIZE=127 MC_SHORT_SIZE=26 $< $(EXTRA)
+sip_parser_table.c: ${srcdir}/sip_parser_table.c.in ${EXTRA} sip_bad_mask
+	${AWK_SIP_AWK} PT=$@ TEMPLATE=${srcdir}/sip_parser_table.c.in \
+		FLAGFILE=${srcdir}/sip_bad_mask \
+		MC_HASH_SIZE=127 MC_SHORT_SIZE=26 \
+		${SS_SIP_H} ${EXTRA}
 
-sofia-sip/sip_extra.h: sofia-sip/sip_extra.h.in sip_extra_headers.txt
+sofia-sip/sip_extra.h: ${srcdir}/sofia-sip/sip_extra.h.in ${EXTRA}
 	@-mkdir -p sofia-sip 2>/dev/null
 	${AWK_SIP_AWK} PR=$@ NO_FIRST=1 NO_LAST=1 \
 		PACKAGE_NAME="${PACKAGE_NAME}" \
 		PACKAGE_VERSION="${PACKAGE_VERSION}" \
 		TEMPLATE1=${srcdir}/sofia-sip/sip_hclasses.h.in \
 		TEMPLATE2=${srcdir}/sofia-sip/sip_protos.h.in \
-		TEMPLATE=$< $(EXTRA)
+		TEMPLATE=${srcdir}/sofia-sip/sip_extra.h.in ${EXTRA}

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_basic.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_basic.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_basic.c	Tue Apr 24 10:14:28 2007
@@ -899,7 +899,7 @@
   sip_header_t *h;
 
   n = url_xtra(us->us_url);
-  h = sip_header_alloc(home, sip_to_class, n);    
+  h = sip_header_alloc(home, hc, n);    
 
   if (h) {
     sip_addr_t *a = h->sh_to;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_event.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_event.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_event.c	Tue Apr 24 10:14:28 2007
@@ -44,6 +44,8 @@
 #include <stddef.h>
 #include <stdlib.h>
 #include <string.h>
+#include <limits.h>
+
 #include <assert.h>
 
 /* ====================================================================== */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_extra.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_extra.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_extra.c	Tue Apr 24 10:14:28 2007
@@ -46,6 +46,7 @@
 #include <stddef.h>
 #include <stdlib.h>
 #include <string.h>
+#include <limits.h>
 
 #include <assert.h>
 
@@ -757,6 +758,8 @@
 
 /* ====================================================================== */
 
+#if SU_HAVE_EXPERIMENTAL
+
 /**@SIP_HEADER sip_suppress_body_if_match Suppress-Body-If-Match Header
  *
  * The @b Suppress-Body-If-Match header field identifies a SIP event content
@@ -773,7 +776,7 @@
  *
  * @sa @RFC3265, draft-niemi-sip-subnot-etags-01.txt
  *
- * @NEW_1_12_5. Note that #sip_t does not contain @a
+ * @EXP_1_12_5. Note that #sip_t does not contain @a
  * sip_suppress_body_if_match field, but sip_suppress_body_if_match()
  * function should be used for accessing the @b Suppress-Body-If-Match
  * header structure.
@@ -839,7 +842,7 @@
  *
  * @sa @RFC3265, draft-niemi-sip-subnot-etag-01
  *
- * @NEW_1_12_5. Note that #sip_t does not contain @a
+ * @EXP_1_12_5. Note that #sip_t does not contain @a
  * sip_suppress_notify_if_match field, but sip_suppress_notify_if_match()
  * function should be used for accessing the @b Suppress-Notify-If-Match
  * header structure.
@@ -887,4 +890,4 @@
   return msg_generic_e(b, bsiz, h, f);
 }
 
-
+#endif

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_extra_headers.txt
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_extra_headers.txt	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_extra_headers.txt	Tue Apr 24 10:14:28 2007
@@ -4,10 +4,15 @@
 # The line format is: 
 # C-name @SINCE sip_t-like-comment
 #
+# Put all experimental things after EXPERIMENTAL HEADER LIST STARTS HERE...
+#
 #### EXTRA HEADER LIST STARTS HERE ####
 
-refer_sub @VERSION_1_12_5 /**< Refer-Sub header */
-suppress_body_if_match @VERSION_1_12_5 /**< Suppress-Body-If-Match header */
-suppress_notify_if_match @VERSION_1_12_5 /**< Suppress-Notify-If-Match header*/
+refer_sub @NEW_1_12_5 /**< Refer-Sub header */
+
+#### EXPERIMENTAL HEADER LIST STARTS HERE ####
+
+suppress_body_if_match @EXP_1_12_5 /**< Suppress-Body-If-Match header */
+suppress_notify_if_match @EXP_1_12_5 /**< Suppress-Notify-If-Match header */
 
 #### EXTRA HEADER LIST ENDS HERE ####

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_feature.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_feature.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_feature.c	Tue Apr 24 10:14:28 2007
@@ -336,7 +336,7 @@
   return msg_list_e(b, bsiz, h, f);
 }
 
-/** Check if required feature is supported.
+/** Check if required feature is not supported.
  *
  * @retval NULL if all the required features are supported
  * @retval pointer to a @Unsupported header or
@@ -351,7 +351,7 @@
 }
 
 
-/** Check if required feature is supported.
+/** Check if required feature is not supported.
  *
  * @retval NULL if all the required features are supported
  * @retval pointer to a @Unsupported header or
@@ -370,7 +370,7 @@
 }
 
 
-/** Ensure that required features are supported.
+/** Check if required features are not supported.
  *
  * The supported features can be listed in @Supported, @Require or 
  * @ProxyRequire headers (in @a supported, @a by_require, or @a

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_mime.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_mime.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_mime.c	Tue Apr 24 10:14:28 2007
@@ -43,6 +43,7 @@
 #include <stddef.h>
 #include <stdlib.h>
 #include <string.h>
+#include <limits.h>
 #include <assert.h>
 
 /* ====================================================================== */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_parser.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_parser.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_parser.c	Tue Apr 24 10:14:28 2007
@@ -60,9 +60,9 @@
 char const sip_version_2_0[] = "SIP/2.0";
 
 /** Default message class */
-extern msg_mclass_t sip_mclass[];
+extern msg_mclass_t const sip_mclass[];
 
-msg_mclass_t *sip_default_mclass(void)
+msg_mclass_t const *sip_default_mclass(void)
 {
   return sip_mclass;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_prack.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_prack.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_prack.c	Tue Apr 24 10:14:28 2007
@@ -46,6 +46,7 @@
 #include <string.h>
 #include <stdio.h>
 #include <assert.h>
+#include <limits.h>
 
 /* ====================================================================== */
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_pref_util.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_pref_util.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_pref_util.c	Tue Apr 24 10:14:28 2007
@@ -44,6 +44,8 @@
 #include <sofia-sip/sip_util.h>
 #include <sofia-sip/sip_status.h>
 
+static double parse_number(char const *str, char **return_end);
+
 /** Parse a single preference */
 int sip_prefs_parse(union sip_pref *sp, 
 		    char const **in_out_s, 
@@ -107,16 +109,16 @@
     s0 = s[0];
 
     if (s0 == '=')
-      sp->sp_type = sp_range, n1 = n2 = strtod(s = s + 1, &e);
+      sp->sp_type = sp_range, n1 = n2 = parse_number(s = s + 1, &e);
     else if (s0 == '<' && s[1] == '=')
-      sp->sp_type = sp_range, n1 = DBL_MIN, n2 = strtod(s = s + 2, &e);
+      sp->sp_type = sp_range, n1 = -DBL_MAX, n2 = parse_number(s = s + 2, &e);
     else if (s0 == '>' && s[1] == '=')
-      sp->sp_type = sp_range, n1 = strtod(s = s + 2, &e), n2 = DBL_MAX;
-    else if (((n1 = strtod(s, &e)) != 0.0 || s != e) && e[0] == ':')
-      sp->sp_type = sp_range, n2 = strtod(s = e + 1, &e);
+      sp->sp_type = sp_range, n1 = parse_number(s = s + 2, &e), n2 = DBL_MAX;
+    else if (((n1 = parse_number(s, &e)) != 0.0 || s != e) && e[0] == ':')
+      sp->sp_type = sp_range, n2 = parse_number(s = e + 1, &e);
     else
       /* Error in conversion */
-      sp->sp_type = sp_error, n1 = DBL_MAX, n2 = DBL_MIN;
+      sp->sp_type = sp_error, n1 = DBL_MAX, n2 = -DBL_MAX;
 
     if (s == e && (n1 == 0.0 || n2 == 0.0))
       sp->sp_type = sp_error;      /* Error in conversion */
@@ -155,6 +157,46 @@
   return sp->sp_type != sp_error;
 }
 
+/** Parse number:
+ * number          =  [ "+" / "-" ] 1*DIGIT ["." 0*DIGIT]
+ */
+static double parse_number(char const *str, char **return_end)
+{
+  double value = 0.0;
+  double decimal = 0.1;
+  char d, sign = '+';
+
+  if (return_end)
+    *return_end = (char *)str;
+
+  d = *str;
+
+  if (d == '+' || d == '-')
+    sign = d, d = *++str;
+
+  if (!('0' <= d && d <= '9'))
+    return value;
+
+  for (; '0' <= d && d <= '9'; d = *++str)
+    value = value * 10 + (d - '0');
+
+  if (d == '.') for (d = *++str; '0' <= d && d <= '9'; d = *++str) {
+    value += (d - '0') * decimal; decimal *= 0.1;
+  }
+
+  if (value > DBL_MAX)
+    value = DBL_MAX;
+
+  if (sign == '-')
+    value = -value;
+
+  if (return_end)
+    *return_end = (char *)str;
+
+  return value;
+}
+
+
 /** Return true if preferences match */
 int sip_prefs_match(union sip_pref const *a, 
 		    union sip_pref const *b)

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_reason.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_reason.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_reason.c	Tue Apr 24 10:14:28 2007
@@ -42,6 +42,8 @@
 #include <stddef.h>
 #include <stdlib.h>
 #include <string.h>
+#include <limits.h>
+
 #include <assert.h>
 
 /**@SIP_HEADER sip_reason Reason Header

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_refer.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_refer.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_refer.c	Tue Apr 24 10:14:28 2007
@@ -45,6 +45,8 @@
 #include <stddef.h>
 #include <stdlib.h>
 #include <string.h>
+#include <limits.h>
+
 #include <assert.h>
 
 /* ====================================================================== */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_tag_class.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_tag_class.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_tag_class.c	Tue Apr 24 10:14:28 2007
@@ -46,6 +46,7 @@
 #include <assert.h>
 #include <stddef.h>
 #include <string.h>
+#include <limits.h>
 
 /** Tag class for SIP header tags. @HIDE */
 tag_class_t siphdrtag_class[1] = 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_util.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_util.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sip_util.c	Tue Apr 24 10:14:28 2007
@@ -247,8 +247,8 @@
     if (port || host_is_ip_address(host))
       transport = NULL;
   }
-  else if (port && host_is_ip_address(host) &&
-	   strcmp(port, SIP_DEFAULT_SERV) == 0) {
+  else if (port && strcmp(port, SIP_DEFAULT_SERV) == 0 &&
+	   (host_is_ip_address(host) || host_has_domain_invalid(host))) {
     port = NULL;
   }
 
@@ -258,10 +258,11 @@
   /* Make transport parameter lowercase */
   if (transport && strlen(transport) < (sizeof _transport)) {
     char *s = strcpy(_transport, transport);
+    short c;
 
-    for (s = _transport; *s && *s != ';'; s++)
-      if (isupper(*s))
-	*s = tolower(*s);
+    for (s = _transport; (c = *s) && c != ';'; s++)
+      if (isupper(c))
+	*s = tolower(c);
 
     transport = _transport;
   }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_header.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_header.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_header.h	Tue Apr 24 10:14:28 2007
@@ -58,7 +58,7 @@
 SOFIA_BEGIN_DECLS
 
 /** Return built-in SIP parser object. */
-SOFIAPUBFUN msg_mclass_t *sip_default_mclass(void);
+SOFIAPUBFUN msg_mclass_t const *sip_default_mclass(void);
 
 /** Check that sip_t is a SIP structure (not RTSP or HTTP). @HIDE */
 #define sip_is_sip(sip) ((sip) && (sip)->sip_ident == SIP_PROTOCOL_TAG)
@@ -345,9 +345,15 @@
 SOFIAPUBFUN
 int sip_has_feature(msg_list_t const *supported, char const *feature);
 
+/** Return true if the method is listed in @Allow header. */
 SOFIAPUBFUN int sip_is_allowed(sip_allow_t const *allow, 
 			       sip_method_t method, char const *name);
 
+/** Check if the well-known method is listed in @Allow header. @NEW_1_12_6 */
+#define SIP_IS_ALLOWED(allow, method) \
+  (sip_method_unknown < (method) && (method) < 32 && \
+   (allow) && ((allow)->k_bitmap & (1 << (method))) != 0)
+
 /* ---------------------------------------------------------------------------
  * Bitmasks for header classifications
  */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_parser.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_parser.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_parser.h	Tue Apr 24 10:14:28 2007
@@ -192,10 +192,6 @@
 #define sip_params_copy_xtra	msg_params_copy_xtra
 #define sip_params_copy		msg_params_copy
 
-#define sip_params_add      	msg_params_add
-#define sip_params_cmp      	msg_params_cmp
-#define sip_params_replace  	msg_params_replace
-
 SOFIAPUBFUN int sip_generic_xtra(sip_generic_t const *g);
 
 SOFIAPUBFUN sip_generic_t *sip_generic_dup(su_home_t *home, 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_util.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_util.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/sofia-sip/sip_util.h	Tue Apr 24 10:14:28 2007
@@ -42,21 +42,11 @@
 #include <sofia-sip/string0.h>
 #endif
 
-SOFIA_BEGIN_DECLS
+#ifndef MSG_HEADER_H
+#include <sofia-sip/msg_header.h>
+#endif
 
-/* @deprecated
- * These are just wrappers around msg_params_*() functions. 
- *
- * Use msg_header_*_param() functions instead.
- */
-SOFIAPUBFUN char const *sip_params_find(sip_param_t const pp[],
-					char const *token);
-SOFIAPUBFUN int sip_params_add(su_home_t *sh, 
-			       sip_param_t **pparams,
-			       char const *param);
-SOFIAPUBFUN int sip_params_cmp(sip_param_t const a[], sip_param_t const b[]);
-SOFIAPUBFUN int sip_params_replace(su_home_t *,
-				   sip_param_t **pparams, char const *param);
+SOFIA_BEGIN_DECLS
 
 SOFIAPUBFUN
 sip_contact_t *
@@ -159,8 +149,8 @@
    */
   struct sp_range {
     enum sp_type spr_type;
-    double spr_lower;
-    double spr_upper;
+    double spr_lower;		/**< Lower limit. Lowest value is -DBL_MAX. */
+    double spr_upper;		/**< Upper limit. Highest value is DBL_MAX. */
   } sp_range;
 };
 
@@ -210,6 +200,13 @@
 sip_security_client_select(sip_security_client_t const *client,
 			   sip_security_server_t const *server);
 
+/* Compatibility stuff */
+
+#define sip_params_add      	msg_params_add
+#define sip_params_cmp      	msg_params_cmp
+#define sip_params_replace  	msg_params_replace
+#define sip_params_find         msg_params_find
+
 SOFIA_END_DECLS
 
 #endif /** !defined(SIP_UTIL_H) */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/test_date.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/test_date.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/test_date.c	Tue Apr 24 10:14:28 2007
@@ -33,6 +33,8 @@
  * @date Wed Mar 21 19:12:13 2001 ppessi
  */
 
+#include "config.h"
+
 #include <stdio.h>
 #include <sofia-sip/string0.h>
 #include <stddef.h>
@@ -42,12 +44,12 @@
 #include <sofia-sip/sip_header.h>
 #include <sofia-sip/msg_date.h>
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, 
 	  "usage: test_date [SIP-date] "
 	  "[YYYYy][DDd][HHh][MMm][SS[s]]\n");
-  exit(1);
+  exit(exitcode);
 }
 
 int main(int ac, char *av[])
@@ -83,7 +85,7 @@
 	case 's': delta += t2; break;
 	default:
 	  fprintf(stderr, "test_date: %s is not valid time offset\n" , av[2]);
-	  usage();
+	  usage(1);
 	  break;
 	}
       }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/test_sip_msg.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/test_sip_msg.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/test_sip_msg.c	Tue Apr 24 10:14:28 2007
@@ -65,7 +65,7 @@
   return *o != *n;
 }
 
-int test_msg_class(msg_mclass_t *mc)
+int test_msg_class(msg_mclass_t const *mc)
 {
   int i, j, N;
 
@@ -159,7 +159,7 @@
   int m, tcp;
   sip_t *sip;
   int exitcode = 0; 
-  msg_mclass_t *sip_mclass = sip_default_mclass();
+  msg_mclass_t const *sip_mclass = sip_default_mclass();
   msg_t *msg = msg_create(sip_mclass, MSG_FLG_EXTRACT_COPY);
   msg_iovec_t iovec[1];
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/torture_sip.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/torture_sip.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/torture_sip.c	Tue Apr 24 10:14:28 2007
@@ -354,7 +354,7 @@
     su_home_t home[1] = { SU_HOME_INIT(home) };
     char const *display;
     url_t url[1];
-    char const * const *params;
+    msg_param_t const *params;
     char const *comment;
     char const na[] = "Raaka Arska <tel:+358501970>;param=1;humppa (test) ";
     char const na2[] = "tel:+358501970;param=1;humppa (test) ";
@@ -412,7 +412,12 @@
     TEST_1(sip_from_tag(home, f, "tag=jxahudsf") == 0);
     su_free(home, f);
 
+    TEST_1(f = sip_from_create(home, (void *)"<sip:joe at bar;tag=bar> (joe)"));
+    TEST_1(sip_is_from((sip_header_t*)f));
+    su_free(home, f);
+
     TEST_1(t = sip_to_create(home, (void *)"<sip:joe at bar;tag=bar> (joe)"));
+    TEST_1(sip_is_to((sip_header_t*)t));
     TEST_1(sip_to_tag(home, t, "tag=jxahudsf") == 0);
     TEST_S(t->a_tag, "jxahudsf");
     TEST(msg_header_replace_param(home, t->a_common, "tag=bar"), 1);
@@ -511,7 +516,7 @@
 
     v = sip_via_make(home, "SIP/2.0/UDP domain.invalid:5060"); TEST_1(v);
     s = sip_contact_string_from_via(home, v, NULL, v->v_protocol);
-    TEST_S(s, "<sip:domain.invalid:5060;transport=udp>");
+    TEST_S(s, "<sip:domain.invalid;transport=udp>");
     su_free(home, v), su_free(home, s);
 
     TEST_1(sip_transport_has_tls("SIP/2.0/TLS-SCTP"));
@@ -739,8 +744,6 @@
   }
 
   END();
-
-  return 0;
 }
 
 msg_t *read_message(int flags, char const buffer[])
@@ -1653,7 +1656,11 @@
   TEST(count(sip->sip_content_type->c_common), 1);
   TEST(count(sip->sip_route->r_common), 0);
   TEST(count(sip->sip_record_route->r_common), 4);
+#if SU_HAVE_EXPERIMENTAL
   TEST(count(sip->sip_unknown->un_common), 2);
+#else
+  TEST(count(sip->sip_unknown->un_common), 4);
+#endif
   TEST(count(sip->sip_error->er_common), 1);
   TEST(count(sip->sip_max_forwards->mf_common), 1);
   TEST(count(sip->sip_min_expires->me_common), 1);
@@ -1667,6 +1674,7 @@
   TEST(sip->sip_max_forwards->mf_count, 12);
   TEST(sip->sip_min_expires->me_delta, 150);
 
+#if SU_HAVE_EXPERIMENTAL
   {
     sip_suppress_body_if_match_t *sbim;
     sip_suppress_notify_if_match_t *snim;
@@ -1683,6 +1691,7 @@
     TEST_SIZE(offsetof(msg_generic_t, g_value),
 	      offsetof(sip_suppress_notify_if_match_t, snim_tag));
   }
+#endif
 
   TEST_1(sip->sip_from->a_display);
   TEST_S(sip->sip_from->a_display, "h");
@@ -2526,6 +2535,7 @@
 }
 
 #include <float.h>
+#include <math.h>
 
 int test_caller_prefs(void)
 {
@@ -2641,7 +2651,7 @@
     
   TEST_1(sip_prefs_parse(sp, &s, &negate));
   TEST(sp->sp_type, sp_range);
-  TEST_D(sp->sp_range.spr_lower, DBL_MIN);
+  TEST_D(sp->sp_range.spr_lower, -DBL_MAX);
   TEST_D(sp->sp_range.spr_upper, 3.0);
   TEST_1(sip_prefs_match(sp, sp));
   TEST_1(!negate);
@@ -2659,7 +2669,7 @@
 
   TEST_1(sip_prefs_parse(sp, &s, &negate));
   TEST(sp->sp_type, sp_range);
-  TEST_D(sp->sp_range.spr_lower, DBL_MIN);
+  TEST_D(sp->sp_range.spr_lower, -DBL_MAX);
   TEST_D(sp->sp_range.spr_upper, 6.0);
   TEST_1(sip_prefs_match(sp, sp));
   TEST_1(negate);
@@ -2678,6 +2688,46 @@
   TEST_1(!sip_prefs_parse(sp, &s, &negate));
   TEST(sp->sp_type, sp_init);
 
+  /* Numeric */
+  s = "\" !#="
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111."
+
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111"
+    "1111111111111111111111111111111111111111,"
+    " #<=-16"
+    "\"";
+
+  negate = 0; memset(sp, 0, sizeof sp);
+
+  TEST_1(sip_prefs_parse(sp, &s, &negate));
+  TEST(sp->sp_type, sp_range);
+  TEST_D(sp->sp_range.spr_lower, DBL_MAX);
+  TEST_D(sp->sp_range.spr_upper, DBL_MAX);
+  TEST_1(sip_prefs_match(sp, sp));
+  TEST_1(negate);
+
+  TEST_1(sip_prefs_parse(sp, &s, &negate));
+  TEST(sp->sp_type, sp_range);
+  TEST_D(sp->sp_range.spr_lower, -DBL_MAX);
+  TEST_D(sp->sp_range.spr_upper, -16.0);
+  TEST_1(sip_prefs_match(sp, sp));
+  TEST_1(!negate);
+
   error = 12;
 
   TEST_1(sip_prefs_matching("\"INVITE,MESSAGE,SUBSCRIBE\"", 
@@ -3206,11 +3256,12 @@
   END();
 }
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, 
-	  "usage: %s [-v]\n", 
+	  "usage: %s [-v] [-a]\n", 
 	  name);
+  exit(exitcode);
 }
 
 char *lastpart(char *path)
@@ -3231,8 +3282,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   if (!test_mclass)

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/validator.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/validator.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sip/validator.c	Tue Apr 24 10:14:28 2007
@@ -180,7 +180,7 @@
     return path;
 }
 
-msg_mclass_t *mclass = NULL;
+msg_mclass_t const *mclass = NULL;
 
 int validate_file(int fd, char const *name, context_t *ctx);
 int validate_dump(char *, off_t, context_t *ctx);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -53,11 +53,11 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile soa.docs $(BUILT_SOURCES)
+EXTRA_DIST =		soa.docs $(BUILT_SOURCES)
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
 
 TAG_DLL_FLAGS =		LIST=soa_tag_list
\ No newline at end of file

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/soa.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/soa.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/soa.c	Tue Apr 24 10:14:28 2007
@@ -167,7 +167,7 @@
   struct soa_namenode const *n;
   struct soa_namenode *e;
 
-  SU_DEBUG_9(("soa_add(%s%s%s, %p) called\n", NICE(name), actions));
+  SU_DEBUG_9(("soa_add(%s%s%s, %p) called\n", NICE(name), (void *)actions));
 
   if (name == NULL || actions == NULL)
     return su_seterrno(EFAULT);
@@ -227,7 +227,7 @@
   size_t namelen;
 
   SU_DEBUG_9(("soa_create(\"%s\", %p, %p) called\n",
-	      name ? name : "default", root, magic));
+	      name ? name : "default", (void *)root, (void *)magic));
 
   if (name && name[0]) {
     struct soa_namenode const *n;
@@ -276,7 +276,7 @@
 
   SU_DEBUG_9(("soa_clone(%s::%p, %p, %p) called\n",
 	      parent_ss ? parent_ss->ss_actions->soa_name : "",
-	      parent_ss, root, magic));
+	      (void *)parent_ss, (void *)root, (void *)magic));
 
   if (parent_ss == NULL || root == NULL)
     return (void)su_seterrno(EFAULT), NULL;
@@ -302,7 +302,7 @@
 soa_session_t *soa_session_ref(soa_session_t *ss)
 {
   SU_DEBUG_9(("soa_session_ref(%s::%p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
   return su_home_ref(ss->ss_home);
 }
 
@@ -310,7 +310,7 @@
 void soa_session_unref(soa_session_t *ss)
 {
   SU_DEBUG_9(("soa_session_unref(%s::%p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
   su_home_unref(ss->ss_home);
 }
 
@@ -350,7 +350,7 @@
 void soa_destroy(soa_session_t *ss)
 {
   SU_DEBUG_9(("soa_destroy(%s::%p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (ss) {
     ss->ss_active = 0;
@@ -396,7 +396,7 @@
   int n;
 
   SU_DEBUG_9(("soa_set_params(%s::%p, ...) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (ss == NULL)
     return su_seterrno(EFAULT), -1;
@@ -606,7 +606,7 @@
   int n;
 
   SU_DEBUG_9(("soa_get_params(%s::%p, ...) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (ss == NULL)
     return su_seterrno(EFAULT), -1;
@@ -688,7 +688,7 @@
   tagi_t *params = NULL;
 
   SU_DEBUG_9(("soa_get_paramlist(%s::%p, ...) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (ss) {
     ta_start(ta, tag, value);
@@ -756,7 +756,7 @@
 			      char const **return_phrase)
 {
   SU_DEBUG_9(("soa_error_as_sip_response(%s::%p, ...) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (ss == NULL || ss->ss_status < 400 || ss->ss_status >= 700) {
     if (return_phrase)
@@ -777,7 +777,7 @@
   char *reason;
 
   SU_DEBUG_9(("soa_error_as_sip_reason(%s::%p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (ss == NULL)
     return "SIP;cause=500;text=\"Internal Server Error\"";
@@ -832,8 +832,8 @@
   char const *sdp_str;
 
   SU_DEBUG_9(("soa_get_capability_sdp(%s::%p, [%p], [%p], [%p]) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss,
-	      return_sdp, return_sdp_str, return_len));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss,
+	      (void *)return_sdp, (void *)return_sdp_str, (void *)return_len));
 
   if (ss == NULL)
     return (void)su_seterrno(EFAULT), -1;
@@ -878,7 +878,7 @@
 			   char const *str, issize_t len)
 {
   SU_DEBUG_9(("soa_set_capability_sdp(%s::%p, %p, %p, "MOD_ZD") called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, sdp, str, (ssize_t)len));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss, (void *)sdp, (void *)str, (ssize_t)len));
 
   return soa_set_sdp(ss, soa_capability_sdp_kind, sdp, str, len);
 }
@@ -964,8 +964,8 @@
   char const *sdp_str;
 
   SU_DEBUG_9(("soa_get_user_sdp(%s::%p, [%p], [%p], [%p]) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss,
-	      return_sdp, return_sdp_str, return_len));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss,
+			  (void *)return_sdp, (void *)return_sdp_str, (void *)return_len));
 
   if (ss == NULL)
     return (void)su_seterrno(EFAULT), -1;
@@ -1036,7 +1036,7 @@
 		     char const *str, issize_t len)
 {
   SU_DEBUG_9(("soa_set_user_sdp(%s::%p, %p, %p, "MOD_ZD") called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, sdp, str, (ssize_t)len));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss, (void *)sdp, (void *)str, (ssize_t)len));
 
   return soa_set_sdp(ss, soa_user_sdp_kind, sdp, str, len);
 }
@@ -1081,8 +1081,8 @@
   char const *sdp_str;
 
   SU_DEBUG_9(("soa_get_remote_sdp(%s::%p, [%p], [%p], [%p]) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss,
-	      return_sdp, return_sdp_str, return_len));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss,
+			  (void *)return_sdp, (void *)return_sdp_str, (void *)return_len));
 
   if (ss == NULL)
     return (void)su_seterrno(EFAULT), -1;
@@ -1155,7 +1155,7 @@
 		       char const *str, issize_t len)
 {
   SU_DEBUG_9(("soa_set_remote_sdp(%s::%p, %p, %p, "MOD_ZD") called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, sdp, str, (ssize_t)len));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss, (void *)sdp, (void *)str, (ssize_t)len));
 
   return soa_set_sdp(ss, soa_remote_sdp_kind, sdp, str, len);
 }
@@ -1198,7 +1198,7 @@
 int soa_clear_remote_sdp(soa_session_t *ss)
 {
   SU_DEBUG_9(("soa_clear_remote_sdp(%s::%p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (!ss)
     return (void)su_seterrno(EFAULT), -1;
@@ -1253,8 +1253,8 @@
   char const *sdp_str;
 
   SU_DEBUG_9(("soa_get_local_sdp(%s::%p, [%p], [%p], [%p]) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss,
-	      return_sdp, return_sdp_str, return_len));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss,
+			  (void *)return_sdp, (void *)return_sdp_str, (void *)return_len));
 
   if (ss == NULL)
     return (void)su_seterrno(EFAULT), -1;
@@ -1286,7 +1286,7 @@
   int complete;
 
   SU_DEBUG_9(("soa_init_offer_answer(%s::%p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (!ss)
     return 0;
@@ -1308,7 +1308,7 @@
 char **soa_media_features(soa_session_t *ss, int live, su_home_t *home)
 {
   SU_DEBUG_9(("soa_media_features(%s::%p, %u, %p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, live, home));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss, live, (void *)home));
 
   if (ss)
     return ss->ss_actions->soa_media_features(ss, live, home);
@@ -1324,7 +1324,7 @@
 char const * const * soa_sip_require(soa_session_t const *ss)
 {
   SU_DEBUG_9(("soa_sip_require(%s::%p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (ss)
     return ss->ss_actions->soa_sip_require(ss);
@@ -1341,7 +1341,7 @@
 char const * const * soa_sip_supported(soa_session_t const *ss)
 {
   SU_DEBUG_9(("soa_sip_supported(%s::%p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   if (ss)
     return ss->ss_actions->soa_sip_supported(ss);
@@ -1360,7 +1360,7 @@
 			    char const * const * require)
 {
   SU_DEBUG_9(("soa_remote_sip_features(%s::%p, %p, %p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, supported, require));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss, (void *)supported, (void *)require));
 
   if (ss)
     return ss->ss_actions->soa_remote_sip_features(ss, supported, require);
@@ -1405,8 +1405,8 @@
 		       int always,
 		       soa_callback_f *completed)
 {
-  SU_DEBUG_9(("soa_generate_offer(%s::%p, %u, %p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, always, completed));
+  SU_DEBUG_9(("soa_generate_offer(%s::%p, %u) called\n",
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss, always));
 
   /** @ERROR EFAULT Bad address. */
   if (ss == NULL)
@@ -1493,8 +1493,8 @@
 int soa_generate_answer(soa_session_t *ss,
 			soa_callback_f *completed)
 {
-  SU_DEBUG_9(("soa_generate_answer(%s::%p, %p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, completed));
+  SU_DEBUG_9(("soa_generate_answer(%s::%p) called\n",
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   /** @ERROR EFAULT Bad address as @a ss. */
   if (ss == NULL)
@@ -1573,8 +1573,8 @@
 int soa_process_answer(soa_session_t *ss,
 		       soa_callback_f *completed)
 {
-  SU_DEBUG_9(("soa_process_answer(%s::%p, %p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, completed));
+  SU_DEBUG_9(("soa_process_answer(%s::%p) called\n",
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   /** @ERROR EFAULT Bad address as @a ss. */
   if (ss == NULL)
@@ -1654,8 +1654,8 @@
 int soa_process_reject(soa_session_t *ss,
 		       soa_callback_f *completed)
 {
-  SU_DEBUG_9(("soa_process_reject(%s::%p, %p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, completed));
+  SU_DEBUG_9(("soa_process_reject(%s::%p) called\n",
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   /** @ERROR EFAULT Bad address as @a ss. */
   if (ss == NULL)
@@ -1711,7 +1711,7 @@
 int soa_activate(soa_session_t *ss, char const *option)
 {
   SU_DEBUG_9(("soa_activate(%s::%p, %s%s%s) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, NICE(option)));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss, NICE(option)));
 
   /** @ERROR EFAULT Bad address as @a ss. */
   if (ss == NULL)
@@ -1741,7 +1741,7 @@
 int soa_deactivate(soa_session_t *ss, char const *option)
 {
   SU_DEBUG_9(("soa_deactivate(%s::%p, %s%s%s) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss, NICE(option)));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss, NICE(option)));
 
   /** @ERROR EFAULT Bad address as @a ss. */
   if (ss == NULL)
@@ -1763,7 +1763,7 @@
 void soa_terminate(soa_session_t *ss, char const *option)
 {
   SU_DEBUG_9(("soa_terminate(%s::%p) called\n",
-	      ss ? ss->ss_actions->soa_name : "", ss));
+	      ss ? ss->ss_actions->soa_name : "", (void *)ss));
 
   /** @ERROR EFAULT Bad address as @a ss. */
   if (ss == NULL)
@@ -1799,49 +1799,65 @@
 /** Return true if audio has been activated. */
 int soa_is_audio_active(soa_session_t const *ss)
 {
-  return ss ? ss->ss_local_activity->ma_audio : SOA_ACTIVE_DISABLED;
+  int ma = ss ? ss->ss_local_activity->ma_audio : SOA_ACTIVE_DISABLED;
+  if (ma >= 4) ma |= -8;
+  return ma;
 }
 
 /** Return true if video has been activated. */
 int soa_is_video_active(soa_session_t const *ss)
 {
-  return ss ? ss->ss_local_activity->ma_video : SOA_ACTIVE_DISABLED;
+  int ma = ss ? ss->ss_local_activity->ma_video : SOA_ACTIVE_DISABLED;
+  if (ma >= 4) ma |= -8;
+  return ma;
 }
 
 /** Return true if image sharing has been activated. */
 int soa_is_image_active(soa_session_t const *ss)
 {
-  return ss ? ss->ss_local_activity->ma_image : SOA_ACTIVE_DISABLED;
+  int ma = ss ? ss->ss_local_activity->ma_image : SOA_ACTIVE_DISABLED;
+  if (ma >= 4) ma |= -8;
+  return ma;
 }
 
 /** Return true if messaging session has been activated. */
 int soa_is_chat_active(soa_session_t const *ss)
 {
-  return ss ? ss->ss_local_activity->ma_chat : SOA_ACTIVE_DISABLED;
+  int ma = ss ? ss->ss_local_activity->ma_chat : SOA_ACTIVE_DISABLED;
+  if (ma >= 4) ma |= -8;
+  return ma;
 }
 
 /** Return true if remote audio is active (not on hold). */
 int soa_is_remote_audio_active(soa_session_t const *ss)
 {
-  return ss ? ss->ss_remote_activity->ma_audio : SOA_ACTIVE_DISABLED;
+  int ma = ss ? ss->ss_remote_activity->ma_audio : SOA_ACTIVE_DISABLED;
+  if (ma >= 4) ma |= -8;
+  return ma;
 }
 
 /** Return true if remote video is active (not on hold). */
 int soa_is_remote_video_active(soa_session_t const *ss)
 {
-  return ss ? ss->ss_remote_activity->ma_video : SOA_ACTIVE_DISABLED;
+  int ma = ss ? ss->ss_remote_activity->ma_video : SOA_ACTIVE_DISABLED;
+  if (ma >= 4) ma |= -8;
+  return ma;
 }
 
 /** Return true if image sharing is active (not on hold). */
 int soa_is_remote_image_active(soa_session_t const *ss)
 {
-  return ss ? ss->ss_remote_activity->ma_image : SOA_ACTIVE_DISABLED;
+  int ma = ss ? ss->ss_remote_activity->ma_image : SOA_ACTIVE_DISABLED;
+  if (ma >= 4) ma |= -8;
+  return ma;
 }
 
 /** Return true if chat session is active (not on hold). */
 int soa_is_remote_chat_active(soa_session_t const *ss)
 {
-  return ss ? ss->ss_remote_activity->ma_chat : SOA_ACTIVE_DISABLED;
+  int ma = ss ? ss->ss_remote_activity->ma_chat : SOA_ACTIVE_DISABLED;
+  if (ma >= 4) ma |= -8;
+  return ma;
 }
 
 /* ======================================================================== */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/soa_static.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/soa_static.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/soa_static.c	Tue Apr 24 10:14:28 2007
@@ -822,7 +822,7 @@
   sdp_mode_t recv_mode;
 
   SU_DEBUG_7(("soa_sdp_mode_set_is_needed(%p, %p, \"%s\"): called\n",
-	      session, remote, hold ? hold : ""));
+	      (void *)session, (void *)remote, hold ? hold : ""));
 
   if (!session )
     return 0;
@@ -865,7 +865,7 @@
   sdp_mode_t send_mode, recv_mode;
 
   SU_DEBUG_7(("soa_sdp_mode_set(%p, %p, \"%s\"): called\n",
-	      session, remote, hold ? hold : ""));
+	      (void *)session, (void *)remote, hold ? hold : ""));
 
   if (!session || !session->sdp_media)
     return 0;
@@ -928,7 +928,8 @@
 
   su_home_auto(tmphome, sizeof tmphome);
 
-  SU_DEBUG_7(("soa_static_offer_answer_action(%p, %s): called\n", ss, by));
+  SU_DEBUG_7(("soa_static_offer_answer_action(%p, %s): called\n",
+	      (void *)ss, by));
 
   if (user == NULL)
     return soa_set_status(ss, 500, "No session set by user");
@@ -954,7 +955,8 @@
   if (local == NULL) switch (action) {
   case generate_offer:
   case generate_answer:
-    SU_DEBUG_7(("soa_static(%p, %s): generating local description\n", ss, by));
+    SU_DEBUG_7(("soa_static(%p, %s): %s\n", (void *)ss, by,
+		"generating local description"));
 
     local = local0;
     *local = *user, local->sdp_media = NULL;
@@ -987,7 +989,7 @@
       break;
     if (local != local0)
       *local0 = *local, local = local0;
-    SU_DEBUG_7(("soa_static(%p, %s): %s\n", ss, by, 
+    SU_DEBUG_7(("soa_static(%p, %s): %s\n", (void *)ss, by, 
 		"upgrade with local description"));
     soa_sdp_upgrade(ss, tmphome, local, user, user);
     break;
@@ -999,7 +1001,7 @@
     if (1) {
       if (local != local0)
 	*local0 = *local, local = local0;
-      SU_DEBUG_7(("soa_static(%p, %s): %s\n", ss, by,
+      SU_DEBUG_7(("soa_static(%p, %s): %s\n", (void *)ss, by,
 		  "upgrade with remote description"));
       soa_sdp_upgrade(ss, tmphome, local, user, remote);
     }
@@ -1032,7 +1034,8 @@
 	} while (0)
 	DUP_LOCAL(local);
       }
-      SU_DEBUG_7(("soa_static(%p, %s): marking rejected media\n", ss, by));
+      SU_DEBUG_7(("soa_static(%p, %s): %s\n", (void *)ss, by, 
+		  "marking rejected media"));
       soa_sdp_reject(tmphome, local, remote);
     }
     break;
@@ -1065,7 +1068,7 @@
     if (ss->ss_local_remote_version == remote_version)
       break;
     if (1 /* We don't have good test for codecs */) {
-      SU_DEBUG_7(("soa_static(%p, %s): %s\n", ss, by,
+      SU_DEBUG_7(("soa_static(%p, %s): %s\n", (void *)ss, by,
 		  "upgrade codecs with remote description"));
       if (local != local0) {
 	*local0 = *local, local = local0; 
@@ -1143,7 +1146,8 @@
       ss->ss_previous_remote_version = ss->ss_local_remote_version;
     }
 
-    SU_DEBUG_7(("soa_static(%p, %s): storing local description\n", ss, by));
+    SU_DEBUG_7(("soa_static(%p, %s): %s\n", (void *)ss, by,
+		"storing local description"));
 
     /* Update the unparsed and pretty-printed descriptions  */
     if (soa_description_set(ss, ss->ss_local, local, NULL, 0) < 0) {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/sofia-sip/soa_session.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/sofia-sip/soa_session.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/sofia-sip/soa_session.h	Tue Apr 24 10:14:28 2007
@@ -163,10 +163,10 @@
 
   struct soa_media_activity
   {
-    int ma_audio:4; /**< Audio activity (send/recv) */
-    int ma_video:4; /**< Video activity (send/recv) */
-    int ma_image:4; /**< Image activity (send/recv) for JPIP */
-    int ma_chat:4;  /**< Chat activity (send/recv) */
+    unsigned ma_audio:4; /**< Audio activity (send/recv) */
+    unsigned ma_video:4; /**< Video activity (send/recv) */
+    unsigned ma_image:4; /**< Image activity (send/recv) for JPIP */
+    unsigned ma_chat:4;  /**< Chat activity (send/recv) */
   } ss_local_activity[1], ss_remote_activity[1];
 
   /** Capabilities as specified by application */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/test_soa.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/test_soa.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/soa/test_soa.c	Tue Apr 24 10:14:28 2007
@@ -353,7 +353,9 @@
   soa_session_t *a, *b;
 
   char const *caps = NONE, *offer = NONE, *answer = NONE;
-  isize_t capslen = -1, offerlen = -1, answerlen = -1;
+  isize_t capslen = (isize_t)-1;
+  isize_t offerlen = (isize_t)-1;
+  isize_t answerlen = (isize_t)-1;
 
   su_home_t home[1] = { SU_HOME_INIT(home) };
 
@@ -611,7 +613,7 @@
   soa_session_t *a, *b;
 
   char const *offer = NONE, *answer = NONE;
-  isize_t offerlen = -1, answerlen = -1;
+  isize_t offerlen = (isize_t)-1, answerlen = (isize_t)-1;
 
   sdp_session_t const *a_sdp, *b_sdp;
   sdp_media_t const *m;
@@ -1243,12 +1245,12 @@
 }
 #endif
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, 
-	  "usage: %s [-v|-q] [-l level] [-p outbound-proxy-uri]\n", 
+	  "usage: %s [-v|-q] [-a] [-l level] [-p outbound-proxy-uri]\n", 
 	  name);
-  exit(1);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -1261,6 +1263,8 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else if (strcmp(argv[i], "-q") == 0)
       tstflags &= ~tst_verbatim;
     else if (strcmp(argv[i], "-1") == 0)
@@ -1277,7 +1281,7 @@
 	level = 3, rest = "";
 
       if (rest == NULL || *rest)
-	usage();
+	usage(1);
       
       su_log_set_level(soa_log, level);
     }
@@ -1294,7 +1298,7 @@
       break;
     }
     else
-      usage();
+      usage(1);
   }
 
   if (o_attach) {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -51,7 +51,7 @@
 # ----------------------------------------------------------------------
 # Distribution
 
-EXTRA_DIST =		Doxyfile sresolv.docs
+EXTRA_DIST =		sresolv.docs
 
 dist_noinst_DATA = run_test_sresolv \
 	root.zone rndc.conf \
@@ -61,4 +61,5 @@
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/run_test_sresolv
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/run_test_sresolv	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/run_test_sresolv	Tue Apr 24 10:14:28 2007
@@ -1,4 +1,4 @@
-#! /bin/bash
+#! /bin/sh
 #
 # Run sresolv_test using our own name server
 #
@@ -55,8 +55,13 @@
     done
 fi
 
-# No named, no fun
-type -p named >/dev/null || exit 77
+# No BIND 9, no fun
+{ type -p named >/dev/null &&
+  named -v | grep -q BIND.*9 
+} || {
+echo test_sresolv: there is no BIND 9 named in you path, skipping
+exit 77
+} 
 
 if eval $ipv6
 then

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres.c	Tue Apr 24 10:14:28 2007
@@ -70,6 +70,10 @@
 #endif
 #endif
 
+#if HAVE_IPHLPAPI_H
+#include <iphlpapi.h>
+#endif
+
 #include <time.h>
 
 #include "sofia-resolv/sres.h"
@@ -159,6 +163,7 @@
 #define INVALID_SOCKET ((sres_socket_t)-1)
 #endif
 
+#define SRES_TIME_MAX ((time_t)LONG_MAX)
 
 #if !HAVE_INET_PTON
 int inet_pton(int af, char const *src, void *dst);
@@ -211,7 +216,10 @@
 
   /** ICMP/temporary error received, zero when successful. */
   time_t                  dns_icmp;
-  /** Persisten error, zero when successful. */
+  /** Persistent error, zero when successful or timeout. 
+   *
+   * Never selected if dns_error is SRES_TIME_MAX.
+   */
   time_t                  dns_error;
 };
 
@@ -434,7 +442,7 @@
 static
 sres_server_t *sres_next_server(sres_resolver_t *res, 
 				uint8_t *in_out_i,
-				int timeout);
+				int always);
 
 static
 int sres_send_dns_query(sres_resolver_t *res, sres_query_t *q);
@@ -541,7 +549,7 @@
 #include <winreg.h>
 #endif
 
-/**@var SRESOLV_DEBUG
+/**@ingroup sresolv_env
  *
  * Environment variable determining the debug log level for @b sresolv
  * module.
@@ -551,7 +559,9 @@
  * 
  * @sa <su_debug.h>, sresolv_log, SOFIA_DEBUG
  */
-extern char const SRESOLV_DEBUG[];
+#ifdef DOXYGEN
+extern char const SRESOLV_DEBUG[]; /* dummy declaration for Doxygen */
+#endif
 
 /**Debug log for @b sresolv module. 
  * 
@@ -626,7 +636,7 @@
  *                       (overriding options in conf_file)
  *
  * @par Environment Variables
- * - LOCALDOMAIN overrides @c domain or @c search directives
+ * - #LOCALDOMAIN overrides @c domain or @c search directives
  * - #RES_OPTIONS overrides values of @a options in resolv.conf
  * - #SRES_OPTIONS overrides values of @a options in resolv.conf, #RES_OPTIONS,
  *   and @a options, ... list given as argument for this function
@@ -923,8 +933,8 @@
   size_t dlen;
   
   char b[8];
-  SU_DEBUG_9(("sres_query(%p, %p, %p, %s, \"%s\") called\n",
-	      res, callback, context, sres_record_type(type, b), domain));
+  SU_DEBUG_9(("sres_query(%p, %p, %s, \"%s\") called\n",
+			  (void *)res, (void *)context, sres_record_type(type, b), domain));
 
   if (res == NULL || domain == NULL)
     return su_seterrno(EFAULT), (void *)NULL;
@@ -990,8 +1000,8 @@
   unsigned dots; char const *dot;
   char b[8];
 
-  SU_DEBUG_9(("sres_search(%p, %p, %p, %s, \"%s\") called\n",
-	      res, callback, context, sres_record_type(type, b), domain));
+  SU_DEBUG_9(("sres_search(%p, %p, %s, \"%s\") called\n",
+			  (void *)res, (void *)context, sres_record_type(type, b), domain));
 
   if (res == NULL || domain == NULL)
     return su_seterrno(EFAULT), (void *)NULL;
@@ -1235,7 +1245,7 @@
   int i;
 
   SU_DEBUG_9(("sres_search_cached_answers(%p, %s, \"%s\") called\n",
-	      res, sres_record_type(type, rooted_domain), domain));
+	      (void *)res, sres_record_type(type, rooted_domain), domain));
 
   if (!res || !name)
     return su_seterrno(EFAULT), (void *)NULL;
@@ -1895,6 +1905,36 @@
 #define MAX_DATALEN           65535
 
 /**
+ * Uses IP Helper IP to get DNS servers list.
+ */
+static int sres_parse_win32_ip(sres_config_t *c)
+{
+  int ret = -1;
+
+#if HAVE_IPHLPAPI_H
+  DWORD dw;
+  su_home_t *home = c->c_home;
+  ULONG size = sizeof(FIXED_INFO);
+
+  do {
+    FIXED_INFO *info = (FIXED_INFO *)su_alloc(home, size);
+    dw = GetNetworkParams(info, &size);
+    if (dw == ERROR_SUCCESS) {
+      IP_ADDR_STRING* addr = &info->DnsServerList;
+      for (; addr; addr = addr->Next) {
+       SU_DEBUG_3(("Adding nameserver: %s\n", addr->IpAddress.String));
+       sres_parse_nameserver(c, addr->IpAddress.String);
+      }
+      ret = 0;
+    }
+    su_free(home, info);
+  } while (dw == ERROR_BUFFER_OVERFLOW);
+#endif
+
+  return ret;
+}
+
+/**
  * Parses name servers listed in registry key 'key+lpValueName'. The
  * key is expected to contain a whitespace separate list of
  * name server IP addresses.
@@ -2072,7 +2112,7 @@
 #if _WIN32    
     /* note: no 127.0.0.1 on win32 systems */
     /* on win32, query the registry for nameservers */
-    if (sres_parse_win32_reg(c) == 0) 
+    if (sres_parse_win32_ip(c) == 0 || sres_parse_win32_reg(c) == 0)
       /* success */;
     else
       /* now what? */;
@@ -2203,21 +2243,24 @@
   return i;
 }
 
-/**Environment variable containing options for Sofia resolver. The options
+#if DOXYGEN_ONLY
+/**@ingroup sresolv_env
+ *
+ * Environment variable containing options for Sofia resolver. The options
  * recognized by Sofia resolver are as follows:
- * - debug           turn on debugging (no effect)
- * - ndots:<i>n</i>  when searching, try first to query name as absolute
- *                   domain if it contains at least <i>n</i> dots
- * - timeout:<i>secs</i> timeout in seconds
- * - attempts:<i>n</i> fail after <i>n</i> retries
- * - rotate          use round robin selection of nameservers
- * - no-check-names  do not check names for invalid characters
- * - inet6           (no effect) 
- * - ip6-dotint      IPv6 addresses are resolved using suffix ".ip6.int"
- *                   instead of the standard ".ip6.arpa" suffix
- * - ip6-bytestring  (no effect)
+ * - @b debug           turn on debugging (no effect)
+ * - @b ndots:<i>n</i>  when searching, try first to query name as absolute
+ *                      domain if it contains at least <i>n</i> dots
+ * - @b timeout:<i>secs</i> timeout in seconds
+ * - @b attempts:<i>n</i> fail after <i>n</i> retries
+ * - @b rotate          use round robin selection of nameservers
+ * - @b no-check-names  do not check names for invalid characters
+ * - @b inet6           (no effect) 
+ * - @b ip6-dotint      IPv6 addresses are resolved using suffix ".ip6.int"
+ *                      instead of the standard ".ip6.arpa" suffix
+ * - @b ip6-bytestring  (no effect)
  * The following option is a Sofia-specific extension:
- * - no-edns0        do not try to use EDNS0 extension (@RFC2671)
+ * - @b no-edns0        do not try to use EDNS0 extension (@RFC2671)
  *
  * The same options can be listed in @b options directive in resolv.conf, or
  * in #RES_OPTIONS environment variable. Note that options given in
@@ -2228,15 +2271,26 @@
  *
  * @sa Manual page for resolv.conf, #RES_OPTIONS.
  */
-extern char const SRES_OPTIONS[];
+extern SRES_OPTIONS;
 
-/**Environment variable containing resolver options. This environment
+/**@ingroup sresolv_env
+ *
+ * Environment variable containing resolver options. This environment
  * variable is also used by standard BIND resolver.
  *
  * @sa Manual page for resolv.conf, #SRES_OPTIONS.
  */
-extern char const RES_OPTIONS[];
+extern RES_OPTIONS;
 
+/**@ingroup sresolv_env
+ *
+ * Environment variable containing search domain. This environment
+ * variable is also used by standard BIND resolver.
+ *
+ * @sa Manual page for resolv.conf, #RES_OPTIONS, #SRES_OPTIONS.
+ */
+extern LOCALDOMAIN;
+#endif
 
 /* Parse options line or #SRES_OPTIONS or #RES_OPTIONS environment variable. */
 static int 
@@ -2263,7 +2317,7 @@
       value += strspn(value, " \t");
 
     if (n > 65536) {
-      SU_DEBUG_3(("sres: %s: invalid %*.s\n", c->c_filename,
+      SU_DEBUG_3(("sres: %s: invalid %*.0s\n", c->c_filename,
 		  (int)(len + extra), b));
       continue;
     }
@@ -2288,7 +2342,7 @@
     else if (MATCH("no-edns0")) c->c_opt.edns = edns_not_supported;
     else if (MATCH("edns0")) c->c_opt.edns = edns0_configured;
     else {
-      SU_DEBUG_3(("sres: %s: unknown option %*.s\n",
+      SU_DEBUG_3(("sres: %s: unknown option %*.0s\n",
 		  c->c_filename, (int)(len + extra), b));
     }
   }
@@ -2437,7 +2491,7 @@
     if (!servers[i])
       break;
 
-    if (servers[i]->dns_socket != -1) {
+    if (servers[i]->dns_socket != INVALID_SOCKET) {
       if (res->res_updcb)
 	res->res_updcb(res->res_async, INVALID_SOCKET, servers[i]->dns_socket);
       sres_close(servers[i]->dns_socket);
@@ -2467,14 +2521,13 @@
   int family = dns->dns_addr->ss_family;
   sres_socket_t s;
 
-  if (dns->dns_socket != -1)
+  if (dns->dns_socket != INVALID_SOCKET)
     return dns->dns_socket;
 
   s = socket(family, SOCK_DGRAM, IPPROTO_UDP);
   if (s == -1) {
     SU_DEBUG_1(("%s: %s: %s\n", "sres_server_socket", "socket",
 		su_strerror(su_errno())));
-    dns->dns_error = time(NULL);
     return s;
   }
 
@@ -2517,7 +2570,6 @@
 		su_strerror(su_errno()), lb, ipaddr, rb,
 		ntohs(((struct sockaddr_in *)dns->dns_addr)->sin_port)));
     sres_close(s);
-    dns->dns_error = time(NULL);
     return INVALID_SOCKET;
   }
   
@@ -2526,7 +2578,6 @@
       SU_DEBUG_1(("%s: %s: %s\n", "sres_server_socket", "update callback",
 		  su_strerror(su_errno())));
       sres_close(s);
-      dns->dns_error = time(NULL);
       return INVALID_SOCKET;
     }
   }
@@ -2547,7 +2598,7 @@
   sres_message_t m[1];
   uint8_t i, i0, N = res->res_n_servers;
   sres_socket_t s;
-  int transient, error = 0;
+  int error = 0;
   ssize_t size, no_edns_size, edns_size;
   uint16_t id = q->q_id;
   uint16_t type = q->q_type;
@@ -2558,7 +2609,7 @@
 
   if (now == 0) time(&now);
 
-  SU_DEBUG_9(("sres_send_dns_query(%p, %p) called\n", res, q));
+  SU_DEBUG_9(("sres_send_dns_query(%p, %p) called\n", (void *)res, (void *)q));
 
   if (domain == NULL)
     return -1;
@@ -2600,17 +2651,14 @@
     return -1;
   }
 
-  transient = 0;
+  i0 = q->q_i_server;
+  if (i0 > N) i0 = 0; /* Number of DNS servers reduced */
+  dns = servers[i = i0];
 
-  i0 = q->q_i_server; if (i0 > N) i0 = 0; /* Number of DNS servers reduced */
+  if (res->res_config->c_opt.rotate || dns->dns_error || dns->dns_icmp)
+    dns = sres_next_server(res, &q->q_i_server, 1), i = q->q_i_server;
 
-  if (res->res_config->c_opt.rotate || 
-      servers[i0]->dns_error || servers[i0]->dns_icmp)
-    dns = sres_next_server(res, &q->q_i_server, 0), i = q->q_i_server;
-  else 
-    dns = servers[i0], i = i0;
-
-  for (; dns; dns = sres_next_server(res, &i, 0)) {
+  for (; dns; dns = sres_next_server(res, &i, 1)) {
     /* If server supports EDNS, include EDNS0 record */
     q->q_edns = dns->dns_edns;
     /* 0 (no EDNS) or 1 (EDNS supported) additional data records */
@@ -2620,17 +2668,18 @@
 
     s = sres_server_socket(res, dns);
 
+    if (s == INVALID_SOCKET) {
+      dns->dns_icmp = now;
+      dns->dns_error = SRES_TIME_MAX;
+      continue;
+    }
+
     /* Send the DNS message via the UDP socket */
-    if (s != INVALID_SOCKET && sres_send(s, m->m_data, size, 0) == size)
+    if (sres_send(s, m->m_data, size, 0) == size)
       break;
-
     error = su_errno();
-    dns->dns_icmp = now;
-    /* EINVAL is returned if destination address is bad */
-    if (transient++ < 3 && error != EINVAL && s != -1)
-      continue;
-    transient = 0;
 
+    dns->dns_icmp = now;
     dns->dns_error = now;	/* Mark as a bad destination */
   }
 
@@ -2645,46 +2694,76 @@
 
   SU_DEBUG_5(("%s(%p, %p) id=%u %s %s (to [%s]:%u)\n", 
 	      "sres_send_dns_query",
-	      res, q, id, sres_record_type(type, b), domain, 
+	      (void *)res, (void *)q, id, sres_record_type(type, b), domain, 
 	      dns->dns_name, 
 	      htons(((struct sockaddr_in *)dns->dns_addr)->sin_port)));
 
   return 0;
 }
 
+/** Retry time after ICMP error */
+#define DNS_ICMP_TIMEOUT 60
+
+/** Retry time after immediate error */
+#define DNS_ERROR_TIMEOUT 10
 
-/** Select next server */
+/** Select next server.
+ *
+ * @param res resolver object
+ * @param[in,out] in_out_i index to DNS server table
+ * @param always return always a server
+ */
 static
 sres_server_t *sres_next_server(sres_resolver_t *res, 
 				uint8_t *in_out_i,
-				int timeout)
+				int always)
 {
   int i, j, N;
-  sres_server_t **servers;
-
-  assert(res && in_out_i);
+  sres_server_t *dns, **servers;
+  time_t now = res->res_now;
 
   N = res->res_n_servers;
   servers = res->res_servers;
   i = *in_out_i;
 
   assert(res->res_servers && res->res_servers[i]);
+
+  for (j=0; j < N; j++) {
+    dns = servers[j]; if (!dns) continue;
+    if (dns->dns_icmp + DNS_ICMP_TIMEOUT < now)
+      dns->dns_icmp = 0;
+    if (dns->dns_error + DNS_ERROR_TIMEOUT < now &&
+	dns->dns_error != SRES_TIME_MAX)
+      dns->dns_error = 0;
+  }
   
   /* Retry using another server? */
   for (j = (i + 1) % N; (j != i); j = (j + 1) % N) {
-    if (servers[j]->dns_icmp == 0) {
-      return *in_out_i = j, servers[j];
+    dns = servers[j]; if (!dns) continue;
+    if (dns->dns_icmp == 0) {
+      return *in_out_i = j, dns;
     }
   }
 
   for (j = (i + 1) % N; (j != i); j = (j + 1) % N) {
-    if (servers[j]->dns_error == 0) {
-      return *in_out_i = j, servers[j];
+    dns = servers[j]; if (!dns) continue;
+    if (dns->dns_error == 0) {
+      return *in_out_i = j, dns;
     }
   }
 
-  if (timeout)
-    return servers[i];
+  if (!always)
+    return NULL;
+
+  dns = servers[i]; 
+  if (dns && dns->dns_error < now && dns->dns_error != SRES_TIME_MAX)
+    return dns;
+
+  for (j = (i + 1) % N; j != i; j = (j + 1) % N) {
+    dns = servers[j]; if (!dns) continue;
+    if (dns->dns_error < now && dns->dns_error != SRES_TIME_MAX)
+      return *in_out_i = j, dns;
+  }
   
   return NULL;
 }
@@ -2763,7 +2842,7 @@
     }
 
     SU_DEBUG_5(("sres(q=%p): reporting errors for %u %s\n",
-		q, q->q_type, q->q_name));
+		(void *)q, q->q_type, q->q_name));
  
     sres_remove_query(q->q_res, q, 1);
     (q->q_callback)(q->q_context, q, answers);
@@ -2822,15 +2901,21 @@
   sres_cache_clean(res->res_cache, res->res_now);
 }
 
-/** Resend DNS query, report error if cannot resend any more. */
+/** Resend DNS query, report error if cannot resend any more.
+ * 
+ * @param res  resolver object
+ * @param q    query object
+ * @param timeout  true if resent because of timeout
+ *                (false if because icmp error report)
+ */
 static void
 sres_resend_dns_query(sres_resolver_t *res, sres_query_t *q, int timeout)
 {
   uint8_t i, N;
   sres_server_t *dns;
-
-  SU_DEBUG_9(("sres_resend_dns_query(%p, %p, %u) called\n",
-	      res, q, timeout));
+  
+  SU_DEBUG_9(("sres_resend_dns_query(%p, %p, %s) called\n",
+	      (void *)res, (void *)q, timeout ? "timeout" : "error"));
   
   N = res->res_n_servers;
 
@@ -2956,6 +3041,11 @@
 
     s = sres_server_socket(res, dns);
 
+    if (s == INVALID_SOCKET) {	/* Mark as a bad destination */
+      dns->dns_icmp = SRES_TIME_MAX;
+      dns->dns_error = SRES_TIME_MAX;	
+    }
+
     return_sockets[i++] = s;
   }
 
@@ -2998,7 +3088,8 @@
   int n;
   char info[128] = "";
 
-  SU_DEBUG_9(("%s(%p, %u) called\n", "sres_resolver_error", res, socket));
+  SU_DEBUG_9(("%s(%p, %u) called\n", "sres_resolver_error",
+	      (void *)res, socket));
 
   msg->msg_name = name, msg->msg_namelen = sizeof(name);
   msg->msg_iov = iov, msg->msg_iovlen = 1;
@@ -3111,7 +3202,8 @@
   int errcode = 0;
   socklen_t errorlen = sizeof(errcode);
 
-  SU_DEBUG_9(("%s(%p, %u) called\n", "sres_resolver_error", res, socket));
+  SU_DEBUG_9(("%s(%p, %u) called\n", "sres_resolver_error",
+	      (void *)res, socket));
 
   getsockopt(socket, SOL_SOCKET, SO_ERROR, (void *)&errcode, &errorlen);
 
@@ -3176,7 +3268,7 @@
 	  continue;
 
 	/* Resend query/report error to application */
-	sres_resend_dns_query(res, q, 1);
+	sres_resend_dns_query(res, q, 0);
 
 	if (q != res->res_queries->qt_table[i])
 	  i--;
@@ -3203,7 +3295,8 @@
   struct sockaddr_storage from[1];
   socklen_t fromlen = sizeof from;
 
-  SU_DEBUG_9(("%s(%p, %u) called\n", "sres_resolver_receive", res, socket));
+  SU_DEBUG_9(("%s(%p, %u) called\n", "sres_resolver_receive",
+	      (void *)res, socket));
 
   memset(m, 0, offsetof(sres_message_t, m_data)); 
   
@@ -3282,7 +3375,7 @@
 #endif
 
     SU_DEBUG_5(("sres_resolver_receive(%p, %p) id=%u (from [%s]:%u)\n", 
-		res, query, m->m_id, 
+		(void *)res, (void *)query, m->m_id, 
 		host, ntohs(((struct sockaddr_in *)from)->sin_port)));
   }
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres_blocking.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres_blocking.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres_blocking.c	Tue Apr 24 10:14:28 2007
@@ -86,7 +86,13 @@
 #elif HAVE_SELECT
   struct { sres_socket_t fd; } fds[SRES_MAX_NAMESERVERS];
 #else
-#error No wait mechanism!
+#warning No guaranteed wait mechanism!
+/* typedef struct os_specific su_wait_t; */
+struct _pollfd {
+  sres_socket_t fd;   /* file descriptor */
+  short events;     /* requested events */
+  short revents;    /* returned events */
+} fds[SRES_MAX_NAMESERVERS];
 #endif
   sres_record_t ***return_records;  
 };

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres_cache.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres_cache.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sres_cache.c	Tue Apr 24 10:14:28 2007
@@ -178,7 +178,7 @@
   *return_cached = NULL;
 
   SU_DEBUG_9(("%s(%p, %s, \"%s\") called\n", "sres_cache_get",
-	      cache, sres_record_type(type, b), domain));
+	      (void *)cache, sres_record_type(type, b), domain));
 
   hash = sres_hash_key(domain);
 
@@ -241,7 +241,7 @@
   UNLOCK(cache);
 
   SU_DEBUG_9(("%s(%p, %s, \"%s\") returned %d entries\n", "sres_cache_get", 
-	      cache, sres_record_type(type, b), domain, rr_count));
+	      (void *)cache, sres_record_type(type, b), domain, rr_count));
 
   *return_cached = result;
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sresolv.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sresolv.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sresolv.c	Tue Apr 24 10:14:28 2007
@@ -186,8 +186,8 @@
   int i, index = -1, error = 0;
   int N = SRES_MAX_NAMESERVERS;
 
-  SU_DEBUG_9(("sres_sofia_update(%p, %d, %d)\n", srs, 
-	      (int)new_socket, (int)old_socket));
+  SU_DEBUG_9(("sres_sofia_update(%p, %d, %d)\n",
+	      (void *)srs, (int)new_socket, (int)old_socket));
 
   if (srs == NULL)
     return 0;
@@ -297,7 +297,7 @@
   if (!srs)
     return su_seterrno(EINVAL);
 
-  if (sres_resolver_set_async(res, sres_sofia_update, srs, 1) < 0)
+  if (sres_resolver_set_async(res, sres_sofia_update, srs, 1) == NULL)
     return INVALID_SOCKET;
 
   if (srs->srs_socket != INVALID_SOCKET)

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sresolv.docs
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sresolv.docs	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/sresolv.docs	Tue Apr 24 10:14:28 2007
@@ -261,3 +261,10 @@
 @endcode
 
 */
+
+/** @defgroup sresolv_env Environment Variables Used by sresolv Module
+
+In addition to the standard #RES_OPTIONS and #LOCALDOMAIN environment
+variables, the #SRES_OPTIONS and #SRESOLV_DEBUG variables are supported.
+
+*/
\ No newline at end of file

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/test_sresolv.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/test_sresolv.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/sresolv/test_sresolv.c	Tue Apr 24 10:14:28 2007
@@ -64,7 +64,6 @@
 #include <sofia-resolv/sres_async.h>
 #include <sofia-resolv/sres_record.h>
 
-#include <sofia-sip/su.h>
 #include <sofia-sip/su_alloc.h>
 
 #include <assert.h>
@@ -101,7 +100,7 @@
   sres_record_t  **result;
 
   int              timeout;
-  int              sink;
+  sres_socket_t    sink;
   int              sinkidx;
   char const      *sinkconf;
   
@@ -120,6 +119,84 @@
 
 static int tstflags = 0;
 
+#if HAVE_WINSOCK2_H
+
+/* Posix send() */
+static inline 
+ssize_t sres_send(sres_socket_t s, void *b, size_t length, int flags)
+{
+  if (length > INT_MAX)
+    length = INT_MAX;
+  return (ssize_t)send(s, b, (int)length, flags);
+}
+
+static inline 
+ssize_t sres_sendto(sres_socket_t s, void *b, size_t length, int flags,
+		    struct sockaddr const *sa, socklen_t salen)
+{
+  if (length > INT_MAX)
+    length = INT_MAX;
+  return (ssize_t)sendto(s, b, (int)length, flags, (void *)sa, (int)salen);
+}
+
+/* Posix recvfrom() */
+static inline 
+ssize_t sres_recvfrom(sres_socket_t s, void *buffer, size_t length, int flags,
+		      struct sockaddr *from, socklen_t *fromlen)
+{
+  int retval, ilen;
+
+  if (fromlen)
+    ilen = *fromlen;
+
+  if (length > INT_MAX)
+    length = INT_MAX;
+
+  retval = recvfrom(s, buffer, (int)length, flags, 
+		    (void *)from, fromlen ? &ilen : NULL);
+
+  if (fromlen)
+    *fromlen = ilen;
+
+  return (ssize_t)retval;
+}
+
+static sres_socket_t sres_socket(int af, int socktype, int protocol)
+{
+  return socket(af, socktype, protocol);
+}
+
+static inline
+int sres_close(sres_socket_t s)
+{
+  return closesocket(s);
+}
+
+#if !defined(IPPROTO_IPV6)
+#if HAVE_SIN6
+#include <tpipv6.h>
+#else
+#if !defined(__MINGW32__)
+struct sockaddr_storage {
+    short ss_family;
+    char ss_pad[126];
+};
+#endif
+#endif
+#endif
+#else
+
+#define sres_send(s,b,len,flags) send((s),(b),(len),(flags))
+#define sres_sendto(s,b,len,flags,a,alen) \
+  sendto((s),(b),(len),(flags),(a),(alen))
+#define sres_recvfrom(s,b,len,flags,a,alen) \
+  recvfrom((s),(b),(len),(flags),(a),(alen))
+#define sres_close(s) close((s))
+#define SOCKET_ERROR   (-1)
+#define INVALID_SOCKET ((sres_socket_t)-1)
+#define sres_socket(x,y,z) socket((x),(y),(z))
+#endif
+
 #if 1
 
 #if HAVE_POLL && 0
@@ -145,7 +222,7 @@
 int test_socket(sres_context_t *ctx)
 {
   int af;
-  su_sockeet_t s1, s2, s3, s4;
+  sres_socket_t s1, s2, s3, s4;
   struct sockaddr_storage a[1];
   struct sockaddr_storage a1[1], a2[1], a3[1], a4[1];
   struct sockaddr_in *sin = (void *)a;
@@ -160,10 +237,10 @@
   af = AF_INET;
 
   for (;;) {
-    TEST_1((s1 = su_socket(af, SOCK_DGRAM, 0)) != INVALID_SOCKET);
-    TEST_1((s2 = su_socket(af, SOCK_DGRAM, 0)) != INVALID_SOCKET);
-    TEST_1((s3 = su_socket(af, SOCK_DGRAM, 0)) != INVALID_SOCKET);
-    TEST_1((s4 = su_socket(af, SOCK_DGRAM, 0)) != INVALID_SOCKET);
+    TEST_1((s1 = sres_socket(af, SOCK_DGRAM, 0)) != INVALID_SOCKET);
+    TEST_1((s2 = sres_socket(af, SOCK_DGRAM, 0)) != INVALID_SOCKET);
+    TEST_1((s3 = sres_socket(af, SOCK_DGRAM, 0)) != INVALID_SOCKET);
+    TEST_1((s4 = sres_socket(af, SOCK_DGRAM, 0)) != INVALID_SOCKET);
 
     TEST_1(setblocking(s1, 0) == 0);
     TEST_1(setblocking(s2, 0) == 0);
@@ -212,13 +289,13 @@
     TEST(connect(s2, sa4, a4len), 0);
     TEST(getsockname(s2, (struct sockaddr *)a2, &a2len), 0);
 
-    TEST(sendto(s1, "foo", 3, 0, sa4, a4len), 3);
-    TEST(recvfrom(s4, buf, sizeof buf, 0, sa, &alen), 3);
-    TEST(sendto(s4, "bar", 3, 0, sa, alen), 3);
-    TEST(recvfrom(s2, buf, sizeof buf, 0, sa, &alen), -1);
-    TEST(recvfrom(s1, buf, sizeof buf, 0, sa, &alen), 3);
+    TEST(sres_sendto(s1, "foo", 3, 0, sa4, a4len), 3);
+    TEST(sres_recvfrom(s4, buf, sizeof buf, 0, sa, &alen), 3);
+    TEST(sres_sendto(s4, "bar", 3, 0, sa, alen), 3);
+    TEST(sres_recvfrom(s2, buf, sizeof buf, 0, sa, &alen), -1);
+    TEST(sres_recvfrom(s1, buf, sizeof buf, 0, sa, &alen), 3);
 
-    su_close(s1), su_close(s2), su_close(s3), su_close(s4);
+    sres_close(s1), sres_close(s2), sres_close(s3), sres_close(s4);
 
     break;
   }
@@ -1356,14 +1433,15 @@
 {
   char *tmpdir = getenv("TMPDIR");
   char *template;
-  int fd, sink;
+  int fd;
+  sres_socket_t sink;
   struct sockaddr_in sin[1];
   socklen_t sinsize = sizeof sin;
   FILE *f;
   
   BEGIN();
 
-  sink = socket(AF_INET, SOCK_DGRAM, 0); TEST_1(sink != -1);
+  sink = socket(AF_INET, SOCK_DGRAM, 0); TEST_1(sink != INVALID_SOCKET);
   TEST(getsockname(sink, (struct sockaddr *)sin, &sinsize), 0);
   sin->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   TEST(bind(sink, (struct sockaddr *)sin, sinsize), 0);
@@ -1427,7 +1505,7 @@
   if (ctx->sinkidx)
     su_root_deregister(ctx->root, ctx->sinkidx);
   ctx->sinkidx = 0;
-  su_close(ctx->sink), ctx->sink = -1;
+  sres_close(ctx->sink), ctx->sink = INVALID_SOCKET;
 
   END();
 }
@@ -1452,7 +1530,7 @@
 
   result = sres_cached_answers(res, sres_type_a, domain);
 
-#if 0
+#if 0  /* Currently, we do not create error records */
   TEST_1(result); TEST_1(result[0] != NULL);
 
   rr_soa = result[0]->sr_soa;
@@ -1463,7 +1541,6 @@
 
   sres_free_answers(res, result);
 #else
-  /* Currently, we do not create error records */
   TEST_1(result == NULL);
 #endif
 
@@ -1541,12 +1618,12 @@
 /* Convert lowercase hex to binary */
 static
 void *hex2bin(char const *test_name,
-	      char const *hex1, char const *hex2, unsigned *binsize)
+	      char const *hex1, char const *hex2, size_t *binsize)
 {
   char output[2048];
   char *bin;
   char const *b;
-  int j;
+  size_t j;
 
   if (hex1 == NULL || binsize == NULL)
     return NULL;
@@ -1619,18 +1696,19 @@
 {
   sres_resolver_t *res = ctx->resolver;
   sres_query_t *q = NULL;
-  int c = ctx->sink;
+  sres_socket_t c = ctx->sink;
   struct sockaddr_storage ss[1];
   struct sockaddr *sa = (void *)ss;
-  socklen_t salen = sizeof ss, binlen;
+  socklen_t salen = sizeof ss;
   char *bin;
-  int i, n;
+  size_t i, binlen;
+  ssize_t n;
   char const *domain = "example.com";
   char query[512];
 
   BEGIN();
 
-  TEST_1(ctx->sink != -1 && ctx->sink != 0);
+  TEST_1(ctx->sink != INVALID_SOCKET && ctx->sink != (sres_socket_t)0);
 
   /* Prepare for test_answer() callback */
   sres_free_answers(ctx->resolver, ctx->result); 
@@ -1641,19 +1719,19 @@
   TEST_1(bin = hex2bin(__func__, hextest, NULL, &binlen));
 
   /* Send responses with one erroneus byte */
-  for (i = 1; i < (int)binlen; i++) {
+  for (i = 1; i < binlen; i++) {
     if (!q) {
       /* We got an error => make new query */
       TEST_1(q = sres_query(res, test_answer, ctx, /* Send query */
 				 sres_type_naptr, domain));
-      TEST_1((n = recvfrom(c, query, sizeof query, 0, sa, &salen)) != -1);
+      TEST_1((n = sres_recvfrom(c, query, sizeof query, 0, sa, &salen)) != -1);
       memcpy(bin, query, 2); /* Copy ID */
     }
     if (i != 1)
       bin[i] ^= 0xff;
     else
       bin[3] ^= SRES_FORMAT_ERR; /* format error -> EDNS0 failure */
-    n = sendto(c, bin, binlen, 0, sa, salen);
+    n = sres_sendto(c, bin, binlen, 0, sa, salen);
     if (i != 1)
       bin[i] ^= 0xff;
     else
@@ -1669,15 +1747,15 @@
   }
 
   /* Send runt responses */
-  for (i = 1; i <= (int)binlen; i++) {
+  for (i = 1; i <= binlen; i++) {
     if (!q) {
       /* We got an error => make new query */
       TEST_1(q = sres_query(res, test_answer, ctx, /* Send query */
 				 sres_type_naptr, domain));
-      TEST_1((n = recvfrom(c, query, sizeof query, 0, sa, &salen)) != -1);
+      TEST_1((n = sres_recvfrom(c, query, sizeof query, 0, sa, &salen)) != -1);
       memcpy(bin, query, 2); /* Copy ID */
     }
-    n = sendto(c, bin, i, 0, sa, salen);
+    n = sres_sendto(c, bin, i, 0, sa, salen);
     if (n == -1)
       perror("sendto");
     while (!poll_sockets(ctx))
@@ -1848,8 +1926,8 @@
     
   TEST(sres_resolver_sockets(res, &socket, 1), n);
 
-#if HAVE_SA_LEN			
-  /* We fail this test in BSD systems */
+#if !__linux
+  /* We fail this test in most systems */
   /* conf_file looks like this:
 --8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--
 nameserver 0.0.0.2
@@ -1886,11 +1964,16 @@
 }
 #endif
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, 
-	  "usage: %s [-v] [-l level] [-] [conf-file] [error-conf-file]\n", 
+	  "usage: %s OPTIONS [-] [conf-file] [error-conf-file]\n"
+	  "\twhere OPTIONS are\n"
+	  "\t    -v be verbose\n"
+	  "\t    -a abort on error\n"
+	  "\t    -l level\n",
 	  name);
+  exit(exitcode);
 }
 
 #include <sofia-sip/su_log.h>
@@ -1912,6 +1995,8 @@
     }
     else if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else if (strcmp(argv[i], "--no-alarm") == 0) {
       o_alarm = 0;
     }
@@ -1930,20 +2015,20 @@
 	level = 3, rest = "";
 
       if (rest == NULL || *rest)
-	usage();
+	usage(1);
       
       su_log_set_level(sresolv_log, level);
     } else
-      usage();
+      usage(1);
   }
 
   if (o_attach) {
-    char buf[8];
+    char buf[8], *line;
 
     fprintf(stderr, "test_sresolv: started with pid %u"
 	    " (press enter to continue)\n", getpid());
 
-    fgets(buf, sizeof buf, stdin);
+    line = fgets(buf, sizeof buf, stdin); (void) line;
   }
 #if HAVE_ALARM
   else if (o_alarm) {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -38,14 +38,7 @@
 
 COVERAGE_INPUT = 	$(libstun_la_SOURCES) $(include_sofia_HEADERS)
 
-LDADD =			\
-			libstun.la
-			../sresolv/libsresolv.la \
-			../su/libsu.la
-
-stunc_LDADD = libstun.la ../sresolv/libsresolv.la ../su/libsu.la
-
-lookup_stun_server_LDADD = libstun.la ../sresolv/libsresolv.la ../su/libsu.la
+LDADD = 		libstun.la ../sresolv/libsresolv.la ../su/libsu.la
 
 # ----------------------------------------------------------------------
 # tests
@@ -53,11 +46,11 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile stun.docs cert.pem key.pem
+EXTRA_DIST =		stun.docs cert.pem key.pem
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
 
 TAG_DLL_FLAGS =		LIST=stun_tag_list

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/stun.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/stun.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/stun.c	Tue Apr 24 10:14:28 2007
@@ -57,7 +57,7 @@
 #include <ws2tcpip.h>
 #endif
 
-#if defined(HAVE_OPENSSL)
+#if HAVE_OPENSSL
 #include <openssl/opensslv.h>
 #endif
 
@@ -181,7 +181,7 @@
   su_sockaddr_t     sr_local_addr[1];   /**< local address */
   su_sockaddr_t     sr_destination[1];
 
-  stun_state_t      sr_state;           /**< Progress states */
+  stun_req_state_t  sr_state;           /**< Progress states */
   int               sr_retry_count;     /**< current retry number */
   long              sr_timeout;         /**< timeout for next sendto() */
 
@@ -218,7 +218,7 @@
   stun_discovery_magic_t *sh_dns_pend_ctx;
   tagi_t             *sh_dns_pend_tags;
 
-#if defined(HAVE_OPENSSL)
+#if HAVE_OPENSSL
   SSL_CTX        *sh_ctx;           /**< SSL context for TLS */
   SSL            *sh_ssl;           /**< SSL handle for TLS */
 #else
@@ -316,7 +316,7 @@
 }
 
 
-#if defined(HAVE_OPENSSL)
+#if HAVE_OPENSSL
 char const stun_version[] = 
  "sofia-sip-stun using " OPENSSL_VERSION_TEXT;
 #else
@@ -325,7 +325,9 @@
 #endif
 
 static int do_action(stun_handle_t *sh, stun_msg_t *binding_response);
+#if HAVE_OPENSSL
 static int stun_tls_callback(su_root_magic_t *m, su_wait_t *w, su_wakeup_arg_t *arg);
+#endif
 static int process_binding_request(stun_request_t *req, stun_msg_t *binding_response);
 static stun_discovery_t *stun_discovery_create(stun_handle_t *sh,
 					       stun_action_t action,
@@ -349,9 +351,11 @@
 static void stun_sendto_timer_cb(su_root_magic_t *magic, 
 				 su_timer_t *t,
 				 su_timer_arg_t *arg);
+#if HAVE_OPENSSL
 static void stun_tls_connect_timer_cb(su_root_magic_t *magic, 
 				      su_timer_t *t,
 				      su_timer_arg_t *arg);
+#endif
 static void stun_test_lifetime_timer_cb(su_root_magic_t *magic, 
 					su_timer_t *t,
 					su_timer_arg_t *arg);
@@ -526,7 +530,7 @@
 			      stun_discovery_magic_t *magic,
 			      tag_type_t tag, tag_value_t value, ...)
 {
-#if defined(HAVE_OPENSSL)
+#if HAVE_OPENSSL
   int events = -1;
   int one, err = -1;
   su_wait_t wait[1] = { SU_WAIT_INIT };
@@ -1280,8 +1284,9 @@
  * Internal functions
  *******************************************************************/
 
-#if defined(HAVE_OPENSSL)
-static int stun_tls_callback(su_root_magic_t *m, su_wait_t *w, su_wakeup_arg_t *arg)
+#if HAVE_OPENSSL
+static 
+int stun_tls_callback(su_root_magic_t *m, su_wait_t *w, su_wakeup_arg_t *arg)
 {
   stun_discovery_t *sd = arg;
   stun_handle_t *self = sd->sd_handle;
@@ -1298,7 +1303,7 @@
 
   enter;
 
-  SU_DEBUG_7(("%s(%p): events%s%s%s%s\n", __func__, self,
+  SU_DEBUG_7(("%s(%p): events%s%s%s%s\n", __func__, (void *)self,
 	      events & SU_WAIT_CONNECT ? " CONNECTED" : "",
 	      events & SU_WAIT_ERR     ? " ERR"       : "",
 	      events & SU_WAIT_IN      ? " IN"        : "",
@@ -1528,15 +1533,11 @@
 
   return 0;
 }
-#else
-static int stun_tls_callback(su_root_magic_t *m, su_wait_t *w, su_wakeup_arg_t *arg)
-{
-  return 0;
-}
+
 #endif /* HAVE_OPENSSL */
 
 
-#if defined(HAVE_OPENSSL)
+#if HAVE_OPENSSL
 static void stun_tls_connect_timer_cb(su_root_magic_t *magic, 
 				      su_timer_t *t,
 				      su_timer_arg_t *arg)
@@ -1566,12 +1567,7 @@
 
   return;
 }
-#else
-static void stun_tls_connect_timer_cb(su_root_magic_t *magic, 
-				      su_timer_t *t,
-				      su_timer_arg_t *arg)
-{
-}
+
 #endif /* HAVE_OPENSSL */
 
 /** Compose a STUN message of the format defined by stun_msg_t
@@ -1664,7 +1660,7 @@
 
   enter;
 
-  SU_DEBUG_7(("%s(%p): events%s%s%s\n", __func__, self,
+  SU_DEBUG_7(("%s(%p): events%s%s%s\n", __func__, (void *)self,
 	      events & SU_WAIT_IN ? " IN" : "",
 	      events & SU_WAIT_OUT ? " OUT" : "",
 	      events & SU_WAIT_ERR ? " ERR" : ""));
@@ -1846,7 +1842,7 @@
     if (stun_process_error_response(binding_response) < 0) {
       SU_DEBUG_3(("%s: Error in Binding Error Response.\n", __func__));
     }
-    req->sr_state = stun_discovery_error;
+    req->sr_state = stun_req_error;
       
     break;
   }
@@ -1936,7 +1932,7 @@
     return 0;
   }
   else if (req->sr_from_y == 0) {
-    if (req->sr_state != stun_discovery_timeout) {
+    if (req->sr_state != stun_req_timeout) {
       /* mapping with X still valid */
       sd->sd_lt_cur = sd->sd_lt;
       sd->sd_lt = (int) (sd->sd_lt + sd->sd_lt_max) / 2;
@@ -2322,8 +2318,6 @@
 
     default:
       break;
-      
-      return;
     }
 
     /* Destroy me immediately */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/stun_internal.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/stun_internal.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/stun/stun_internal.h	Tue Apr 24 10:14:28 2007
@@ -71,7 +71,9 @@
 
 SOFIA_BEGIN_DECLS
 
+#ifdef DOXYGEN
 extern char const STUN_DEBUG[]; /* dummy declaration for Doxygen */
+#endif
 
 /* XXX -- mela: note that this are 100 times too small */
 #if 1

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -77,7 +77,11 @@
 	su_alloc.c su_alloc_lock.c su_strdup.c su_sprintf.c \
 	su_strlst.c su_vector.c \
 	su_time.c su_time0.c \
-	su_wait.c su_root.c su_timer.c su_port.c su_port.h \
+	su_wait.c su_root.c su_timer.c \
+	su_port.c  su_port.h \
+	su_base_port.c su_pthread_port.c su_socket_port.c \
+	su_poll_port.c su_epoll_port.c su_select_port.c su_kqueue_port.c \
+	su_devpoll_port.c \
 	su_localinfo.c \
 	su_os_nw.c \
 	su_taglist.c su_tag.c su_tag_io.c \
@@ -88,8 +92,8 @@
 EXTRA_libsu_la_SOURCES = \
 			memmem.c strtoull.c strcasestr.c \
 			memspn.c memcspn.c memccpy.c \
-			inet_ntop.c inet_pton.c getopt.c \
-			su_tag_ref.c
+			inet_ntop.c inet_pton.c poll.c getopt.c \
+			su_tag_ref.c su_win32_port.c
 
 libsu_la_LIBADD = 	$(REPLACE_LIBADD)
 libsu_la_DEPENDENCIES = $(REPLACE_LIBADD)
@@ -101,7 +105,7 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST = 		Doxyfile su.docs \
+EXTRA_DIST = 		su.docs \
 			run_addrinfo run_localinfo run_test_su
 
 dist_pkgdata_SCRIPTS = 	tag_dll.awk
@@ -116,4 +120,4 @@
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/addrinfo.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/addrinfo.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/addrinfo.c	Tue Apr 24 10:14:28 2007
@@ -1,7 +1,7 @@
 /*
  * This file is part of the Sofia-SIP package
  *
- * Copyright (C) 2005 Nokia Corporation.
+ * Copyright (C) 2005,2007 Nokia Corporation.
  *
  * Contact: Pekka Pessi <pekka.pessi at nokia.com>
  *
@@ -26,12 +26,13 @@
  * 
  * @section synopsis Synopsis
  *
- * <tt>addrinfo [-pcn46] host service</tt>
+ * <tt>addrinfo [-pcn46] service-name host</tt>
  *
  * @section description Description
  * 
  * The @em addrinfo utility will use su_getaddrinfo() to resolve the network
- * services and print resolved names.
+ * services and print resolved names. See sect 6.1 of RFC3493 and the getaddrinfo(3)
+ * manual page of POSIX 1003.1g, for more information.
  *
  * @section options Options
  *
@@ -56,7 +57,7 @@
  * Written by Pekka Pessi <pekka -dot pessi -at- nokia -dot- com>
  *
  * @section copyright Copyright
- * Copyright (C) 2005 Nokia Corporation.
+ * Copyright (C) 2005,2007 Nokia Corporation.
  *
  * This program is free software; see the source for copying conditions.
  * There is @b NO warranty; not even for @b MERCHANTABILITY or <b>FITNESS
@@ -72,7 +73,7 @@
 #include "sofia-sip/su.h"
 
 char const help[] =
-"usage: addrinfo [-pnc46] [domainname]\n"
+"usage: addrinfo [-pnc46] <servicename> <domainname>\n"
 "\t-p query for passive open\n"
 "\t-n use numeric host names\n"
 "\t-c ask for canonic names\n"

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/run_test_su
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/run_test_su	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/run_test_su	Tue Apr 24 10:14:28 2007
@@ -1,19 +1,34 @@
-#! /bin/bash
+#! /bin/sh
 
 rc=0
 
+run=no
+
+for SU_PORT in select kqueue devpoll epoll poll ; do
+
+export SU_PORT
+
+egrep -q -i '^#define have_(sys_)?'$SU_PORT ../../config.h ||
+continue
+
+run=yes
+
 if $VALGRIND ./test_su ; then
-    echo PASS: multithread test_su
+    echo PASS: multithread test_su with $SU_PORT
 else
-    echo FAIL: multithread test_su failed
+    echo FAIL: multithread test_su with $SU_PORT failed
     rc=1
 fi
 
 if $VALGRIND ./test_su -s ; then
-    echo PASS: singlethread test_su
+    echo PASS: singlethread test_su with $SU_PORT
 else
-    echo FAIL: singlethread test_su failed
+    echo FAIL: singlethread test_su with $SU_PORT failed
     rc=1
 fi
 
+done
+
+test $run = no && exit 77
+
 exit $rc

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/htable.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/htable.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/htable.h	Tue Apr 24 10:14:28 2007
@@ -106,7 +106,7 @@
 HTABLE_SCOPE entry_t **prefix##_next(prefix##_t const *, entry_t * const *ee); \
 HTABLE_SCOPE void prefix##_append(prefix##_t *pr, entry_t const *e); \
 HTABLE_SCOPE void prefix##_insert(prefix##_t *pr, entry_t const *e); \
-HTABLE_SCOPE void prefix##_remove(prefix##_t *, entry_t const *e)
+HTABLE_SCOPE int prefix##_remove(prefix##_t *, entry_t const *e)
 
 /** Hash table implementation.
  *
@@ -220,13 +220,13 @@
 } \
 \
 HTABLE_SCOPE \
-void prefix##_remove(prefix##_t *pr, entry_t const *e) \
+int prefix##_remove(prefix##_t *pr, entry_t const *e) \
 { \
   size_t i, j, k; \
   size_t size = pr->pr##_size; \
   entry_t **htable = pr->pr##_table; \
 \
-  if (!e) return; \
+  if (!e) return -1; \
 \
   /* Search for entry */ \
   for (i = hfun(e) % size; htable[i]; i = (i + 1) % size) \
@@ -234,7 +234,7 @@
       break; \
 \
   /* Entry is not in table? */ \
-  assert(htable[i]); if (!e) return; \
+  if (!htable[i]) return -1; \
 \
   /* Move table entries towards their primary place  */ \
   for (j = (i + 1) % size; htable[j]; j = (j + 1) % size) { \
@@ -252,6 +252,8 @@
   pr->pr##_used--; \
 \
   htable[i] = NULL; \
+\
+  return 0; \
 } \
 extern int prefix##_dummy
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/htable2.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/htable2.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/htable2.h	Tue Apr 24 10:14:28 2007
@@ -240,7 +240,7 @@
     if (is_equal(e, htable[i])) \
       break; \
 \
-  assert(is_used(htable[i])); if (!is_used(htable[i])) return -1; \
+  if (!is_used(htable[i])) return -1; \
 \
   /* Move table entries towards their primary place  */ \
   for (j = (i + 1) % size; is_used(htable[j]); j = (j + 1) % size) { \

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su.h	Tue Apr 24 10:14:28 2007
@@ -220,13 +220,15 @@
  * } WSABUF, *LPWSABUF;
  * @endcode
  *
- * @note Ordering of the fields is reversed on Windows. Do not initialize this
- * structure with static initializer, but assign both fields separately.
+ * @note Ordering of the fields is reversed on Windows. Do not initialize
+ * this structure with static initializer, but assign both fields
+ * separately. Note that the type of the siv_len is #su_ioveclen_t which is
+ * defined as u_long on Windows and size_t on POSIX.
  *
  * For historical reasons, the structure is known as #msg_iovec_t in @msg
  * module.
  *
- * @sa #su_iovec_t, #su_ioveclen_t, SU_IOVECLEN_MAX, su_vsend(), su_vrecv(), 
+ * @sa #su_ioveclen_t, SU_IOVECLEN_MAX, su_vsend(), su_vrecv(), 
  * #msg_iovec_t, msg_iovec(), msg_recv_iovec(), 
  * @c struct @c iovec defined in <sys/uio.h>, writev(2), readv(2),
  * sendmsg(), recvmsg(),

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_bm.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_bm.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_bm.h	Tue Apr 24 10:14:28 2007
@@ -45,15 +45,15 @@
 
 SOFIAPUBFUN bm_fwd_table_t *bm_memmem_study(char const *needle, size_t nlen);
 
-SOFIAPUBFUN char const* bm_memmem(char const *haystack, size_t hlen,
-				  char const *needle, size_t nlen,
-				  bm_fwd_table_t *fwd);
+SOFIAPUBFUN char *bm_memmem(char const *haystack, size_t hlen,
+			    char const *needle, size_t nlen,
+			    bm_fwd_table_t *fwd);
 
 SOFIAPUBFUN bm_fwd_table_t *bm_memcasemem_study(char const *needle, size_t);
 
-SOFIAPUBFUN char const* bm_memcasemem(char const *haystack, size_t hlen,
-				      char const *needle, size_t nlen,
-				      bm_fwd_table_t *fwd);
+SOFIAPUBFUN char *bm_memcasemem(char const *haystack, size_t hlen,
+				char const *needle, size_t nlen,
+				bm_fwd_table_t *fwd);
 
 SOFIA_END_DECLS
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_configure.h.in
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_configure.h.in	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_configure.h.in	Tue Apr 24 10:14:28 2007
@@ -75,6 +75,12 @@
 /** Define as 1 if you have OSX CoreFoundation interface */
 #undef SU_HAVE_OSX_CF_API
 
+/** Define as 1 if you want to enable experimental features.
+ *
+ * Use --enable-experimental with ./configure
+ */
+#undef SU_HAVE_EXPERIMENTAL
+
 /** Define as 1 if you have inline functions */
 #undef SU_HAVE_INLINE
 /** Define as suitable declarator inline functions */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_debug.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_debug.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_debug.h	Tue Apr 24 10:14:28 2007
@@ -74,9 +74,9 @@
 #endif
 
 #define SU_DEBUG_DEF(level) \
-  static SU_INLINE void su_debug_##level(char const *fmt, ...) \
+  su_inline void su_debug_##level(char const *fmt, ...) \
     __attribute__ ((__format__ (printf, 1, 2))); \
-  void su_debug_##level(char const *fmt, ...) \
+  su_inline void su_debug_##level(char const *fmt, ...) \
     { va_list ap; va_start(ap, fmt); su_vllog(SU_LOG, level, fmt, ap); va_end(ap); }
 
 SU_DEBUG_DEF(0)

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_tag.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_tag.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_tag.h	Tue Apr 24 10:14:28 2007
@@ -174,7 +174,7 @@
 #if SU_HAVE_INLINE
 su_inline tag_value_t tag_int_v(int v) { return (tag_value_t)v; }
 su_inline tag_value_t tag_int_vr(int *vp) { return (tag_value_t)vp; }
-su_inline tag_value_t tag_uint_v(size_t v) { return (tag_value_t)v; }
+su_inline tag_value_t tag_uint_v(unsigned v) { return (tag_value_t)v; }
 su_inline tag_value_t tag_uint_vr(unsigned *vp) { return (tag_value_t)vp; }
 su_inline tag_value_t tag_usize_v(usize_t v) { return (tag_value_t)v; }
 su_inline tag_value_t tag_usize_vr(usize_t *vp) { return (tag_value_t)vp; }
@@ -197,9 +197,9 @@
   static inline tag_value_t tag_ptr_v(void const *v)
   { return (tag_value_t)v; }
   static inline tag_value_t tag_ptr_vr(void *vp, void const *p) 
-  { return(tag_value_t)vp; }
+  { return (tag_value_t)vp; }
   static inline tag_value_t tag_str_v(char *v) { return (tag_value_t)v; }
-  static inline tag_value_t tag_str_vr(char **vp) {return(tag_value_t)vp;}
+  static inline tag_value_t tag_str_vr(char **vp) {return (tag_value_t)vp;}
 }
 #endif
 su_inline tag_value_t tag_filter_v(tag_filter_f *v) {return(tag_value_t)v;}
@@ -208,10 +208,14 @@
 #define tag_int_vr(v)  (tag_value_t)(v)
 #define tag_uint_v(v)  (tag_value_t)(v)
 #define tag_uint_vr(v) (tag_value_t)(v)
+#define tag_usize_v(v) (tag_value_t)(v)
+#define tag_usize_vr(v) (tag_value_t)(v)
 #define tag_bool_v(v)  (tag_value_t)(v != 0)
 #define tag_bool_vr(v) (tag_value_t)(v)
 #define tag_ptr_v(v)   (tag_value_t)(v)
 #define tag_ptr_vr(v,x) (tag_value_t)(v)
+#define tag_cptr_v(v)   (tag_value_t)(v)
+#define tag_cptr_vr(v,x) (tag_value_t)(v)
 #define tag_cstr_v(v)  (tag_value_t)(v)
 #define tag_cstr_vr(v) (tag_value_t)(v)
 #define tag_str_v(v)   (tag_value_t)(v)

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_time.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_time.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_time.h	Tue Apr 24 10:14:28 2007
@@ -104,9 +104,8 @@
 SOFIAPUBFUN uint32_t su_ntp_fraq(su_time_t t);
 SOFIAPUBFUN uint32_t su_time_ms(su_time_t t);
 #else
-static SU_INLINE
 /** Middle 32 bit of NTP timestamp. */
-uint32_t su_ntp_fraq(su_time_t t)
+su_inline uint32_t su_ntp_fraq(su_time_t t)
 {
   /*
    * Multiply usec by 0.065536 (ie. 2**16 / 1E6)
@@ -116,9 +115,8 @@
   return (t.tv_sec << 16) + (1024 * t.tv_usec + 7812) / 15625;
 }
 
-static SU_INLINE
 /** Time as milliseconds. */
-uint32_t su_time_ms(su_time_t t)
+su_inline uint32_t su_time_ms(su_time_t t)
 {
   return t.tv_sec * 1000 + (t.tv_usec + 500) / 1000;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_wait.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_wait.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/su_wait.h	Tue Apr 24 10:14:28 2007
@@ -30,6 +30,7 @@
  * @file sofia-sip/su_wait.h Syncronization and threading interface.
  *
  * @author Pekka Pessi <Pekka.Pessi at nokia.com>
+ * @author Martti Mela <Martti.Mela at nokia.com>
  * 
  * @date Created: Tue Sep 14 15:51:04 1999 ppessi
  */
@@ -44,6 +45,7 @@
 #ifndef SU_TIME_H
 #include "sofia-sip/su_time.h"
 #endif
+
 #if SU_HAVE_POLL
 #include <sys/poll.h>
 #endif
@@ -53,7 +55,36 @@
 /* ---------------------------------------------------------------------- */
 /* Constants */
 
-#if SU_HAVE_POLL || DOCUMENTATION_ONLY
+#if SU_HAVE_KQUEUE
+/** Compare wait object. @HI */
+#define SU_WAIT_CMP(x, y) \
+ (((x).ident - (y).ident) ? ((x).ident - (y).ident) : ((x).flags - (y).flags))
+
+/** Incoming data is available on socket. @HI */
+#define SU_WAIT_IN      (EVFILT_READ)
+/** Data can be sent on socket. @HI */
+#define SU_WAIT_OUT     (EVFILT_WRITE)
+/** Socket is connected. @HI */
+#define SU_WAIT_CONNECT (EVFILT_WRITE)
+/** An error occurred on socket. @HI */
+#define SU_WAIT_ERR     (EV_ERROR)
+/** The socket connection was closed. @HI */
+#define SU_WAIT_HUP     (EV_EOF)
+/** A listening socket accepted a new connection. @HI */
+#define SU_WAIT_ACCEPT  (EVFILT_READ)
+
+/** No timeout for su_wait(). */
+#define SU_WAIT_FOREVER (-1)
+/** The return value of su_wait() if timeout occurred. */
+#define SU_WAIT_TIMEOUT (-2)
+
+/** Initializer for a wait object. @HI */
+#define SU_WAIT_INIT    { INVALID_SOCKET, 0, 0, 0, 0, NULL }
+
+/** Maximum number of sources supported by su_wait() */
+#define SU_WAIT_MAX    (0x7fffffff)
+
+#elif SU_HAVE_POLL || DOCUMENTATION_ONLY
 /** Compare wait object. @HI */
 #define SU_WAIT_CMP(x, y) \
  (((x).fd - (y).fd) ? ((x).fd - (y).fd) : ((x).events - (y).events))
@@ -101,35 +132,73 @@
 #define SU_WAIT_MAX    (64)
 
 #else
-#define SU_WAIT_CMP(x, y) 
-#define SU_WAIT_IN      
-#define SU_WAIT_OUT     
-#define SU_WAIT_ERR     
-#define SU_WAIT_HUP     
-#define SU_WAIT_ACCEPT  
-#define SU_WAIT_FOREVER 
-#define SU_WAIT_TIMEOUT 
+/* If nothing works, try these */
+
+#define	POLLIN		0x001
+#define	POLLPRI		0x002
+#define	POLLOUT		0x004
+
+#ifdef __USE_XOPEN
+#define	POLLRDNORM	0x040
+#define	POLLRDBAND	0x080
+#define	POLLWRNORM	0x100
+#define	POLLWRBAND	0x200
+#endif
+
+/* These for pollfd.revents */
+#define POLLERR         0x008
+#define POLLHUP         0x010
+#define POLLNVAL        0x020
+
+#define SU_WAIT_CMP(x, y) \
+ (((x).fd - (y).fd) ? ((x).fd - (y).fd) : ((x).events - (y).events))
+
+#define SU_WAIT_IN      POLLIN
+#define SU_WAIT_OUT     POLLOUT
+#define SU_WAIT_CONNECT POLLOUT
+#define SU_WAIT_ERR     POLLERR
+#define SU_WAIT_HUP     POLLHUP
+#define SU_WAIT_ACCEPT  POLLIN
+#define SU_WAIT_FOREVER (-1)
+#define SU_WAIT_TIMEOUT (-2)
 
-#define SU_WAIT_INIT
+#define SU_WAIT_INIT    { INVALID_SOCKET, 0, 0 }
+
+/** Maximum number of sources supported by su_wait() */
+#define SU_WAIT_MAX    (0x7fffffff)
 
 #endif
 
 /* ---------------------------------------------------------------------- */
 /* Types */
 
-#if 0
-typedef struct _pollfd {
-  su_socket_t fd;           /* file descriptor */
-  short events;     /* requested events */
-  short revents;    /* returned events */
-} su_wait_t;
+/** Wait object. */
+#if SU_HAVE_KQUEUE
+typedef struct kevent su_wait_t;
 #elif SU_HAVE_POLL
 typedef struct pollfd su_wait_t;
 #elif SU_HAVE_WINSOCK
 typedef HANDLE su_wait_t;
 #else
-/** Wait object. */
-typedef struct os_specific su_wait_t;
+/* typedef struct os_specific su_wait_t; */
+typedef struct pollfd su_wait_t;
+struct pollfd {
+  su_socket_t fd;   /* file descriptor */
+  short events;     /* requested events */
+  short revents;    /* returned events */
+};
+
+
+/* Type used for the number of file descriptors.  */
+typedef unsigned long int nfds_t;
+
+/* Poll the file descriptors described by the NFDS structures starting at
+   FDS.  If TIMEOUT is nonzero and not -1, allow TIMEOUT milliseconds for
+   an event to occur; if TIMEOUT is -1, block until an event occurs.
+   Returns the number of file descriptors with events, zero if timed out,
+   or -1 for errors.  */
+int poll (struct pollfd *__fds, nfds_t __nfds, int __timeout);
+
 #endif
 
 /* Used by AD */
@@ -191,7 +260,7 @@
  */
 typedef SU_WAKEUP_ARG_T su_wakeup_arg_t;
 
-/** Wakeup callback function prototype. 
+/** Wakeup callback function pointer type. 
  *
  * Whenever a registered wait object receives an event, the @link
  * ::su_wakeup_f callback function @endlink is invoked.
@@ -316,9 +385,13 @@
 #define SU_MSG_R_INIT   { NULL }
 
 /** Message delivery function type. */
-typedef void (*su_msg_f)(su_root_magic_t *magic, 
-			 su_msg_r msg,
-			 su_msg_arg_t *arg);
+typedef void su_msg_function(su_root_magic_t *magic, 
+			     su_msg_r msg,
+			     su_msg_arg_t *arg);
+
+/** Message delivery function pointer type. */
+typedef su_msg_function *su_msg_f;
+
 
 /* ---------------------------------------------------------------------- */
 
@@ -350,11 +423,15 @@
 SOFIAPUBFUN int su_wait_events(su_wait_t *wait, su_socket_t s);
 SOFIAPUBFUN int su_wait_mask(su_wait_t *dst, su_socket_t s, int events);
 
-#if SU_HAVE_POLL
+#if !HAVE_WIN32 && (SU_HAVE_POLL || HAVE_SELECT)
 static inline
 su_socket_t su_wait_socket(su_wait_t *wait)
 {
+#if SU_HAVE_KQUEUE
+  return wait->ident;
+#else
   return wait->fd;
+#endif
 }
 #endif
 
@@ -362,6 +439,7 @@
 SOFIAPUBFUN su_root_t *su_root_create(su_root_magic_t *magic)
   __attribute__((__malloc__));
 SOFIAPUBFUN void su_root_destroy(su_root_t*);
+SOFIAPUBFUN char const *su_root_name(su_root_t *self);
 SOFIAPUBFUN int su_root_set_magic(su_root_t *self, su_root_magic_t *magic);
 SOFIAPUBFUN su_root_magic_t *su_root_magic(su_root_t *root);
 SOFIAPUBFUN int su_root_register(su_root_t*, su_wait_t *, 
@@ -472,6 +550,34 @@
 SOFIAPUBFUN int su_clone_pause(su_clone_r);
 SOFIAPUBFUN int su_clone_resume(su_clone_r);
 
+/* ---------------------------------------------------------------------- */
+/* Different su_root_t implementations */
+
+typedef su_port_t *su_port_create_f(void);
+typedef int su_clone_start_f(su_root_t *parent,
+			    su_clone_r return_clone,
+			    su_root_magic_t *magic,
+			    su_root_init_f init,
+			    su_root_deinit_f deinit);
+
+SOFIAPUBFUN void su_port_prefer(su_port_create_f *f, su_clone_start_f *);
+
+SOFIAPUBFUN su_port_create_f su_default_port_create;
+SOFIAPUBFUN su_port_create_f su_epoll_port_create;
+SOFIAPUBFUN su_port_create_f su_poll_port_create;
+SOFIAPUBFUN su_port_create_f su_wsaevent_port_create;
+SOFIAPUBFUN su_port_create_f su_select_port_create;
+SOFIAPUBFUN su_port_create_f su_kqueue_port_create;
+SOFIAPUBFUN su_port_create_f su_devpoll_port_create;
+
+SOFIAPUBFUN su_clone_start_f su_default_clone_start;
+SOFIAPUBFUN su_clone_start_f su_epoll_clone_start;
+SOFIAPUBFUN su_clone_start_f su_poll_clone_start;
+SOFIAPUBFUN su_clone_start_f su_wsaevent_clone_start;
+SOFIAPUBFUN su_clone_start_f su_select_clone_start;
+SOFIAPUBFUN su_clone_start_f su_kqueue_clone_start;
+SOFIAPUBFUN su_clone_start_f su_devpoll_clone_start;
+
 SOFIA_END_DECLS
 
 #endif /* SU_WAIT_H */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/tstdef.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/tstdef.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/sofia-sip/tstdef.h	Tue Apr 24 10:14:28 2007
@@ -145,13 +145,14 @@
   tst_verbatim = 1,
   /** If (TSTFLAGS & tst_abort) is non-zero, abort() when failed. */
   tst_abort = 2,
+  /** If (TSTFLAGS & tst_log) is non-zero, log intermediate results. */
+  tst_log = 4
 };
 
 #ifndef TSTFLAGS
 #error <TSTFLAGS is not defined>
 #endif
 
-#ifdef TSTFLAGS
 /** Begin a test function. @HIDE */
 #define BEGIN() BEGIN_(TSTFLAGS); { extern int tstdef_dummy
 /** End a test function. @HIDE */
@@ -179,17 +180,12 @@
 /** Test that @a suite has same size as @a expected. @HIDE */
 #define TEST_SIZE(suite, expected) TEST_SIZE_(TSTFLAGS, suite, expected)
 
-#else
-/* Deprecated */
-#define TEST0(flags, suite) TEST_1_(flags, suite)
-#define TEST_1(flags, suite) TEST_1_(flags, suite)
-#define TEST_VOID(flags, suite) TEST_VOID_(flags, suite)
-#define TEST(flags, suite, expect) TEST_(flags, suite, expect)
-#define TEST64(flags, suite, expect) TEST64_(flags, suite, expect)
-#define TEST_S(flags, suite, expect) TEST_S_(flags, suite, expect)
-#define BEGIN(flags) BEGIN_(flags) { extern int tstdef_dummy
-#define END(flags) (void) tstdef_dummy;  } END_(flags) 
-#endif
+/** Print in torture test with -l option */
+#define TEST_LOG(x)		       \
+  do {				       \
+    if (tstflags & tst_log)	       \
+      printf x;			       \
+  } while(0)
 
 #define TEST_FAILED(flags) \
   ((flags) & tst_abort) ? abort() : (void)0; return 1

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su.c	Tue Apr 24 10:14:28 2007
@@ -32,14 +32,16 @@
 
 #include "config.h" 
 
-#include <stdio.h>
-#include <string.h>
-#include <signal.h>
-
 #include "sofia-sip/su.h"
 #include "sofia-sip/su_log.h"
 #include "sofia-sip/su_alloc.h"
 
+#include <stdio.h>
+#include <string.h>
+#if HAVE_SIGNAL
+#include <signal.h>
+#endif
+
 #if !SU_HAVE_BSDSOCK && !SU_HAVE_WINSOCK
 #error Bad configuration
 #endif
@@ -67,7 +69,9 @@
 {
   su_home_threadsafe(NULL);
 
+#if HAVE_SIGPIPE
   signal(SIGPIPE, SIG_IGN);	/* we want to get EPIPE instead */
+#endif
 
   su_log_init(su_log_default);
   su_log_init(su_log_global);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_addrinfo.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_addrinfo.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_addrinfo.c	Tue Apr 24 10:14:28 2007
@@ -887,10 +887,16 @@
 		   su_addrinfo_t const *hints,
 		   su_addrinfo_t **res)
 {
+  int retval;
+  su_addrinfo_t *ai;
+
+  if (!service || service[0] == '\0')
+    service = "0";
+
 #if HAVE_SCTP
   if (res && hints && hints->ai_protocol == IPPROTO_SCTP) {
-    su_addrinfo_t *ai, system_hints[1];
-    int retval, socktype;
+    su_addrinfo_t system_hints[1];
+    int socktype;
 
     socktype = hints->ai_socktype;
     
@@ -920,7 +926,31 @@
   }
 #endif
 
-  return getaddrinfo(node, service, hints, res);
+  retval = getaddrinfo(node, service, hints, res);
+
+  if (retval == 0) {
+    for (ai = *res; ai; ai = ai->ai_next) {
+      if (ai->ai_protocol)
+	continue;
+
+      if (hints && hints->ai_protocol) {
+	ai->ai_protocol = hints->ai_protocol;
+	continue;
+      }
+
+      if (ai->ai_family != AF_INET 
+#if SU_HAVE_IN6
+	  && ai->ai_family != AF_INET6
+#endif
+	  ) continue;
+
+      if (ai->ai_socktype == SOCK_STREAM)
+	ai->ai_protocol = IPPROTO_TCP;
+      else if (ai->ai_socktype == SOCK_DGRAM)
+	ai->ai_protocol = IPPROTO_UDP;
+    }
+  }
+  return retval;
 }
 
 /** Free su_addrinfo_t structure allocated by su_getaddrinfo(). */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_alloc.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_alloc.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_alloc.c	Tue Apr 24 10:14:28 2007
@@ -87,8 +87,8 @@
  *
  * As you might have guessed, it is also possible to use reference counting
  * with home objects. The function su_home_ref() increases the reference
- * count, su_home_unref() decreases. A newly allocated home object has
- * reference count of 1.
+ * count, su_home_unref() decreases it. A newly allocated or initialized
+ * home object has reference count of 1.
  *
  * @note Please note that while it is possible to create new references to
  * secondary home objects which have a parent home, the secondary home
@@ -104,10 +104,13 @@
  * @note
  *
  * The su_home_destroy() function is deprecated as it does not free the home
- * object itself.
+ * object itself. Like su_home_deinit(), it should be called only on home
+ * objects with reference count of 1.
  *
- * The function su_home_init() initializes a home object with infinite
- * reference count. It must be deinitialized with su_home_deinit().
+ * The function su_home_init() initializes a home object structure. When the
+ * initialized home object is destroyed or deinitialized or its reference
+ * count reaches zero, the memory allocate thorugh it reclaimed but the home
+ * object structure itself is not freed.
  *
  * @section su_home_destructor_usage Destructors
  *
@@ -148,19 +151,20 @@
  * @section su_alloc_threadsafe Threadsafe Operation
  *
  * If multiple threads need to access same home object, it must be marked as
- * @c threadsafe by calling su_home_threadsafe() with the home pointer as
+ * @e threadsafe by calling su_home_threadsafe() with the home pointer as
  * argument. The threadsafeness is not inherited by clones.
  *
  * The threadsafe home objects can be locked and unlocked with
- * su_home_mutex_lock() and su_home_mutex_unlock().
+ * su_home_mutex_lock() and su_home_mutex_unlock(). These operations are
+ * no-op on home object that is not threadsafe.
  *
  * @section su_alloc_preloading Preloading a Memory Home
  *
- * In some situations there is quite heavy overhead when using the global
- * heap allocator. The overhead caused by the large number of small
+ * In some situations there is quite heavy overhead if the global heap
+ * allocator is used. The overhead caused by the large number of small
  * allocations can be reduced by using su_home_preload(): it allocates or
  * preloads some a memory to home to be used as a kind of private heap. The
- * preloaded memory area is then used to satisfy small enough allocations.
+ * preloaded memory area is then used to satisfy small enough allocations. 
  * For instance, the SIP parser typically preloads some 2K of memory when it
  * starts to parse the message.
  *
@@ -172,10 +176,9 @@
  * far as possible; if it is not enough, allocation is made from heap.
  *
  * The word @e auto refers to the automatic scope; however, the home object
- * initialized with su_home_auto() must be explicitly deinitialized with
- * su_home_deinit() when the program exits the scope where the stack frame
- * used in su_home_auto() was allocate.
- * 
+ * that was initialized with su_home_auto() must be explicitly deinitialized
+ * with su_home_deinit() or su_home_unref() when the program exits the scope
+ * where the stack frame used in su_home_auto() was allocated.
  */
 
 #include <sofia-sip/su_config.h>
@@ -196,6 +199,8 @@
 void (*su_home_mutex_locker)(void *mutex);
 void (*su_home_mutex_unlocker)(void *mutex);
 
+void (*su_home_destroy_mutexes)(void *mutex);
+
 #define MEMLOCK(h)   \
   (((h) && (h)->suh_lock ? su_home_locker((h)->suh_lock) : (void)0), (h)->suh_blocks)
 #define UNLOCK(h) (((h) && (h)->suh_lock ? su_home_unlocker((h)->suh_lock) : (void)0), NULL)
@@ -221,10 +226,10 @@
 
 #define ALIGNMENT (8)
 #define ALIGN(n) (size_t)(((n) + (ALIGNMENT - 1)) & (size_t)~(ALIGNMENT - 1))
-#define SIZEBITS (sizeof (size_t) * 8 - 1)
+#define SIZEBITS (sizeof (unsigned) * 8 - 1)
 
 typedef struct {
-  size_t   sua_size:SIZEBITS;	/**< Size of the block */
+  unsigned sua_size:SIZEBITS;	/**< Size of the block */
   unsigned sua_home:1;		/**< Is this another home? */
   unsigned :0;
   void    *sua_data;		/**< Data pointer */
@@ -242,8 +247,9 @@
 
   unsigned    sub_prsize:16;	/**< Preload size */
   unsigned    sub_prused:16;	/**< Used from preload */
-  unsigned    sub_auto:1;	/**< struct su_block_s is from stack! */
-  unsigned    sub_preauto:1;	/**< Preload is from stack! */
+  unsigned    sub_hauto:1;      /**< "Home" is not from malloc */
+  unsigned    sub_auto:1;	/**< struct su_block_s is not from malloc */
+  unsigned    sub_preauto:1;	/**< Preload is not from malloc */
   unsigned    sub_auto_all:1;	/**< Everything is from stack! */
   unsigned :0;
 
@@ -255,7 +261,7 @@
 static void su_home_stats_alloc(su_block_t *, void *p, void *preload,
 				size_t size, int zero);
 static void su_home_stats_free(su_block_t *sub, void *p, void *preload,
-			       size_t size);
+			       unsigned size);
 
 static void _su_home_deinit(su_home_t *home);
 
@@ -345,7 +351,7 @@
   size_t size, term;
   assert(sua);
   if (sua) {
-    size = sua->sua_size;
+    size = (size_t)sua->sua_size;
     memcpy(&term, (char *)sua->sua_data + size, sizeof (term));
     assert(size - term == 0);
     return size - term == 0;
@@ -358,8 +364,9 @@
 
 /** Allocate the block hash table.
  *
- * The function su_hash_alloc() allocates a block hash table of @a n
- * elements.
+ * @internal
+ *
+ * Allocate a block hash table of @a n elements.
  *
  * @param home  pointer to home object
  * @param n     number of buckets in hash table
@@ -372,8 +379,12 @@
 {
   su_block_t *b = calloc(1, offsetof(su_block_t, sub_nodes[n]));
 
-  if (b)
+  if (b) {
+    /* Implicit su_home_init(); */
+    b->sub_ref = 1;
+    b->sub_hauto = 1;
     b->sub_n = n;
+  }
 
   return b;
 }
@@ -382,6 +393,8 @@
 
 /** Allocate a memory block.
  *
+ * @internal
+ *
  * Precondition: locked home
  *
  * @param home home to allocate
@@ -399,7 +412,10 @@
 {
   void *data, *preload = NULL;
   
-  assert (size < (1UL << SIZEBITS));
+  assert (size < (((size_t)1) << SIZEBITS));
+
+  if (size >= ((size_t)1) << SIZEBITS)
+    return (void)(errno = ENOMEM), NULL;
 
   if (sub == NULL || 3 * sub->sub_used > 2 * sub->sub_n) {
     /* Resize the hash table */
@@ -429,6 +445,7 @@
       b2->sub_preload = sub->sub_preload;
       b2->sub_prsize = sub->sub_prsize;
       b2->sub_prused = sub->sub_prused;
+      b2->sub_hauto = sub->sub_hauto;
       b2->sub_preauto = sub->sub_preauto;
       b2->sub_destructor = sub->sub_destructor;
       /* auto_all is not copied! */
@@ -473,7 +490,7 @@
     if (!preload)
       sub->sub_auto_all = 0;
 
-    if (zero == do_clone) {
+    if (zero >= do_clone) {
       /* Prepare cloned home */ 
       su_home_t *subhome = data;
 
@@ -485,13 +502,13 @@
 
       subhome->suh_size = (unsigned)size;
       subhome->suh_blocks->sub_parent = home;
-      subhome->suh_blocks->sub_ref = 1;
+      subhome->suh_blocks->sub_hauto = 0;
     }
 
     /* OK, add the block to the hash table. */
 
     sua = su_block_add(sub, data); assert(sua);
-    sua->sua_size = size;
+    sua->sua_size = (unsigned)size;
     sua->sua_home = zero > 1;
 
     if (sub->sub_stats)
@@ -525,16 +542,16 @@
   assert(size >= sizeof (*home));
 
   if (size < sizeof (*home))
-    return (errno = EINVAL), NULL;
+    return (void)(errno = EINVAL), NULL;
   else if (size > INT_MAX)
-    return (errno = ENOMEM), NULL;
+    return (void)(errno = ENOMEM), NULL;
 
   home = calloc(1, size);
   if (home) {
     home->suh_size = (int)size;
     home->suh_blocks = su_hash_alloc(SUB_N);
     if (home->suh_blocks)
-      home->suh_blocks->sub_ref = 1;
+      home->suh_blocks->sub_hauto = 0;
     else
       free(home), home = NULL;
   }
@@ -612,12 +629,10 @@
 
 /**Unreference a su_home_t object.
  *
- * The function su_home_unref() decrements the reference count on a home
- * object and destroys and frees it and the memory allocations using it.
- *
- * @param home memory pool object to be unreferences
+ * Decrements the reference count on home object and destroys and frees it
+ * and the memory allocations using it if the reference count reaches 0.
  *
- * The function return values is 
+ * @param home memory pool object to be unreferenced
  *
  * @retval 1 if object was freed
  * @retval 0 if object is still alive
@@ -650,8 +665,10 @@
     return 1;
   }
   else {
+    int hauto = sub->sub_hauto;
     _su_home_deinit(home);
-    free(home);
+    if (!hauto)
+      free(home);
     /* UNLOCK(home); */
     return 1;
   }
@@ -725,7 +742,7 @@
 
 /** Allocate a memory block.
  *
- * The function su_alloc() allocates a memory block of a given @a size.
+ * Allocates a memory block of a given @a size.
  *
  * If @a home is NULL, this function behaves exactly like malloc().
  *
@@ -752,9 +769,9 @@
 
 /**Free a memory block.
  *
- * The function su_free() frees a single memory block. The @a home must be
- * the owner of the memory block (usually the memory home used to allocate
- * the memory block, or NULL if no home was used).
+ * Frees a single memory block. The @a home must be the owner of the memory
+ * block (usually the memory home used to allocate the memory block, or NULL
+ * if no home was used).
  *
  * @param home  pointer to home object
  * @param data  pointer to the memory block to be freed
@@ -792,7 +809,7 @@
       }
 
 #if MEMCHECK != 0
-      memset(data, 0xaa, allocation->sua_size);
+      memset(data, 0xaa, (size_t)allocation->sua_size);
 #endif
 
       memset(allocation, 0, sizeof (*allocation));
@@ -810,9 +827,9 @@
 
 /** Check home consistency.
  *
- * The function su_home_check() ensures that the home structure and all
- * memory blocks allocated through it are consistent.  It can be used to
- * catch memory allocation and usage errors.
+ * Ensures that the home structure and all memory blocks allocated through
+ * it are consistent. It can be used to catch memory allocation and usage
+ * errors.
  *
  * @param home Pointer to a memory home.
  */
@@ -851,11 +868,10 @@
 /**
  * Create an su_home_t object.
  *
- * The function su_home_create() creates a home object.  A home object is
- * used to collect multiple memory allocations, so that they all can be
- * freed by calling su_home_unref().
+ * Creates a home object. A home object is used to collect multiple memory
+ * allocations, so that they all can be freed by calling su_home_unref().
  *
- * @return This function returns a pointer to an @c su_home_t object, or @c
+ * @return This function returns a pointer to an #su_home_t object, or 
  * NULL upon an error. 
  */
 su_home_t *su_home_create(void)
@@ -863,10 +879,10 @@
   return su_home_new(sizeof(su_home_t));
 }
 
-/** Deinitialize a home object
+/** Destroy a home object
  *
- * The function su_home_destroy() frees all memory blocks associated with a
- * home object. Note that the home object is not freed.
+ * Frees all memory blocks associated with a home object. Note that the home
+ * object structure is not freed.
  *
  * @param home pointer to a home object
  *
@@ -876,14 +892,22 @@
  */
 void su_home_destroy(su_home_t *home)
 {
-  su_home_deinit(home);
-  /* XXX - home itself is not destroyed */
+  if (MEMLOCK(home)) {
+    assert(home->suh_blocks);
+    assert(home->suh_blocks->sub_ref == 1);
+    if (!home->suh_blocks->sub_hauto)
+      /* should warn user */;
+    home->suh_blocks->sub_hauto = 1;
+    _su_home_deinit(home);
+    /* UNLOCK(home); */
+  }
 }
 
 /** Initialize an su_home_t struct.
  *
- * The function su_home_init() initializes an su_home_t structure. It can be
- * used when the home structure is allocated from stack.
+ * Initializes an su_home_t structure. It can be used when the home
+ * structure is allocated from stack or when the home structure is part of
+ * an another object.
  *
  * @param home pointer to home object
  *
@@ -894,10 +918,14 @@
  */
 int su_home_init(su_home_t *home)
 {
+  su_block_t *sub;
+    
   if (home == NULL)
     return -1;
 
-  home->suh_blocks = su_hash_alloc(SUB_N);
+  home->suh_blocks = sub = su_hash_alloc(SUB_N);
+  if (!sub)
+    return -1;
 
   return 0;
 }
@@ -949,6 +977,9 @@
       free(b);
 
     home->suh_blocks = NULL;
+
+    if (home->suh_lock)
+      su_home_destroy_mutexes(home->suh_lock);
   }
 
   home->suh_lock = NULL;
@@ -956,9 +987,9 @@
 
 /** Free memory blocks allocated through home.
  *
- * The function @c su_home_deinit() frees the memory blocks associated with
- * the home object allocated otherwise. It does not free the home object
- * itself. Use su_home_unref() to free the home object.
+ * Frees the memory blocks associated with the home object allocated. It
+ * does not free the home object itself. Use su_home_unref() to free the
+ * home object.
  *
  * @param home pointer to home object
  *
@@ -967,7 +998,9 @@
 void su_home_deinit(su_home_t *home)
 {
   if (MEMLOCK(home)) {
-    assert(home->suh_blocks && home->suh_blocks->sub_ref == 0);
+    assert(home->suh_blocks);
+    assert(home->suh_blocks->sub_ref == 1);
+    assert(home->suh_blocks->sub_hauto);
     _su_home_deinit(home);
     /* UNLOCK(home); */
   }
@@ -975,11 +1008,11 @@
 
 /**Move allocations from a su_home_t object to another.
  *
- * The function su_home_move() moves allocations made through the @a src
- * home object under the @a dst home object. It is handy, for example, if an
- * operation allocates some number of blocks that should be freed upon an
- * error. It uses a temporary home and moves the blocks from temporary to a
- * proper home when successful, but frees the temporary home upon an error.
+ * Moves allocations made through the @a src home object under the @a dst
+ * home object. It is handy, for example, if an operation allocates some
+ * number of blocks that should be freed upon an error. It uses a temporary
+ * home and moves the blocks from temporary to a proper home when
+ * successful, but frees the temporary home upon an error.
  *
  * If @a src has destructor, it is called before starting to move.
  *
@@ -1111,8 +1144,8 @@
 
 /** Preload a memory home from stack.
  *
- * The function su_home_auto() initalizes a memory home using an area
- * allocated from stack. Poor mans alloca().
+ * Initializes a memory home using an area allocated from stack. Poor man's
+ * alloca().
  */
 su_home_t *su_home_auto(void *area, isize_t size)
 {
@@ -1142,10 +1175,12 @@
     size = prepsize + 65535;
 
   sub->sub_n = SUB_N_AUTO;
+  sub->sub_ref = 1;
   sub->sub_preload = p + prepsize;
   sub->sub_prsize = (unsigned)(size - prepsize);
-  sub->sub_preauto = 1;
+  sub->sub_hauto = 1;
   sub->sub_auto = 1;
+  sub->sub_preauto = 1;
   sub->sub_auto_all = 1;
 
   return home;
@@ -1154,7 +1189,7 @@
 
 /** Reallocate a memory block.
  *
- *   The function su_realloc() allocates a memory block of @a size bytes.
+ *   Allocates a memory block of @a size bytes.
  *   It copies the old block contents to the new block and frees the old
  *   block.
  *
@@ -1165,7 +1200,7 @@
  *   @param size  size of the memory block to be allocated
  *   
  * @return
- *   This function returns a pointer to the allocated memory block or
+ *   A pointer to the allocated memory block or
  *   NULL if an error occurred.
  */
 void *su_realloc(su_home_t *home, void *data, isize_t size)
@@ -1216,7 +1251,7 @@
 #endif
       memset(sua, 0, sizeof *sua);
       sub->sub_used--;
-      su_block_add(sub, ndata)->sua_size = size;
+      su_block_add(sub, ndata)->sua_size = (unsigned)size;
     }
     UNLOCK(home);
 
@@ -1238,7 +1273,7 @@
       }
 
       sub->sub_prused = (unsigned)p2;
-      sua->sua_size = size;
+      sua->sua_size = (unsigned)size;
 
 #if MEMCHECK_EXTRA
       memcpy((char *)data + size, &term, sizeof (term));
@@ -1247,7 +1282,7 @@
       return data;
     }
   }
-  else if (size < sua->sua_size) {
+  else if (size < (size_t)sua->sua_size) {
     /* Reduce existing preload */
     if (sub->sub_stats) {
       su_home_stats_free(sub, data, data, sua->sua_size);
@@ -1256,7 +1291,7 @@
 #if MEMCHECK_EXTRA
     memcpy((char *)data + size, &term, sizeof (term));
 #endif
-    sua->sua_size = size;
+    sua->sua_size = (unsigned)size;
     UNLOCK(home);
     return data;
   }
@@ -1271,7 +1306,10 @@
 	su_home_stats_free(sub, data, data, sua->sua_size);
     }
     
-    memcpy(ndata, data, sua->sua_size < size ? sua->sua_size : size);
+    memcpy(ndata, data,
+	   (size_t)sua->sua_size < size
+	   ? (size_t)sua->sua_size
+	   : size);
 #if MEMCHECK_EXTRA
     memcpy((char *)ndata + size, &term, sizeof (term));
 #endif
@@ -1281,7 +1319,7 @@
 
     memset(sua, 0, sizeof *sua); sub->sub_used--;
 
-    su_block_add(sub, ndata)->sua_size = size;
+    su_block_add(sub, ndata)->sua_size = (unsigned)size;
   }
 
   UNLOCK(home);
@@ -1327,7 +1365,7 @@
 
 /**Allocate and zero a memory block.
  *
- * The function su_zalloc() allocates a memory block with a given size from
+ * Allocates a memory block with a given size from
  * given memory home @a home and zeroes the allocated block.
  *
  *  @param home  pointer to memory pool object
@@ -1359,9 +1397,9 @@
 
 /** Allocate a structure
  *
- * The function su_salloc() allocates a structure with a given size, zeros
+ * Allocates a structure with a given size, zeros
  * it, and initializes the size field to the given size.  The size field
- * is the first in the structure. It has type of int. 
+ * is an int at the beginning of the structure. Note that it has type of int. 
  *
  * @param home  pointer to memory pool object
  * @param size  size of the structure
@@ -1540,7 +1578,8 @@
 }
 
 static 
-void su_home_stats_free(su_block_t *sub, void *p, void *preload, size_t size)
+void su_home_stats_free(su_block_t *sub, void *p, void *preload,
+			unsigned size)
 {
   su_home_stat_t *hs = sub->sub_stats;
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_alloc_lock.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_alloc_lock.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_alloc_lock.c	Tue Apr 24 10:14:28 2007
@@ -39,6 +39,7 @@
 #if SU_HAVE_PTHREADS
 #include <pthread.h>
 #include <assert.h>
+#include <stdlib.h>
 
 extern void (*su_home_locker)(void *mutex);
 extern void (*su_home_unlocker)(void *mutex);
@@ -46,6 +47,8 @@
 extern void (*su_home_mutex_locker)(void *mutex);
 extern void (*su_home_mutex_unlocker)(void *mutex);
 
+extern void (*su_home_destroy_mutexes)(void *mutex);
+
 /** Mutex */
 static void mutex_locker(void *_mutex)
 {
@@ -58,6 +61,15 @@
   pthread_mutex_t *mutex = _mutex;
   pthread_mutex_unlock(mutex + 1);
 }
+
+static void mutex_destroy(void *_mutex)
+{
+  pthread_mutex_t *mutex = _mutex;
+  pthread_mutex_destroy(mutex + 0);
+  pthread_mutex_destroy(mutex + 1);
+  free(_mutex);
+}
+
 #endif
 
 
@@ -65,7 +77,7 @@
  *
  * Convert a memory home object as thread-safe by allocating mutexes and
  * modifying function pointers in su_alloc.c module.
-
+ *
  * @param home memory home object to be converted thread-safe.
  *
  * @retval 0 when successful,
@@ -94,9 +106,10 @@
     su_home_mutex_unlocker = mutex_unlocker;
     su_home_locker = (void (*)(void *))pthread_mutex_lock;
     su_home_unlocker = (void (*)(void *))pthread_mutex_unlock;
+    su_home_destroy_mutexes = mutex_destroy;
   }
 
-  mutex = su_alloc(home, 2 * sizeof (pthread_mutex_t));
+  mutex = calloc(1, 2 * (sizeof *mutex));
   assert(mutex);
   if (mutex) {
     /* Mutex for memory operations */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_bm.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_bm.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_bm.c	Tue Apr 24 10:14:28 2007
@@ -108,7 +108,7 @@
 /** Search for a substring using Boyer-Moore algorithm.
  * @ingroup su_bm
  */
-char const*
+char *
 bm_memmem(char const *haystack, size_t hlen,
 	  char const *needle, size_t nlen,
 	  bm_fwd_table_t *fwd)
@@ -117,14 +117,14 @@
   bm_fwd_table_t fwd0[1];
 
   if (nlen == 0)
-    return haystack;
+    return (char *)haystack;
   if (needle == NULL || haystack == NULL || nlen > hlen)
     return NULL;
 
   if (nlen == 1) {
     for (i = 0; i < hlen; i++)
       if (haystack[i] == needle[0])
-	return haystack + i;
+	return (char *)haystack + i;
     return NULL;
   }
 
@@ -139,7 +139,7 @@
 		  (int)(i - j), "", (int)j, needle, needle + j + 1, 
 		  j == 0 ? "match!" : "back by 1"));
       if (j == 0)
-	return haystack + i;
+	return (char *)haystack + i;
       i--, j--;
     }
     else {
@@ -207,7 +207,7 @@
 /** Search for substring using Boyer-Moore algorithm.
  * @ingroup su_bm
  */
-char const*
+char *
 bm_memcasemem(char const *haystack, size_t hlen,
 	      char const *needle, size_t nlen,
 	      bm_fwd_table_t *fwd)
@@ -216,14 +216,14 @@
   bm_fwd_table_t fwd0[1];
 
   if (nlen == 0)
-    return haystack;
+    return (char *)haystack;
   if (needle == 0 || haystack == 0 || nlen > hlen)
     return NULL;
 
   if (nlen == 1) {
     for (i = 0; i < hlen; i++)
       if (haystack[i] == needle[0])
-	return haystack + i;
+	return (char *)haystack + i;
     return NULL;
   }
 
@@ -245,7 +245,7 @@
 		  (int)(i - j), "", (int)j, needle, needle + j + 1, 
 		  j == 0 ? "match!" : "back by 1"));
       if (j == 0)
-	return haystack + i;
+	return (char *)haystack + i;
       i--, j--;
     }
     else {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_localinfo.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_localinfo.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_localinfo.c	Tue Apr 24 10:14:28 2007
@@ -1045,7 +1045,9 @@
 {
   struct ifaddrs *ifa, *results;
   int error = 0;
+#if SU_HAVE_IN6
   int v4_mapped = (hints->li_flags & LI_V4MAPPED) != 0;
+#endif
   char *canonname = NULL;
 
   if (getifaddrs(&results) < 0) {
@@ -1057,7 +1059,10 @@
 
   for (ifa = results; ifa; ifa = ifa->ifa_next) {
     su_localinfo_t *li;
-    su_sockaddr_t *su, su2[1];
+    su_sockaddr_t *su;
+#if SU_HAVE_IN6
+    su_sockaddr_t su2[1];
+#endif
     socklen_t sulen;
     int scope, flags = 0, gni_flags = 0, if_index = 0;
     char const *ifname = 0;
@@ -1075,15 +1080,19 @@
     if (su->su_family == AF_INET) {
       sulen = sizeof(su->su_sin);
       scope = li_scope4(su->su_sin.sin_addr.s_addr);
+#if SU_HAVE_IN6
       if (v4_mapped)
 	sulen = sizeof(su->su_sin6);
+#endif
     }
+#if SU_HAVE_IN6
     else if (su->su_family == AF_INET6) {
       if (IN6_IS_ADDR_MULTICAST(&su->su_sin6.sin6_addr))
 	continue;
       sulen = sizeof(su->su_sin6);
       scope = li_scope6(&su->su_sin6.sin6_addr);
     }
+#endif
     else 
       continue;
 
@@ -1102,6 +1111,7 @@
     if (scope == LI_SCOPE_HOST || scope == LI_SCOPE_LINK)
       gni_flags = NI_NUMERICHOST;
 
+#if SU_HAVE_IN6
     if (v4_mapped && su->su_family == AF_INET) {
       /* Map IPv4 address to IPv6 address */
       memset(su2, 0, sizeof(*su2));
@@ -1110,6 +1120,7 @@
       ((int32_t*)&su2->su_sin6.sin6_addr)[3] = su->su_sin.sin_addr.s_addr;
       su = su2;
     }
+#endif
 
     if ((error = li_name(hints, gni_flags, su, &canonname)) < 0)
       break;
@@ -1188,7 +1199,7 @@
 int win_localinfo(su_localinfo_t const hints[1], su_localinfo_t **rresult)
 {
   /* This is Windows XP code, for both IPv6 and IPv4. */
-  size_t iaa_size = 2048;
+  ULONG iaa_size = 2048;
   IP_ADAPTER_ADDRESSES *iaa0, *iaa;
   int error, loopback_seen = 0;
   int v4_mapped = (hints->li_flags & LI_V4MAPPED) != 0;
@@ -1197,7 +1208,7 @@
   int flags = GAA_FLAG_SKIP_MULTICAST;
   *rresult = NULL; next = rresult;
 
-  iaa0 = malloc(iaa_size);
+  iaa0 = malloc((size_t)iaa_size);
   if (!iaa0) {
     SU_DEBUG_1(("su_localinfo: memory exhausted\n"));
     error = ELI_MEMORY;
@@ -1209,7 +1220,25 @@
       error = GetAdaptersAddresses(hints->li_family, flags, NULL, iaa0, &iaa_size);
   }
   if (error) {
-    SU_DEBUG_1(("su_localinfo: GetAdaptersAddresses failed: %d\n", error));
+    char const *empty = "";
+    LPTSTR msg = empty;
+
+    if (error == ERROR_NO_DATA) {
+      error = ELI_NOADDRESS;
+      goto err;
+    }
+
+    if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | 
+	               FORMAT_MESSAGE_FROM_SYSTEM | 
+	               FORMAT_MESSAGE_IGNORE_INSERTS,
+	  	       NULL,
+	  	       error,
+		       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+		       msg, 0, NULL))
+      msg = empty;
+ 
+    SU_DEBUG_1(("su_localinfo: GetAdaptersAddresses: %s (%d)\n", msg, error));
+    if (msg != empty) LocalFree((LPVOID)msg);
     error = ELI_SYSTEM;
     goto err;
   }
@@ -1218,7 +1247,7 @@
     IP_ADAPTER_UNICAST_ADDRESS *ua;
     IP_ADAPTER_UNICAST_ADDRESS lua[1];
     int if_index = iaa->IfIndex;
-    int ifnamelen = 0;
+    size_t ifnamelen = 0;
     char ifname[16];
 
     for (ua = iaa->FirstUnicastAddress; ;ua = ua->Next) {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_log.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_log.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_log.c	Tue Apr 24 10:14:28 2007
@@ -63,7 +63,7 @@
  * messages based on message priority.
  *
  * @sa @ref debug_logs, <sofia-sip/su_log.h>, 
- * su_llog(), su_vllog(), #su_log_t, #SU_LOG,
+ * su_llog(), su_vllog(), #su_log_t, #SU_DEBUG,
  * SU_DEBUG_0(), SU_DEBUG_1(), SU_DEBUG_2(), SU_DEBUG_3(), SU_DEBUG_5(), 
  * SU_DEBUG_7(), SU_DEBUG_9()
  */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_os_nw.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_os_nw.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_os_nw.c	Tue Apr 24 10:14:28 2007
@@ -46,10 +46,14 @@
 #include "sofia-sip/su_os_nw.h"
 #include "sofia-sip/su_debug.h"
 
-/* Works only with pthreads */
-#if SU_HAVE_PTHREADS
+#if defined(__APPLE_CC__)
+# define SU_NW_CHANGE_PTHREAD 1
+#endif
 
-#include <pthread.h>
+#if defined (SU_NW_CHANGE_PTHREAD)
+# define SU_HAVE_NW_CHANGE 1
+# include <pthread.h>
+#endif
 
 #if defined(__APPLE_CC__)
 #include <AvailabilityMacros.h>
@@ -68,8 +72,9 @@
   SCDynamicStoreRef           su_storeRef[1];
   CFRunLoopSourceRef          su_sourceRef[1];
 #endif
-
+#if defined (SU_NW_CHANGE_PTHREAD)
   pthread_t                   su_os_thread;
+#endif
 
   su_network_changed_f       *su_network_changed_cb;
   su_network_changed_magic_t *su_network_changed_magic;
@@ -109,7 +114,7 @@
 		    sizeof *snc) == SU_FAILURE) {
 
     return;
-  }    
+  }
 
   snc2 = su_msg_data(rmsg); assert(snc2);
   snc2->su_root = snc->su_root;
@@ -119,7 +124,7 @@
   snc2->su_os_thread = snc->su_os_thread;
   snc2->su_network_changed_cb = snc->su_network_changed_cb;
   snc2->su_network_changed_magic = snc->su_network_changed_magic;
-  
+
   if (su_msg_send(rmsg) == SU_FAILURE) {
     su_msg_destroy(rmsg);
     return;
@@ -219,10 +224,7 @@
 
     return err;
 }
-#endif /* __APPLE_CC__ */
-
 
-#if defined(__APPLE_CC__)
 static void *su_start_nw_os_thread(void *ptr)
 {
   su_network_changed_t *snc = (su_network_changed_t *) ptr;
@@ -249,19 +251,13 @@
 			     su_network_changed_f *network_changed_cb,
 			     su_network_changed_magic_t *magic)
 {
-#if defined (__APPLE_CC__)
   su_network_changed_t *snc = NULL;
-#endif
 
   assert(home && root && network_changed_cb && magic);
 
-  /* Not implemented for others than OSX */
-#if !defined (__APPLE_CC__)
-  return NULL;
-#else
-
+#if defined (SU_HAVE_NW_CHANGE)
   snc = su_zalloc(home, sizeof *snc);
-  
+
   if (!snc)
     return NULL;
 
@@ -269,15 +265,16 @@
   snc->su_root = root;
   snc->su_network_changed_cb = network_changed_cb;
   snc->su_network_changed_magic = magic;
-  
+
+# if defined (SU_NW_CHANGE_PTHREAD)
   if ((pthread_create(&(snc->su_os_thread), NULL,
 		      su_start_nw_os_thread,
 		      (void *) snc)) != 0) {
     return NULL;
   }
-
-  return snc;
+# endif
 #endif
+  return snc;
 }
 
 /** Remove a callback registered for the network change event.
@@ -288,20 +285,3 @@
 {
   return -1;
 }
-
-#else
-
-su_network_changed_t
-*su_root_add_network_changed(su_home_t *home, su_root_t *root,
-			     su_network_changed_f *network_changed_cb,
-			     su_network_changed_magic_t *magic)
-{
-  return NULL;
-}
-
-int su_root_remove_network_changed(su_network_changed_t *snc)
-{
-  return -1;
-}
-
-#endif /* SU_HAVE_PTHREADS */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_osx_runloop.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_osx_runloop.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_osx_runloop.c	Tue Apr 24 10:14:28 2007
@@ -31,22 +31,13 @@
  * poll/select/WaitForMultipleObjects and message passing functionality.
  *
  * @author Pekka Pessi <Pekka.Pessi at nokia.com>
- * @author Kai Vehmanen <kai.vehmanen at nokia.com>
+ * @author Martti Mela <martti.mela at nokia.com>
  *
  * @date Created: Tue Sep 14 15:51:04 1999 ppessi
  */
 
 #include "config.h"
 
-/* React to multiple events per one poll() to make sure 
- * that high-priority events can never completely mask other events.
- * Enabled by default on all platforms except WIN32 */
-#ifndef WIN32
-#define SU_ENABLE_MULTISHOT_POLL 1
-#else
-#define SU_ENABLE_MULTISHOT_POLL 0
-#endif
-
 #include <stdlib.h>
 #include <assert.h>
 #include <stdarg.h>
@@ -55,9 +46,8 @@
 #include <limits.h>
 #include <errno.h>
 
-#define SU_PORT_IMPLEMENTATION 1
+#define su_port_s su_osx_port_s 
 
-#include "sofia-sip/su.h"
 #include "su_port.h"
 #include "sofia-sip/su_osx_runloop.h"
 #include "sofia-sip/su_alloc.h"
@@ -71,163 +61,121 @@
 #define enter (void)0
 #endif
 
-
-#if SU_HAVE_PTHREADS
-/* Pthread implementation */
-#include <pthread.h>
-#define SU_HAVE_MBOX 1
-#else
-#define SU_HAVE_MBOX 0
-#endif
-
-#if HAVE_SOCKETPAIR
-#define MBOX_SEND  1
-#else
-#define MBOX_SEND  0
-#endif
-
 static su_port_t *su_osx_runloop_create(void) __attribute__((__malloc__));
 
 /* Callback for CFObserver and CFSocket */
-static
-void cf_observer_cb(CFRunLoopObserverRef observer, 
-		    CFRunLoopActivity activity, 
-		    void *info);
-static void su_port_osx_socket_cb(CFSocketRef s, 
+static void cf_observer_cb(CFRunLoopObserverRef observer, 
+			   CFRunLoopActivity activity, 
+			   void *info);
+
+static void su_osx_port_socket_cb(CFSocketRef s, 
 				  CFSocketCallBackType callbackType, 
 				  CFDataRef address, 
 				  const void *data, 
 				  void *info);
-static CFSocketCallBackType map_poll_event_to_cf_event(int events);
 
-static void su_port_osx_lock(su_port_t *self, char const *who);
-static void su_port_osx_unlock(su_port_t *self, char const *who);
-static void su_port_osx_incref(su_port_t *self, char const *who);
-static void su_port_osx_decref(su_port_t *self, int blocking, char const *who);
+static void su_osx_port_deinit(void *arg);
 
-static int su_port_osx_send(su_port_t *self, su_msg_r rmsg);
+static void su_osx_port_decref(su_port_t *self, int blocking, char const *who)
+{
+  (void)su_base_port_decref(self, blocking, who);
+}
+
+
+static CFSocketCallBackType map_poll_event_to_cf_event(int events);
+
+static int su_osx_port_send(su_port_t *self, su_msg_r rmsg);
 
-static int su_port_osx_register(su_port_t *self,
+static int su_osx_port_register(su_port_t *self,
 			    su_root_t *root, 
 			    su_wait_t *wait, 
 			    su_wakeup_f callback,
 			    su_wakeup_arg_t *arg,
 			    int priority);
-static int su_port_osx_unregister(su_port_t *port,
+static int su_osx_port_unregister(su_port_t *port,
 			      su_root_t *root, 
 			      su_wait_t *wait,	
 			      su_wakeup_f callback, 
 			      su_wakeup_arg_t *arg);
 
-static int su_port_osx_deregister(su_port_t *self, int i);
-
-static int su_port_osx_unregister_all(su_port_t *self,
-			   su_root_t *root);
-
-static int su_port_osx_getmsgs(su_port_t *self);
-static
-int su_port_osx_eventmask(su_port_t *self, int index, int socket, int events);
-static
-void su_port_osx_run(su_port_t *self);
-static
-void su_port_osx_break(su_port_t *self);
-static
-su_duration_t su_port_osx_step(su_port_t *self, su_duration_t tout);
-
-#if 0
-unsigned su_port_query(su_port_t *, su_wait_t *, unsigned n_waits);
-void su_port_event(su_port_t *, su_wait_t *waitobj);
-#endif
-
-static
-int su_port_osx_own_thread(su_port_t const *port);
-
-static
-int su_port_osx_add_prepoll(su_port_t *port,
-			su_root_t *root, 
-			su_prepoll_f *, 
-			su_prepoll_magic_t *);
+static int su_osx_port_deregister(su_port_t *self, int i);
 
-static
-int su_port_osx_remove_prepoll(su_port_t *port,
+static int su_osx_port_unregister_all(su_port_t *self,
 			   su_root_t *root);
 
-static
-su_timer_t **su_port_osx_timers(su_port_t *port);
+static int su_osx_port_eventmask(su_port_t *, int , int, int );
+static void su_osx_port_run(su_port_t *self);
+static void su_osx_port_break(su_port_t *self);
+static su_duration_t su_osx_port_step(su_port_t *self, su_duration_t tout);
 
-static
-int su_port_osx_multishot(su_port_t *port, int multishot);
+static int su_osx_port_multishot(su_port_t *port, int multishot);
 
-static
-int su_port_osx_threadsafe(su_port_t *port);
+static int su_osx_port_wait_events(su_port_t *self, su_duration_t tout);
 
-static
-int su_port_osx_yield(su_port_t *port);
+static char const *su_osx_port_name(su_port_t const *self)
+{
+  return "CFRunLoop";
+}
 
-su_port_vtable_t const su_port_osx_vtable[1] =
+su_port_vtable_t const su_osx_port_vtable[1] =
   {{
-      /* su_vtable_size: */ sizeof su_port_osx_vtable,
-      su_port_osx_lock,
-      su_port_osx_unlock,
-      su_port_osx_incref,
-      su_port_osx_decref,
-      NULL /* su_port_osx_runloop */, /* XXX - was: gsource, */
-      su_port_osx_send,
-      su_port_osx_register,
-      su_port_osx_unregister,
-      su_port_osx_deregister,
-      su_port_osx_unregister_all,
-      su_port_osx_eventmask,
-      su_port_osx_run,
-      su_port_osx_break,
-      su_port_osx_step,
-      su_port_osx_own_thread,
-      su_port_osx_add_prepoll,
-      su_port_osx_remove_prepoll,
-      su_port_osx_timers,
-      su_port_osx_multishot,
-      su_port_osx_threadsafe,
-      su_port_osx_yield
+      /* su_vtable_size: */ sizeof su_osx_port_vtable,
+      su_pthread_port_lock,
+      su_pthread_port_unlock,
+      su_base_port_incref,
+      su_osx_port_decref,
+      su_base_port_gsource,
+      su_osx_port_send,
+      su_osx_port_register,
+      su_osx_port_unregister,
+      su_osx_port_deregister,
+      su_osx_port_unregister_all,
+      su_osx_port_eventmask,
+      su_osx_port_run,
+      su_osx_port_break,
+      su_osx_port_step,
+      su_pthread_port_own_thread,
+      su_base_port_add_prepoll,
+      su_base_port_remove_prepoll,
+      su_base_port_timers,
+      su_osx_port_multishot,
+      su_base_port_threadsafe,
+      su_base_port_yield,
+      su_osx_port_wait_events,
+      su_base_port_getmsgs,
+      su_base_port_getmsgs_from,
+      su_osx_port_name,
+      su_base_port_start_shared,
+      su_pthread_port_wait,
+      su_pthread_port_execute,
     }};
 
-static int su_port_osx_wait_events(su_port_t *self, su_duration_t tout);
-
-
-/* *
+/*
  * Port is a per-thread reactor.  
  *
  * Multiple root objects executed by single thread share a su_port_t object. 
  */
-struct su_port_s {
-  su_home_t        sup_home[1];
+struct su_osx_port_s {
+  su_socket_port_t sup_socket[1];
 
-  su_port_vtable_t const *sup_vtable;
-  
-  unsigned         sup_running;
-  unsigned         sup_source_fired;
+#define sup_pthread sup_socket->sup_base
+#define sup_base sup_socket->sup_base->sup_base
+#define sup_home sup_socket->sup_base->sup_base->sup_home
 
-
-#if SU_HAVE_PTHREADS
-  pthread_t        sup_tid;
-  pthread_mutex_t  sup_mutex[1];
-#if __CYGWIN__
-  pthread_mutex_t  sup_reflock[1];
-  int              sup_ref;
-#else
-  pthread_rwlock_t sup_ref[1];
-#endif
-#else
-  int              sup_ref;
-#endif
-
-#if SU_HAVE_MBOX
-  su_socket_t      sup_mbox[MBOX_SEND + 1];
-  su_wait_t        sup_mbox_wait;
-#endif
+  unsigned         sup_source_fired;
 
   CFRunLoopRef        sup_main_loop;
   CFRunLoopSourceRef *sup_sources;
   CFSocketRef        *sup_sockets;
+
+  CFRunLoopObserverRef sup_observer;
+  CFRunLoopObserverContext sup_observer_cntx[1];
+  /* Struct for CFSocket callbacks; contains current CFSource index */
+  struct osx_magic {
+    su_port_t *o_port;
+    int        o_current;
+    int        o_count;
+  } osx_magic[1];
   
   unsigned         sup_multishot; /**< Multishot operation? */
 
@@ -257,147 +205,10 @@
   su_root_t      **sup_wait_roots; 
 
   su_wait_t       *sup_waits; 
-
-  /* Pre-poll callback */
-  su_prepoll_f    *sup_prepoll; 
-  su_prepoll_magic_t *sup_pp_magic;
-  su_root_t       *sup_pp_root;
-
-  /* Timer list */
-  su_timer_t      *sup_timers;
-
-  /* Message list - this is protected by lock  */
-  su_msg_t        *sup_head;
-  su_msg_t       **sup_tail;
-
-#if 0
-  int              sup_free_index;   /**< Number of first free index */
-  int             *sup_indices; /** Indices to registrations */
-
-  int             *sup_reverses; /** Reverse index */
-  su_wakeup_f     *sup_wait_cbs; 
-  su_wakeup_arg_t**sup_wait_args; 
-  su_root_t      **sup_wait_roots; 
-
-  su_wait_t       *sup_waits; 
-
-  /* Pre-poll callback */
-  su_prepoll_f    *sup_prepoll; 
-  su_prepoll_magic_t *sup_pp_magic;
-  su_root_t       *sup_pp_root;
-
-  /* Timer list */
-  su_timer_t      *sup_timers;
-
-  /* Message list - this is protected by lock  */
-  su_msg_t        *sup_head;
-  su_msg_t       **sup_tail;
-#endif
 };
 
 
-/* Struct for CFSocket callbacks; contains current CFSource index */
-typedef struct {
-  su_port_t *o_port;
-  int        o_current;
-  int        o_count;
-} osx_magic_t;
-
-
-#if SU_HAVE_PTHREADS
-#define SU_PORT_OSX_OWN_THREAD(p)   (pthread_equal((p)->sup_tid, pthread_self()))
-
-#if __CYGWIN__
-
-/* Debugging versions */
-#define SU_PORT_OSX_INITREF(p)      (pthread_mutex_init((p)->sup_reflock, NULL), printf("initref(%p)\n", (p)))
-#define SU_PORT_OSX_INCREF(p, f)    (pthread_mutex_lock(p->sup_reflock), p->sup_ref++, pthread_mutex_unlock(p->sup_reflock), printf("incref(%p) by %s\n", (p), f))
-#define SU_PORT_OSX_DECREF(p, f)    do {					\
-    pthread_mutex_lock(p->sup_reflock);	p->sup_ref--; pthread_mutex_unlock(p->sup_reflock); \
-    if ((p->sup_ref) == 0) {			\
-      printf("decref(%p) to 0 by %s\n", (p), f); su_port_osx_destroy(p); }	\
-    else { printf("decref(%p) to %u by %s\n", (p), p->sup_ref, f); }  } while(0)
-
-#define SU_PORT_OSX_ZAPREF(p, f)    do { printf("zapref(%p) by %s\n", (p), f), \
-    pthread_mutex_lock(p->sup_reflock);	p->sup_ref--; pthread_mutex_unlock(p->sup_reflock); \
-  if ((p->sup_ref) != 0) { \
-    assert(!"SU_PORT_OSX_ZAPREF"); } \
-  su_port_osx_destroy(p); } while(0)
-
-#define SU_PORT_OSX_INITLOCK(p) \
-   (pthread_mutex_init((p)->sup_mutex, NULL), printf("init_lock(%p)\n", p))
-
-#define SU_PORT_OSX_LOCK(p, f)    \
-   (printf("%ld at %s locking(%p)...", pthread_self(), f, p), pthread_mutex_lock((p)->sup_mutex), printf(" ...%ld at %s locked(%p)...", pthread_self(), f, p))
-
-#define SU_PORT_OSX_UNLOCK(p, f)  \
-  (pthread_mutex_unlock((p)->sup_mutex), printf(" ...%ld at %s unlocked(%p)\n", pthread_self(), f, p))
-
-#elif 1
-#define SU_PORT_OSX_INITREF(p)      (pthread_rwlock_init(p->sup_ref, NULL))
-#define SU_PORT_OSX_INCREF(p, f)    (pthread_rwlock_rdlock(p->sup_ref))
-#define SU_PORT_OSX_DECREF(p, f)    do { pthread_rwlock_unlock(p->sup_ref); \
-  if (pthread_rwlock_trywrlock(p->sup_ref) == 0) su_port_osx_destroy(p); } while(0)
-
-#define SU_PORT_OSX_ZAPREF(p, f)    do { pthread_rwlock_unlock(p->sup_ref); \
-  if (pthread_rwlock_trywrlock(p->sup_ref) != 0) { \
-    assert(!"SU_PORT_OSX_ZAPREF"); pthread_rwlock_wrlock(p->sup_ref); } \
-  su_port_osx_destroy(p); } while(0)
-
-#define SU_PORT_OSX_INITLOCK(p)     (pthread_mutex_init((p)->sup_mutex, NULL))
-#define SU_PORT_OSX_LOCK(p, f)      (pthread_mutex_lock((p)->sup_mutex))
-#define SU_PORT_OSX_UNLOCK(p, f)    (pthread_mutex_unlock((p)->sup_mutex))
-
-#else
-
-/* Debugging versions */
-#define SU_PORT_OSX_INITREF(p)      (pthread_rwlock_init((p)->sup_ref, NULL), printf("initref(%p)\n", (p)))
-#define SU_PORT_OSX_INCREF(p, f)    (pthread_rwlock_rdlock(p->sup_ref), printf("incref(%p) by %s\n", (p), f))
-#define SU_PORT_OSX_DECREF(p, f)    do {					\
-    pthread_rwlock_unlock(p->sup_ref);					\
-    if (pthread_rwlock_trywrlock(p->sup_ref) == 0) {			\
-      printf("decref(%p) to 0 by %s\n", (p), f); su_port_osx_destroy(p); }	\
-    else { printf("decref(%p) by %s\n", (p), f); }  } while(0)
-
-#define SU_PORT_OSX_ZAPREF(p, f)    do { printf("zapref(%p) by %s\n", (p), f), \
-  pthread_rwlock_unlock(p->sup_ref); \
-  if (pthread_rwlock_trywrlock(p->sup_ref) != 0) { \
-    assert(!"SU_PORT_OSX_ZAPREF"); pthread_rwlock_wrlock(p->sup_ref); } \
-  su_port_osx_destroy(p); } while(0)
-
-#define SU_PORT_OSX_INITLOCK(p) \
-   (pthread_mutex_init((p)->sup_mutex, NULL), printf("init_lock(%p)\n", p))
-
-#define SU_PORT_OSX_LOCK(p, f)    \
-   (printf("%ld at %s locking(%p)...", pthread_self(), f, p), pthread_mutex_lock((p)->sup_mutex), printf(" ...%ld at %s locked(%p)...", pthread_self(), f, p))
-
-#define SU_PORT_OSX_UNLOCK(p, f)  \
-  (pthread_mutex_unlock((p)->sup_mutex), printf(" ...%ld at %s unlocked(%p)\n", pthread_self(), f, p))
-
-#endif
-
-#else /* !SU_HAVE_PTHREADS */
-
-#define SU_PORT_OSX_OWN_THREAD(p)  1
-#define SU_PORT_OSX_INITLOCK(p)    (void)(p)
-#define SU_PORT_OSX_LOCK(p, f)      (void)(p)
-#define SU_PORT_OSX_UNLOCK(p, f)    (void)(p)
-#define SU_PORT_OSX_ZAPREF(p, f)    ((p)->sup_ref--)
-
-#define SU_PORT_OSX_INITREF(p)      ((p)->sup_ref = 1)
-#define SU_PORT_OSX_INCREF(p, f)    ((p)->sup_ref++)
-#define SU_PORT_OSX_DECREF(p, f) \
-do { if (--((p)->sup_ref) == 0) su_port_osx_destroy(p); } while (0);
-
-#endif
-
-#if SU_HAVE_MBOX
-static int su_port_osx_wakeup(su_root_magic_t *magic, 
-			  su_wait_t *w,
-			  su_wakeup_arg_t *arg);
-#endif
-
-static void su_port_osx_destroy(su_port_t *self);
+/* XXX - mela static void su_osx_port_destroy(su_port_t *self); */
 
 /** Create a reactor object.
  *
@@ -414,7 +225,6 @@
   return su_root_create_with_port(magic, su_osx_runloop_create());
 }
 
-
 void osx_enabler_cb(CFSocketRef s, 
 		    CFSocketCallBackType type, 
 		    CFDataRef address, 
@@ -422,35 +232,32 @@
 		    void *info)
 {
   CFRunLoopRef  rl;
-  osx_magic_t  *magic = (osx_magic_t *) info;
+  struct osx_magic  *magic = (struct osx_magic *) info;
   su_port_t    *self = magic->o_port;
   su_duration_t tout = 0;
   su_time_t     now = su_now();
   
   rl = CFRunLoopGetCurrent();
 
-  if (self->sup_running) {
+  if (self->sup_base->sup_running) {
     
-    if (self->sup_prepoll)
-      self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
+    if (self->sup_base->sup_prepoll)
+      self->sup_base->sup_prepoll(self->sup_base->sup_pp_magic, self->sup_base->sup_pp_root);
     
-    if (self->sup_head)
-      su_port_osx_getmsgs(self);
+    if (self->sup_base->sup_head)
+      su_base_port_getmsgs(self);
     
-    if (self->sup_timers)
-      su_timer_expire(&self->sup_timers, &tout, now);
+    if (self->sup_base->sup_timers)
+      su_timer_expire(&self->sup_base->sup_timers, &tout, now);
   }
   
   CFRunLoopWakeUp(rl);
-  
 }
 
 
 /**@internal
  *
- * Allocates and initializes a message port. It creates a mailbox used to.
- * wake up the tasks waiting on the port if needed.  Currently, the
- * mailbox is simply an UDP socket connected to itself.
+ * Allocates and initializes a message port.
  *
  * @return
  *   If successful a pointer to the new message port is returned, otherwise
@@ -458,142 +265,60 @@
  */
 su_port_t *su_osx_runloop_create(void)
 {
-  su_port_t *self;
-
-  SU_DEBUG_9(("su_osx_runloop_create() called\n"));
-
-  self = su_home_clone(NULL, sizeof(*self));
-
-  if (self) {
-#if SU_HAVE_MBOX
-    int af;
-    su_socket_t mb = INVALID_SOCKET;
-    char const *why;
-#endif
-    CFRunLoopObserverRef cf_observer; 
-    osx_magic_t *osx_magic = NULL;
-    CFRunLoopObserverContext cf_observer_cntx[1] = {{0, NULL, NULL,
-						     NULL, NULL}};
+  su_port_t *self = su_home_new(sizeof *self);
 
-    self->sup_vtable = su_port_osx_vtable;
-    
-    SU_PORT_OSX_INITREF(self);
-    SU_PORT_OSX_INITLOCK(self);
-    self->sup_tail = &self->sup_head;
-
-    self->sup_multishot = 0; /* XXX (SU_ENABLE_MULTISHOT_POLL) != 0; */
-
-#if SU_HAVE_PTHREADS
-    self->sup_tid = pthread_self();
-#endif
-  
-#if SU_HAVE_MBOX
-#if HAVE_SOCKETPAIR
-#if defined(AF_LOCAL)
-    af = AF_LOCAL;
-#else
-    af = AF_UNIX;
-#endif
-    if (socketpair(af, SOCK_STREAM, 0, self->sup_mbox) == -1) {
-      why = "su_port_osx_init: socketpair"; goto error;
-    }
-
-    mb = self->sup_mbox[0];
-    su_setblocking(self->sup_mbox[0], 0);
-    su_setblocking(self->sup_mbox[1], 0);
-#else
-    {
-      struct sockaddr_in sin = { sizeof(struct sockaddr_in), 0 };
-      socklen_t sinsize = sizeof sin;
-      struct sockaddr *sa = (struct sockaddr *)&sin;
-
-      af = PF_INET;
-
-      self->sup_mbox[0] = mb = su_socket(af, SOCK_DGRAM, IPPROTO_UDP);
-      if (mb == INVALID_SOCKET) {
-	why = "su_port_osx_init: socket"; goto error;
-      }
-  
-      sin.sin_family = AF_INET;
-      sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* 127.1 */
-      
-      /* Get a port for us */
-      if (bind(mb, sa, sizeof sin) == -1) {
-	why = "su_port_osx_init: bind"; goto error;
-      }
+  if (!self)
+    return self;
 
-      if (getsockname(mb, sa, &sinsize) == -1) {
-	why = "su_port_osx_init: getsockname"; goto error;
-      }
-    
-      if (connect(mb, sa, sinsize) == -1) {
-	why = "su_port_osx_init: connect"; goto error;
-      }
-    }
-#endif    
+  enter;
 
-    if (su_wait_create(&self->sup_mbox_wait, mb, SU_WAIT_IN) == -1) {
-      why = "su_port_osx_init: su_wait_create"; goto error;
-    }
+  if (su_home_destructor(su_port_home(self), su_osx_port_deinit) < 0)
+    return su_home_unref(su_port_home(self)), NULL;
 
-    if (su_port_osx_register(self, NULL, &self->sup_mbox_wait,
-			     su_port_osx_wakeup, 
-			     (su_wakeup_arg_t *)self->sup_mbox, 0)
-	== -1) {
-      why = "su_port_osx_create: su_port_osx_register"; goto error;
-    }
+  self->sup_multishot = SU_ENABLE_MULTISHOT_POLL;
 
-    osx_magic = calloc(1, sizeof(*osx_magic));
-    osx_magic->o_port = self;
-    cf_observer_cntx->info = osx_magic;
-    
-    cf_observer =
-      CFRunLoopObserverCreate(NULL, kCFRunLoopAfterWaiting | kCFRunLoopBeforeWaiting,
-			      TRUE, 0, cf_observer_cb, cf_observer_cntx);
-    
+  if (su_socket_port_init(self->sup_base, su_osx_port_vtable) == 0) {
+    self->osx_magic->o_port = self;
+    self->sup_observer_cntx->info = self->osx_magic;
+    self->sup_observer =
+      CFRunLoopObserverCreate(NULL, 
+			      kCFRunLoopAfterWaiting | kCFRunLoopBeforeWaiting,
+			      TRUE, 0, cf_observer_cb, self->sup_observer_cntx);
+#if 0
     CFRunLoopAddObserver(CFRunLoopGetCurrent(),
-			 cf_observer,
+			 self->sup_observer,
 			 kCFRunLoopDefaultMode);
-    
-    SU_DEBUG_9(("su_port_osx_create() returns %p\n", self));
-    
-    return self;
-    
-  error:
-    su_perror(why);
-    su_port_osx_destroy(self), self = NULL;
 #endif
   }
-  
-  SU_DEBUG_9(("su_port_osx_create() returns %p\n", self));
-  
+  else
+    return su_home_unref(su_port_home(self)), NULL;
+
   return self;
 }
 
-
 static
 void cf_observer_cb(CFRunLoopObserverRef observer, 
 		    CFRunLoopActivity activity, 
 		    void *info)
 {
   CFRunLoopRef  rl;
-  osx_magic_t  *magic = (osx_magic_t *) info;
+  struct osx_magic  *magic = (struct osx_magic *) info;
   su_port_t    *self = magic->o_port;
   su_duration_t tout = 0;
   su_time_t     now = su_now();
 
   rl = CFRunLoopGetCurrent();
 
-  if (self->sup_running) {
+  if (self->sup_base->sup_running) {
 
-    if (self->sup_prepoll)
-      self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
+    if (self->sup_base->sup_prepoll)
+      self->sup_base->sup_prepoll(self->sup_base->sup_pp_magic, self->sup_base->sup_pp_root);
     
-    if (self->sup_head)
-      su_port_osx_getmsgs(self);
+    if (self->sup_base->sup_head)
+      su_port_getmsgs(self);
     
-    if (self->sup_timers)
-      su_timer_expire(&self->sup_timers, &tout, now);
+    if (self->sup_base->sup_timers)
+      su_timer_expire(&self->sup_base->sup_timers, &tout, now);
   } else
     SU_DEBUG_9(("cf_observer_cb(): PORT IS NOT RUNNING!\n"));
 
@@ -603,70 +328,13 @@
 }
 
 /** @internal Destroy a port. */
-void su_port_osx_destroy(su_port_t *self)
+static void su_osx_port_deinit(void *arg)
 {
-  assert(self);
-
-  SU_DEBUG_9(("su_port_osx_destroy() called\n"));
-
-#if SU_HAVE_MBOX
-  if (self->sup_mbox[0] != INVALID_SOCKET) {
-    su_port_osx_unregister(self, NULL, &self->sup_mbox_wait, NULL, 
-		       (su_wakeup_arg_t *)self->sup_mbox);
-    su_wait_destroy(&self->sup_mbox_wait);
-    su_close(self->sup_mbox[0]); self->sup_mbox[0] = INVALID_SOCKET;
-#if HAVE_SOCKETPAIR
-    su_close(self->sup_mbox[1]); self->sup_mbox[1] = INVALID_SOCKET;
-#endif
-    SU_DEBUG_9(("su_port_osx_destroy() close mailbox\n"));
-  }
-#endif
-  if (self->sup_sources) 
-    free(self->sup_sources), self->sup_sources = NULL;
-  if (self->sup_sockets) 
-    free(self->sup_sockets), self->sup_sockets = NULL;
-  if (self->sup_waits) 
-    free(self->sup_waits), self->sup_waits = NULL;
-  if (self->sup_wait_cbs)
-    free(self->sup_wait_cbs), self->sup_wait_cbs = NULL;
-  if (self->sup_wait_args)
-    free(self->sup_wait_args), self->sup_wait_args = NULL;
-  if (self->sup_wait_roots)
-    free(self->sup_wait_roots), self->sup_wait_roots = NULL;
-  if (self->sup_reverses)
-    free(self->sup_reverses), self->sup_reverses = NULL;
-  if (self->sup_indices)
-    free(self->sup_indices), self->sup_indices = NULL;
-
-  SU_DEBUG_9(("su_port_osx_destroy() freed registrations\n"));
+  su_port_t *self = arg;
 
-  su_home_zap(self->sup_home);
+  SU_DEBUG_9(("%s(%p) called\n", "su_osx_port_deinit", (void *)self));
 
-  SU_DEBUG_9(("su_port_osx_destroy() returns\n"));
-
-}
-
-static void su_port_osx_lock(su_port_t *self, char const *who)
-{
-  SU_PORT_OSX_LOCK(self, who);
-}
-
-static void su_port_osx_unlock(su_port_t *self, char const *who)
-{
-  SU_PORT_OSX_UNLOCK(self, who);
-}
-
-static void su_port_osx_incref(su_port_t *self, char const *who)
-{
-  SU_PORT_OSX_INCREF(self, who);
-}
-
-static void su_port_osx_decref(su_port_t *self, int blocking, char const *who)
-{
-  if (blocking)
-    SU_PORT_OSX_ZAPREF(self, who);
-  else
-    SU_PORT_OSX_DECREF(self, who);
+  su_socket_port_deinit(self->sup_base);
 }
 
 static
@@ -692,6 +360,7 @@
 }
 
 
+#if 0
 static
 int map_cf_event_to_poll_event(CFSocketCallBackType type)
 {
@@ -711,18 +380,18 @@
 
   return event;
 }
-
+#endif
 
 static
-void su_port_osx_socket_cb(CFSocketRef s, 
+void su_osx_port_socket_cb(CFSocketRef s, 
 			   CFSocketCallBackType type, 
 			   CFDataRef address, 
 			   const void *data, 
 			   void *info)
 {
-  osx_magic_t       *magic = (osx_magic_t *) info;
-  su_port_t         *self = magic->o_port;
-  int                curr = magic->o_current;
+  struct osx_magic *magic = (struct osx_magic *) info;
+  su_port_t        *self = magic->o_port;
+  int               curr = magic->o_current;
   su_duration_t tout = 0;
   
 #if SU_HAVE_POLL
@@ -742,13 +411,13 @@
 			  &waits[n], 
 			  self->sup_wait_args[n]);
     
-    if (self->sup_running) {
-      su_port_osx_getmsgs(self);
+    if (self->sup_base->sup_running) {
+      su_port_getmsgs(self);
       
-      if (self->sup_timers)
-	su_timer_expire(&self->sup_timers, &tout, su_now());
+      if (self->sup_base->sup_timers)
+	su_timer_expire(&self->sup_base->sup_timers, &tout, su_now());
 
-      if (self->sup_head)
+      if (self->sup_base->sup_head)
 	tout = 0;
 
       /* CFRunLoopWakeUp(CFRunLoopGetCurrent()); */
@@ -761,37 +430,20 @@
   
 }
 
-#if SU_HAVE_MBOX
-/** @internal Message box wakeup function. */
-static int su_port_osx_wakeup(su_root_magic_t *magic, /* NULL */
-			      su_wait_t *w,
-			      su_wakeup_arg_t *arg)
-{
-  char buf[32];
-  su_socket_t s = *(su_socket_t *)arg;
-  su_wait_events(w, s);
-  recv(s, buf, sizeof(buf), 0);
-
-  /* CFRunLoopWakeUp(CFRunLoopGetCurrent()); */
-
-  return 0;
-}
-#endif
-
 /** @internal Send a message to the port. */
-int su_port_osx_send(su_port_t *self, su_msg_r rmsg)
+int su_osx_port_send(su_port_t *self, su_msg_r rmsg)
 {
   CFRunLoopRef rl;
 
   if (self) {
     int wakeup;
 
-    SU_PORT_OSX_LOCK(self, "su_port_osx_send");
+    //XXX - mela SU_OSX_PORT_LOCK(self, "su_osx_port_send");
     
-    wakeup = self->sup_head == NULL;
+    wakeup = self->sup_base->sup_head == NULL;
 
-    *self->sup_tail = rmsg[0]; rmsg[0] = NULL;
-    self->sup_tail = &(*self->sup_tail)->sum_next;
+    *self->sup_base->sup_tail = rmsg[0]; rmsg[0] = NULL;
+    self->sup_base->sup_tail = &(*self->sup_base->sup_tail)->sum_next;
 
 #if SU_HAVE_MBOX
     /* if (!pthread_equal(pthread_self(), self->sup_tid)) */
@@ -808,7 +460,7 @@
     }
 #endif
 
-    SU_PORT_OSX_UNLOCK(self, "su_port_osx_send");
+    //XXX - mela SU_OSX_PORT_UNLOCK(self, "su_osx_port_send");
 
     rl = CFRunLoopGetCurrent();
     CFRunLoopWakeUp(rl);
@@ -820,48 +472,6 @@
     return -1;
   }
 }
-
-/** @internal
- * Execute the messages in the incoming queue until the queue is empty..
- *
- * @param self - pointer to a port object
- *
- * @retval Number of messages sent
- */
-int su_port_osx_getmsgs(su_port_t *self)
-{
-  int n = 0;
-
-  if (self->sup_head) {
-    su_msg_f f;
-    su_msg_t *msg, *queue;
-
-    SU_PORT_OSX_LOCK(self, "su_port_getmsgs");
-
-    queue = self->sup_head;
-    self->sup_tail = &self->sup_head;
-    self->sup_head = NULL;
-
-    SU_PORT_OSX_UNLOCK(self, "su_port_osx_getmsgs");
-
-    for (msg = queue; msg; msg = queue) {
-      queue = msg->sum_next;
-      msg->sum_next = NULL;
-
-      f = msg->sum_func;
-      if (f) 
-	f(SU_ROOT_MAGIC(msg->sum_to->sut_root), &msg, msg->sum_data);
-      su_msg_delivery_report(&msg);
-      n++;
-    }
-
-    /* Check for wait events that may have been generated by messages */
-    su_port_osx_wait_events(self, 0);
-  }
-
-  return n;
-}
-
 static int o_count;
 
 /** @internal
@@ -882,9 +492,9 @@
  *              (0 is normal, 1 important, 2 realtime)
  * 
  * @return
- *   The function @su_port_osx_register returns nonzero index of the wait object, 
+ *   The function @su_osx_port_register returns nonzero index of the wait object, 
  *   or -1 upon an error.  */
-int su_port_osx_register(su_port_t *self,
+int su_osx_port_register(su_port_t *self,
 			 su_root_t *root, 
 			 su_wait_t *wait, 
 			 su_wakeup_f callback,
@@ -896,11 +506,11 @@
   CFRunLoopSourceRef *sources, source;
   CFSocketRef cf_socket, *sockets;
   int events = 0;
-  osx_magic_t *osx_magic = NULL;
+  struct osx_magic *osx_magic = NULL;
   CFSocketContext cf_socket_cntx[1] = {{0, NULL, NULL, NULL, NULL}};
   CFOptionFlags flags = 0;
 
-  assert(SU_PORT_OSX_OWN_THREAD(self));
+  // XXX - mela assert(SU_OSX_PORT_OWN_THREAD(self));
 
   n = self->sup_n_waits;
 
@@ -1024,7 +634,7 @@
 
   cf_socket = CFSocketCreateWithNative(NULL,
 				       (CFSocketNativeHandle) su_wait_socket(wait),
-				       events, su_port_osx_socket_cb, cf_socket_cntx);
+				       events, su_osx_port_socket_cb, cf_socket_cntx);
 
   flags = CFSocketGetSocketFlags(cf_socket);
   flags &= ~kCFSocketCloseOnInvalidate;
@@ -1053,7 +663,7 @@
 
 /** Deregister a su_wait_t object. */
 static
-int su_port_osx_deregister0(su_port_t *self, int i)
+int su_osx_port_deregister0(su_port_t *self, int i)
 {
   CFRunLoopRef rl;
   int n, N, *indices, *reverses;
@@ -1127,7 +737,7 @@
 
 /** Unregister a su_wait_t object.
  *  
- *  The function su_port_osx_unregister() unregisters a su_wait_t object. The
+ *  The function su_osx_port_unregister() unregisters a su_wait_t object. The
  *  wait object, a callback function and a argument are removed from the
  *  port object.
  * 
@@ -1140,7 +750,7 @@
  * 
  * @return Nonzero index of the wait object, or -1 upon an error.
  */
-int su_port_osx_unregister(su_port_t *self,
+int su_osx_port_unregister(su_port_t *self,
 		       su_root_t *root, 
 		       su_wait_t *wait,	
 		       su_wakeup_f callback, /* XXX - ignored */
@@ -1149,13 +759,13 @@
   int n, N;
 
   assert(self);
-  assert(SU_PORT_OSX_OWN_THREAD(self));
+  // XXX - mela assert(SU_OSX_PORT_OWN_THREAD(self));
 
   N = self->sup_n_waits;
 
   for (n = 0; n < N; n++) {
     if (SU_WAIT_CMP(wait[0], self->sup_waits[n]) == 0) {
-      return su_port_osx_deregister0(self, self->sup_reverses[n]);
+      return su_osx_port_deregister0(self, self->sup_reverses[n]);
     }
   }
 
@@ -1166,7 +776,7 @@
 
 /** Deregister a su_wait_t object.
  *  
- *  The function su_port_osx_deregister() deregisters a su_wait_t registrattion. 
+ *  The function su_osx_port_deregister() deregisters a su_wait_t registrattion. 
  *  The wait object, a callback function and a argument are removed from the
  *  port object.
  * 
@@ -1175,13 +785,13 @@
  * 
  * @return Index of the wait object, or -1 upon an error.
  */
-int su_port_osx_deregister(su_port_t *self, int i)
+int su_osx_port_deregister(su_port_t *self, int i)
 {
   su_wait_t wait[1] = { SU_WAIT_INIT };
   int retval;
 
   assert(self);
-  assert(SU_PORT_OSX_OWN_THREAD(self));
+  // XXX - mela assert(SU_OSX_PORT_OWN_THREAD(self));
 
   if (i <= 0 || i > self->sup_size_waits)
     return su_seterrno(EBADF);
@@ -1189,7 +799,7 @@
   if (self->sup_indices[i] < 0)
     return su_seterrno(EBADF);
     
-  retval = su_port_osx_deregister0(self, i);
+  retval = su_osx_port_deregister0(self, i);
 
   su_wait_destroy(wait);
 
@@ -1200,7 +810,7 @@
 /** @internal
  * Unregister all su_wait_t objects.
  *
- * The function su_port_osx_unregister_all() unregisters all su_wait_t objects
+ * The function su_osx_port_unregister_all() unregisters all su_wait_t objects
  * and destroys all queued timers associated with given root object.
  * 
  * @param  self     - pointer to port object
@@ -1208,7 +818,7 @@
  * 
  * @return Number of wait objects removed.
  */
-int su_port_osx_unregister_all(su_port_t *self, 
+int su_osx_port_unregister_all(su_port_t *self, 
 			   su_root_t *root)
 {
   int i, j, index, N;
@@ -1221,7 +831,7 @@
   CFRunLoopSourceRef *sources;
   CFSocketRef        *sockets;
 
-  assert(SU_PORT_OSX_OWN_THREAD(self));
+  // XXX - assert(SU_OSX_PORT_OWN_THREAD(self));
 
   N          = self->sup_n_waits;
   indices    = self->sup_indices;
@@ -1295,7 +905,7 @@
 
 /**Set mask for a registered event. @internal
  *
- * The function su_port_osx_eventmask() sets the mask describing events that can
+ * The function su_osx_port_eventmask() sets the mask describing events that can
  * signal the registered callback.
  *
  * @param port   pointer to port object
@@ -1306,12 +916,12 @@
  * @retval 0 when successful,
  * @retval -1 upon an error.
  */
-int su_port_osx_eventmask(su_port_t *self, int index, int socket, int events)
+int su_osx_port_eventmask(su_port_t *self, int index, int socket, int events)
 {
   int n, ret;
 
   assert(self);
-  assert(SU_PORT_OSX_OWN_THREAD(self));
+  // XXX - mela assert(SU_OSX_PORT_OWN_THREAD(self));
 
   if (index <= 0 || index > self->sup_size_waits)
     return su_seterrno(EBADF);
@@ -1330,7 +940,7 @@
 /** @internal
  *
  *  Copies the su_wait_t objects from the port. The number of wait objects
- *  can be found out by calling su_port_osx_query() with @a n_waits as zero.
+ *  can be found out by calling su_osx_port_query() with @a n_waits as zero.
  * 
  * @note This function is called only by friends.
  *
@@ -1340,11 +950,11 @@
  *
  * @return Number of wait objects, or 0 upon an error.
  */
-unsigned su_port_osx_query(su_port_t *self, su_wait_t *waits, unsigned n_waits)
+unsigned su_osx_port_query(su_port_t *self, su_wait_t *waits, unsigned n_waits)
 {
   unsigned n;
 
-  assert(SU_PORT_OSX_OWN_THREAD(self));
+  // XXX - mela assert(SU_OSX_PORT_OWN_THREAD(self));
 
   n = self->sup_n_waits;
 
@@ -1360,7 +970,7 @@
 
 /** @internal Enable multishot mode.
  *
- * The function su_port_osx_multishot() enables, disables or queries the
+ * The function su_osx_port_multishot() enables, disables or queries the
  * multishot mode for the port. The multishot mode determines how the events
  * are scheduled by port. If multishot mode is enabled, port serves all the
  * sockets that have received network events. If it is disables, only first
@@ -1373,7 +983,7 @@
  * @retval 1 multishot mode is enabled
  * @retval -1 an error occurred
  */
-int su_port_osx_multishot(su_port_t *self, int multishot)
+int su_osx_port_multishot(su_port_t *self, int multishot)
 {
   if (multishot < 0)
     return self->sup_multishot;
@@ -1383,12 +993,14 @@
     return (errno = EINVAL), -1;
 }
 
+#if 0
 /** @internal Enable threadsafe operation. */
 static
-int su_port_osx_threadsafe(su_port_t *port)
+int su_osx_port_threadsafe(su_port_t *port)
 {
   return su_home_threadsafe(port->sup_home);
 }
+#endif
 
 /** Prepare root to be run on OSX Run Loop.
  *
@@ -1408,23 +1020,23 @@
   CFRunLoopRef rl;
   su_duration_t tout = 0;
 
-  assert(SU_PORT_OSX_OWN_THREAD(self));
+  // XXX - mela assert(SU_OSX_PORT_OWN_THREAD(self));
 
   enter;
 
-  self->sup_running = 1;
+  self->sup_base->sup_running = 1;
   rl = CFRunLoopGetCurrent();
 
-  if (self->sup_prepoll)
-    self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
+  if (self->sup_base->sup_prepoll)
+    self->sup_base->sup_prepoll(self->sup_base->sup_pp_magic, self->sup_base->sup_pp_root);
 
-  if (self->sup_head)
-    su_port_osx_getmsgs(self);
+  if (self->sup_base->sup_head)
+    su_port_getmsgs(self);
   
-  if (self->sup_timers)
-    su_timer_expire(&self->sup_timers, &tout, su_now());
+  if (self->sup_base->sup_timers)
+    su_timer_expire(&self->sup_base->sup_timers, &tout, su_now());
 
-  if (!self->sup_running)
+  if (!self->sup_base->sup_running)
     return;
 
   CFRetain(rl);
@@ -1435,45 +1047,45 @@
 
 /** @internal Main loop.
  * 
- * The function @c su_port_osx_run() waits for wait objects and the timers
+ * The function @c su_osx_port_run() waits for wait objects and the timers
  * associated with the port object.  When any wait object is signaled or
  * timer is expired, it invokes the callbacks, and returns waiting.
  * 
- * The function @c su_port_osx_run() runs until @c su_port_osx_break() is called
+ * The function @c su_osx_port_run() runs until @c su_osx_port_break() is called
  * from a callback.
  * 
  * @param self     pointer to port object
  * 
  */
-void su_port_osx_run(su_port_t *self)
+void su_osx_port_run(su_port_t *self)
 {
   CFRunLoopRef rl;
   su_duration_t tout = 0;
 
-  assert(SU_PORT_OSX_OWN_THREAD(self));
+  // XXX - mela assert(SU_OSX_PORT_OWN_THREAD(self));
 
   enter;
 
-  self->sup_running = 1;
+  self->sup_base->sup_running = 1;
   rl = CFRunLoopGetCurrent();
 
-  if (self->sup_prepoll)
-    self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
+  if (self->sup_base->sup_prepoll)
+    self->sup_base->sup_prepoll(self->sup_base->sup_pp_magic, self->sup_base->sup_pp_root);
 
-  if (self->sup_head)
-    su_port_osx_getmsgs(self);
+  if (self->sup_base->sup_head)
+    su_port_getmsgs(self);
   
-  if (self->sup_timers)
-    su_timer_expire(&self->sup_timers, &tout, su_now());
+  if (self->sup_base->sup_timers)
+    su_timer_expire(&self->sup_base->sup_timers, &tout, su_now());
 
-  if (!self->sup_running)
+  if (!self->sup_base->sup_running)
     return;
 
   CFRetain(rl);
   self->sup_main_loop = rl;
 
   /* if there are messages do a quick wait */
-  if (self->sup_head)
+  if (self->sup_base->sup_head)
     tout = 0;
 
   CFRunLoopRun();
@@ -1484,70 +1096,70 @@
 
 #if tuning
 /* This version can help tuning... */
-void su_port_osx_run_tune(su_port_t *self)
+void su_osx_port_run_tune(su_port_t *self)
 {
   int i;
   int timers = 0, messages = 0, events = 0;
   su_duration_t tout = 0, tout0;
   su_time_t started = su_now(), woken = started, bedtime = woken;
 
-  assert(SU_PORT_OSX_OWN_THREAD(self));
+  // XXX - mela assert(SU_OSX_PORT_OWN_THREAD(self));
 
-  for (self->sup_running = 1; self->sup_running;) {
+  for (self->sup_base->sup_running = 1; self->sup_base->sup_running;) {
     tout0 = tout, tout = 2000;
 
     timers = 0, messages = 0;
 
-    if (self->sup_prepoll)
-      self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
+    if (self->sup_base->sup_prepoll)
+      self->sup_base->sup_prepoll(self->sup_base->sup_pp_magic, self->sup_base->sup_pp_root);
 
-    if (self->sup_head)
-      messages = su_port_osx_getmsgs(self);
+    if (self->sup_base->sup_head)
+      messages = su_port_getmsgs(self);
 
-    if (self->sup_timers)
-      timers = su_timer_expire(&self->sup_timers, &tout, su_now());
+    if (self->sup_base->sup_timers)
+      timers = su_timer_expire(&self->sup_base->sup_timers, &tout, su_now());
 
-    if (!self->sup_running)
+    if (!self->sup_base->sup_running)
       break;
 
-    if (self->sup_head)      /* if there are messages do a quick wait */
+    if (self->sup_base->sup_head)      /* if there are messages do a quick wait */
       tout = 0;
 
     bedtime = su_now();
 
-    events = su_port_osx_wait_events(self, tout);
+    events = su_osx_port_wait_events(self, tout);
 
     woken = su_now();
 
     if (messages || timers || events)
-      SU_DEBUG_1(("su_port_osx_run(%p): %.6f: %u messages %u timers %u "
+      SU_DEBUG_1(("su_osx_port_run(%p): %.6f: %u messages %u timers %u "
 		  "events slept %.6f/%.3f\n",
 		  self, su_time_diff(woken, started), messages, timers, events,
 		  su_time_diff(woken, bedtime), tout0 * 1e-3));
 
-    if (!self->sup_running)
+    if (!self->sup_base->sup_running)
       break;
   }
 }
 #endif
 
 /** @internal
- * The function @c su_port_osx_break() is used to terminate execution of @c
- * su_port_osx_run(). It can be called from a callback function.
+ * The function @c su_osx_port_break() is used to terminate execution of @c
+ * su_osx_port_run(). It can be called from a callback function.
  * 
  * @param self     pointer to port
  * 
  */
-void su_port_osx_break(su_port_t *self)
+void su_osx_port_break(su_port_t *self)
 {
   if (self->sup_main_loop)
     CFRunLoopStop(self->sup_main_loop);
 
-  self->sup_running = 0; 
+  self->sup_base->sup_running = 0; 
 }
 
 /** @internal
- * The function @c su_port_osx_wait_events() is used to poll() for wait objects
+ * The function @c su_osx_port_wait_events() is used to poll() for wait objects
  *
  * @param self     pointer to port
  * @param tout     timeout in milliseconds
@@ -1555,7 +1167,7 @@
  * @return number of events handled
  */
 static
-int su_port_osx_wait_events(su_port_t *self, su_duration_t tout)
+int su_osx_port_wait_events(su_port_t *self, su_duration_t tout)
 {
   int i, events = 0;
   su_wait_t *waits = self->sup_waits;
@@ -1600,21 +1212,6 @@
   return events;
 }
 
-/** @internal 
- * Used to check wait events in callbacks that take lots of time
- *
- * This function does a timeout 0 poll() and runs wait objects.
- *
- * @param port     pointer to port
- *
- * @return number of events handled
- */
-static
-int su_port_osx_yield(su_port_t *port)
-{
-  return su_port_osx_wait_events(port, 0);
-}
-
 /** @internal Block until wait object is signaled or timeout.
  *
  * This function waits for wait objects and the timers associated with 
@@ -1631,15 +1228,13 @@
  *   Milliseconds to the next invocation of timer, or @c SU_WAIT_FOREVER if
  *   there are no active timers.
  */
-su_duration_t su_port_osx_step(su_port_t *self, su_duration_t tout)
+su_duration_t su_osx_port_step(su_port_t *self, su_duration_t tout)
 {
   CFRunLoopRef rl;
   su_time_t now = su_now();
   CFAbsoluteTime start;
   int ret, timeout = tout > INT32_MAX ? INT32_MAX : tout;
 
-  assert(SU_PORT_OSX_OWN_THREAD(self));
-
   rl = CFRunLoopGetCurrent();
 
   if (!rl)
@@ -1650,138 +1245,33 @@
   if (tout < timeout)
     timeout = tout;
 
-  if (self->sup_prepoll)
-    self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
+  if (self->sup_base->sup_prepoll)
+    self->sup_base->sup_prepoll(self->sup_base->sup_pp_magic, self->sup_base->sup_pp_root);
 
-  if (self->sup_head)
-    su_port_osx_getmsgs(self);
+  if (self->sup_base->sup_head)
+    su_base_port_getmsgs(self);
 
-  if (self->sup_timers)
-    su_timer_expire(&self->sup_timers, &tout, now);
+  if (self->sup_base->sup_timers)
+    su_timer_expire(&self->sup_base->sup_timers, &tout, now);
 
   /* if there are messages do a quick wait */
-  if (self->sup_head)
+  if (self->sup_base->sup_head)
     tout = 0;
 
-  start = CFAbsoluteTimeGetCurrent();
-  for (;;) {
-    /* Run loop with only one pass, indicate if a source was processed */
-    ret = CFRunLoopRunInMode(kCFRunLoopDefaultMode,
-			     0,
-			     TRUE);
-
-    /* Ok, one of our sources was fired */
-    if (self->sup_source_fired == 1) {
-      self->sup_source_fired = 0;
-      break;
-    }
+  ret = CFRunLoopRunInMode(kCFRunLoopDefaultMode,
+			   tout/1000000.0,
+			   true);
 
-    /* Check how long to run this loop */
-    if (CFAbsoluteTimeGetCurrent() >= start + timeout / 1000)
-      break;
-  }
-  
-  if (self->sup_head)
-    su_port_osx_getmsgs(self);
+  CFRunLoopWakeUp(rl);
+
+  if (self->sup_base->sup_head)
+    su_base_port_getmsgs(self);
 
-  if (self->sup_timers)
-    su_timer_expire(&self->sup_timers, &tout, su_now());
+  if (self->sup_base->sup_timers)
+    su_timer_expire(&self->sup_base->sup_timers, &tout, su_now());
 
-  if (self->sup_head)
+  if (self->sup_base->sup_head)
     tout = 0;
 
   return tout;
 }
-
-
-/** @internal
- * Checks if the calling thread owns the port object.
- *
- * @param self pointer to a port object
- *
- * @retval true (nonzero) if the calling thread owns the port,
- * @retval false (zero) otherwise.
- */
-int su_port_osx_own_thread(su_port_t const *self)
-{
-  return self == NULL || SU_PORT_OSX_OWN_THREAD(self);
-}
-
-#if 0
-/** @internal
- *  Prints out the contents of the port.
- *
- * @param self pointer to a port
- * @param f    pointer to a file (if @c NULL, uses @c stdout).
- */
-void su_port_osx_dump(su_port_t const *self, FILE *f)
-{
-  int i;
-#define IS_WAIT_IN(x) (((x)->events & SU_WAIT_IN) ? "IN" : "")
-#define IS_WAIT_OUT(x) (((x)->events & SU_WAIT_OUT) ? "OUT" : "")
-#define IS_WAIT_ACCEPT(x) (((x)->events & SU_WAIT_ACCEPT) ? "ACCEPT" : "")
-
-  if (f == NULL)
-    f = stdout;
-
-  fprintf(f, "su_port_osx_t at %p:\n", self);
-  fprintf(f, "\tport is%s running\n", self->sup_running ? "" : "not ");
-#if SU_HAVE_PTHREADS
-  fprintf(f, "\tport tid %p\n", (void *)self->sup_tid);
-#endif
-#if SU_HAVE_MBOX
-  fprintf(f, "\tport mbox %d (%s%s%s)\n", self->sup_mbox[0],
-	  IS_WAIT_IN(&self->sup_mbox_wait),
-	  IS_WAIT_OUT(&self->sup_mbox_wait),
-	  IS_WAIT_ACCEPT(&self->sup_mbox_wait));
-#endif
-  fprintf(f, "\t%d wait objects\n", self->sup_n_waits);
-  for (i = 0; i < self->sup_n_waits; i++) {
-    
-  }
-}
-
-#endif
-
-/* =========================================================================
- * Pre-poll() callback
- */
-
-int su_port_osx_add_prepoll(su_port_t *port,
-			su_root_t *root, 
-			su_prepoll_f *callback, 
-			su_prepoll_magic_t *magic)
-{
-  if (port->sup_prepoll)
-    return -1;
-
-  port->sup_prepoll = callback;
-  port->sup_pp_magic = magic;
-  port->sup_pp_root = root;
-
-  return 0;
-}
-
-int su_port_osx_remove_prepoll(su_port_t *port,
-			   su_root_t *root)
-{
-  if (port->sup_pp_root != root)
-    return -1;
-
-  port->sup_prepoll = NULL;
-  port->sup_pp_magic = NULL;
-  port->sup_pp_root = NULL;
-
-  return 0;
-}
-
-/* =========================================================================
- * Timers
- */
-
-static
-su_timer_t **su_port_osx_timers(su_port_t *self)
-{
-  return &self->sup_timers;
-}
-

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_port.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_port.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_port.c	Tue Apr 24 10:14:28 2007
@@ -27,8 +27,9 @@
  *
  * OS-Independent Socket Syncronization Interface.
  *
- * This looks like nth reincarnation of "reactor".  It implements the
- * poll/select/WaitForMultipleObjects and message passing functionality.
+ * This looks like nth reincarnation of "reactor". It implements the
+ * poll/select/WaitForMultipleObjects and message passing functionality. 
+ * This is virtual implementation:
  *
  * @author Pekka Pessi <Pekka.Pessi at nokia.com>
  * @author Kai Vehmanen <kai.vehmanen at nokia.com>
@@ -38,1443 +39,423 @@
 
 #include "config.h"
 
-/* React to multiple events per one poll() to make sure 
- * that high-priority events can never completely mask other events.
- * Enabled by default on all platforms except WIN32 */
-#ifndef WIN32
-#define SU_ENABLE_MULTISHOT_POLL 1
-#else
-#define SU_ENABLE_MULTISHOT_POLL 0
-#endif
-
-#include <stdlib.h>
-#include <assert.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-#include <limits.h>
-#include <errno.h>
+#define SU_CLONE_T      su_msg_t
 
-#define SU_PORT_IMPLEMENTATION 1
+#define su_port_s su_virtual_port_s
 
-#include "sofia-sip/su.h"
 #include "su_port.h"
-#include "sofia-sip/su_alloc.h"
 
-#if SU_HAVE_PTHREADS
-/* Pthread implementation */
-#include <pthread.h>
-#define SU_HAVE_MBOX 1
-#else
-#define SU_HAVE_MBOX 0
-#endif
-
-#if HAVE_SOCKETPAIR
-#define MBOX_SEND  1
-#else
-#define MBOX_SEND  0
-#endif
+#include <string.h>
+#include <stdlib.h>
 
+/** Create the default su_port_t implementation. */
+su_port_t *su_default_port_create(void)
+{
 #if HAVE_EPOLL
-#include <sys/epoll.h>
-
-#define POLL2EPOLL_NEEDED \
-  (POLLIN != EPOLLIN || POLLOUT != EPOLLOUT || POLLPRI != EPOLLPRI || \
-   POLLERR != EPOLLERR || POLLHUP != EPOLLHUP)
- 
-#define POLL2EPOLL(e) (e & (POLLIN|POLLOUT|POLLPRI|POLLERR|POLLHUP))
-#define EPOLL2POLL(e) (e & (POLLIN|POLLOUT|POLLPRI|POLLERR|POLLHUP))
-
-#endif
-
-static void su_port_lock(su_port_t *self, char const *who);
-static void su_port_unlock(su_port_t *self, char const *who);
-static void su_port_incref(su_port_t *self, char const *who);
-static void su_port_decref(su_port_t *self, int blocking, char const *who);
-
-static struct _GSource *su_port_gsource(su_port_t *port);
-
-static int su_port_send(su_port_t *self, su_msg_r rmsg);
-
-static int su_port_register(su_port_t *self,
-			    su_root_t *root, 
-			    su_wait_t *wait, 
-			    su_wakeup_f callback,
-			    su_wakeup_arg_t *arg,
-			    int priority);
-static int su_port_unregister(su_port_t *port,
-			      su_root_t *root, 
-			      su_wait_t *wait,	
-			      su_wakeup_f callback, 
-			      su_wakeup_arg_t *arg);
-
-static int su_port_deregister(su_port_t *self, int i);
-
-static int su_port_unregister_all(su_port_t *self,
-			   su_root_t *root);
-static
-int su_port_eventmask(su_port_t *self, int index, int socket, int events);
-static
-void su_port_run(su_port_t *self);
-static
-void su_port_break(su_port_t *self);
-static
-su_duration_t su_port_step(su_port_t *self, su_duration_t tout);
-
-static
-int su_port_own_thread(su_port_t const *port);
-
-static
-int su_port_add_prepoll(su_port_t *port,
-			su_root_t *root, 
-			su_prepoll_f *, 
-			su_prepoll_magic_t *);
-
-static
-int su_port_remove_prepoll(su_port_t *port,
-			   su_root_t *root);
-
-static
-su_timer_t **su_port_timers(su_port_t *port);
-
-static
-int su_port_multishot(su_port_t *port, int multishot);
-
-static
-int su_port_threadsafe(su_port_t *port);
-
-static
-int su_port_yield(su_port_t *port);
-
-su_port_vtable_t const su_port_vtable[1] =
-  {{
-      /* su_vtable_size: */ sizeof su_port_vtable,
-      su_port_lock,
-      su_port_unlock,
-      su_port_incref,
-      su_port_decref,
-      su_port_gsource,
-      su_port_send,
-      su_port_register,
-      su_port_unregister,
-      su_port_deregister,
-      su_port_unregister_all,
-      su_port_eventmask,
-      su_port_run,
-      su_port_break,
-      su_port_step,
-      su_port_own_thread,
-      su_port_add_prepoll,
-      su_port_remove_prepoll,
-      su_port_timers,
-      su_port_multishot,
-      su_port_threadsafe,
-      su_port_yield
-    }};
-
-static int su_port_wait_events(su_port_t *self, su_duration_t tout);
-
-
-/** 
- * Port is a per-thread reactor.  
- *
- * Multiple root objects executed by single thread share a su_port_t object. 
- */
-struct su_port_s {
-  su_home_t        sup_home[1];
-
-  su_port_vtable_t const *sup_vtable;
-  
-  unsigned         sup_running;
-
-#if SU_HAVE_PTHREADS
-  pthread_t        sup_tid;
-  pthread_mutex_t  sup_mutex[1];
-#if __CYGWIN__
-  pthread_mutex_t  sup_reflock[1];
-  int              sup_ref;
-#else
-  pthread_rwlock_t sup_ref[1];
-#endif
+  return su_epoll_port_create();
+#elif HAVE_KQUEUE
+  return su_kqueue_port_create();
+#elif HAVE_SYS_DEVPOLL_H
+  return su_devpoll_port_create();
+#elif HAVE_POLL_PORT
+  return su_poll_port_create();
+#elif HAVE_WIN32
+  return su_wsaevent_port_create();
+#elif HAVE_SELECT
+  return su_select_port_create();
 #else
-  int              sup_ref;
-#endif
-
-#if SU_HAVE_MBOX
-  su_socket_t      sup_mbox[MBOX_SEND + 1];
-  su_wait_t        sup_mbox_wait;
+  return NULL;
 #endif
+}
 
+int su_default_clone_start(su_root_t *parent,
+			   su_clone_r return_clone,
+			   su_root_magic_t *magic,
+			   su_root_init_f init,
+			   su_root_deinit_f deinit)
+{
 #if HAVE_EPOLL
-  /** epoll() fd */
-  int              sup_epoll;
-#endif
-
-  unsigned         sup_multishot; /**< Multishot operation? */
-
-  unsigned         sup_registers; /** Counter incremented by 
-				      su_port_register() or 
-				      su_port_unregister()
-				   */
-  int              sup_n_waits; /**< Active su_wait_t in su_waits */
-  int              sup_size_waits; /**< Size of allocate su_waits */
-
-  int              sup_pri_offset; /**< Offset to prioritized waits */
-
-#if !SU_HAVE_WINSOCK
-#define INDEX_MAX (0x7fffffff)
-#else 
-  /* We use WSAWaitForMultipleEvents() */
-#define INDEX_MAX (64)
-#endif
-
-  /** Indices from index returned by su_root_register() to tables below. 
-   *
-   * Free elements are negative. Free elements form a list, value of free
-   * element is (0 - index of next free element).
-   *
-   * First element sup_indices[0] points to first free element. 
-   */
-  int             *sup_indices;
-
-  int             *sup_reverses; /** Reverse index */
-  su_wakeup_f     *sup_wait_cbs; 
-  su_wakeup_arg_t**sup_wait_args; 
-  su_root_t      **sup_wait_roots; 
-
-  su_wait_t       *sup_waits; 
-
-  /* Pre-poll callback */
-  su_prepoll_f    *sup_prepoll; 
-  su_prepoll_magic_t *sup_pp_magic;
-  su_root_t       *sup_pp_root;
-
-  /* Timer list */
-  su_timer_t      *sup_timers;
-
-  /* Message list - this is protected by lock  */
-  su_msg_t        *sup_head;
-  su_msg_t       **sup_tail;
-};
-
-#if SU_HAVE_PTHREADS
-#define SU_PORT_OWN_THREAD(p)   (pthread_equal((p)->sup_tid, pthread_self()))
-
-#if __CYGWIN__
-
-/* Debugging versions */
-#define SU_PORT_INITREF(p)      (pthread_mutex_init((p)->sup_reflock, NULL), printf("initref(%p)\n", (p)))
-#define SU_PORT_INCREF(p, f)    (pthread_mutex_lock(p->sup_reflock), p->sup_ref++, pthread_mutex_unlock(p->sup_reflock), printf("incref(%p) by %s\n", (p), f))
-#define SU_PORT_DECREF(p, f)    do {					\
-    pthread_mutex_lock(p->sup_reflock);	p->sup_ref--; pthread_mutex_unlock(p->sup_reflock); \
-    if ((p->sup_ref) == 0) {			\
-      printf("decref(%p) to 0 by %s\n", (p), f); su_port_destroy(p); }	\
-    else { printf("decref(%p) to %u by %s\n", (p), p->sup_ref, f); }  } while(0)
-
-#define SU_PORT_ZAPREF(p, f)    do { printf("zapref(%p) by %s\n", (p), f), \
-    pthread_mutex_lock(p->sup_reflock);	p->sup_ref--; pthread_mutex_unlock(p->sup_reflock); \
-  if ((p->sup_ref) != 0) { \
-    assert(!"SU_PORT_ZAPREF"); } \
-  su_port_destroy(p); } while(0)
-
-#define SU_PORT_INITLOCK(p) \
-   (pthread_mutex_init((p)->sup_mutex, NULL), printf("init_lock(%p)\n", p))
-
-#define SU_PORT_LOCK(p, f)    \
-   (printf("%ld at %s locking(%p)...", pthread_self(), f, p), pthread_mutex_lock((p)->sup_mutex), printf(" ...%ld at %s locked(%p)...", pthread_self(), f, p))
-
-#define SU_PORT_UNLOCK(p, f)  \
-  (pthread_mutex_unlock((p)->sup_mutex), printf(" ...%ld at %s unlocked(%p)\n", pthread_self(), f, p))
-
-#elif 1
-#define SU_PORT_INITREF(p)      (pthread_rwlock_init(p->sup_ref, NULL))
-#define SU_PORT_INCREF(p, f)    (pthread_rwlock_rdlock(p->sup_ref))
-#define SU_PORT_DECREF(p, f)    do { pthread_rwlock_unlock(p->sup_ref); \
-  if (pthread_rwlock_trywrlock(p->sup_ref) == 0) su_port_destroy(p); } while(0)
-
-#define SU_PORT_ZAPREF(p, f)    do { pthread_rwlock_unlock(p->sup_ref); \
-  if (pthread_rwlock_trywrlock(p->sup_ref) != 0) { \
-    assert(!"SU_PORT_ZAPREF"); pthread_rwlock_wrlock(p->sup_ref); } \
-  su_port_destroy(p); } while(0)
-
-#define SU_PORT_INITLOCK(p)     (pthread_mutex_init((p)->sup_mutex, NULL))
-#define SU_PORT_LOCK(p, f)      (pthread_mutex_lock((p)->sup_mutex))
-#define SU_PORT_UNLOCK(p, f)    (pthread_mutex_unlock((p)->sup_mutex))
-
+  return su_epoll_clone_start(parent, return_clone, magic, init, deinit);
+#elif HAVE_KQUEUE
+  return su_kqueue_clone_start(parent, return_clone, magic, init, deinit);
+#elif HAVE_SYS_DEVPOLL_H
+  return su_devpoll_clone_start(parent, return_clone, magic, init, deinit);
+#elif HAVE_POLL_PORT
+  return su_poll_clone_start(parent, return_clone, magic, init, deinit);
+#elif HAVE_WIN32
+  return su_wsaevent_clone_start(parent, return_clone, magic, init, deinit);
+#elif HAVE_SELECT
+  return su_select_clone_start(parent, return_clone, magic, init, deinit);
 #else
-
-/* Debugging versions */
-#define SU_PORT_INITREF(p)      (pthread_rwlock_init((p)->sup_ref, NULL), printf("initref(%p)\n", (p)))
-#define SU_PORT_INCREF(p, f)    (pthread_rwlock_rdlock(p->sup_ref), printf("incref(%p) by %s\n", (p), f))
-#define SU_PORT_DECREF(p, f)    do {					\
-    pthread_rwlock_unlock(p->sup_ref);					\
-    if (pthread_rwlock_trywrlock(p->sup_ref) == 0) {			\
-      printf("decref(%p) to 0 by %s\n", (p), f); su_port_destroy(p); }	\
-    else { printf("decref(%p) by %s\n", (p), f); }  } while(0)
-
-#define SU_PORT_ZAPREF(p, f)    do { printf("zapref(%p) by %s\n", (p), f), \
-  pthread_rwlock_unlock(p->sup_ref); \
-  if (pthread_rwlock_trywrlock(p->sup_ref) != 0) { \
-    assert(!"SU_PORT_ZAPREF"); pthread_rwlock_wrlock(p->sup_ref); } \
-  su_port_destroy(p); } while(0)
-
-#define SU_PORT_INITLOCK(p) \
-   (pthread_mutex_init((p)->sup_mutex, NULL), printf("init_lock(%p)\n", p))
-
-#define SU_PORT_LOCK(p, f)    \
-   (printf("%ld at %s locking(%p)...", pthread_self(), f, p), pthread_mutex_lock((p)->sup_mutex), printf(" ...%ld at %s locked(%p)...", pthread_self(), f, p))
-
-#define SU_PORT_UNLOCK(p, f)  \
-  (pthread_mutex_unlock((p)->sup_mutex), printf(" ...%ld at %s unlocked(%p)\n", pthread_self(), f, p))
-
-#endif
-
-#else /* !SU_HAVE_PTHREADS */
-
-#define SU_PORT_OWN_THREAD(p)  1
-#define SU_PORT_INITLOCK(p)    (void)(p)
-#define SU_PORT_LOCK(p, f)      (void)(p)
-#define SU_PORT_UNLOCK(p, f)    (void)(p)
-#define SU_PORT_ZAPREF(p, f)    ((p)->sup_ref--)
-
-#define SU_PORT_INITREF(p)      ((p)->sup_ref = 1)
-#define SU_PORT_INCREF(p, f)    ((p)->sup_ref++)
-#define SU_PORT_DECREF(p, f) \
-do { if (--((p)->sup_ref) == 0) su_port_destroy(p); } while (0);
-
-#endif
-
-#if SU_HAVE_MBOX
-static int su_port_wakeup(su_root_magic_t *magic, 
-			  su_wait_t *w,
-			  su_wakeup_arg_t *arg);
+  errno = ENOSYS;
+  return -1;
 #endif
+}
 
-static void su_port_destroy(su_port_t *self);
+static su_port_create_f *preferred_su_port_create;
+static su_clone_start_f *preferred_su_clone_start;
 
-/**@internal
+/** Explicitly set the preferred su_port_t implementation.
  *
- * Allocates and initializes a message port. It creates a mailbox used to.
- * wake up the tasks waiting on the port if needed.  Currently, the
- * mailbox is simply an UDP socket connected to itself.
- *
- * @return
- *   If successful a pointer to the new message port is returned, otherwise
- *   NULL is returned.  
+ * @sa su_epoll_port_create(), su_poll_port_create(), su_select_port_create()
  */
-su_port_t *su_port_create(void)
+void su_port_prefer(su_port_create_f *create,
+		    su_clone_start_f *start)
 {
-  su_port_t *self;
-
-  SU_DEBUG_9(("su_port_create() called\n"));
-
-  self = su_home_clone(NULL, sizeof(*self));
-
-  if (self) {
-#if SU_HAVE_MBOX
-    int af;
-    su_socket_t mb = INVALID_SOCKET;
-    char const *why;
-#endif
-
-    self->sup_vtable = su_port_vtable;
-    
-    SU_PORT_INITREF(self);
-    SU_PORT_INITLOCK(self);
-    self->sup_tail = &self->sup_head;
-
-    self->sup_multishot = (SU_ENABLE_MULTISHOT_POLL) != 0;
+  if (create) preferred_su_port_create = create;
+  if (start) preferred_su_clone_start = start;
+}
 
-#if SU_HAVE_PTHREADS
-    self->sup_tid = pthread_self();
-#endif
+void su_port_set_system_preferences(char const *name)
+{
+  su_port_create_f *create = preferred_su_port_create;
+  su_clone_start_f *start = preferred_su_clone_start;
 
+  if (name == NULL)
+      ;
 #if HAVE_EPOLL
-    self->sup_epoll = epoll_create(su_root_size_hint);
-    if (self->sup_epoll == -1)
-      SU_DEBUG_3(("su_port(%p): epoll_create(): %s\n", self, strerror(errno)));
-    else
-      SU_DEBUG_9(("su_port(%p): epoll_create() => %u: OK\n",
-		  self, self->sup_epoll));
+  else if (strcmp(name, "epoll") == 0) {
+    create = su_epoll_port_create;
+    start = su_epoll_clone_start;
+  }
 #endif
-  
-#if SU_HAVE_MBOX
-#if HAVE_SOCKETPAIR
-#if defined(AF_LOCAL)
-    af = AF_LOCAL;
-#else
-    af = AF_UNIX;
+#if HAVE_KQUEUE
+  else if (strcmp(name, "kqueue") == 0) {
+    create = su_kqueue_port_create;
+    start = su_kqueue_clone_start;
+  }
 #endif
-    if (socketpair(af, SOCK_STREAM, 0, self->sup_mbox) == -1) {
-      why = "su_port_init: socketpair"; goto error;
-    }
-
-    mb = self->sup_mbox[0];
-    su_setblocking(self->sup_mbox[0], 0);
-    su_setblocking(self->sup_mbox[1], 0);
-#else
-    {
-      struct sockaddr_in sin = { sizeof(struct sockaddr_in), 0 };
-      socklen_t sinsize = sizeof sin;
-      struct sockaddr *sa = (struct sockaddr *)&sin;
-
-      af = PF_INET;
-
-      self->sup_mbox[0] = mb = su_socket(af, SOCK_DGRAM, IPPROTO_UDP);
-      if (mb == INVALID_SOCKET) {
-	why = "su_port_init: socket"; goto error;
-      }
-  
-      sin.sin_family = AF_INET;
-      sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* 127.1 */
-      
-      /* Get a port for us */
-      if (bind(mb, sa, sizeof sin) == -1) {
-	why = "su_port_init: bind"; goto error;
-      }
-
-      if (getsockname(mb, sa, &sinsize) == -1) {
-	why = "su_port_init: getsockname"; goto error;
-      }
-    
-      if (connect(mb, sa, sinsize) == -1) {
-	why = "su_port_init: connect"; goto error;
-      }
-    }
-#endif    
-
-    if (su_wait_create(&self->sup_mbox_wait, mb, SU_WAIT_IN) == -1) {
-      why = "su_port_init: su_wait_create"; goto error;
-    }
-
-    if (su_port_register(self, NULL, &self->sup_mbox_wait, su_port_wakeup, 
-			 (su_wakeup_arg_t *)self->sup_mbox, 0)
-	== -1) {
-      why = "su_port_create: su_port_register"; goto error;
-    }
-
-    SU_DEBUG_9(("su_port_create() returns %p\n", self));
-
-    return self;
-
-  error:
-    su_perror(why);
-    su_port_destroy(self), self = NULL;
+#if HAVE_SYS_DEVPOLL_H
+  else if (strcmp(name, "devpoll") == 0) {
+    create = su_devpoll_port_create;
+    start = su_devpoll_clone_start;
+  }
 #endif
+#if HAVE_POLL_PORT
+  else if (strcmp(name, "poll") == 0) {
+    create = su_poll_port_create;
+    start = su_poll_clone_start;
   }
-
-  SU_DEBUG_9(("su_port_create() returns %p\n", self));
-
-  return self;
-}
-
-/** @internal Destroy a port. */
-void su_port_destroy(su_port_t *self)
-{
-  assert(self);
-
-  SU_DEBUG_9(("su_port_destroy() called\n"));
-
-#if SU_HAVE_MBOX
-  if (self->sup_mbox[0] != INVALID_SOCKET) {
-    su_port_unregister(self, NULL, &self->sup_mbox_wait, NULL, 
-		       (su_wakeup_arg_t *)self->sup_mbox);
-    su_wait_destroy(&self->sup_mbox_wait);
-    su_close(self->sup_mbox[0]); self->sup_mbox[0] = INVALID_SOCKET;
-#if HAVE_SOCKETPAIR
-    su_close(self->sup_mbox[1]); self->sup_mbox[1] = INVALID_SOCKET;
 #endif
-    SU_DEBUG_9(("su_port_destroy() close mailbox\n"));
+#if HAVE_WIN32
+  else if (strcasecmp(name, "wsaevent") == 0) {
+    create = su_wsaevent_port_create;
+    start = su_wsaevent_clone_start;
+  }
+#elif HAVE_SELECT
+  else if (strcmp(name, "select") == 0) {
+    create = su_select_port_create;
+    start = su_select_clone_start;
   }
 #endif
-  if (self->sup_waits) 
-    free(self->sup_waits), self->sup_waits = NULL;
-  if (self->sup_wait_cbs)
-    free(self->sup_wait_cbs), self->sup_wait_cbs = NULL;
-  if (self->sup_wait_args)
-    free(self->sup_wait_args), self->sup_wait_args = NULL;
-  if (self->sup_wait_roots)
-    free(self->sup_wait_roots), self->sup_wait_roots = NULL;
-  if (self->sup_reverses)
-    free(self->sup_reverses), self->sup_reverses = NULL;
-  if (self->sup_indices)
-    free(self->sup_indices), self->sup_indices = NULL;
 
-  SU_DEBUG_9(("su_port_destroy() freed registrations\n"));
+  if (create == NULL) 
+    create = su_default_port_create;
 
-  su_home_zap(self->sup_home);
+  if (!preferred_su_port_create ||
+      preferred_su_port_create == su_default_port_create) 
+    preferred_su_port_create = create;
 
-  SU_DEBUG_9(("su_port_destroy() returns\n"));
+  if (start == NULL)
+    start = su_default_clone_start;
 
+  if (!preferred_su_clone_start || 
+      preferred_su_clone_start == su_default_clone_start)
+    preferred_su_clone_start = start;
 }
 
-static void su_port_lock(su_port_t *self, char const *who)
-{
-  SU_PORT_LOCK(self, who);
-}
-
-static void su_port_unlock(su_port_t *self, char const *who)
-{
-  SU_PORT_UNLOCK(self, who);
-}
-
-static void su_port_incref(su_port_t *self, char const *who)
-{
-  SU_PORT_INCREF(self, who);
-}
-
-static void su_port_decref(su_port_t *self, int blocking, char const *who)
-{
-  if (blocking)
-    SU_PORT_ZAPREF(self, who);
-  else
-    SU_PORT_DECREF(self, who);
-}
-
-static struct _GSource *su_port_gsource(su_port_t *self)
+/** Create the preferred su_port_t implementation. */
+su_port_t *su_port_create(void)
 {
-  return NULL;
-}
+  if (preferred_su_port_create == NULL)
+    su_port_set_system_preferences(getenv("SU_PORT"));
 
-#if SU_HAVE_MBOX
-/** @internal Message box wakeup function. */
-static int su_port_wakeup(su_root_magic_t *magic, /* NULL */
-			  su_wait_t *w,
-			  su_wakeup_arg_t *arg)
-{
-  char buf[32];
-  su_socket_t s = *(su_socket_t *)arg;
-  su_wait_events(w, s);
-  recv(s, buf, sizeof(buf), 0);
-  return 0;
+  return preferred_su_port_create();
 }
-#endif
 
-/** @internal Send a message to the port. */
-int su_port_send(su_port_t *self, su_msg_r rmsg)
+/** Return name of the su_port_t instance. */
+char const *su_port_name(su_port_t const *port)
 {
-  if (self) {
-    int wakeup;
-
-    SU_PORT_LOCK(self, "su_port_send");
-    
-    wakeup = self->sup_head == NULL;
-
-    *self->sup_tail = rmsg[0]; rmsg[0] = NULL;
-    self->sup_tail = &(*self->sup_tail)->sum_next;
-
-#if SU_HAVE_MBOX
-    /* if (!pthread_equal(pthread_self(), self->sup_tid)) */
-    if (wakeup)
-    {
-      assert(self->sup_mbox[MBOX_SEND] != INVALID_SOCKET);
-
-      if (send(self->sup_mbox[MBOX_SEND], "X", 1, 0) == -1) {
-#if HAVE_SOCKETPAIR
-	if (su_errno() != EWOULDBLOCK)
-#endif
-	  su_perror("su_msg_send: send()");
-      }
-    }
-#endif
-
-    SU_PORT_UNLOCK(self, "su_port_send");
-
-    return 0;
-  }
-  else {
-    su_msg_destroy(rmsg);
-    return -1;
-  }
+  return port->sup_vtable->su_port_name(port);
 }
 
-/** @internal
- * Execute the messages in the incoming queue until the queue is empty..
- *
- * @param self - pointer to a port object
- *
- * @retval Number of messages sent
+/* ========================================================================
+ * su_clone_t
  */
-int su_port_getmsgs(su_port_t *self)
-{
-  int n = 0;
-
-  if (self->sup_head) {
-    su_msg_f f;
-    su_msg_t *msg, *queue;
-
-    SU_PORT_LOCK(self, "su_port_getmsgs");
-
-    queue = self->sup_head;
-    self->sup_tail = &self->sup_head;
-    self->sup_head = NULL;
-
-    SU_PORT_UNLOCK(self, "su_port_getmsgs");
-
-    for (msg = queue; msg; msg = queue) {
-      queue = msg->sum_next;
-      msg->sum_next = NULL;
-
-      f = msg->sum_func;
-      if (f) 
-	f(SU_ROOT_MAGIC(msg->sum_to->sut_root), &msg, msg->sum_data);
-      su_msg_delivery_report(&msg);
-      n++;
-    }
-
-    /* Check for wait events that may have been generated by messages */
-    su_port_wait_events(self, 0);
-  }
 
-  return n;
-}
-
-/** @internal
- *
- *  Register a @c su_wait_t object. The wait object, a callback function and
- *  a argument pointer is stored in the port object.  The callback function
- *  will be called when the wait object is signaled.
- *
- *  Please note if identical wait objects are inserted, only first one is
- *  ever signalled.
+/**@ingroup su_wait
  * 
- * @param self	     pointer to port
- * @param root	     pointer to root object
- * @param waits	     pointer to wait object
- * @param callback   callback function pointer
- * @param arg	     argument given to callback function when it is invoked
- * @param priority   relative priority of the wait object 
- *              (0 is normal, 1 important, 2 realtime)
+ * @page su_clone_t Clone Objects
+ *
+ * The process may be divided into many tasks via cloning. Several tasks may
+ * run in context of one thread, or each task may be run by its own thread. 
+ * However, only a single thread can execute code within a task. There can
+ * be a 1-to-N mapping from thread to tasks. Thus, software using tasks can
+ * be executed by multiple threads in a multithreaded environment and by a
+ * single thread in a singlethreaded environment.
  * 
- * @return
- *   Positive index of the wait object, 
- *   or -1 upon an error.
- */
-int su_port_register(su_port_t *self,
-		     su_root_t *root, 
-		     su_wait_t *wait, 
-		     su_wakeup_f callback,
-		     su_wakeup_arg_t *arg,
-		     int priority)
-{
-  int i, j, n;
-
-  assert(SU_PORT_OWN_THREAD(self));
-
-  n = self->sup_n_waits;
-
-  if (n >= SU_WAIT_MAX)
-    return su_seterrno(ENOMEM);
-
-  if (n >= self->sup_size_waits) {
-    /* Reallocate size arrays */
-    int size;
-    int *indices;
-    int *reverses;
-    su_wait_t *waits;
-    su_wakeup_f *wait_cbs;
-    su_wakeup_arg_t **wait_args;
-    su_root_t **wait_tasks;
-
-    if (self->sup_size_waits == 0)
-      size = su_root_size_hint;
-    else 
-      size = 2 * self->sup_size_waits;
-
-    if (size < SU_WAIT_MIN)
-      size = SU_WAIT_MIN;
-
-    /* Too large */
-    if (-3 - size > 0)
-      return (errno = ENOMEM), -1;
-
-    indices = realloc(self->sup_indices, (size + 1) * sizeof(*indices));
-    if (indices) {
-      self->sup_indices = indices;
-
-      if (self->sup_size_waits == 0)
-	indices[0] = -1;
-
-      for (i = self->sup_size_waits + 1; i <= size; i++)
-	indices[i] = -1 - i;
-    }
-
-    reverses = realloc(self->sup_reverses, size * sizeof(*waits));
-    if (reverses) {
-      for (i = self->sup_size_waits; i < size; i++)
-	reverses[i] = -1;
-      self->sup_reverses = reverses;
-    }
-      
-    waits = realloc(self->sup_waits, size * sizeof(*waits));
-    if (waits)
-      self->sup_waits = waits;
-
-    wait_cbs = realloc(self->sup_wait_cbs, size * sizeof(*wait_cbs));
-    if (wait_cbs)
-      self->sup_wait_cbs = wait_cbs;
-
-    wait_args = realloc(self->sup_wait_args, size * sizeof(*wait_args));
-    if (wait_args)
-      self->sup_wait_args = wait_args;
-
-    /* Add sup_wait_roots array, if needed */
-    wait_tasks = realloc(self->sup_wait_roots, size * sizeof(*wait_tasks));
-    if (wait_tasks) 
-      self->sup_wait_roots = wait_tasks;
-
-    if (!(indices && 
-	  reverses && waits && wait_cbs && wait_args && wait_tasks)) {
-      return -1;
-    }
-
-    self->sup_size_waits = size;
-  }
-
-  i = -self->sup_indices[0]; assert(i <= self->sup_size_waits);
-
-#if HAVE_EPOLL
-  if (self->sup_epoll != -1) {
-    struct epoll_event ev;
-
-    ev.events = POLL2EPOLL(wait->events);
-    ev.data.u64 = 0;
-    ev.data.u32 = (uint32_t)i;
-
-    if (epoll_ctl(self->sup_epoll, EPOLL_CTL_ADD, wait->fd, &ev) == -1) {
-      SU_DEBUG_0(("EPOLL_CTL_ADD(%u, %u) failed: %s\n",
-		  wait->fd, ev.events, strerror(errno)));
-      return -1;
-    }
-  }
-  else
-#endif  
-  if (priority > 0) {
-    /* Insert */
-    for (n = self->sup_n_waits; n > 0; n--) {
-      j = self->sup_reverses[n-1]; assert(self->sup_indices[j] == n - 1);
-      self->sup_indices[j] = n;
-      self->sup_reverses[n] = j;
-      self->sup_waits[n] = self->sup_waits[n-1];
-      self->sup_wait_cbs[n] = self->sup_wait_cbs[n-1];
-      self->sup_wait_args[n] = self->sup_wait_args[n-1];
-      self->sup_wait_roots[n] = self->sup_wait_roots[n-1];	
-    }
-
-    self->sup_pri_offset++;
-  }
-  else {
-    /* Append - no need to move anything */
-    n = self->sup_n_waits;
-  }
-
-  self->sup_n_waits++;
-
-  self->sup_indices[0] = self->sup_indices[i];  /* Free index */
-  self->sup_indices[i] = n;
-
-  self->sup_reverses[n] = i;
-  self->sup_waits[n] = *wait;
-  self->sup_wait_cbs[n] = callback;
-  self->sup_wait_args[n] = arg;
-  self->sup_wait_roots[n] = root;
-
-  self->sup_registers++;
-
-  /* Just like epoll, we return -1 or positive integer */
-
-  return i;
-}
-
-/** Deregister a su_wait_t object. */
-static
-int su_port_deregister0(su_port_t *self, int i)
-{
-  int n, N, *indices, *reverses;
-
-  indices = self->sup_indices;
-  reverses = self->sup_reverses;
-
-  n = indices[i]; assert(n >= 0);
-
-#if HAVE_EPOLL
-  if (self->sup_epoll != -1) {
-    su_wait_t *wait = &self->sup_waits[n];
-    struct epoll_event ev;
-
-    ev.events = POLL2EPOLL(wait->events);
-    ev.data.u64 = (uint64_t)0;
-    ev.data.u32 = (uint32_t)i;
-
-    if (epoll_ctl(self->sup_epoll, EPOLL_CTL_DEL, wait->fd, &ev) == -1) {
-      SU_DEBUG_1(("su_port(%p): EPOLL_CTL_DEL(%u): %s\n", self, 
-		  wait->fd, su_strerror(su_errno())));
-    }
-  }
-#endif
-
-  N = --self->sup_n_waits;
-  
-  if (n < self->sup_pri_offset) {
-    int j = --self->sup_pri_offset;
-    if (n != j) {
-      assert(reverses[j] > 0);
-      assert(indices[reverses[j]] == j);
-      indices[reverses[j]] = n;
-      reverses[n] = reverses[j];
-
-      self->sup_waits[n] = self->sup_waits[j];
-      self->sup_wait_cbs[n] = self->sup_wait_cbs[j];
-      self->sup_wait_args[n] = self->sup_wait_args[j];
-      self->sup_wait_roots[n] = self->sup_wait_roots[j];
-      n = j;
-    }
-  }
-
-  if (n < N) {
-    assert(reverses[N] > 0);
-    assert(indices[reverses[N]] == N);
-
-    indices[reverses[N]] = n;
-    reverses[n] = reverses[N];
-
-    self->sup_waits[n] = self->sup_waits[N];
-    self->sup_wait_cbs[n] = self->sup_wait_cbs[N];
-    self->sup_wait_args[n] = self->sup_wait_args[N];
-    self->sup_wait_roots[n] = self->sup_wait_roots[N];
-    n = N;
-  }
-
-  reverses[n] = -1;
-  memset(&self->sup_waits[n], 0, sizeof self->sup_waits[n]);
-  self->sup_wait_cbs[n] = NULL;
-  self->sup_wait_args[n] = NULL;
-  self->sup_wait_roots[n] = NULL;
-  
-  indices[i] = indices[0];
-  indices[0] = -i;
-
-  self->sup_registers++;
-
-  return i;
-}
-
-
-/** Unregister a su_wait_t object.
- *  
- *  The function su_port_unregister() unregisters a su_wait_t object. The
- *  wait object, a callback function and a argument are removed from the
- *  port object.
+ * The clones are useful for handling tasks that can be executed by a
+ * separate threads, but which do not block excessively. When threads are
+ * not available or they are not needed, clones can also be run in a
+ * single-threaded mode. Running in single-threaded mode is especially
+ * useful while debugging.
  * 
- * @param self     - pointer to port object
- * @param root     - pointer to root object
- * @param wait     - pointer to wait object
- * @param callback - callback function pointer (may be NULL)
- * @param arg      - argument given to callback function when it is invoked 
- *                   (may be NULL)
+ * A clone task is created with function su_clone_start(). Each clone has
+ * its own root object (su_root_t), which holds a context pointer
+ * (su_root_magic_t *). The context object can be different from that of 
+ * parent task.
  *
- * @deprecated Use su_port_deregister() instead. 
+ * When a clone is started, the clone initialization function is called. The
+ * initialization function should do whatever initialization there is to be
+ * performed, register I/O events and timers, and then return. If the
+ * initialization is successful, the clone task reverts to run the event
+ * loop and invoking the event callbacks until its parent stops it by
+ * calling su_clone_wait() which invokes the deinit function. The clone task
+ * is destroyed when the deinit function returns. 
  *
- * @return Nonzero index of the wait object, or -1 upon an error.
+ * The public API consists of following functions:
+ *    - su_clone_start()
+ *    - su_clone_task()
+ *    - su_clone_wait()
+ *    - su_clone_forget()
+ *
+ * @note 
+ * There is only one event loop for each thread which can be shared by
+ * multiple clone tasks. Therefore, the clone tasks can not explicitly run
+ * or step the event loop, but they are limited to event callbacks. A clone
+ * task may not call su_root_break(), su_root_run() or su_root_step().
  */
-int su_port_unregister(su_port_t *self,
-		       su_root_t *root, 
-		       su_wait_t *wait,	
-		       su_wakeup_f callback, /* XXX - ignored */
-		       su_wakeup_arg_t *arg)
-{
-  int n, N;
 
-  assert(self);
-  assert(SU_PORT_OWN_THREAD(self));
-
-  N = self->sup_n_waits;
-
-  for (n = 0; n < N; n++) {
-    if (SU_WAIT_CMP(wait[0], self->sup_waits[n]) == 0) {
-      return su_port_deregister0(self, self->sup_reverses[n]);
-    }
-  }
-
-  su_seterrno(ENOENT);
-
-  return -1;
+static int su_root_init_nothing(su_root_t *root, su_root_magic_t *magic)
+{
+  return 0;
 }
 
-/** Deregister a su_wait_t object.
- *  
- *  The function su_port_deregister() deregisters a su_wait_t registrattion. 
- *  The wait object, a callback function and a argument are removed from the
- *  port object.
- * 
- * @param self     - pointer to port object
- * @param i        - registration index
- * 
- * @return Index of the wait object, or -1 upon an error.
- */
-int su_port_deregister(su_port_t *self, int i)
+static void su_root_deinit_nothing(su_root_t *root, su_root_magic_t *magic)
 {
-  su_wait_t wait[1] = { SU_WAIT_INIT };
-  int retval;
-
-  assert(self);
-  assert(SU_PORT_OWN_THREAD(self));
-
-  if (i <= 0 || i > self->sup_size_waits)
-    return su_seterrno(EBADF);
-
-  if (self->sup_indices[i] < 0)
-    return su_seterrno(EBADF);
-    
-  retval = su_port_deregister0(self, i);
-
-  su_wait_destroy(wait);
-
-  return retval;
 }
 
-
-/** @internal
- * Unregister all su_wait_t objects.
+/** Start a clone task.
  *
- * The function su_port_unregister_all() unregisters all su_wait_t objects
- * and destroys all queued timers associated with given root object.
- * 
- * @param  self     - pointer to port object
- * @param  root     - pointer to root object
- * 
- * @return Number of wait objects removed.
- */
-int su_port_unregister_all(su_port_t *self, 
-			   su_root_t *root)
-{
-  int i, j, index, N;
-  int             *indices, *reverses;
-  su_wait_t       *waits;
-  su_wakeup_f     *wait_cbs;
-  su_wakeup_arg_t**wait_args;
-  su_root_t      **wait_roots;
-
-  assert(SU_PORT_OWN_THREAD(self));
-
-  N          = self->sup_n_waits;
-  indices    = self->sup_indices;
-  reverses   = self->sup_reverses;
-  waits      = self->sup_waits; 
-  wait_cbs   = self->sup_wait_cbs; 
-  wait_args  = self->sup_wait_args;
-  wait_roots = self->sup_wait_roots; 
-  
-  for (i = j = 0; i < N; i++) {
-    index = reverses[i]; assert(index > 0 && indices[index] == i);
-
-    if (wait_roots[i] == root) {
-      /* XXX - we should free all resources associated with this, too */
-#if HAVE_EPOLL
-      if (self->sup_epoll != -1) {
-	int fd = waits[i].fd;
-	struct epoll_event ev;
-
-	ev.events = POLL2EPOLL(waits[i].events);
-	ev.data.u64 = (uint64_t)0;
-	ev.data.u32 = (uint32_t)index;
-
-	if (epoll_ctl(self->sup_epoll, EPOLL_CTL_DEL, fd, &ev) == -1) {
-	  SU_DEBUG_1(("EPOLL_CTL_DEL(%u): %s\n", 
-		      waits[i].fd, su_strerror(su_errno())));
-	}
-      }
-#endif
-      if (i < self->sup_pri_offset)
-	self->sup_pri_offset--;
+ * Allocate and initialize a sub-task. Depending on the su_root_threading()
+ * settings, a separate thread may be created to execute the sub-task. The
+ * sub-task is represented by clone handle to the rest of the application. 
+ * The function su_clone_start() returns the clone handle in @a
+ * return_clone. The clone handle is used to communicate with the newly
+ * created clone task using messages.
+ *
+ * A new #su_root_t object is created for the sub-task with the @a magic as
+ * the root context pointer. Because the sub-task may or may not have its
+ * own thread, all its activity must be scheduled via this root object. In
+ * other words, the sub-task can be schedule
+ * -# I/O events with su_root_register()
+ * -# timers with su_timer_set(), su_timer_set_at() or su_timer_run()
+ * -# messages with su_msg_send().
+ *
+ * Messages can also be used to pass information between tasks or threads.
+ *
+ * In multi-threaded implementation, su_clone_start() launches a new thread,
+ * and the initialization routine is executed by this newly created thread. 
+ * The calling thread blocks until the initialization routine completes. If
+ * the initialization routine returns #su_success (0), the sub-task is
+ * considered to be created successfully. After the successful
+ * initialization, the sub-task continues to execeute the function
+ * su_root_run().
+ *
+ * In single-threaded implementations, just a new root object is created. 
+ * The initialization routine is called directly from su_clone_start().
+ *
+ * If the initalization function @a init fails, the sub-task (either the
+ * newly created thread or the current thread executing the su_clone_start()
+ * function) calls the deinitialization function, and su_clone_start()
+ * returns NULL.
+ *
+ * @param parent   root to be cloned
+ * @param return_clone reference to a clone [OUT]
+ * @param magic    pointer to user data
+ * @param init     initialization function
+ * @param deinit   deinitialization function
+ *
+ * @return 0 if successfull, -1 upon an error.
+ *
+ * @note Earlier documentation mentioned that @a parent could be NULL. That
+ * feature has never been implemented, however.
+ *
+ * @sa su_root_threading(), su_clone_task(), su_clone_stop(), su_clone_wait(),
+ * su_clone_forget().
+ */
+int su_clone_start(su_root_t *parent,
+		   su_clone_r return_clone,
+		   su_root_magic_t *magic,
+		   su_root_init_f init,
+		   su_root_deinit_f deinit)
+{
+  su_port_vtable_t const *svp;
+
+  if (init == NULL)
+    init = su_root_init_nothing;
+  if (deinit == NULL)
+    deinit = su_root_deinit_nothing;
 
-      indices[index] = indices[0];
-      indices[0] = -index;
-      continue;
-    }
-
-    if (i != j) {
-      indices[index] = j;
-      reverses[j]   = reverses[i];
-      waits[j]      = waits[i];
-      wait_cbs[j]   = wait_cbs[i];
-      wait_args[j]  = wait_args[i];
-      wait_roots[j] = wait_roots[i];
-    }
     
-    j++;
+  if (parent == NULL || parent->sur_threading) {
+    if (preferred_su_clone_start == NULL)
+      su_port_set_system_preferences(getenv("SU_PORT"));
+    return preferred_su_clone_start(parent, return_clone, magic, init, deinit);
   }
-  
-  for (i = j; i < N; i++) {
-    reverses[i] = -1;
-    wait_cbs[i] = NULL;
-    wait_args[i] = NULL;
-    wait_roots[i] = NULL;
-  }
-  memset(&waits[j], 0, (char *)&waits[N] - (char *)&waits[j]);
 
-  self->sup_n_waits = j;
-  self->sup_registers++;
+  svp = parent->sur_task->sut_port->sup_vtable;
+
+  if (svp->su_port_start_shared == NULL)
+    return su_seterrno(EINVAL);
 
-  return N - j;
+  /* Return a task sharing the same port. */
+  return svp->su_port_start_shared(parent, return_clone, magic, init, deinit);
 }
 
-/**Set mask for a registered event. @internal
- *
- * The function su_port_eventmask() sets the mask describing events that can
- * signal the registered callback.
- *
- * @param port   pointer to port object
- * @param index  registration index
- * @param socket socket
- * @param events new event mask
+/** Get reference to a clone task.
+ * 
+ * @param clone Clone pointer
  *
- * @retval 0 when successful,
- * @retval -1 upon an error.
+ * @return A reference to the task structure of the clone.
  */
-int su_port_eventmask(su_port_t *self, int index, int socket, int events)
+_su_task_r su_clone_task(su_clone_r clone)
 {
-  int n;
-  assert(self);
-  assert(SU_PORT_OWN_THREAD(self));
-
-  if (index <= 0 || index > self->sup_size_waits)
-    return su_seterrno(EBADF);
-  n = self->sup_indices[index];
-  if (n < 0)
-    return su_seterrno(EBADF);
-
-#if HAVE_EPOLL
-  if (self->sup_epoll != -1) {
-    su_wait_t *wait = &self->sup_waits[n];
-    struct epoll_event ev;
-
-    wait->events = events;
-
-    ev.events = POLL2EPOLL(events);
-    ev.data.u64 = (uint64_t)0;
-    ev.data.u32 = (uint32_t)index;
-
-    if (epoll_ctl(self->sup_epoll, EPOLL_CTL_MOD, wait->fd, &ev) == -1) {
-      SU_DEBUG_1(("su_port(%p): EPOLL_CTL_MOD(%u): %s\n", self, 
-		  wait->fd, su_strerror(su_errno())));
-      return -1;
-    }
-  }
-#endif
-
-  return su_wait_mask(&self->sup_waits[n], socket, events);
+  return su_msg_to(clone);
 }
 
-#if 0
-/** @internal
- *
- * Copies the su_wait_t objects from the port. The number of wait objects
- * can be found out by calling su_port_query() with @a n_waits as zero.
+/**Forget the clone.
  * 
- * @note This function is called only by friends.
+ * Normally, the clone task executes until it is stopped.  If the parent
+ * task does not need to stop the task, it can "forget" the clone.  The
+ * clone exits independently of the parent task.
  *
- * @param self     - pointer to port object
- * @param waits    - pointer to array to which wait objects are copied
- * @param n_waits  - number of wait objects fitting in array waits
- *
- * @return Number of wait objects, or 0 upon an error.
+ * @param rclone Reference to the clone.
  */
-unsigned su_port_query(su_port_t *self, su_wait_t *waits, unsigned n_waits)
+void su_clone_forget(su_clone_r rclone)
 {
-  unsigned n;
-
-  assert(SU_PORT_OWN_THREAD(self));
-
-  n = self->sup_n_waits;
-
-  if (n_waits != 0) {
-    if (waits && n_waits >= n)
-      memcpy(waits, self->sup_waits, n * sizeof(*waits));
-    else
-      n = 0;
-  }
-
-  return n;
+  su_msg_destroy(rclone);
 }
-#endif
 
-/** @internal Enable multishot mode.
+/** Stop the clone.
  *
- * The function su_port_multishot() enables, disables or queries the
- * multishot mode for the port. The multishot mode determines how the events
- * are scheduled by port. If multishot mode is enabled, port serves all the
- * sockets that have received network events. If it is disables, only first
- * socket event is served.
- *
- * @param self      pointer to port object
- * @param multishot multishot mode (0 => disables, 1 => enables, -1 => query)
+ * This can used only if clone task has sent no report messages (messages
+ * with delivery report sent back to clone).
  * 
- * @retval 0 multishot mode is disabled
- * @retval 1 multishot mode is enabled
- * @retval -1 an error occurred
+ * @deprecated. Use su_clone_wait().
  */
-int su_port_multishot(su_port_t *self, int multishot)
-{
-  if (multishot < 0)
-    return self->sup_multishot;
-  else if (multishot == 0 || multishot == 1)
-    return self->sup_multishot = multishot;
-  else 
-    return (errno = EINVAL), -1;
-}
-
-/** @internal Enable threadsafe operation. */
-static
-int su_port_threadsafe(su_port_t *port)
+void su_clone_stop(su_clone_r rclone)
 {
-  return su_home_threadsafe(port->sup_home);
+  su_msg_send(rclone);
 }
 
-/** @internal Main loop.
- * 
- * The function @c su_port_run() waits for wait objects and the timers
- * associated with the port object.  When any wait object is signaled or
- * timer is expired, it invokes the callbacks, and returns waiting.
- * 
- * The function @c su_port_run() runs until @c su_port_break() is called
- * from a callback.
- * 
- * @param self     pointer to port object
- * 
+/** Stop a clone and wait until it is has completed.
+ *
+ * The function su_clone_wait() is used to stop the clone task and wait
+ * until it has cleaned up. The clone task is destroyed asynchronously. The
+ * parent sends a message to clone, clone deinitializes itself and then
+ * replies. After the reply message is received by the parent, it will send
+ * a third message back to clone.
+ *
+ * The parent destroy all messages to or from clone task before calling
+ * su_clone_wait(). The parent task may not send any messages to the clone
+ * after calling su_clone_wait(). The su_clone_wait() function blocks until
+ * the cloned task is destroyed. During that time, the parent task must be
+ * prepared to process all the messages sent by clone task. This includes
+ * all the messages sent by clone before destroy the message reached the
+ * clone.
  */
-void su_port_run(su_port_t *self)
+void su_clone_wait(su_root_t *root, su_clone_r rclone)
 {
-  su_duration_t tout = 0;
-
-  assert(SU_PORT_OWN_THREAD(self));
-
-  for (self->sup_running = 1; self->sup_running;) {
-    tout = 2000;
-
-    if (self->sup_prepoll)
-      self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
-
-    if (self->sup_head)
-      su_port_getmsgs(self);
-
-    if (self->sup_timers)
-      su_timer_expire(&self->sup_timers, &tout, su_now());
-
-    if (!self->sup_running)
-      break;
-
-    if (self->sup_head)      /* if there are messages do a quick wait */
-      tout = 0;
-
-    su_port_wait_events(self, tout);
+  if (rclone[0]) {
+    assert(root == NULL || root == su_msg_from(rclone)->sut_root);
+    su_port_wait(rclone);
   }
 }
 
-#if tuning
-/* This version can help tuning... */
-void su_port_run_tune(su_port_t *self)
-{
-  int i;
-  int timers = 0, messages = 0, events = 0;
-  su_duration_t tout = 0, tout0;
-  su_time_t started = su_now(), woken = started, bedtime = woken;
-
-  assert(SU_PORT_OWN_THREAD(self));
-
-  for (self->sup_running = 1; self->sup_running;) {
-    tout0 = tout, tout = 2000;
-
-    timers = 0, messages = 0;
-
-    if (self->sup_prepoll)
-      self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
-
-    if (self->sup_head)
-      messages = su_port_getmsgs(self);
-
-    if (self->sup_timers)
-      timers = su_timer_expire(&self->sup_timers, &tout, su_now());
-
-    if (!self->sup_running)
-      break;
-
-    if (self->sup_head)      /* if there are messages do a quick wait */
-      tout = 0;
-
-    bedtime = su_now();
-
-    events = su_port_wait_events(self, tout);
-
-    woken = su_now();
-
-    if (messages || timers || events)
-      SU_DEBUG_1(("su_port_run(%p): %.6f: %u messages %u timers %u "
-		  "events slept %.6f/%.3f\n",
-		  self, su_time_diff(woken, started), messages, timers, events,
-		  su_time_diff(woken, bedtime), tout0 * 1e-3));
-
-    if (!self->sup_running)
-      break;
-  }
-}
-#endif
-
-/** @internal
- * The function @c su_port_break() is used to terminate execution of @c
- * su_port_run(). It can be called from a callback function.
- * 
- * @param self     pointer to port
- * 
- */
-void su_port_break(su_port_t *self)
-{
-  self->sup_running = 0; 
-}
-
-/** @internal
- * The function @c su_port_wait_events() is used to poll() for wait objects
+/** Pause a clone.
  *
- * @param self     pointer to port
- * @param tout     timeout in milliseconds
+ * Obtain an exclusive lock on clone's private data.
  *
- * @return number of events handled
+ * @retval 0 if successful (and clone is paused)
+ * @retval -1 upon an error
+ *
+ * @deprecated Never implemented.
  */
-static
-int su_port_wait_events(su_port_t *self, su_duration_t tout)
+int su_clone_pause(su_clone_r rclone)
 {
-  int i, events = 0;
-  su_wait_t *waits = self->sup_waits;
-  int n = self->sup_n_waits;
-  su_root_t *root;
-#if HAVE_POLL
-  unsigned version = self->sup_registers;
-#endif
-#if HAVE_EPOLL
-  
-  if (self->sup_epoll != -1) {
-    int const M = 4;
-    struct epoll_event ev[M];
-    int j, index;
-    int *indices = self->sup_indices;
-    
-    n = epoll_wait(self->sup_epoll, ev, self->sup_multishot ? M : 1, tout);
-
-    assert(n <= M);
+#if 0
+  su_root_t *cloneroot = su_task_root(su_msg_to(rclone));
 
-    for (j = 0; j < n; j++) {
-      su_root_t *root;
-      su_root_magic_t *magic;
-
-      if (!ev[j].events || ev[j].data.u32 > INDEX_MAX)
-	continue;
-      index = (int)ev[j].data.u32;
-      assert(index > 0 && index <= self->sup_size_waits);
-      i = indices[index]; assert(i >= 0 && i <= self->sup_n_waits);
-      root = self->sup_wait_roots[i];
-      magic = root ? su_root_magic(root) : NULL;
-      waits[i].revents = ev[j].events;
-      self->sup_wait_cbs[i](magic, &waits[i], self->sup_wait_args[i]);
-      events++;
-      /* Callback function used su_register()/su_deregister() */
-      if (version != self->sup_registers)
-	break;
-    }
-    
-    return n < 0 ? n : events;
-  }
-#endif
+  if (!cloneroot)
+    return (errno = EFAULT), -1;
 
-  i = su_wait(waits, (unsigned)n, tout);
+  if (SU_ROOT_OWN_THREAD(cloneroot))
+    /* We own it already */
+    return 0;
 
-  if (i >= 0 && i < n) {
-#if HAVE_POLL			
-    /* poll() can return events for multiple wait objects */
-    if (self->sup_multishot) {
-      for (; i < n; i++) {
-        if (waits[i].revents) {
-          root = self->sup_wait_roots[i];
-          self->sup_wait_cbs[i](root ? su_root_magic(root) : NULL,
-                                &waits[i],
-                                self->sup_wait_args[i]);
-          events++;
-          /* Callback function used su_register()/su_deregister() */
-          if (version != self->sup_registers)
-            break;
-        }
-      }
-    }
-#else /* !HAVE_POLL */
-    if (0) {
-    }
+  return su_port_pause(cloneroot->sur_port);
+#else
+  return errno = ENOSYS, -1;
 #endif
-    else {
-      root = self->sup_wait_roots[i];
-      self->sup_wait_cbs[i](root ? su_root_magic(root) : NULL,
-                            &self->sup_waits[i],
-                            self->sup_wait_args[i]);
-      events++;
-    }
-  }
-
-  return events;
 }
 
-/** @internal 
- * Used to check wait events in callbacks that take lots of time
- *
- * This function does a timeout 0 poll() and runs wait objects.
- *
- * @param port     pointer to port
+/** Resume a clone.
  *
- * @return number of events handled
- */
-static
-int su_port_yield(su_port_t *port)
-{
-  return su_port_wait_events(port, 0);
-}
-
-/** @internal Block until wait object is signaled or timeout.
+ * Give up an exclusive lock on clone's private data.
  *
- * This function waits for wait objects and the timers associated with 
- * the root object.  When any wait object is signaled or timer is
- * expired, it invokes the callbacks. 
- * 
- *   This function returns when a callback has been invoked or @c tout
- *   milliseconds is elapsed. 
+ * @retval 0 if successful (and clone is resumed)
+ * @retval -1 upon an error
  *
- * @param self     pointer to port
- * @param tout     timeout in milliseconds
- * 
- * @return
- *   Milliseconds to the next invocation of timer, or @c SU_WAIT_FOREVER if
- *   there are no active timers.
+ * @deprecated Never implemented.
  */
-su_duration_t su_port_step(su_port_t *self, su_duration_t tout)
+int su_clone_resume(su_clone_r rclone)
 {
-  su_time_t now = su_now();
-
-  assert(SU_PORT_OWN_THREAD(self));
-
-  if (self->sup_prepoll)
-    self->sup_prepoll(self->sup_pp_magic, self->sup_pp_root);
-
-  if (self->sup_head)
-    su_port_getmsgs(self);
-
-  if (self->sup_timers)
-    su_timer_expire(&self->sup_timers, &tout, now);
-
-  /* if there are messages do a quick wait */
-  if (self->sup_head)
-    tout = 0;
-
-  if (su_port_wait_events(self, tout))
-    tout = 0;
-  else
-    tout = SU_WAIT_FOREVER;
-
-  if (self->sup_head)
-    su_port_getmsgs(self);
+#if 0
+  su_root_t *cloneroot = su_task_root(su_msg_to(rclone));
 
-  if (self->sup_timers)
-    su_timer_expire(&self->sup_timers, &tout, su_now());
+  if (!cloneroot)
+    return (errno = EFAULT), -1;
 
-  if (self->sup_head)
-    tout = 0;
+  if (SU_ROOT_OWN_THREAD(cloneroot))
+    /* We cannot give it away */
+    return 0;
 
-  return tout;
+  return su_port_resume(cloneroot->sur_port);
+#else
+  return errno = ENOSYS, -1;
+#endif
 }
 
-
-/** @internal
- * Checks if the calling thread owns the port object.
- *
- * @param self pointer to a port object
- *
- * @retval true (nonzero) if the calling thread owns the port,
- * @retval false (zero) otherwise.
- */
-int su_port_own_thread(su_port_t const *self)
+void su_port_wait(su_clone_r rclone)
 {
-  return self == NULL || SU_PORT_OWN_THREAD(self);
-}
+  su_port_t *cloneport;
 
-#if 0
-/** @internal
- *  Prints out the contents of the port.
- *
- * @param self pointer to a port
- * @param f    pointer to a file (if @c NULL, uses @c stdout).
- */
-void su_port_dump(su_port_t const *self, FILE *f)
-{
-  int i;
-#define IS_WAIT_IN(x) (((x)->events & SU_WAIT_IN) ? "IN" : "")
-#define IS_WAIT_OUT(x) (((x)->events & SU_WAIT_OUT) ? "OUT" : "")
-#define IS_WAIT_ACCEPT(x) (((x)->events & SU_WAIT_ACCEPT) ? "ACCEPT" : "")
-
-  if (f == NULL)
-    f = stdout;
-
-  fprintf(f, "su_port_t at %p:\n", self);
-  fprintf(f, "\tport is%s running\n", self->sup_running ? "" : "not ");
-#if SU_HAVE_PTHREADS
-  fprintf(f, "\tport tid %p\n", (void *)self->sup_tid);
-#endif
-#if SU_HAVE_MBOX
-  fprintf(f, "\tport mbox %d (%s%s%s)\n", self->sup_mbox[0],
-	  IS_WAIT_IN(&self->sup_mbox_wait),
-	  IS_WAIT_OUT(&self->sup_mbox_wait),
-	  IS_WAIT_ACCEPT(&self->sup_mbox_wait));
-#endif
-  fprintf(f, "\t%d wait objects\n", self->sup_n_waits);
-  for (i = 0; i < self->sup_n_waits; i++) {
-    
-  }
+  cloneport = su_msg_to(rclone)->sut_port;
+  cloneport->sup_vtable->su_port_wait(rclone);
 }
 
-#endif
-
-/* =========================================================================
- * Pre-poll() callback
- */
-
-int su_port_add_prepoll(su_port_t *port,
-			su_root_t *root, 
-			su_prepoll_f *callback, 
-			su_prepoll_magic_t *magic)
+int su_port_execute(su_task_r const task,
+		    int (*function)(void *), void *arg,
+		    int *return_value)
 {
-  if (port->sup_prepoll)
-    return -1;
-
-  port->sup_prepoll = callback;
-  port->sup_pp_magic = magic;
-  port->sup_pp_root = root;
+  if (!task->sut_port->sup_vtable->su_port_execute)
+    return errno = ENOSYS, -1;
 
-  return 0;
+  return task->sut_port->sup_vtable->
+    su_port_execute(task, function, arg, return_value);
 }
 
-int su_port_remove_prepoll(su_port_t *port,
-			   su_root_t *root)
+#if notyet && nomore
+int su_port_pause(su_port_t *self)
 {
-  if (port->sup_pp_root != root)
-    return -1;
-
-  port->sup_prepoll = NULL;
-  port->sup_pp_magic = NULL;
-  port->sup_pp_root = NULL;
-
-  return 0;
+  assert(self->sup_vtable->su_port_pause);
+  return self->sup_vtable->su_port_pause(self);
 }
 
-/* =========================================================================
- * Timers
- */
-
-static
-su_timer_t **su_port_timers(su_port_t *self)
+int su_port_resume(su_port_t *self)
 {
-  return &self->sup_timers;
+  assert(self->sup_vtable->su_port_resume);
+  return self->sup_vtable->su_port_resume(self);
 }
+#endif

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_port.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_port.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_port.h	Tue Apr 24 10:14:28 2007
@@ -86,7 +86,7 @@
 #define SU_ROOT_MAGIC(r) ((r) ? (r)->sur_magic : NULL)
 
 /** Virtual function table for port */
-typedef struct {
+typedef struct su_port_vtable {
   unsigned su_vtable_size;
   void (*su_port_lock)(su_port_t *port, char const *who);
   void (*su_port_unlock)(su_port_t *port, char const *who);
@@ -128,80 +128,114 @@
   int (*su_port_multishot)(su_port_t *port, int multishot);
 
   int (*su_port_threadsafe)(su_port_t *port);
-  
   /* Extension from > 1.12.0 */
   int (*su_port_yield)(su_port_t *port);
+  /* Extension from >= 1.12.4 */
+  int (*su_port_wait_events)(su_port_t *port, su_duration_t timeout);
+  int (*su_port_getmsgs)(su_port_t *port);
+  /* Extension from >= 1.12.5 */
+  int (*su_port_getmsgs_from)(su_port_t *port, su_port_t *cloneport);
+  char const *(*su_port_name)(su_port_t const *port);
+  int (*su_port_start_shared)(su_root_t *root,
+			      su_clone_r return_clone,
+			      su_root_magic_t *magic,
+			      su_root_init_f init,
+			      su_root_deinit_f deinit);
+  void (*su_port_wait)(su_clone_r rclone);
+  int (*su_port_execute)(su_task_r const task,
+			 int (*function)(void *), void *arg,
+			 int *return_value);  
 } su_port_vtable_t;
 
 SOFIAPUBFUN su_port_t *su_port_create(void)
      __attribute__((__malloc__));
 
+/* Extension from >= 1.12.5 */
+
 SOFIAPUBFUN void su_msg_delivery_report(su_msg_r msg);
 SOFIAPUBFUN su_duration_t su_timer_next_expires(su_timer_t const * t,
 						su_time_t now);
 SOFIAPUBFUN su_root_t *su_root_create_with_port(su_root_magic_t *magic,
-						su_port_t *port);
+						su_port_t *port)
+  __attribute__((__malloc__));
+
+/* Extension from >= 1.12.6 */
 
-#if SU_PORT_IMPLEMENTATION
+SOFIAPUBFUN char const *su_port_name(su_port_t const *port);
 
+/* ---------------------------------------------------------------------- */
+
+/* React to multiple events per one poll() to make sure 
+ * that high-priority events can never completely mask other events.
+ * Enabled by default on all platforms except WIN32 */
+#if !defined(WIN32)
+#define SU_ENABLE_MULTISHOT_POLL 1
 #else
-struct su_port_s {
-  su_home_t               sup_home[1];
+#define SU_ENABLE_MULTISHOT_POLL 0
+#endif
+
+/* ---------------------------------------------------------------------- */
+/* Virtual functions */
+
+typedef struct su_virtual_port_s {
+  su_home_t        sup_home[1];
   su_port_vtable_t const *sup_vtable;
-};
+} su_virtual_port_t;
+
+static inline
+su_home_t *su_port_home(su_port_t const *self)
+{
+  return (su_home_t *)self;
+}
 
 static inline
 void su_port_lock(su_port_t *self, char const *who)
 {
-  if (self) self->sup_vtable->su_port_lock(self, who);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base) base->sup_vtable->su_port_lock(self, who);
 }
 
-#define SU_PORT_LOCK(p, f)      (su_port_lock(p, #f))
- 
 static inline
 void su_port_unlock(su_port_t *self, char const *who)
 {
-  if (self) self->sup_vtable->su_port_unlock(self, who);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base) base->sup_vtable->su_port_unlock(self, who);
 }
 
-#define SU_PORT_UNLOCK(p, f)    (su_port_unlock(p, #f))
-
 static inline
 void su_port_incref(su_port_t *self, char const *who)
 {
-  if (self) self->sup_vtable->su_port_incref(self, who);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base) base->sup_vtable->su_port_incref(self, who);
 }
 
-#define SU_PORT_INCREF(p, f)    (su_port_incref(p, #f))
- 
 static inline
 void su_port_decref(su_port_t *self, char const *who)
 {
-  if (self) self->sup_vtable->su_port_decref(self, 0, who);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base) base->sup_vtable->su_port_decref(self, 0, who);
 }
 
-#define SU_PORT_DECREF(p, f)    (su_port_decref(p, #f))
-
 static inline
 void su_port_zapref(su_port_t *self, char const *who)
 {
-  if (self) self->sup_vtable->su_port_decref(self, 1, who);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base) base->sup_vtable->su_port_decref(self, 1, who);
 }
 
-#define SU_PORT_ZAPREF(p, f)    (su_port_zapref(p, #f))
-
 static inline
 struct _GSource *su_port_gsource(su_port_t *self)
 {
-  return self ? self->sup_vtable->su_port_gsource(self) : NULL;
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  return base ? base->sup_vtable->su_port_gsource(self) : NULL;
 }
 
-
 static inline
 int su_port_send(su_port_t *self, su_msg_r rmsg)
 {
-  if (self) 
-    return self->sup_vtable->su_port_send(self, rmsg);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base) 
+    return base->sup_vtable->su_port_send(self, rmsg);
   errno = EINVAL;
   return -1;
 }
@@ -215,8 +249,9 @@
 		     su_wakeup_arg_t *arg,
 		     int priority)
 {
-  if (self)
-    return self->sup_vtable->su_port_register(self, root, wait,
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->su_port_register(self, root, wait,
 					      callback, arg, priority);
   errno = EINVAL;
   return -1;
@@ -229,8 +264,9 @@
 		       su_wakeup_f callback, 
 		       su_wakeup_arg_t *arg)
 {
-  if (self)
-    return self->sup_vtable->
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->
       su_port_unregister(self, root, wait, callback, arg);
   errno = EINVAL;
   return -1;
@@ -239,9 +275,9 @@
 static inline
 int su_port_deregister(su_port_t *self, int i)
 {
-  if (self)
-    return self->sup_vtable->
-      su_port_deregister(self, i);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->su_port_deregister(self, i);
   errno = EINVAL;
   return -1;
 }
@@ -250,8 +286,9 @@
 int su_port_unregister_all(su_port_t *self,
 			   su_root_t *root)
 {
-  if (self)
-    return self->sup_vtable->
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->
       su_port_unregister_all(self, root);
   errno = EINVAL;
   return -1;
@@ -260,10 +297,11 @@
 static inline
 int su_port_eventmask(su_port_t *self, int index, int socket, int events)
 {
-  if (self)
-    return self->sup_vtable->
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->
       su_port_eventmask(self, index, socket, events);
-  assert(self);
+  assert(base);
   errno = EINVAL;
   return -1;
 }
@@ -271,22 +309,25 @@
 static inline
 void su_port_run(su_port_t *self)
 {
-  if (self)
-    self->sup_vtable->su_port_run(self);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    base->sup_vtable->su_port_run(self);
 }
 
 static inline
 void su_port_break(su_port_t *self)
 {
-  if (self)
-    self->sup_vtable->su_port_break(self);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    base->sup_vtable->su_port_break(self);
 }
 
 static inline
 su_duration_t su_port_step(su_port_t *self, su_duration_t tout)
 {
-  if (self)
-    return self->sup_vtable->su_port_step(self, tout);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->su_port_step(self, tout);
   errno = EINVAL;
   return (su_duration_t)-1;
 }
@@ -295,7 +336,8 @@
 static inline
 int su_port_own_thread(su_port_t const *self)
 {
-  return self == NULL || self->sup_vtable->su_port_own_thread(self);
+  su_virtual_port_t const *base = (su_virtual_port_t *)self;
+  return base == NULL || base->sup_vtable->su_port_own_thread(self);
 }
 
 static inline
@@ -304,8 +346,9 @@
 			su_prepoll_f *prepoll, 
 			su_prepoll_magic_t *magic)
 {
-  if (self)
-    return self->sup_vtable->
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->
       su_port_add_prepoll(self, root, prepoll, magic);
   errno = EINVAL;
   return -1;
@@ -315,8 +358,9 @@
 int su_port_remove_prepoll(su_port_t *self,
 			   su_root_t *root)
 {
-  if (self)
-    return self->sup_vtable->su_port_remove_prepoll(self, root);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->su_port_remove_prepoll(self, root);
   errno = EINVAL;
   return -1;
 }
@@ -324,8 +368,9 @@
 static inline
 su_timer_t **su_port_timers(su_port_t *self)
 {
-  if (self)
-    return self->sup_vtable->su_port_timers(self);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->su_port_timers(self);
   errno = EINVAL;
   return NULL;
 }
@@ -333,10 +378,11 @@
 static inline
 int su_port_multishot(su_port_t *self, int multishot)
 {
-  if (self)
-    return self->sup_vtable->su_port_multishot(self, multishot);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->su_port_multishot(self, multishot);
 
-  assert(self);
+  assert(base);
   errno = EINVAL;
   return -1;
 }
@@ -344,17 +390,201 @@
 static inline
 int su_port_threadsafe(su_port_t *self)
 {
-  if (self)
-    return self->sup_vtable->su_port_threadsafe(self);
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+  if (base)
+    return base->sup_vtable->su_port_threadsafe(self);
 
-  assert(self);
+  assert(base);
   errno = EINVAL;
   return -1;
 }
 
+static inline
+int su_port_getmsgs(su_port_t *self)
+{
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+
+  return base->sup_vtable->su_port_getmsgs(self);
+}
+
+static inline
+int su_port_getmsgs_from(su_port_t *self, su_port_t *cloneport)
+{
+  su_virtual_port_t *base = (su_virtual_port_t *)self;
+
+  return base->sup_vtable->su_port_getmsgs_from(self, cloneport);
+}
+
+SOFIAPUBFUN void su_port_wait(su_clone_r rclone);
+
+SOFIAPUBFUN int su_port_execute(su_task_r const task,
+				int (*function)(void *), void *arg,
+				int *return_value);
+
+/* ---------------------------------------------------------------------- */
+
+/** Base port object.
+ *
+ * Port is a per-thread reactor. Multiple root objects executed by a single
+ * thread share the su_port_t object.
+ */
+typedef struct su_base_port_s {
+  su_home_t        sup_home[1];
+  su_port_vtable_t const *sup_vtable;
+
+  /* Implementation may vary stuff below, too. */
+  
+  /* Pre-poll callback */
+  su_prepoll_f    *sup_prepoll; 
+  su_prepoll_magic_t *sup_pp_magic;
+  su_root_t       *sup_pp_root;
+
+  /* Message list - this is protected by su_port_lock()/su_port_unlock() */
+  su_msg_t        *sup_head, **sup_tail;
+
+  /* Timer list */
+  su_timer_t      *sup_timers;
+
+  unsigned         sup_running;	  /**< In su_root_run() loop? */
+} su_base_port_t;
 
+/* Base methods */
+
+SOFIAPUBFUN int su_base_port_init(su_port_t *, su_port_vtable_t const *);
+SOFIAPUBFUN void su_base_port_deinit(su_port_t *self);
+
+SOFIAPUBFUN void su_base_port_lock(su_port_t *self, char const *who);
+SOFIAPUBFUN void su_base_port_unlock(su_port_t *self, char const *who);
+
+SOFIAPUBFUN int su_base_port_own_thread(su_port_t const *self);
+
+SOFIAPUBFUN void su_base_port_incref(su_port_t *self, char const *who);
+SOFIAPUBFUN int su_base_port_decref(su_port_t *self,
+				    int blocking,
+				    char const *who);
+
+SOFIAPUBFUN struct _GSource *su_base_port_gsource(su_port_t *self);
+
+SOFIAPUBFUN su_socket_t su_base_port_mbox(su_port_t *self);
+SOFIAPUBFUN int su_base_port_send(su_port_t *self, su_msg_r rmsg);
+SOFIAPUBFUN int su_base_port_getmsgs(su_port_t *self);
+SOFIAPUBFUN int su_base_port_getmsgs_from(su_port_t *self,
+					   su_port_t *from);
+
+SOFIAPUBFUN void su_base_port_run(su_port_t *self);
+SOFIAPUBFUN void su_base_port_break(su_port_t *self);
+SOFIAPUBFUN su_duration_t su_base_port_step(su_port_t *self,
+					    su_duration_t tout);
+
+SOFIAPUBFUN int su_base_port_add_prepoll(su_port_t *self,
+					 su_root_t *root, 
+					 su_prepoll_f *, 
+					 su_prepoll_magic_t *);
+
+SOFIAPUBFUN int su_base_port_remove_prepoll(su_port_t *self, su_root_t *root);
+
+SOFIAPUBFUN su_timer_t **su_base_port_timers(su_port_t *self);
+
+SOFIAPUBFUN int su_base_port_multishot(su_port_t *self, int multishot);
+SOFIAPUBFUN int su_base_port_threadsafe(su_port_t *self);
+SOFIAPUBFUN int su_base_port_yield(su_port_t *self);
+
+SOFIAPUBFUN int su_base_port_start_shared(su_root_t *parent,
+					  su_clone_r return_clone,
+					  su_root_magic_t *magic,
+					  su_root_init_f init,
+					  su_root_deinit_f deinit);
+SOFIAPUBFUN void su_base_port_wait(su_clone_r rclone);
+
+/* ---------------------------------------------------------------------- */
+
+#if SU_HAVE_PTHREADS
+
+#include <pthread.h>
+
+/** Pthread port object */ 
+typedef struct su_pthread_port_s {
+  su_base_port_t   sup_base[1];
+  struct su_pthread_port_waiting_parent 
+                  *sup_waiting_parent;
+  pthread_t        sup_tid;
+#if 0
+  pthread_mutex_t  sup_runlock[1];
+  pthread_cond_t   sup_resume[1];
+  short            sup_paused;	/**< True if thread is paused */
+#endif
+  short            sup_thread;	/**< True if thread is active */
+} su_pthread_port_t;
+
+/* Pthread methods */
+
+SOFIAPUBFUN int su_pthread_port_init(su_port_t *, su_port_vtable_t const *);
+SOFIAPUBFUN void su_pthread_port_deinit(su_port_t *self);
+
+SOFIAPUBFUN void su_pthread_port_lock(su_port_t *self, char const *who);
+SOFIAPUBFUN void su_pthread_port_unlock(su_port_t *self, char const *who);
+
+SOFIAPUBFUN int su_pthread_port_own_thread(su_port_t const *self);
+
+#if 0				/* not yet  */
+SOFIAPUBFUN int su_pthread_port_send(su_port_t *self, su_msg_r rmsg);
+
+SOFIAPUBFUN su_port_t *su_pthread_port_create(void);
+SOFIAPUBFUN su_port_t *su_pthread_port_start(su_root_t *parent,
+					     su_clone_r return_clone,
+					     su_root_magic_t *magic,
+					     su_root_init_f init,
+					     su_root_deinit_f deinit);
+#endif
+
+SOFIAPUBFUN int su_pthreaded_port_start(su_port_create_f *create,
+					su_root_t *parent,
+					su_clone_r return_clone,
+					su_root_magic_t *magic,
+					su_root_init_f init,
+					su_root_deinit_f deinit);
+
+SOFIAPUBFUN void su_pthread_port_wait(su_clone_r rclone);
+SOFIAPUBFUN int su_pthread_port_execute(su_task_r const task,
+					int (*function)(void *), void *arg,
+					int *return_value);
+
+
+#if 0
+SOFIAPUBFUN int su_pthread_port_pause(su_port_t *self);
+SOFIAPUBFUN int su_pthread_port_resume(su_port_t *self);
 #endif
 
+#else
+
+typedef su_base_port_t su_pthread_port_t;
+
+#define su_pthread_port_init   su_base_port_init
+#define su_pthread_port_deinit su_base_port_deinit
+#define su_pthread_port_lock   su_base_port_lock
+#define su_pthread_port_unlock su_base_port_unlock
+#define su_pthread_port_own_thread su_base_port_own_thread
+#define su_pthread_port_wait   su_base_port_wait
+#define su_pthread_port_execute  su_base_port_execute
+
+#endif
+
+/* ====================================================================== */
+/* Mailbox port using sockets */
+
+#define SU_MBOX_SIZE 2
+
+typedef struct su_socket_port_s {
+  su_pthread_port_t sup_base[1];
+  int               sup_mbox_index;
+  su_socket_t       sup_mbox[SU_MBOX_SIZE];
+} su_socket_port_t;
+
+SOFIAPUBFUN int su_socket_port_init(su_socket_port_t *, 
+				    su_port_vtable_t const *);
+SOFIAPUBFUN void su_socket_port_deinit(su_socket_port_t *self);
+SOFIAPUBFUN int su_socket_port_send(su_port_t *self, su_msg_r rmsg);
+
 SOFIA_END_DECLS
 
 #endif /* SU_PORT_H */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_root.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_root.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_root.c	Tue Apr 24 10:14:28 2007
@@ -48,22 +48,9 @@
 
 struct su_root_s;
 
-typedef struct su_cloned_s {
-  struct su_root_s *sc_root;
-  int *sc_wait;
-#if SU_HAVE_PTHREADS
-  pthread_t  sc_tid;
-  pthread_mutex_t sc_pause[1];
-  pthread_cond_t sc_resume[1];
-  int sc_paused;
-#endif  
-} su_cloned_t;
-
 #define SU_ROOT_MAGIC_T struct su_root_magic_s
 #define SU_WAKEUP_ARG_T struct su_wakeup_arg_s
 #define SU_TIMER_ARG_T  struct su_timer_arg_s
-#define SU_CLONE_T      su_msg_t
-#define SU_MSG_ARG_T    struct su_cloned_s
 
 #include "su_port.h"
 #include "sofia-sip/su_alloc.h"
@@ -136,11 +123,11 @@
 
 #define SU_TASK_ZAP(t, f) \
   while (t->sut_port) { \
-   SU_PORT_DECREF(t->sut_port, f); t->sut_port = NULL; break; }
+   su_port_decref(t->sut_port, #f); t->sut_port = NULL; break; }
 
 #define SU_TASK_ZAPP(t, f) \
   do { if (t->sut_port) { \
-   SU_PORT_DECREF(t->sut_port, f); t->sut_port = NULL; } \
+   su_port_decref(t->sut_port, #f); t->sut_port = NULL; } \
    t->sut_root = NULL; } while(0)
 
 /**
@@ -186,7 +173,7 @@
 
   task->sut_root = root;
   if ((task->sut_port = port)) {
-    SU_PORT_INCREF(port, su_task_new);
+    su_port_incref(port, "su_task_new");
   }
   return task;
 }
@@ -207,14 +194,14 @@
 
   port = src->sut_port;
   if (port) {
-    SU_PORT_INCREF(port, su_task_copy);
+    su_port_incref(port, "su_task_copy");
   }
 
   dst[0] = src[0];
 }
 
 #define SU_TASK_COPY(d, s, by) (void)((d)[0]=(s)[0], \
-  (s)->sut_port?(void)SU_PORT_INCREF(s->sut_port, by):(void)0)
+  (s)->sut_port?(void)su_port_incref(s->sut_port, #by):(void)0)
 
 /**
  * Moves a task handle.
@@ -242,8 +229,10 @@
  */
 int su_task_cmp(su_task_r const a, su_task_r const b)
 {
-  intptr_t retval = a->sut_port - b->sut_port;
-  retval = retval ? retval : (char *)a->sut_root - (char *)b->sut_root;
+  intptr_t retval = (char *)a->sut_port - (char *)b->sut_port;
+
+  if (retval == 0)
+    retval = (char *)a->sut_root - (char *)b->sut_root;
 
   if (sizeof(retval) != sizeof(int)) {
     if (retval < 0)
@@ -329,32 +318,7 @@
   return task ? su_port_timers(task->sut_port) : NULL;
 }
 
-#if SU_HAVE_PTHREADS
-
-struct su_task_execute
-{
-  pthread_mutex_t mutex[1];
-  pthread_cond_t cond[1];
-  int (*function)(void *);
-  void *arg;
-  int value;
-};
-
-static void _su_task_execute(su_root_magic_t *m,
-			     su_msg_r msg,
-			     su_msg_arg_t *a)
-{
-  struct su_task_execute *frame = *(struct su_task_execute **)a;
-  pthread_mutex_lock(frame->mutex);
-  frame->value = frame->function(frame->arg);
-  frame->function = NULL;	/* Mark as completed */
-  pthread_cond_signal(frame->cond);
-  pthread_mutex_unlock(frame->mutex);
-}
-
-#endif
-
-/** Execute by task thread
+/** Execute the @a function by @a task thread.
  *
  * @retval 0 if successful
  * @retval -1 upon an error
@@ -367,42 +331,7 @@
     return (errno = EFAULT), -1;
 
   if (!su_port_own_thread(task->sut_port)) {
-#if SU_HAVE_PTHREADS
-    int success;
-    su_msg_r m = SU_MSG_R_INIT;
-    struct su_task_execute frame = {
-      { PTHREAD_MUTEX_INITIALIZER },
-      { PTHREAD_COND_INITIALIZER },
-      function, arg, 0
-    };
-
-    if (su_msg_create(m, task, su_task_null,
-		      _su_task_execute, (sizeof &frame)) < 0)
-      return -1;
-
-    *(struct su_task_execute **)su_msg_data(m) = &frame;
-
-    pthread_mutex_lock(frame.mutex);
-
-    success = su_msg_send(m);
-
-    if (success == 0)
-      while (frame.function)
-	pthread_cond_wait(frame.cond, frame.mutex);
-    else
-      su_msg_destroy(m);
-
-    pthread_mutex_unlock(frame.mutex);
-    pthread_mutex_destroy(frame.mutex);
-    pthread_cond_destroy(frame.cond);
-
-    if (return_value)
-      *return_value = frame.value;
-
-    return success;
-#else
-    return (errno = ENOSYS), -1;
-#endif
+    return su_port_execute(task, function, arg, return_value);
   }
   else {
     int value = function(arg);
@@ -420,51 +349,6 @@
 
 int su_timer_reset_all(su_timer_t **t0, su_task_r);
 
-/**@ingroup su_wait
- * 
- * @page su_clone_t Clone Objects
- *
- * The process may be divided into many tasks via cloning. Several tasks may
- * run in context of one thread, or each task may be run by its own thread. 
- * However, only a single thread can execute code within a task. There can
- * be a 1-to-N mapping from thread to tasks. Thus, software using tasks can
- * be executed by multiple threads in a multithreaded environment and by a
- * single thread in a singlethreaded environment.
- * 
- * The clones are useful for handling tasks that can be executed by a
- * separate threads, but which do not block excessively. When threads are
- * not available or they are not needed, clones can also be run in a
- * single-threaded mode. Running in single-threaded mode is especially
- * useful while debugging.
- * 
- * A clone task is created with function su_clone_start(). Each clone has
- * its own root object (su_root_t), which holds a context pointer
- * (su_root_magic_t *). The context object can be different from that of 
- * parent task.
- *
- * When a clone is started, the clone initialization function is called. The
- * initialization function should do whatever initialization there is to be
- * performed, register I/O events and timers, and then return. If the
- * initialization is successful, the clone task reverts to run the event
- * loop and invoking the event callbacks until its parent stops it by
- * calling su_clone_wait() which invokes the deinit function. The clone task
- * is destroyed when the deinit function returns. 
- *
- * The public API consists of following functions:
- *    - su_clone_start()
- *    - su_clone_task()
- *    - su_clone_wait()
- *    - su_clone_forget()
- *
- * @note 
- * There is only one event loop for each thread which can be shared by
- * multiple clone tasks. Therefore, the clone tasks can not explicitly run
- * or step the event loop, but they are limited to event callbacks. A clone
- * task may not call su_root_break(), su_root_run() or su_root_step().
- */
-
-static void su_root_deinit(su_root_t *self);
-
 /* Note that is *not* necessary same as su_root_t,
  * as su_root_t can be extended */
 
@@ -486,9 +370,13 @@
   return su_root_create_with_port(magic, su_port_create());
 }
 
-/** Create a reactor object using given message port.
+/**@internal
  *
- * Allocate and initialize the instance of su_root_t.
+ * Create a reactor object using given message port.
+ *
+ * Allocate and initialize the instance of su_root_t. Note that this
+ * function always uses a reference to su_port_t, even when creating the
+ * root fails.
  *
  * @param magic     pointer to user data
  * @param port      pointer to a message port
@@ -503,7 +391,7 @@
   if (!port)
     return NULL;
 
-  self = su_salloc(NULL, sizeof(struct su_root_s));
+  self = su_salloc(su_port_home(port), sizeof(struct su_root_s));
 
   if (self) {
     self->sur_magic = magic;
@@ -512,15 +400,17 @@
 #else
     self->sur_threading = 0;
 #endif
+    /* This one creates a new reference to port */
     su_task_new(self->sur_task, self, port);
-  } else {
-    su_port_decref(port, "su_root_create");
-  }
+    /* ... so we zap the old one below */
+  } 
+
+  su_port_decref(port, "su_root_create_with_port");
 
   return self;
 }
 
-/** Destroy a synchronization object.
+/** Destroy a root object.
  * 
  *  Stop and free an instance of su_root_t
  *
@@ -528,21 +418,14 @@
  */
 void su_root_destroy(su_root_t *self)
 {
-  if (self) {
-    assert(SU_ROOT_OWN_THREAD(self));
-    su_root_deinit(self);
-    su_free(NULL, self);
-  }
-}
+  su_port_t *port;
+  int unregistered, reset;
+
+  if (!self)
+    return;
+
+  assert(SU_ROOT_OWN_THREAD(self));
 
-/** @internal Deinitialize a synchronization object.
- *
- *  Deinitialize an instance of su_root_t
- *
- * @param self     pointer to a root object.
- */
-static void su_root_deinit(su_root_t *self)
-{
   self->sur_deiniting = 1;
 
   if (self->sur_deinit) {
@@ -552,17 +435,37 @@
     deinit(self, magic);
   }
 
-  if (self->sur_port) {
-    int n_w = su_port_unregister_all(self->sur_port, self);
-    int n_t = su_timer_reset_all(su_task_timers(self->sur_task), self->sur_task);
-
-    if (n_w || n_t)
-      SU_DEBUG_1(("su_root_deinit: "
-		  "%u registered waits, %u timers\n", n_w, n_t));
-  }
+  port = self->sur_port; assert(port);
+
+  unregistered = su_port_unregister_all(port, self);
+  reset = su_timer_reset_all(su_task_timers(self->sur_task), self->sur_task);
+
+  if (unregistered || reset)
+    SU_DEBUG_1(("su_root_destroy: "
+		"%u registered waits, %u timers\n",
+		unregistered, reset));
+
+  SU_TASK_ZAP(self->sur_parent, su_root_destroy);
+
+  su_free(su_port_home(port), self);
+
+  su_port_decref(port, "su_root_destroy");
+}
 
-  SU_TASK_ZAP(self->sur_parent, su_root_deinit);
-  SU_TASK_ZAP(self->sur_task, su_root_deinit);
+/** Get instance name.
+ *
+ * @param self      pointer to a root object
+ *
+ * @return Instance name (e.g., "epoll", "devpoll", "select").
+ *
+ * @NEW_1_12_6
+ */
+char const *su_root_name(su_root_t *self)
+{
+  if (self && self->sur_task->sut_port)
+    return su_port_name(self->sur_task->sut_port);
+  else
+    return NULL;
 }
 
 /** Set the context pointer.
@@ -760,7 +663,6 @@
   }
 }
 
-
 /** Run event and message loop.
  *
  * The function su_root_run() runs the root main loop. The root loop waits
@@ -852,12 +754,20 @@
 int su_root_yield(su_root_t *self)
 {
   if (self && self->sur_task[0].sut_port) {
-    su_port_t *port = self->sur_task[0].sut_port;
+    su_virtual_port_t *port = (su_virtual_port_t *)self->sur_task[0].sut_port;
+    /* Make sure we have su_port_wait_events extension */
+    if (port->sup_vtable->su_vtable_size >= 
+	offsetof(su_port_vtable_t, su_port_wait_events) 
+	&& port->sup_vtable->su_port_wait_events)
+      return port->sup_vtable->
+	su_port_wait_events(self->sur_task[0].sut_port, 0);
+
     /* Make sure we have su_port_yield extension */
     if (port->sup_vtable->su_vtable_size >= 
 	offsetof(su_port_vtable_t, su_port_yield) 
 	&& port->sup_vtable->su_port_yield)
-      return port->sup_vtable->su_port_yield(port);
+    return port->sup_vtable->
+      su_port_yield(self->sur_task[0].sut_port);
   }
   errno = EINVAL;
   return -1;
@@ -919,467 +829,6 @@
   return su_port_remove_prepoll(root->sur_port, root);
 }
 
-/* ========================================================================
- * su_clone_t
- */
-
-/* - su_clone_forget() */
-
-#if SU_HAVE_PTHREADS
-struct clone_args
-{
-  su_root_t      * self;
-  su_root_init_f   init;
-  su_root_deinit_f deinit;
-  pthread_mutex_t  mutex;
-  pthread_cond_t   cv;
-  int              retval;
-  su_msg_r         clone;
-  su_root_t const *parent;
-};
-
-static void su_clone_report2(su_root_magic_t *m,
-			     su_msg_r msg,
-			     su_cloned_t *sc);
-
-static void su_clone_signal_parent(void *varg)
-{
-  struct clone_args *arg = (struct clone_args *)varg;
-
-  pthread_mutex_lock(&arg->mutex);
-  pthread_cond_signal(&arg->cv);
-  pthread_mutex_unlock(&arg->mutex);
-}
-
-/** Message function for clone message.
- *
- * This calls the clone task deinitialization function, which should make
- * sure that no more messages are sent by clone task.
- *
- * @sa su_clone_wait()
- */
-static void su_clone_break(su_root_magic_t *m,
-			   su_msg_r msg,
-			   su_cloned_t *sc)
-{
-  su_root_t *root = sc->sc_root;
-
-  root->sur_deiniting = 1;
-
-  if (root->sur_deinit) {
-    su_root_deinit_f deinit = root->sur_deinit;
-    su_root_magic_t *magic = root->sur_magic;
-    root->sur_deinit = NULL;
-    deinit(root, magic);
-  }
-}
-
-/** Delivery report function for clone message.
- *
- * This is executed by parent task. This is the last message sent by clone task.
- */
-static void su_clone_report(su_root_magic_t *m,
-			    su_msg_r msg,
-			    su_cloned_t *sc)
-{
-  su_msg_report(msg, su_clone_report2);
-}
-
-/** Back delivery report function for clone message.
- *
- * This is executed by clone task. It completes the three way handshake and
- * it is used to signal clone that it can destroy its port.
- */
-static void su_clone_report2(su_root_magic_t *m,
-			    su_msg_r msg,
-			    su_cloned_t *sc)
-{
-  su_root_break(sc->sc_root);
-  if (sc->sc_wait)
-    *sc->sc_wait = 0;
-}
-
-static void *su_clone_main(void *varg)
-{
-  struct clone_args *arg = (struct clone_args *)varg;
-  su_root_t *self = arg->self;
-  su_port_t *port;
-  su_cloned_t *sc;
-
-  pthread_cleanup_push(su_clone_signal_parent, varg);
-
-#if SU_HAVE_WINSOCK
-  su_init();
-#endif
-
-  port = su_port_create();
-  if (!port)
-    pthread_exit(NULL);
-  su_port_threadsafe(port);
-  SU_PORT_INCREF(port, su_clone_main);
-
-  /* Change task ownership */
-  SU_PORT_INCREF(self->sur_task->sut_port = port, su_clone_main);
-  self->sur_task->sut_root = self;
-
-  if (su_msg_create(arg->clone,
-		    self->sur_task, su_root_task(arg->parent),
-		    su_clone_break, sizeof(self)) != 0) {
-    su_port_decref(self->sur_port, "su_clone_main");
-    self->sur_port = NULL;
-    pthread_exit(NULL);
-  }
-
-  su_msg_report(arg->clone, su_clone_report);
-
-  sc = su_msg_data(arg->clone);
-  sc->sc_root = self;
-  sc->sc_tid = pthread_self();
-
-  pthread_mutex_init(sc->sc_pause, NULL);
-  pthread_cond_init(sc->sc_resume, NULL);
-  pthread_mutex_lock(sc->sc_pause);
-
-  if (arg->init && arg->init(self, self->sur_magic) != 0) {
-    if (arg->deinit)
-      arg->deinit(self, self->sur_magic);
-    su_msg_destroy(arg->clone);
-    su_port_decref(self->sur_port, "su_clone_main");
-    self->sur_port = NULL;
-    pthread_exit(NULL);
-  }
-
-  arg->retval = 0;
-
-  pthread_cleanup_pop(1);  /* signal change of ownership */
-
-  su_root_run(self);   /* Do the work */
-
-  su_root_destroy(self);   /* Cleanup root */   
-
-  SU_PORT_ZAPREF(port, su_clone_main);
-
-#if SU_HAVE_WINSOCK
-  su_deinit();
-#endif
-
-  return NULL;
-}
-#endif
-
-static void su_clone_xyzzy(su_root_magic_t *m,
-			   su_msg_r msg,
-			   su_cloned_t *sc)
-{
-  su_root_destroy(sc->sc_root);
-  if (sc->sc_wait)
-    *sc->sc_wait = 0;
-}
-
-/** Start a clone task.
- *
- * The function su_clone_start() allocates and initializes a sub-task. 
- * Depending on the settings, a separate thread may be created to execute
- * the sub-task. The sub-task is represented by clone handle to the rest of
- * the application. The function su_clone_start() returns the clone handle
- * in @a return_clone. The clone handle is used to communicate with the
- * newly created clone task using messages.
- *
- * A new #su_root_t object is created for the sub-task with the @a magic as
- * the root context pointer. Because the sub-task may or may not have its
- * own thread, all its activity must be scheduled via this root object. In
- * other words, the sub-task can be schedule
- * -# I/O events with su_root_register()
- * -# timers with su_timer_set(), su_timer_set_at() or su_timer_run()
- * -# messages with su_msg_send().
- *
- * Messages can also be used to pass information between tasks or threads.
- *
- * In multi-threaded implementation, su_clone_start() launches a new thread,
- * and the initialization routine is executed by this newly created thread. 
- * The calling thread blocks until the initialization routine completes. If
- * the initialization routine returns #su_success (0), the sub-task is
- * considered to be created successfully. After the successful
- * initialization, the sub-task continues to execeute the function
- * su_root_run().
- *
- * In single-threaded implementations, just a new root object is created. 
- * The initialization routine is called directly from su_clone_start().
- *
- * If the initalization function @a init fails, the sub-task (either the
- * newly created thread or the current thread executing the su_clone_start()
- * function) calls the deinitialization function, and su_clone_start()
- * returns NULL.
- *
- * @param parent   root to be cloned (may be NULL if multi-threaded)
- * @param return_clone reference to a clone [OUT]
- * @param magic    pointer to user data
- * @param init     initialization function
- * @param deinit   deinitialization function
- *
- * @return 0 if successfull, -1 upon an error.
- *
- * @sa su_root_threading(), su_clone_task(), su_clone_stop(), su_clone_wait(),
- * su_clone_forget().
- */
-int su_clone_start(su_root_t *parent,
-		   su_clone_r return_clone,
-		   su_root_magic_t *magic,
-		   su_root_init_f init,
-		   su_root_deinit_f deinit)
-{
-  su_root_t *child;
-  int retval = -1;
-
-  if (parent) {
-    assert(SU_ROOT_OWN_THREAD(parent));
-    assert(parent->sur_port);
-  }
-#if !SU_HAVE_PTHREADS
-  else {
-    /* if we don't have threads, we *must* have parent root */
-    return -1;
-  }
-#endif
-
-  child = su_salloc(NULL, sizeof(struct su_root_s));
-
-#if SU_HAVE_PTHREADS
-  if (child && (parent == NULL || parent->sur_threading)) {
-    struct clone_args arg = {
-      NULL, NULL, NULL,
-      PTHREAD_MUTEX_INITIALIZER,
-      PTHREAD_COND_INITIALIZER,
-      -1,
-      SU_MSG_R_INIT,
-      NULL
-    };
-
-    int thread_created = 0;
-    pthread_t tid;
-
-    su_port_threadsafe(parent->sur_port);
-
-    arg.self = child;
-    arg.init = init;
-    arg.deinit = deinit;
-    arg.parent = parent;
-
-    child->sur_magic = magic;
-    child->sur_deinit = deinit;
-    child->sur_threading = parent->sur_threading;
-
-    SU_TASK_COPY(child->sur_parent, su_root_task(parent), su_clone_start);
-
-    pthread_mutex_lock(&arg.mutex);
-    if (pthread_create(&tid, NULL, su_clone_main, &arg) == 0) {
-      pthread_cond_wait(&arg.cv, &arg.mutex);
-      thread_created = 1;
-    }
-    pthread_mutex_unlock(&arg.mutex);
-
-    if (arg.retval != 0) {
-      if (thread_created)
-	pthread_join(tid, NULL);
-      su_root_destroy(child), child = NULL;
-    }
-    else {
-      retval = 0;
-      *return_clone = *arg.clone;
-    }
-  } else
-#endif
-  if (child) {
-    assert(parent);
-
-    child->sur_magic = magic;
-    child->sur_deinit = deinit;
-    child->sur_threading = parent->sur_threading;
-
-    SU_TASK_COPY(child->sur_parent, su_root_task(parent), su_clone_start);
-    SU_TASK_COPY(child->sur_task, child->sur_parent, su_clone_start);
-    su_task_attach(child->sur_task, child);
-
-    if (su_msg_create(return_clone,
-		      child->sur_task, su_root_task(parent),
-		      su_clone_xyzzy, sizeof(child)) == 0) {
-      if (init == NULL || init(child, magic) == 0) {
-	su_cloned_t *sc = su_msg_data(return_clone);
-	sc->sc_root = child;
-#if SU_HAVE_PTHREADS
-	sc->sc_tid = pthread_self();
-	pthread_mutex_init(sc->sc_pause, NULL);
-	pthread_cond_init(sc->sc_resume, NULL);
-	pthread_mutex_lock(sc->sc_pause);
-#endif
-	retval = 0;
-      } else {
-	if (deinit)
-	  deinit(child, magic);
-	su_msg_destroy(return_clone);
-	su_root_destroy(child), child = NULL;
-      }
-    }
-    else {
-      su_root_destroy(child), child = NULL;
-    }
-  }
-
-  return retval;
-}
-
-/** Get reference to clone task.
- * 
- * @param clone Clone pointer
- *
- * @return A reference to the task structure of the clone.
- */
-_su_task_r su_clone_task(su_clone_r clone)
-{
-  return su_msg_to(clone);
-}
-
-/**Forget the clone.
- * 
- * Normally, the clone task executes until it is stopped.  If the parent
- * task does not need to stop the task, it can "forget" the clone.  The
- * clone exits independently of the parent task.
- *
- * @param rclone Reference to the clone.
- */
-void su_clone_forget(su_clone_r rclone)
-{
-  su_msg_destroy(rclone);
-}
-
-/** Stop the clone.
- *
- * @deprecated. Use su_clone_wait().
- */
-void su_clone_stop(su_clone_r rclone)
-{
-  su_msg_send(rclone);
-}
-
-/** Stop a clone and wait until it is has completed.
- *
- * The function su_clone_wait() is used to stop the clone task and wait
- * until it has cleaned up. The clone task is destroyed asynchronously. The
- * parent sends a message to clone, clone deinitializes itself and then
- * replies. After the reply message is received by the parent, it will send
- * a third message back to clone.
- *
- * The parent destroy all messages to or from clone task before calling
- * su_clone_wait(). The parent task may not send any messages to the clone
- * after calling su_clone_wait(). The su_clone_wait() function blocks until
- * the cloned task is destroyed. During that time, the parent task must be
- * prepared to process all the messages sent by clone task. This includes
- * all the messages sent by clone before destroy message reached the clone.
- */
-void su_clone_wait(su_root_t *root, su_clone_r rclone)
-{
-  su_cloned_t *sc = su_msg_data(rclone);
-
-  if (sc) {
-#if SU_HAVE_PTHREADS
-    pthread_t clone_tid = sc->sc_tid;
-#endif
-    int one = 1;
-    /* This does 3-way handshake. 
-     * First, su_clone_break() is executed by clone. 
-     * The message is returned to parent (this task), 
-     * which executes su_clone_report().
-     * Then the message is again returned to clone, 
-     * which executes su_clone_report2() and exits.
-     */
-    sc->sc_wait = &one;
-    su_msg_send(rclone);
-
-    su_root_step(root, 0);
-    su_root_step(root, 0);
-
-    while (one)
-      su_root_step(root, 10);
-
-#if SU_HAVE_PTHREADS
-    if (!pthread_equal(clone_tid, pthread_self()))
-      pthread_join(clone_tid, NULL);
-#endif
-  }
-}
-
-#if SU_HAVE_PTHREADS		/* No-op without threads */
-static
-void su_clone_paused(su_root_magic_t *magic, su_msg_r msg, su_msg_arg_t *arg)
-{
-  su_cloned_t *cloned = *(su_cloned_t **)arg;
-  assert(cloned);
-  pthread_cond_wait(cloned->sc_resume, cloned->sc_pause);
-}
-#endif
-
-/** Pause a clone.
- *
- * Obtain a exclusive lock on clone's private data.
- *
- * @retval 0 if successful (and clone is paused)
- * @retval -1 upon an error
- */
-int su_clone_pause(su_clone_r rclone)
-{
-#if SU_HAVE_PTHREADS		/* No-op without threads */
-  su_cloned_t *cloned = su_msg_data(rclone);
-  su_msg_r m = SU_MSG_R_INIT;
-
-  if (!cloned)
-    return (errno = EFAULT), -1;
-
-  if (pthread_equal(pthread_self(), cloned->sc_tid))
-    return 0;
-
-  if (su_msg_create(m, su_clone_task(rclone), su_task_null,
-		    su_clone_paused, sizeof cloned) < 0)
-    return -1;
-
-  *(su_cloned_t **)su_msg_data(m) = cloned;
-
-  if (su_msg_send(m) < 0)
-    return -1;
-
-  if (pthread_mutex_lock(cloned->sc_pause) < 0)
-    return -1;
-  pthread_cond_signal(cloned->sc_resume);
-#endif
-
-  return 0;
-}
-
-/** Resume a clone.
- *
- * Give up a exclusive lock on clone's private data.
- *
- * @retval 0 if successful (and clone is resumed)
- * @retval -1 upon an error
- */
-int su_clone_resume(su_clone_r rclone)
-{
-#if SU_HAVE_PTHREADS		/* No-op without threads */
-  su_cloned_t *cloned = su_msg_data(rclone);
-
-  if (!cloned)
-    return (errno = EFAULT), -1;
-
-  if (pthread_equal(pthread_self(), cloned->sc_tid))
-    return 0;
-
-  if (pthread_mutex_unlock(cloned->sc_pause) < 0)
-    return -1;
-#endif
-
-  return 0;
-}
-
-
 /* =========================================================================
  * Messages
  */
@@ -1405,12 +854,9 @@
 		  su_msg_f        wakeup,
 		  isize_t         size)
 {
-  su_port_t *port = to->sut_port;
   su_msg_t *msg;
 
-  SU_PORT_LOCK(port, su_msg_create);
-  msg = su_zalloc(NULL /*port->sup_home*/, sizeof(*msg) + size);
-  SU_PORT_UNLOCK(port, su_msg_create);
+  msg = su_zalloc(NULL, sizeof(*msg) + size);
 
   if (msg) {
     msg->sum_size = sizeof(*msg) + size;
@@ -1522,14 +968,14 @@
   if (rmsg[0]) {
     /* su_port_t *port = rmsg[0]->sum_to->sut_port; */
 
-    /* SU_PORT_INCREF(port, su_msg_destroy); */
+    /* su_port_incref(port, "su_msg_destroy"); */
     SU_TASK_ZAP(rmsg[0]->sum_to, su_msg_destroy);
     SU_TASK_ZAP(rmsg[0]->sum_from, su_msg_destroy);
 
     su_free(NULL /* port->sup_home */, rmsg[0]);
     /* SU_PORT_UNLOCK(port, su_msg_destroy); */
 
-    /* SU_PORT_DECREF(port, su_msg_destroy); */
+    /* su_port_decref(port, "su_msg_destroy"); */
   }
 
   rmsg[0] = NULL;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_time.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_time.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_time.c	Tue Apr 24 10:14:28 2007
@@ -42,9 +42,16 @@
 #include <time.h>
 
 #include "sofia-sip/su_types.h"
-#include "sofia-sip/su_time.h"
 #include "su_module_debug.h"
 
+/* Include bodies of inlined functions */
+#undef su_inline
+#define su_inline
+#undef SU_HAVE_INLINE
+#define SU_HAVE_INLINE 1
+
+#include "sofia-sip/su_time.h"
+
 #if HAVE_SYS_TIME_H
 #include <sys/time.h> /* Get struct timeval */
 #endif

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_timer.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_timer.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_timer.c	Tue Apr 24 10:14:28 2007
@@ -157,8 +157,9 @@
   unsigned char   sut_set;	/**< Timer is set (inserted in tree) */
 };
 
+/** Timer running status */ 
 enum sut_running {
-  reset = 0,
+  reset = 0,		/**< Timer is not running */
   run_at_intervals = 1, /**< Compensate missed wakeup calls */
   run_for_ever = 2	/**< Do not compensate  */
 };
@@ -193,7 +194,10 @@
 	      IS_RED, SET_RED, IS_BLACK, SET_BLACK, COPY_COLOR,
 	      CMP, INSERT, REMOVE);
 
-/** Set the timer. */
+/**@internal Set the timer. 
+ *
+ * @retval 0 when successful (always)
+ */
 static inline int
 su_timer_set0(su_timer_t **timers,
 	      su_timer_t *t,
@@ -212,7 +216,10 @@
   return timers_append(timers, t);
 }
 
-/** Reset the timer. */
+/**@internal Reset the timer. 
+ *
+ * @retval 0 when successful (always)
+ */
 static inline int
 su_timer_reset0(su_timer_t **timers,
 		su_timer_t *t)
@@ -229,6 +236,40 @@
   return 0;
 }
 
+/**@internal Validate timer @a t and return pointer to per-port timer tree.
+ * 
+ * @retval pointer to pointer to timer tree when successful
+ * @retval NULL upon an error
+ */
+static
+su_timer_t **su_timer_tree(su_timer_t const *t,
+			   int use_sut_duration,
+			   char const *caller)
+{
+  su_timer_t **timers;
+
+  if (t == NULL) {
+    SU_DEBUG_1(("%s(%p): %s\n", caller, (void *)t,
+		"NULL argument"));
+    return NULL;
+  }
+
+  timers = su_task_timers(t->sut_task);
+
+  if (timers == NULL)
+    SU_DEBUG_1(("%s(%p): %s\n", caller, (void *)t,
+		"invalid timer"));
+
+  if (use_sut_duration && t->sut_duration == 0) {
+    assert(t->sut_duration > 0);
+    SU_DEBUG_1(("%s(%p): %s\n", caller, (void *)t, 
+		"timer without default duration"));
+    return NULL;
+  }
+
+  return timers;
+}
+
 
 /**Create a timer.
  *
@@ -291,23 +332,12 @@
 			  su_timer_arg_t *arg,
 			  su_duration_t interval)
 {
-  char const *func = "su_timer_set_interval";
-  su_timer_t **timers;
-
-  if (t == NULL) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "NULL argument"));
-    return -1;
-  }
+  su_timer_t **timers = su_timer_tree(t, 0, "su_timer_set_interval");
 
-  timers = su_task_timers(t->sut_task);
-  if (timers == NULL) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "invalid timer"));
+  if (t == NULL)
     return -1;
-  }
-
-  su_timer_set0(timers, t, wakeup, arg, su_now(), interval);
 
-  return 0;
+  return su_timer_set0(timers, t, wakeup, arg, su_now(), interval);
 }
 
 /** Set the timer for the default interval.
@@ -326,18 +356,12 @@
 		 su_timer_f wakeup,
 		 su_timer_arg_t *arg)
 {
-  char const *func = "su_timer_set";
-
-  if (t == NULL)
-    return -1;
+  su_timer_t **timers = su_timer_tree(t, 1, "su_timer_set");
 
-  assert(t->sut_duration > 0);
-  if (t->sut_duration == 0) {
-    SU_DEBUG_0(("%s(%p): %s\n", func, t, "timer without default duration"));
+  if (timers == NULL)
     return -1;
-  }
 
-  return su_timer_set_interval(t, wakeup, arg, t->sut_duration);
+  return su_timer_set0(timers, t, wakeup, arg, su_now(), t->sut_duration);
 }
 
 /** Set timer at known time.
@@ -356,23 +380,12 @@
 		    su_wakeup_arg_t *arg,
 		    su_time_t when)
 {
-  char const *func = "su_timer_set_at";
-  su_timer_t **timers;
+  su_timer_t **timers = su_timer_tree(t, 0, "su_timer_set_at");
 
-  if (t == NULL) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "NULL argument"));
+  if (timers == NULL)
     return -1;
-  }
 
-  timers = su_task_timers(t->sut_task);
-  if (timers == NULL) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "invalid timer"));
-    return -1;
-  }
-
-  su_timer_set0(timers, t, wakeup, arg, when, 0);
-
-  return 0;
+  return su_timer_set0(timers, t, wakeup, arg, when, 0);
 }
 
 /** Set the timer for regular intervals.
@@ -397,34 +410,17 @@
 		 su_timer_f wakeup,
 		 su_timer_arg_t *arg)
 {
-  char const *func = "su_timer_run";
-  su_timer_t **timers;
-  su_time_t now = su_now();
-
-  if (t == NULL) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "NULL argument"));
-    return -1;
-  }
-
-  assert(t->sut_duration > 0);
-  if (t->sut_duration == 0) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "timer without default duration"));
-    return -1;
-  }
+  su_timer_t **timers = su_timer_tree(t, 1, "su_timer_run");
+  su_time_t now;
 
-  timers = su_task_timers(t->sut_task);
-  if (timers == NULL) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "invalid timer"));
+  if (timers == NULL)
     return -1;
-  }
 
   t->sut_running = run_at_intervals;
-  t->sut_run = now;
+  t->sut_run = now = su_now();
   t->sut_woken = 0;
 
-  su_timer_set0(timers, t, wakeup, arg, now, t->sut_duration);
-
-  return 0;
+  return su_timer_set0(timers, t, wakeup, arg, now, t->sut_duration);
 }
 
 /**Set the timer for regular intervals.
@@ -447,37 +443,19 @@
 			  su_timer_f wakeup,
 			  su_timer_arg_t *arg)
 {
-  char const *func = "su_timer_run";
-  su_timer_t **timers;
-  su_time_t now = su_now();
+  su_timer_t **timers = su_timer_tree(t, 1, "su_timer_set_for_ever");
+  su_time_t now;
 
-  if (t == NULL) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "NULL argument"));
+  if (timers == NULL)
     return -1;
-  }
-
-  assert(t->sut_duration > 0);
-  if (t->sut_duration == 0) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "timer without default duration"));
-    return -1;
-  }
-
-  timers = su_task_timers(t->sut_task);
-  if (timers == NULL) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "invalid timer"));
-    return -1;
-  }
 
   t->sut_running = run_for_ever;
-  t->sut_run = now;
+  t->sut_run = now = su_now();
   t->sut_woken = 0;
 
-  su_timer_set0(timers, t, wakeup, arg, now, t->sut_duration);
-
-  return 0;
+  return su_timer_set0(timers, t, wakeup, arg, now, t->sut_duration);
 }
 
-
 /**Reset the timer.
  *
  * Resets (stops) the given timer.
@@ -488,19 +466,12 @@
  */
 int su_timer_reset(su_timer_t *t)
 {
-  char const *func = "su_timer_reset";
-  su_timer_t **timers;
+  su_timer_t **timers = su_timer_tree(t, 0, "su_timer_reset");
 
-  if (t == NULL) {
-    SU_DEBUG_1(("%s(%p): %s\n", func, t, "NULL argument"));
+  if (timers == NULL)
     return -1;
-  }
 
-  timers = su_task_timers(t->sut_task);
-
-  su_timer_reset0(timers, t);
-
-  return 0;
+  return su_timer_reset0(timers, t);
 }
 
 /** @internal Check for expired timers in queue.
@@ -574,6 +545,7 @@
 }
 
 
+/** Calculate duration in milliseconds until next timer expires. */
 su_duration_t su_timer_next_expires(su_timer_t const * t, su_time_t now)
 {
   su_duration_t tout;
@@ -623,14 +595,13 @@
 
 /** Get the root object owning the timer.
  *
- *   The function su_timer_root() return pointer to the root object owning the
- *   timer.
+ * Return pointer to the root object owning the timer.
  *
  * @param t pointer to the timer
  *
- * @return Pointer to the root object owning the timer.
+ * @return Pointer to the root object.
  */
 su_root_t *su_timer_root(su_timer_t const *t)
 {
-  return su_task_root(t->sut_task);
+  return t ? su_task_root(t->sut_task) : NULL;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_wait.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_wait.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/su_wait.c	Tue Apr 24 10:14:28 2007
@@ -31,6 +31,7 @@
  * (poll()/select()/WaitForMultipleObjects()) functionality.
  *
  * @author Pekka Pessi <Pekka.Pessi at nokia.com>
+ * @author Martti Mela <Martti.Mela at nokia.com>
  * @date Created: Tue Sep 14 15:51:04 1999 ppessi
  *
  */
@@ -149,7 +150,7 @@
 
   *newwait = h;
 
-#elif SU_HAVE_POLL
+#elif SU_HAVE_POLL || HAVE_SELECT
   int mode;
 
   if (newwait == NULL || events == 0 || socket == INVALID_SOCKET) {
@@ -187,7 +188,9 @@
   su_wait_t w0 = NULL;
   if (*waitobj)
     WSACloseEvent(*waitobj);
-#elif SU_HAVE_POLL
+#elif SU_HAVE_POLL || HAVE_SELECT
+  su_wait_t w0 = { INVALID_SOCKET, 0, 0 };
+#else
   su_wait_t w0 = { INVALID_SOCKET, 0, 0 };
 #endif
   assert(waitobj != NULL);
@@ -231,7 +234,7 @@
   else
     return i;
 
-#elif SU_HAVE_POLL
+#elif SU_HAVE_POLL || HAVE_SELECT
   for (;;) {
     int i = poll(waits, n, timeout);
 
@@ -273,7 +276,7 @@
 
   return net_events.lNetworkEvents;
 
-#elif SU_HAVE_POLL
+#elif SU_HAVE_POLL || HAVE_SELECT
   /* poll(e, 1, 0); */
   return waitobj->revents;
 #endif
@@ -302,7 +305,8 @@
     WSASetLastError(error);
     return -1;
   }
-#elif SU_HAVE_POLL
+
+#elif SU_HAVE_POLL || HAVE_SELECT
   waitobj->fd = s;
   waitobj->events = events;
   waitobj->revents = 0;

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/tag_dll.awk
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/tag_dll.awk	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/tag_dll.awk	Tue Apr 24 10:14:28 2007
@@ -46,11 +46,18 @@
     fn = FILENAME;
   }
 
-  DLL = fn;
-  sub(/[.]c(at)?/, "_dll.c", DLL);
+  if (REF == "") {
+    REF = fn;
+    sub(/[.]c(at)?/, "_ref.c", REF);
+  }
 
   if (NODLL) DLL = "/dev/null";
 
+  if (DLL == "") {
+    DLL = fn;
+    sub(/[.]c(at)?/, "_dll.c", DLL);
+  }
+
   base = fn;
   sub(/.*\//, "", base);
 
@@ -73,9 +80,6 @@
       "#include <sofia-sip/su_tag_class.h>\n\n" > DLL;
   }
 
-  REF = fn;
-  sub(/[.]c(at)?/, "_ref.c", REF);
-
   printf("/*\n" \
 	 " * PLEASE NOTE: \n" \
 	 " * \n" \
@@ -110,6 +114,11 @@
   print "" > DLL;
 }
 
+/SU_HAVE_EXPERIMENTAL/ { 
+  print $0 > REF; 
+  print $0 > DLL; 
+}
+
 !DEFS && /^tag_typedef_t/ { DEFS = 1; }
 
 DEFS && /tag_typedef_t/ {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_htable.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_htable.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_htable.c	Tue Apr 24 10:14:28 2007
@@ -52,10 +52,10 @@
 
 char const name[] = "htable_test";
 
-void usage(void)
+void usage(int exitcode)
 {
-  fprintf(stderr, "usage: %s [-v|--verbatim]\n", name);
-  exit(2);
+  fprintf(stderr, "usage: %s [-v|--verbatim] [-a|--abort]\n", name);
+  exit(exitcode);
 }
 
 static int table_test(int flags);
@@ -70,8 +70,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbatim") == 0)
       flags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--abort") == 0)
+      flags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= table_test(flags); fflush(stdout);
@@ -179,44 +181,46 @@
 
   BEGIN();
 
-  TEST0(c = context_create());
-  TEST0(add(c, 0, 1)); TEST0(c->c_hash->ht_table[0]);
-  TEST0(add(c, 1, 2)); TEST0(c->c_hash->ht_table[1]);
-  TEST0(add(c, 2, 3)); TEST0(c->c_hash->ht_table[2]);
-  TEST0(add(c, 0, 4)); TEST0(c->c_hash->ht_table[3]);
-  TEST0(add(c, 2, 5)); TEST0(c->c_hash->ht_table[4]);
-
-  TEST0(e = search(c, 1, 2, 0));
-  zap(c, e);
-  TEST0(c->c_hash->ht_table[0]);
-  TEST0(c->c_hash->ht_table[1]);
-  TEST0(c->c_hash->ht_table[2]);
-  TEST0(c->c_hash->ht_table[3]);
-  TEST0(c->c_hash->ht_table[4] == NULL);
+  TEST_1(c = context_create());
+  TEST_1(add(c, 0, 1)); TEST_1(c->c_hash->ht_table[0]);
+  TEST_1(add(c, 1, 2)); TEST_1(c->c_hash->ht_table[1]);
+  TEST_1(add(c, 2, 3)); TEST_1(c->c_hash->ht_table[2]);
+  TEST_1(add(c, 0, 4)); TEST_1(c->c_hash->ht_table[3]);
+  TEST_1(add(c, 2, 5)); TEST_1(c->c_hash->ht_table[4]);
+
+  TEST_1(e = search(c, 1, 2, 0));
+  TEST(htable_remove(c->c_hash, e), 0);
+  TEST(htable_remove(c->c_hash, e), -1);
+  su_free(c->c_home, e);
+  TEST_1(c->c_hash->ht_table[0]);
+  TEST_1(c->c_hash->ht_table[1]);
+  TEST_1(c->c_hash->ht_table[2]);
+  TEST_1(c->c_hash->ht_table[3]);
+  TEST_1(c->c_hash->ht_table[4] == NULL);
 
   zap(c, c->c_hash->ht_table[0]);
 
-  TEST0(c->c_hash->ht_table[0]);
-  TEST0(c->c_hash->ht_table[1] == NULL);
-  TEST0(c->c_hash->ht_table[2]);
-  TEST0(c->c_hash->ht_table[3]);
-  TEST0(c->c_hash->ht_table[4] == NULL);
+  TEST_1(c->c_hash->ht_table[0]);
+  TEST_1(c->c_hash->ht_table[1] == NULL);
+  TEST_1(c->c_hash->ht_table[2]);
+  TEST_1(c->c_hash->ht_table[3]);
+  TEST_1(c->c_hash->ht_table[4] == NULL);
 
-  TEST0(add(c, 0, 6)); TEST0(c->c_hash->ht_table[1]);
-  TEST0(add(c, 1, 7)); TEST0(c->c_hash->ht_table[4]);
+  TEST_1(add(c, 0, 6)); TEST_1(c->c_hash->ht_table[1]);
+  TEST_1(add(c, 1, 7)); TEST_1(c->c_hash->ht_table[4]);
 
   /* Test that zapping entry 0 does not move 2 and 3 */
   zap(c, c->c_hash->ht_table[0]);
-  TEST0(c->c_hash->ht_table[4] == NULL);
+  TEST_1(c->c_hash->ht_table[4] == NULL);
 
   {
     /* Insert entries at the end of hash, then resize and check
        for correct ordering */
     hash_value_t size = c->c_hash->ht_size, h = size - 1;
 
-    TEST0(add(c, h, 0)); TEST0(add(c, h, 1)); TEST0(add(c, h, 2));
-    TEST0(add(c, h, 3)); TEST0(add(c, h, 4)); TEST0(add(c, h, 5));
-    TEST0(add(c, h, 6)); TEST0(add(c, h, 7)); TEST0(add(c, h, 8));
+    TEST_1(add(c, h, 0)); TEST_1(add(c, h, 1)); TEST_1(add(c, h, 2));
+    TEST_1(add(c, h, 3)); TEST_1(add(c, h, 4)); TEST_1(add(c, h, 5));
+    TEST_1(add(c, h, 6)); TEST_1(add(c, h, 7)); TEST_1(add(c, h, 8));
 
     TEST(count(c, h), 9);
     

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_memmem.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_memmem.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_memmem.c	Tue Apr 24 10:14:28 2007
@@ -58,9 +58,10 @@
 
 char const name[] = "test_memmem";
 
-void usage(void)
+void usage(int exitcode)
 {
-  fprintf(stderr, "usage: %s [-v]\n", name);
+  fprintf(stderr, "usage: %s [-v] [-a]\n", name);
+  exit(exitcode);
 }
 
 static int test_notfound(void);
@@ -77,14 +78,25 @@
 
   TEST_P(memmem(haystack, 12, needle, 3), haystack + 2);
   TEST_P(memmem(needle, 3, haystack, 12), NULL);
-  TEST_P(memmem(haystack, 12, "", 0), haystack);
-  TEST_P(memmem(haystack, 12, null, 0), haystack);
-  TEST_P(memmem(haystack, 0, "", 0), haystack);
-  TEST_P(memmem(haystack, 0, null, 0), haystack);
+  
+#if HAVE_MEMMEM
+  if (memmem(haystack, 12, "", 0) == NULL) {
+    fprintf(stderr, "test_memmem.c: "
+	    "*** WARNING: system memmem() fails with empty needle ***\n");
+  }
+  else 
+#endif
+  {
+    TEST_P(memmem(haystack, 12, "", 0), haystack);
+    TEST_P(memmem(haystack, 12, null, 0), haystack);
+    TEST_P(memmem(haystack, 0, "", 0), haystack);
+    TEST_P(memmem(haystack, 0, null, 0), haystack);
+  }
 
   TEST_P(memmem(haystack + 2, 3, needle, 3), haystack + 2);
   TEST_P(memmem(haystack + 2, 2, needle, 3), NULL);
   TEST_P(memmem(a = "a\0bc", 4, "a\0bc", 4), a);
+  TEST_P(memmem(a, 4, "\0bc", 3), a + 1);
 
   END();
 }
@@ -225,8 +237,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       test_flags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      test_flags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= test_notfound(); fflush(stdout);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_su.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_su.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/test_su.c	Tue Apr 24 10:14:28 2007
@@ -36,13 +36,6 @@
 
 #include "config.h"
 
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <signal.h>
-
-#include <assert.h>
-
 struct pinger;
 #define SU_ROOT_MAGIC_T struct pinger
 #define SU_INTERNAL_P   su_root_t *
@@ -53,6 +46,12 @@
 #include "sofia-sip/su_log.h"
 #include "sofia-sip/su_debug.h"
 
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+#include <assert.h>
+
 char const name[] = "su_test";
 
 #if HAVE_FUNC
@@ -410,14 +409,6 @@
   }
 }
 
-static
-RETSIGTYPE term(int n)
-{
-  enter;
-
-  exit(1);
-}
-
 void
 time_test(void)
 {
@@ -440,10 +431,12 @@
     printf("time_test: passed\n");
 }
 
-#if HAVE_ALARM
+#if HAVE_SIGNAL
 #include <unistd.h>
 #include <signal.h>
 
+#if HAVE_ALARM
+
 static RETSIGTYPE sig_alarm(int s)
 {
   enter;
@@ -456,6 +449,18 @@
 static char const no_alarm[] = "";
 #endif
 
+static
+RETSIGTYPE term(int n)
+{
+  enter;
+
+  exit(1);
+}
+#else
+static char const no_alarm[] = "";
+#endif
+
+
 void
 usage(int exitcode)
 {
@@ -519,11 +524,10 @@
     }
   }
 
-  signal(SIGTERM, term);
-
   su_init(); atexit(su_deinit);
 
-  time_test();
+#if HAVE_SIGNAL
+  signal(SIGTERM, term);
 
 #if HAVE_ALARM
   if (opt_alarm) {
@@ -532,8 +536,15 @@
   }
 #endif
 
+#endif
+
+  time_test();
+
   root = su_root_create(NULL);
   if (!root) perror("su_root_create"), exit(1);
+
+  fprintf(stdout, "test_su: testing %s port implementation\n",
+	  su_root_name(root));
   
   su_root_threading(root, !opt_singlethread);
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_rbtree.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_rbtree.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_rbtree.c	Tue Apr 24 10:14:28 2007
@@ -681,11 +681,12 @@
 }
 
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr,
-	  "usage: %s [-v]\n",
+	  "usage: %s [-v] [-a]\n",
 	  name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -696,8 +697,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= test_insert(); fflush(stdout);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su.c	Tue Apr 24 10:14:28 2007
@@ -47,17 +47,10 @@
 #define TSTFLAGS tstflags
 #include <sofia-sip/tstdef.h>
 
-char const *name = "su_torture";
-
-static int test_sockaddr(void);
-
-void usage(void)
-{
-  fprintf(stderr, "usage: %s [-v]\n", name);
-}
+char const *name = "torture_su";
 
 /**  */
-int test_sockaddr(void)
+static int test_sockaddr(void)
 {
   su_localinfo_t hints[1] = {{ LI_CANONNAME }};
   su_localinfo_t *li, *res = NULL;
@@ -100,7 +93,7 @@
   TEST(su_setblocking(s, 1), 0);
   TEST(su_close(s), 0);
 
-  su_freelocalinfo(res);
+  su_freelocalinfo(res), res = NULL;
 
 #if SU_HAVE_IN6
   hints->li_family = AF_INET6;
@@ -111,16 +104,17 @@
   for (li = res; li; li = li->li_next)
     TEST(li->li_family, AF_INET6);
 
-  su_freelocalinfo(res);
+  su_freelocalinfo(res), res = NULL;
 #endif
 
   hints->li_flags |= LI_NUMERIC;
   TEST(su_getlocalinfo(hints, &res), 0);
+  su_freelocalinfo(res), res = NULL;
 
-  hints->li_flags |= LI_NAMEREQD;
   res = NULL;
+  hints->li_flags |= LI_NAMEREQD;
   su_getlocalinfo(hints, &res);
-  su_freelocalinfo(res);
+  su_freelocalinfo(res), res = NULL;
 
   memset(a, 0, sizeof *a); 
   memset(b, 0, sizeof *b); 
@@ -161,7 +155,7 @@
 
 int test_sendrecv(void)
 {
-  int s, l, a;
+  su_socket_t s, l, a;
   int n;
   su_sockaddr_t su, csu;
   socklen_t sulen = sizeof su.su_sin, csulen = sizeof csu.su_sin;
@@ -260,6 +254,120 @@
   END();
 }
 
+#if HAVE_SELECT 
+
+#if HAVE_WIN32
+int test_select(void)
+{
+  return 0;
+}
+#else
+
+#if HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#elif HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <sys/types.h>
+#include <unistd.h>
+
+#ifndef __NFDBITS
+#define __NFDBITS (8 * sizeof (long int))
+#endif
+
+#undef howmany
+/* Size of fd set in bytes. Sorry, octets. */
+#define howmany(n) (((n) + __NFDBITS - 1) / __NFDBITS * (__NFDBITS / 8))
+
+#define FD_ZERO_TO(maxfd, set) \
+  memset((set), 0, howmany(maxfd))
+
+/* Test assumptions in su_select_port implementation */
+int test_select(void)
+{
+  su_socket_t s;
+  su_sockaddr_t su;
+  socklen_t sulen = sizeof su.su_sin;
+  size_t bytes;
+  fd_set *rset, *wset;
+  struct timeval tv;
+
+  BEGIN();
+
+  s = su_socket(AF_INET, SOCK_DGRAM, 0); TEST_1(s != -1);
+
+  memset(&su, 0, sulen);
+  su.su_len = sulen;
+  su.su_family = AF_INET;
+  TEST(inet_pton(AF_INET, "127.0.0.1", &su.su_sin.sin_addr), 1);
+  TEST(bind(s, &su.su_sa, sulen), 0);
+  TEST(getsockname(s, &su.su_sa, &sulen), 0);
+  
+  tv.tv_sec = 0; tv.tv_usec = 1000;
+  TEST(select(0, NULL, NULL, NULL, &tv), 0);
+
+  bytes = howmany(s);
+  TEST_1(rset = malloc(bytes));
+  TEST_1(wset = malloc(bytes));
+
+  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset); FD_SET(s, wset);
+  tv.tv_sec = 0, tv.tv_usec = 1000;
+  TEST(select(s + 1, NULL, wset, NULL, &tv), 1);
+  TEST_1(FD_ISSET(s, wset));
+
+  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset); 
+  FD_SET(s, rset); FD_SET(s, wset);
+  tv.tv_sec = 0, tv.tv_usec = 1000;
+  TEST(select(s + 1, rset, wset, NULL, &tv), 1);
+  TEST_1(!FD_ISSET(s, rset));
+  TEST_1(FD_ISSET(s, wset));
+
+  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset); 
+  FD_SET(s, rset); FD_SET(s, wset);
+  tv.tv_sec = 0, tv.tv_usec = 1000;
+  TEST(select(s + 1, rset, NULL, NULL, &tv), 0);
+  TEST_1(!FD_ISSET(s, rset));
+
+  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset); 
+  FD_SET(s, rset); FD_CLR(s, wset);
+  tv.tv_sec = 0, tv.tv_usec = 1000;
+  TEST(select(s + 1, rset, wset, NULL, &tv), 0);
+  TEST_1(!FD_ISSET(s, rset));
+  TEST_1(!FD_ISSET(s, wset));
+
+  TEST(su_sendto(s, "foo", 3, 0, &su, sulen), 3);
+
+  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset); 
+  FD_SET(s, rset); FD_CLR(s, wset);
+  tv.tv_sec = 0, tv.tv_usec = 1000;
+  TEST(select(s + 1, rset, wset, NULL, &tv), 1);
+  TEST_1(FD_ISSET(s, rset));
+  TEST_1(!FD_ISSET(s, wset));
+
+  FD_ZERO_TO(s, rset); FD_ZERO_TO(s, wset); 
+  FD_SET(s, rset); FD_SET(s, wset);
+  tv.tv_sec = 0, tv.tv_usec = 1000;
+  TEST(select(s + 1, rset, wset, NULL, &tv), 2);
+  TEST_1(FD_ISSET(s, rset));
+  TEST_1(FD_ISSET(s, wset));
+
+  su_close(s);
+
+  free(wset);
+  free(rset);
+
+  END();
+}
+#endif
+
+#else
+int test_select(void)
+{
+  return 0;
+}
+#endif
+
 #include <sofia-sip/su_md5.h>
 
 int test_md5(void)
@@ -379,6 +487,12 @@
   END();
 }
 
+void usage(int exitcode)
+{
+  fprintf(stderr, "usage: %s [-v] [-a]\n", name);
+  exit(exitcode);
+}
+
 int main(int argc, char *argv[])
 {
   int retval = 0;
@@ -389,16 +503,18 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
   
   retval |= test_sockaddr();
   retval |= test_sendrecv();
+  retval |= test_select();
   retval |= test_md5(); fflush(stdout);
 
   su_deinit();
 
   return retval;
 }
-

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_alloc.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_alloc.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_alloc.c	Tue Apr 24 10:14:28 2007
@@ -59,6 +59,12 @@
   (*ex->p)++;
 }
 
+void test_destructor(void *a)
+{
+  su_home_t *h = a;
+  h->suh_size = 13;
+}
+
 /** Test basic memory home operations  */
 static int test_alloc(void)
 {
@@ -78,8 +84,8 @@
 
   d0 = d1a = d1 = d2 = d3 = 0;
   h0->p = &d0; h1->p = &d1a;
-  TEST(su_home_desctructor(h0->home, exdestructor), 0);
-  TEST(su_home_desctructor(h1->home, exdestructor), 0);
+  TEST(su_home_destructor(h0->home, exdestructor), 0);
+  TEST(su_home_destructor(h1->home, exdestructor), 0);
 
   TEST_1(h2 = su_home_ref(h0->home));
   su_home_unref(h0->home);
@@ -95,7 +101,7 @@
   TEST(d1a, destructed_once);
 
   TEST_1(h1 = su_home_clone(h0->home, sizeof(*h1)));
-  TEST(su_home_desctructor(h1->home, exdestructor), 0);
+  TEST(su_home_destructor(h1->home, exdestructor), 0);
   h1->p = &d1;
 
   for (i = 0; i < 128; i++)
@@ -125,7 +131,7 @@
 
   TEST_1(su_in_home(h2->home, m));
   TEST_1(!su_in_home(h2->home, (char *)m + 1));
-  TEST_1(!su_in_home(h2->home, su_in_home));
+  TEST_1(!su_in_home(h2->home, (void *)(intptr_t)su_in_home));
   TEST_1(!su_in_home(h3->home, m));
   TEST_1(!su_in_home(NULL, m));
   TEST_1(!su_in_home(h3->home, NULL));
@@ -161,6 +167,25 @@
   su_home_check(h0->home);
   su_home_zap(h0->home);
 
+  {
+    su_home_t h1[1];
+
+    memset(h1, 0, sizeof h1);
+
+    TEST(su_home_init(h1), 0);
+    TEST(su_home_threadsafe(h1), 0);
+
+    TEST_1(su_home_ref(h1));
+    TEST_1(su_home_ref(h1));
+
+    TEST(su_home_destructor(h1, test_destructor), 0);
+
+    TEST_1(!su_home_unref(h1));
+    TEST_1(!su_home_unref(h1));
+    TEST_1(su_home_unref(h1));
+    TEST(h1->suh_size, 13);
+  }
+
   END();
 }
 
@@ -654,9 +679,10 @@
   END();
 }
 
-void usage(void)
+void usage(int exitcode)
 {
-  fprintf(stderr, "usage: %s [-v]\n", name);
+  fprintf(stderr, "usage: %s [-v] [-a]\n", name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -667,8 +693,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= test_alloc();

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_bm.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_bm.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_bm.c	Tue Apr 24 10:14:28 2007
@@ -43,12 +43,8 @@
 char const *name = "torture_su_bm";
 int tstflags;
 
-#define TORTURELOG(x)		       \
-  do {				       \
-    if (tstflags & (2 * tst_verbatim)) \
-      printf x;			       \
-  } while(0)
-    
+#define TORTURELOG TEST_LOG
+
 #include "su_bm.c"
 
 int test_bm(void)
@@ -192,6 +188,8 @@
 
     s = bm_memmem(hs, strlen(hs), needle, nlen, fwd);
 
+    free(fwd);
+
     TEST_S(s, hs + 1919);
 
     TEST_1(bm_memmem(hs, strlen(hs), Needle, nlen, NULL) == 0);
@@ -211,11 +209,12 @@
 }
 
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, 
-	  "usage: %s [-v]\n", 
+	  "usage: %s [-v] [-a]\n", 
 	  name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -232,10 +231,12 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else if (strcmp(argv[i], "-l") == 0)
-      tstflags |= 2 * tst_verbatim;
+      tstflags |= tst_log;
     else
-      usage();
+      usage(1);
   }
 
   retval |= test_bm(); fflush(stdout);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_port.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_port.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_port.c	Tue Apr 24 10:14:28 2007
@@ -24,7 +24,7 @@
 
 /**
  * @file torture_su_port.c
- * @brief Test su_port interface
+ * @brief Test su_poll_port interface
  *
  * @author Pekka Pessi <Pekka.Pessi at nokia.com>
  * @date Created: Wed Mar 10 17:05:23 2004 ppessi
@@ -39,7 +39,10 @@
 
 #define SU_ROOT_MAGIC_T struct su_root_magic_s
 
-#include "su_port.c"
+#include "su_poll_port.c"
+
+#undef HAVE_EPOLL
+#define HAVE_EPOLL 0
 
 #if HAVE_FUNC
 #elif HAVE_FUNCTION
@@ -56,7 +59,7 @@
 
 char const *name = "torture_su_port";
 
-int N0 = SU_HAVE_MBOX, N = 128, I = 128 + 1;
+int const N0 = SU_MBOX_SIZE > 0, N = 128, I = 129;
 
 int test_sup_indices(su_port_t const *port)
 {
@@ -121,7 +124,7 @@
 
   magic->wakeups[i]++;
 
-#if HAVE_POLL
+#if HAVE_POLL || HAVE_SELECT
   if (w->fd != magic->sockets[i])
     return ++magic->error;
 #endif
@@ -144,7 +147,8 @@
       su_perror("getsockname"), exit(1);
     if (su_sendto(magic->sockets[1], "X", 1, 0, su, sulen) < 0)
       su_perror("su_sendto"), exit(1);
-    n = su_port_wait_events(port, 100);
+    n = su_poll_port_wait_events(port, 100);
+
     if (n != 1)
       return 1;
     if (magic->error)
@@ -188,9 +192,10 @@
 
   su_root_size_hint = 16;
 
-  TEST_1(port = su_port_create());
+  TEST_1(port = su_poll_port_create());
   TEST(su_port_threadsafe(port), 0);
-  SU_PORT_INCREF(port, __func__);
+  /* Before 1.12.4 su_port_create() had reference count 0 after creation */
+  /* su_port_incref(port, "test_register"); */
 
   TEST_1(test_sup_indices(port));
 
@@ -292,16 +297,17 @@
     TEST(su_port_deregister(port, reg[i]), -1);
   }
 
-  TEST_VOID(su_port_decref(port, 1, __func__));
+  TEST_VOID(su_port_decref(port, __func__));
 
   END();
 }
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr,
-	  "usage: %s [-v]\n",
+	  "usage: %s [-v] [-a]\n",
 	  name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -319,8 +325,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   su_init();

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_root.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_root.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_root.c	Tue Apr 24 10:14:28 2007
@@ -37,7 +37,7 @@
 
 #include "config.h"
 
-char const *name = "su_root_test";
+char const *name = "torture_su_root";
 
 #include <stdio.h>
 #include <string.h>
@@ -54,15 +54,19 @@
 
 #include <sofia-sip/su_wait.h>
 #include <sofia-sip/su_alloc.h>
+#include <sofia-sip/su_log.h>
 
-typedef struct test_ep_s {
+struct test_ep_s {
+  test_ep_t     *next, **prev, **list;
   int           i;
   int           s;
   su_wait_t     wait[1];
   int           registered;
   socklen_t     addrlen;
   su_sockaddr_t addr[1];
-} test_ep_at[1];
+};
+
+typedef struct test_ep_s   test_ep_at[1];
 
 struct root_test_s {
   su_home_t  rt_home[1];
@@ -81,11 +85,22 @@
   unsigned   rt_success_init:1;
   unsigned   rt_success_deinit:1;
 
+  unsigned   rt_sent_reporter:1;
+  unsigned   rt_recv_reporter:1;
+  unsigned   rt_reported_reporter:1;
+
+  unsigned :0;
+
   test_ep_at rt_ep[5];
+
+  int rt_sockets, rt_woken;
 };
 
 /** Test root initialization */
-int init_test(root_test_t *rt)
+int init_test(root_test_t *rt,
+	      char const *preference,
+	      su_port_create_f *create,
+	      su_clone_start_f *start)
 {
   su_sockaddr_t su[1] = {{ 0 }};
   int i;
@@ -94,10 +109,15 @@
 
   su_init();
 
-  su->su_family = rt->rt_family;
+  su_port_prefer(create, start);
 
   TEST_1(rt->rt_root = su_root_create(rt));
 
+  printf("%s: testing %s (%s) implementation\n",
+	 name, preference, su_root_name(rt->rt_root));
+
+  su->su_family = rt->rt_family;
+
   for (i = 0; i < 5; i++) {
     test_ep_t *ep = rt->rt_ep[i];
     ep->i = i;
@@ -179,7 +199,6 @@
 static
 su_wakeup_f wakeups[5] = { wakeup0, wakeup1, wakeup2, wakeup3, wakeup4 };
 
-
 static
 void test_run(root_test_t *rt)
 {
@@ -271,6 +290,133 @@
   END();
 }
 
+
+int wakeup_remove(root_test_t *rt, su_wait_t *w, test_ep_t *node)
+{
+  char buffer[64];
+  ssize_t x;
+  test_ep_t *n = node->next; 
+
+  su_wait_events(w, node->s);
+
+  x = recv(node->s, buffer, sizeof(buffer), 0);
+
+  if (x < 0)
+    fprintf(stderr, "%s: %s\n", "recv", su_strerror(su_errno()));
+
+  if (node->prev) {		/* first run */
+    *node->prev = n;
+
+    if (n) {
+      *node->prev = node->next;    
+      node->next->prev = node->prev;
+      sendto(n->s, "foo", 3, 0, (void *)n->addr, n->addrlen);
+    }
+
+    node->next = NULL;
+    node->prev = NULL;
+    
+    if (!*node->list) {
+      su_root_break(rt->rt_root);
+    }
+  }
+  else {			/* second run */
+    if (++rt->rt_woken == rt->rt_sockets)
+      su_root_break(rt->rt_root);
+  }
+
+  return 0;
+}
+
+
+int event_test(root_test_t rt[1])
+{
+  BEGIN();
+  int i = 0, N = 2048;
+  test_ep_t *n, *nodes, *list = NULL;
+  su_sockaddr_t su[1];
+  socklen_t sulen;
+  
+  TEST_1(nodes = calloc(N, sizeof *nodes));
+  
+  memset(su, 0, sulen = sizeof su->su_sin);
+  su->su_len = sizeof su->su_sin;
+  su->su_family = AF_INET;
+  su->su_sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
+
+  for (i = 0; i < N; i++) {
+    n = nodes + i;
+    n->s = su_socket(AF_INET, SOCK_DGRAM, 0);
+
+    if (n->s == INVALID_SOCKET)
+      break;
+
+    n->addrlen = sizeof n->addr;
+
+    n->addr->su_len = sizeof n->addr;
+
+    if (bind(n->s, (void *)su, sulen) < 0) {
+      su_perror("bind()");
+      su_close(n->s);
+      break;
+    }
+      
+    if (getsockname(n->s, (void *)n->addr, &n->addrlen)) {
+      su_perror("getsockname()");
+      su_close(n->s);
+      break;
+    }
+
+    if (su_wait_create(n->wait, n->s, SU_WAIT_IN)) {
+      su_perror("su_wait_create()");
+      su_close(n->s);
+      break;
+    }
+
+    n->registered = su_root_register(rt->rt_root, n->wait, wakeup_remove, n, 0);
+    if (n->registered < 0) {
+      su_wait_destroy(n->wait);
+      su_close(n->s);
+      break;
+    }
+    
+    n->list = &list, n->prev = &list;
+    if ((n->next = list))
+      n->next->prev = &n->next;
+    list = n;
+  }
+
+  TEST_1(i >= 1);
+
+  N = i;
+
+  /* Wake up socket at a time */
+  n = list; sendto(n->s, "foo", 3, 0, (void *)n->addr, n->addrlen);
+
+  su_root_run(rt->rt_root);
+
+  for (i = 0; i < N; i++) {
+    n = nodes + i;
+    TEST_1(n->prev == NULL);
+    sendto(n->s, "bar", 3, 0, (void *)n->addr, n->addrlen);
+  }
+
+  rt->rt_sockets = N;
+
+  /* Wake up all sockets */
+  su_root_run(rt->rt_root);
+
+  for (i = 0; i < N; i++) {
+    n = nodes + i;
+    su_root_deregister(rt->rt_root, n->registered);
+    TEST_1(su_close(n->s) == 0);
+  }
+
+  free(nodes);
+
+  END();
+}
+
 int fail_init(su_root_t *root, root_test_t *rt)
 {
   rt->rt_fail_init = 1;
@@ -293,14 +439,49 @@
   rt->rt_success_deinit = 1;
 }
 
+void receive_a_reporter(root_test_t *rt, 
+			su_msg_r msg,
+			su_msg_arg_t *arg)
+{
+  rt->rt_recv_reporter = 1;
+}
+
+void receive_recv_report(root_test_t *rt, 
+			 su_msg_r msg,
+			 su_msg_arg_t *arg)
+{
+  rt->rt_reported_reporter = 1;
+}
+
+void send_a_reporter_msg(root_test_t *rt, 
+			 su_msg_r msg,
+			 su_msg_arg_t *arg)
+{
+  su_msg_r m = SU_MSG_R_INIT;
+
+  if (su_msg_create(m,
+		    su_msg_from(msg),
+		    su_msg_to(msg),
+		    receive_a_reporter,
+		    0) == 0 &&
+      su_msg_report(m, receive_recv_report) == 0 &&
+      su_msg_send(m) == 0)
+    rt->rt_sent_reporter = 1;
+}
+
 static int clone_test(root_test_t rt[1])
 {
   BEGIN();
 
+  su_msg_r m = SU_MSG_R_INIT;
+
   rt->rt_fail_init = 0;
   rt->rt_fail_deinit = 0;
   rt->rt_success_init = 0;
   rt->rt_success_deinit = 0;
+  rt->rt_sent_reporter = 0;
+  rt->rt_recv_reporter = 0;
+  rt->rt_reported_reporter = 0;
 
   TEST(su_clone_start(rt->rt_root,
 		      rt->rt_clone,
@@ -318,45 +499,108 @@
   TEST_1(rt->rt_success_init);
   TEST_1(!rt->rt_success_deinit);
 
+  /* Make sure 3-way handshake is done as expected */
+  TEST(su_msg_create(m,
+		     su_clone_task(rt->rt_clone),
+		     su_root_task(rt->rt_root),
+		     send_a_reporter_msg,
+		     0), 0);
+  TEST(su_msg_send(m), 0);
+
   TEST_VOID(su_clone_wait(rt->rt_root, rt->rt_clone));
 
   TEST_1(rt->rt_success_deinit);
-  
+  TEST_1(rt->rt_sent_reporter);
+  TEST_1(rt->rt_recv_reporter);
+  TEST_1(rt->rt_reported_reporter);
+
+  rt->rt_recv_reporter = 0;
+
+  /* Make sure we can handle messages done as expected */
+  TEST(su_msg_create(m,
+		     su_root_task(rt->rt_root),
+		     su_task_null,
+		     receive_a_reporter,
+		     0), 0);
+  TEST(su_msg_send(m), 0);
+  su_root_step(rt->rt_root, 0);
+  TEST_1(rt->rt_recv_reporter);
+
+  rt->rt_success_init = 0;
+  rt->rt_success_deinit = 0;
+
   END();
 }
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, 
-	  "usage: %s [-v]\n", 
+	  "usage: %s [-v] [-a]\n", 
 	  name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
 {
-  root_test_t rt[1] = {{{ SU_HOME_INIT(rt) }}};
+  root_test_t *rt, rt0[1] = {{{ SU_HOME_INIT(rt0) }}}, rt1[1];
   int retval = 0;
   int i;
 
+  struct {
+    su_port_create_f *create;
+    su_clone_start_f *start;
+    char const *name;
+  } prefer[] =
+      {
+	{ NULL, NULL, "default" },
+#if HAVE_EPOLL
+	{ su_epoll_port_create, su_epoll_clone_start, "epoll", },
+#endif
+#if HAVE_KQUEUE
+	{ su_kqueue_port_create, su_kqueue_clone_start, "kqueue", },
+#endif
+#if HAVE_SYS_DEVPOLL_H
+	{ su_devpoll_port_create, su_devpoll_clone_start, "devpoll", },
+#endif
+#if HAVE_POLL_PORT
+	{ su_poll_port_create, su_poll_clone_start, "poll" },
+#endif
+#if HAVE_SELECT
+	{ su_select_port_create, su_select_clone_start, "select" },
+#endif
+	{ NULL, NULL }
+      };
+
+  rt = rt0;
   rt->rt_family = AF_INET;
 
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       rt->rt_flags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      rt->rt_flags |= tst_abort;
 #if SU_HAVE_IN6
     else if (strcmp(argv[i], "-6") == 0)
       rt->rt_family = AF_INET6;
 #endif
     else
-      usage();
+      usage(1);
   }
 
-  retval |= init_test(rt);
-  retval |= register_test(rt);
-  retval |= clone_test(rt);
-  su_root_threading(rt->rt_root, 0);
-  retval |= clone_test(rt);
-  retval |= deinit_test(rt);
+  i = 0;
+
+  do {
+    rt = rt1, *rt = *rt0;
+
+    retval |= init_test(rt, prefer[i].name, prefer[i].create, prefer[i].start);
+    retval |= register_test(rt);
+    retval |= event_test(rt);
+    su_root_threading(rt->rt_root, 1);
+    retval |= clone_test(rt);
+    su_root_threading(rt->rt_root, 0);
+    retval |= clone_test(rt);
+    retval |= deinit_test(rt);
+  } while (prefer[++i].create);
 
   return retval;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_root_osx.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_root_osx.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_root_osx.c	Tue Apr 24 10:14:28 2007
@@ -327,11 +327,12 @@
   END();
 }
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, 
-	  "usage: %s [-v]\n", 
+	  "usage: %s [-v] [-a]\n", 
 	  name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -345,12 +346,14 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       rt->rt_flags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      rt->rt_flags |= tst_abort;
 #if SU_HAVE_IN6
     else if (strcmp(argv[i], "-6") == 0)
       rt->rt_family = AF_INET6;
 #endif
     else
-      usage();
+      usage(1);
   }
 
   retval |= init_test(rt);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_tag.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_tag.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_tag.c	Tue Apr 24 10:14:28 2007
@@ -620,11 +620,12 @@
   END();
 }
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, 
-	  "usage: %s [-v]\n", 
+	  "usage: %s [-v] [-a]\n", 
 	  name);
+  exit(exitcode);
 }
 
 int main(int argc, char *argv[])
@@ -637,8 +638,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= test_assumptions();

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_time.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_time.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_time.c	Tue Apr 24 10:14:28 2007
@@ -54,11 +54,12 @@
 static int test2(int flags);
 static int test3(int flags);
 
-void usage(void)
+void usage(int exitcode)
 {
   fprintf(stderr, 
-	  "usage: %s [-v]\n", 
+	  "usage: %s [-v] [-a]\n", 
 	  name);
+  exit(exitcode);
 }
 
 char *lastpart(char *path)
@@ -80,8 +81,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       flags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      flags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= test1(flags); fflush(stdout);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_timer.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_timer.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/su/torture_su_timer.c	Tue Apr 24 10:14:28 2007
@@ -39,7 +39,6 @@
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
-#include <signal.h>
 
 #include <assert.h>
 
@@ -91,6 +90,10 @@
   putchar('X'); fflush(stdout);
 }
 
+#if HAVE_SIGNAL
+
+#include <signal.h>
+
 su_msg_r intr_msg = SU_MSG_R_INIT;
 
 static RETSIGTYPE intr_handler(int signum)
@@ -103,6 +106,8 @@
   su_root_break(tester->root);
 }
 
+#endif
+
 void
 end_test(struct tester *tester, su_timer_t *t, struct timing *ti)
 {
@@ -182,6 +187,7 @@
 
   tester->root = root = su_root_create(tester);
 
+#if HAVE_SIGNAL
   su_msg_create(intr_msg,
 		su_root_task(root),
 		su_root_task(root),
@@ -189,10 +195,10 @@
 
   signal(SIGINT, intr_handler);
 #if HAVE_SIGPIPE
-  signal(SIGPIPE, intr_handler);
   signal(SIGQUIT, intr_handler);
   signal(SIGHUP, intr_handler);
 #endif
+#endif
 
   t = su_timer_create(su_root_task(root), interval);
   t1 = su_timer_create(su_root_task(root), 1);
@@ -217,7 +223,9 @@
 
   su_root_run(root);
 
+#if HAVE_SIGNAL
   su_msg_destroy(intr_msg);
+#endif
 
   su_timer_destroy(t);
   su_timer_destroy(t1);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -35,20 +35,28 @@
 			sofia-sip/tport_plugins.h
 
 TLS_SRC =		tport_type_tls.c tport_tls.c tport_tls.h
-
 if HAVE_TLS
 USE_TLS_SRC = 		$(TLS_SRC)
 endif
 
+STUN_SRC =		tport_stub_stun.c tport_type_stun.c
+if HAVE_STUN
+USE_STUN_SRC = 		$(STUN_SRC)
+endif
+
+HTTP_SRC =		tport_type_connect.c
+if HAVE_NTH
+USE_HTTP_SRC = 		$(HTTP_SRC)
+endif
+
 libtport_la_SOURCES = 	tport.c tport_logging.c \
-			tport_stub_stun.c tport_stub_sigcomp.c \
+			tport_stub_sigcomp.c \
 			tport_type_udp.c tport_type_tcp.c tport_type_sctp.c \
-			tport_type_connect.c tport_type_stun.c \
 			tport_internal.h \
-			tport_tag.c tport_tag_ref.c $(USE_TLS_SRC)
+			tport_tag.c tport_tag_ref.c $(USE_HTTP_SRC) $(USE_TLS_SRC) $(USE_STUN_SRC)
 
 # to make sure all files end up in the dist package
-EXTRA_libtport_la_SOURCES = $(TLS_SRC) 
+EXTRA_libtport_la_SOURCES = $(TLS_SRC) $(STUN_SRC) $(HTTP_SRC)
 
 # Disable for now
 EXTRA_libtport_la_SOURCES += tport_sigcomp.c tport_threadpool.c
@@ -72,10 +80,11 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile tport.docs \
+EXTRA_DIST =		tport.docs \
 			certificates.html agent.pem cafile.pem
 
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
+

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/sofia-sip/tport_tag.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/sofia-sip/tport_tag.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/sofia-sip/tport_tag.h	Tue Apr 24 10:14:28 2007
@@ -389,6 +389,8 @@
  * Use with tport_tcreate(), tport_tbind(), tport_set_params(), nua_create(),
  * nta_agent_create(), nta_agent_add_tport(), nth_engine_create(), or
  * initial nth_site_create().
+ *
+ * @NEW_1_12_5
  */
 #define TPTAG_TOS(x) tptag_tos, tag_int_v((x))
 
@@ -402,6 +404,8 @@
  * nth_engine_create(), or initial nth_site_create().
  *
  * @sa #TPORT_DUMP, TPTAG_DUMP()
+ *
+ * @NEW_1_12_5
  */
 #define TPTAG_LOG(x) tptag_log, tag_bool_v((x))
 
@@ -415,6 +419,8 @@
  * nth_engine_create(), or initial nth_site_create().
  *
  * @sa #TPORT_DUMP, TPTAG_LOG().
+ *
+ * @NEW_1_12_5
  */
 #define TPTAG_DUMP(x) tptag_dump, tag_str_v((x))
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/test_tport.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/test_tport.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/test_tport.c	Tue Apr 24 10:14:28 2007
@@ -112,11 +112,6 @@
 
 SOFIAPUBVAR su_log_t tport_log[];
 
-void usage(void)
-{
-  fprintf(stderr, "usage: %s [-v]\n", name);
-}
-
 static int name_test(tp_test_t *tt)
 {
   tp_name_t tpn[1];
@@ -381,7 +376,7 @@
 {
   tt->tt_status = -1;
   fprintf(stderr, "tp_test_error(%p): error %d (%s) from %s\n", 
-	  tp, errcode, su_strerror(errcode), 
+	  (void *)tp, errcode, su_strerror(errcode), 
 	  remote ? remote : "<unknown destination>");
 }
 
@@ -778,13 +773,15 @@
 
 static int tcp_test(tp_test_t *tt)
 {
+  BEGIN();
+
+#ifndef WIN32			/* Windows seems to be buffering too much */
+
   msg_t *msg = NULL;
   int i;
   tport_t *tp, *tp0;
   char ident[16];
 
-  BEGIN();
-
   /* Create a large message, just to force queueing in sending end */
   TEST(new_test_msg(tt, &msg, "tcp-0", 1, 16 * 64 * 1024), 0);
   test_create_md5(tt, msg);
@@ -861,6 +858,8 @@
 
   tport_decref(&tp0);
 
+#endif
+
   END();
 }
 
@@ -1357,6 +1356,12 @@
   END();
 }
 
+void usage(int exitcode)
+{
+  fprintf(stderr, "usage: %s [-v] [-a]\n", name);
+  exit(exitcode);
+}
+
 int main(int argc, char *argv[])
 {
   int flags = 0;	/* XXX */
@@ -1365,10 +1370,12 @@
   tp_test_t tt[1] = {{{ SU_HOME_INIT(tt) }}};
 
   for (i = 1; argv[i]; i++) {
-    if (strcmp(argv[i], "-v") == 0)
+    if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbatim") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--abort") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   /* Use log */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport.c	Tue Apr 24 10:14:28 2007
@@ -292,7 +292,7 @@
 }
 
 /** MTU for transport  */
-static inline usize_t tport_mtu(tport_t const *self)
+static inline unsigned tport_mtu(tport_t const *self)
 {
   return self->tp_params->tpp_mtu;
 }
@@ -453,7 +453,7 @@
   if (!mr)
     return NULL;
 
-  SU_DEBUG_7(("%s(): %p\n", "tport_create", mr));
+  SU_DEBUG_7(("%s(): %p\n", "tport_create", (void *)mr));
 
   mr->mr_stack = stack;
   mr->mr_tpac = tpac;
@@ -492,7 +492,9 @@
   if (tick < 200)
     tick = 200;
 
+#if HAVE_SOFIA_STUN
   tport_init_stun_server(mr, ta_args(ta));
+#endif
 
   mr->mr_timer = su_timer_create(su_root_task(root), tick);
   su_timer_set(mr->mr_timer, tport_tick, mr);
@@ -516,7 +518,7 @@
 	/* tpac_address */ NULL
       }};
 
-  SU_DEBUG_7(("%s(%p)\n", __func__, self));
+  SU_DEBUG_7(("%s(%p)\n", __func__, (void *)self));
 
   if (self == NULL)
     return;
@@ -531,7 +533,9 @@
   while (mr->mr_primaries)
     tport_zap_primary(mr->mr_primaries);
 
+#if HAVE_SOFIA_STUN
   tport_deinit_stun_server(mr);
+#endif
 
   if (mr->mr_dump_file)
     fclose(mr->mr_dump_file), mr->mr_dump_file = NULL;
@@ -579,7 +583,8 @@
     if (!pri->pri_public)
       tp->tp_addrinfo->ai_addr = &tp->tp_addr->su_sa;
 
-    SU_DEBUG_5(("%s(%p): new primary tport %p\n", __func__, mr, pri));
+    SU_DEBUG_5(("%s(%p): new primary tport %p\n", __func__, (void *)mr,
+		(void *)pri));
   }
 
   *next = pri; 
@@ -706,7 +711,7 @@
   pri->pri_primary->tp_has_connection = 0;
 
   SU_DEBUG_5(("%s(%p): %s " TPN_FORMAT "\n", 
-	      __func__, pri, "listening at",
+			  __func__, (void *)pri, "listening at",
 	      TPN_ARGS(pri->pri_primary->tp_name)));
 
   return pri;
@@ -778,8 +783,8 @@
 
   if (self->tp_pri->pri_vtable->vtp_set_events)
     return self->tp_pri->pri_vtable->vtp_set_events(self);
-
-  SU_DEBUG_7(("tport_set_events(%p): events%s%s%s\n", self,
+  
+  SU_DEBUG_7(("tport_set_events(%p): events%s%s%s\n", (void *)self,
 	      (events & SU_WAIT_IN) ? " IN" : "",
 	      (events & SU_WAIT_OUT) ? " OUT" : "",
 	      SU_WAIT_CONNECT != SU_WAIT_OUT &&
@@ -818,7 +823,7 @@
   self = su_home_clone(mr->mr_home, pri->pri_vtable->vtp_secondary_size);
 
   if (self) {
-    SU_DEBUG_7(("%s(%p): new secondary tport %p\n", __func__, pri, self));
+	  SU_DEBUG_7(("%s(%p): new secondary tport %p\n", __func__, (void *)pri, (void *)self));
 
     self->tp_refs = -1;			/* Freshly allocated  */
     self->tp_master = mr;
@@ -917,8 +922,8 @@
 	    su_wait_destroy(wait),				     \
 	    (SU_LOG_LEVEL >= errlevel ?				     \
 	     su_llog(tport_log, errlevel,			     \
-		     "%s(%p): %s(pf=%d %s/%s): %s\n",		     \
-		     __func__, pri, #what, ai->ai_family,	     \
+		     "%s(%p): %s(pf=%d %s/%s): %s\n",			\
+				 __func__, (void *)pri, #what, ai->ai_family,	\
 		     tpn->tpn_proto,				     \
 		     tport_hostport(buf, sizeof(buf),		     \
 				    (void *)ai->ai_addr, 2),	     \
@@ -983,11 +988,11 @@
 
   if (ai == real_ai) {
     SU_DEBUG_5(("%s(%p): %s to " TPN_FORMAT "\n", 
-		__func__, self, what, TPN_ARGS(self->tp_name)));
+				__func__, (void *)self, what, TPN_ARGS(self->tp_name)));
   }
   else {
     SU_DEBUG_5(("%s(%p): %s via %s to " TPN_FORMAT "\n",
-		__func__, self, what,
+				__func__, (void *)self, what,
 		tport_hostport(buf, sizeof(buf), (void *)ai->ai_addr, 2),
 		TPN_ARGS(self->tp_name)));
   }
@@ -1016,7 +1021,7 @@
   if (self->tp_msg) {
     msg_destroy(self->tp_msg), self->tp_msg = NULL;
     SU_DEBUG_3(("%s(%p): zapped partially received message\n", 
-		__func__, self));
+				__func__, (void *)self));
   }
 
   if (self->tp_queue && self->tp_queue[self->tp_qhead]) {
@@ -1026,16 +1031,18 @@
       n++;
     }
     SU_DEBUG_3(("%s(%p): zapped %lu queued messages\n", 
-		__func__, self, (LU)n));
+				__func__, (void *)self, (LU)n));
   }
 
   if (self->tp_pused) {
-    SU_DEBUG_3(("%s(%p): zapped with pending requests\n", __func__, self));
+	  SU_DEBUG_3(("%s(%p): zapped with pending requests\n", __func__, (void *)self));
   }
 
   mr = self->tp_master;
 
+#if HAVE_SOFIA_STUN
   tport_stun_server_remove_socket(self);
+#endif
 
   if (self->tp_index)
     su_root_deregister(mr->mr_root, self->tp_index);
@@ -1110,7 +1117,7 @@
     || !tport_is_primary(self) || !tport_is_dgram(self);
 
   n = tl_tgets(ta_args(ta),
-	       TPTAG_MTU(tpp->tpp_mtu),
+	       TPTAG_MTU((usize_t)tpp->tpp_mtu),
 	       TPTAG_REUSE(self->tp_reusable),
 	       TPTAG_CONNECT(connect),
 	       TPTAG_QUEUESIZE(tpp->tpp_qsize),
@@ -1146,14 +1153,16 @@
   ta_list ta;
   int n;
   tport_params_t tpp[1], *tpp0;
-
+  
+  usize_t mtu;
   int connect, sdwn_error, reusable, stun_server;
-
+  
   if (self == NULL)
     return su_seterrno(EINVAL);
 
   memcpy(tpp, tpp0 = self->tp_params, sizeof *tpp);
 
+  mtu = tpp->tpp_mtu;
   connect = tpp->tpp_conn_orient;
   sdwn_error = tpp->tpp_sdwn_error;
   reusable = self->tp_reusable;
@@ -1162,7 +1171,7 @@
   ta_start(ta, tag, value);
 
   n = tl_gets(ta_args(ta),
-	      TPTAG_MTU_REF(tpp->tpp_mtu),
+	      TPTAG_MTU_REF(mtu),
 	      TAG_IF(!self->tp_queue, TPTAG_QUEUESIZE_REF(tpp->tpp_qsize)),
 	      TPTAG_IDLE_REF(tpp->tpp_idle),
 	      TPTAG_TIMEOUT_REF(tpp->tpp_timeout),
@@ -1195,6 +1204,9 @@
   if (tpp->tpp_qsize >= 1000)
     tpp->tpp_qsize = 1000;
 
+  if (mtu > UINT_MAX)
+    mtu = UINT_MAX;
+  tpp->tpp_mtu = (unsigned)mtu;
   /* Currently only primary UDP transport can *not* be connection oriented */ 
   tpp->tpp_conn_orient = connect; 
   tpp->tpp_sdwn_error = sdwn_error;
@@ -1226,7 +1238,9 @@
 
 tport_vtable_t const *tport_vtables[TPORT_NUMBER_OF_TYPES + 1] =
 {
+#if HAVE_SOFIA_NTH
   &tport_http_connect_vtable,
+#endif
 #if HAVE_TLS
   &tport_tls_client_vtable,
   &tport_tls_vtable,
@@ -1294,7 +1308,9 @@
     tport_server_bind_set,
     tport_client_bind_set,
     tport_threadpool_set,
+#if HAVE_SOFIA_NTH
     tport_http_connect_set,
+#endif
 #if HAVE_TLS
     tport_tls_set,
 #endif
@@ -1406,8 +1422,8 @@
 
   if (public == tport_type_local)
     public = tport_type_client;
-
-  SU_DEBUG_5(("%s(%p) to " TPN_FORMAT "\n", __func__, mr, TPN_ARGS(tpn)));
+  
+  SU_DEBUG_5(("%s(%p) to " TPN_FORMAT "\n", __func__, (void *)mr, TPN_ARGS(tpn)));
 
   memset(tpn0, 0, sizeof(tpn0));
 
@@ -1467,7 +1483,9 @@
 
   bind6only_check(mr);
 
-  SU_DEBUG_5(("%s(%p) to " TPN_FORMAT "\n", __func__, mr, TPN_ARGS(tpn)));
+  (void)hostname;
+  
+  SU_DEBUG_5(("%s(%p) to " TPN_FORMAT "\n", __func__, (void *)mr, TPN_ARGS(tpn)));
 
   if (tpn->tpn_host == NULL || strcmp(tpn->tpn_host, tpn_any) == 0) {
     /* Use a local IP address */
@@ -1535,7 +1553,7 @@
       tpname->tpn_host = host;
 
       SU_DEBUG_9(("%s(%p): calling tport_listen for %s\n", 
-		  __func__, mr, ai->ai_canonname));
+		  __func__, (void *)mr, ai->ai_canonname));
 
       pri = tport_listen(mr, vtable, tpname, ainfo, tags);
       if (!pri) {
@@ -1582,7 +1600,7 @@
       break;
 
     SU_DEBUG_3(("%s(%p): cannot bind all transports to port %u, trying %u\n", 
-		__func__, mr, old, port));
+				__func__, (void *)mr, old, port));
   }
 
   tport_freeaddrinfo(res);
@@ -1687,7 +1705,7 @@
     int error = tport_getaddrinfo(host, service, hints, return_addrinfo);
     if (error || !*return_addrinfo) {
       SU_DEBUG_3(("%s(%p): su_getaddrinfo(%s, %s) for %s: %s\n", 
-		  __func__, mr, host ? host : "\"\"", service, protocol,
+				  __func__, (void *)mr, host ? host : "\"\"", service, protocol,
 		  su_gai_strerror(error)));
       return su_seterrno(error != EAI_MEMORY ? ENOENT : ENOMEM);
     }
@@ -1738,13 +1756,13 @@
   if (error) {
 #if SU_HAVE_IN6
     SU_DEBUG_3(("%s(%p): su_getlocalinfo() for %s address: %s\n", 
-		__func__, mr, 
+				__func__, (void *)mr, 
 		family == AF_INET6 ? "ip6" 
 		: family == AF_INET ? "ip4" : "ip",
 		su_gli_strerror(error)));
 #else
     SU_DEBUG_3(("%s(%p): su_getlocalinfo() for %s address: %s\n", 
-		__func__, mr, 
+				__func__, (void *)mr, 
 		family == AF_INET ? "ip4" : "ip",
 		su_gli_strerror(error)));
 #endif
@@ -1941,7 +1959,7 @@
  */
 void tport_close(tport_t *self)
 {
-  SU_DEBUG_5(("%s(%p): " TPN_FORMAT "\n", "tport_close", self,
+	SU_DEBUG_5(("%s(%p): " TPN_FORMAT "\n", "tport_close", (void *)self,
 	      TPN_ARGS(self->tp_name)));
 
   self->tp_closed = 1;
@@ -1990,8 +2008,8 @@
 {
   if (!tport_is_secondary(self))
     return -1;
-
-  SU_DEBUG_7(("%s(%p, %d)\n", "tport_shutdown", self, how));
+  
+  SU_DEBUG_7(("%s(%p, %d)\n", "tport_shutdown", (void *)self, how));
 
   if (!tport_is_tcp(self) ||
       how < 0 || 
@@ -2057,7 +2075,7 @@
 	tp_next = tprb_succ(tp);
 	if (tp->tp_queue && tp->tp_queue[tp->tp_qhead]) {
 	  SU_DEBUG_9(("tport_tick(%p) - trying to send to %s/%s:%s\n", 
-		      tp, tp->tp_protoname, tp->tp_host, tp->tp_port));
+				  (void *)tp, tp->tp_protoname, tp->tp_host, tp->tp_port));
 	  tport_send_queue(tp);
 	}
       }      
@@ -2073,7 +2091,7 @@
 	  (int)tp->tp_params->tpp_timeout < ts - (int)tp->tp_time &&
 	  !msg_is_streaming(msg)) {
 	SU_DEBUG_5(("tport_tick(%p): incomplete message idle for %d ms\n",
-		    tp, ts - (int)tp->tp_time));
+				(void *)tp, ts - (int)tp->tp_time));
 	msg_set_streaming(msg, 0);
 	msg_set_flags(msg, MSG_FLG_ERROR | MSG_FLG_TRUNC | MSG_FLG_TIMEOUT);
 	tport_deliver(tp, msg, NULL, NULL, now);
@@ -2094,10 +2112,10 @@
       }
 
       if (closed) {
-	SU_DEBUG_5(("tport_tick(%p): closed, zapping\n", tp));
+		  SU_DEBUG_5(("tport_tick(%p): closed, zapping\n", (void *)tp));
       } else {
 	SU_DEBUG_5(("tport_tick(%p): unused for %d ms, closing and zapping\n",
-		    tp, ts - (int)tp->tp_time));
+				(void *)tp, ts - (int)tp->tp_time));
 	if (!tport_is_closed(tp))
 	  tport_close(tp);
       }
@@ -2125,7 +2143,7 @@
       continue;
 
     SU_DEBUG_1(("tport_flush(%p): %szapping\n",
-		tp, tport_is_closed(tp) ? "" : "closing and "));
+				(void *)tp, tport_is_closed(tp) ? "" : "closing and "));
     if (!tport_is_closed(tp))
       tport_close(tp);
     tport_zap_secondary(tp);
@@ -2364,10 +2382,10 @@
   }
   else {
     if (tport_is_primary(self))
-      SU_DEBUG_3(("%s(%p): %s (with %s)\n", __func__, self, 
+		SU_DEBUG_3(("%s(%p): %s (with %s)\n", __func__, (void *)self, 
 		  errmsg, self->tp_protoname));
     else
-      SU_DEBUG_3(("%s(%p): %s (with %s/%s:%s)\n", __func__, self, 
+		SU_DEBUG_3(("%s(%p): %s (with %s/%s:%s)\n", __func__, (void *)self, 
 		  errmsg, self->tp_protoname, self->tp_host, self->tp_port));
   }
 
@@ -2433,7 +2451,7 @@
 
       if (tport_setname(self, pri->pri_protoname, ai, NULL) != -1) {
 	SU_DEBUG_5(("%s(%p): new connection from " TPN_FORMAT "\n", 
-		    __func__,  self, TPN_ARGS(self->tp_name)));
+				__func__,  (void *)self, TPN_ARGS(self->tp_name)));
 
 	tprb_append(&pri->pri_secondary, self);
 
@@ -2486,8 +2504,8 @@
   su_wait_t wait[1] =  { SU_WAIT_INIT };
 
   int error;
-
-  SU_DEBUG_7(("tport_connected(%p): events%s%s\n", self,
+  
+  SU_DEBUG_7(("tport_connected(%p): events%s%s\n", (void *)self,
 	      events & SU_WAIT_CONNECT ? " CONNECTED" : "",
 	      events & SU_WAIT_ERR ? " ERR" : ""));
 
@@ -2512,7 +2530,7 @@
 
   su_root_deregister(mr->mr_root, self->tp_index);
   self->tp_index = -1;
-  self->tp_events = SU_WAIT_IN | SU_WAIT_ERR;
+  self->tp_events = SU_WAIT_IN | SU_WAIT_ERR | SU_WAIT_HUP;
   if (su_wait_create(wait, self->tp_socket, self->tp_events) == -1 ||
       (self->tp_index = su_root_register(mr->mr_root, 
 					 wait, tport_wakeup, self, 0))
@@ -2537,7 +2555,7 @@
 #endif
 
   SU_DEBUG_7(("%s(%p): events%s%s%s%s%s%s\n", 
-	      "tport_wakeup_pri", self,
+			  "tport_wakeup_pri", (void *)self,
 	      events & SU_WAIT_IN ? " IN" : "",
 	      SU_WAIT_ACCEPT != SU_WAIT_IN && 
 	      (events & SU_WAIT_ACCEPT) ? " ACCEPT" : "",
@@ -2563,7 +2581,7 @@
 #endif
 
   SU_DEBUG_7(("%s(%p): events%s%s%s%s%s\n", 
-	      "tport_wakeup", self,
+			  "tport_wakeup", (void *)self,
 	      events & SU_WAIT_IN ? " IN" : "",
 	      events & SU_WAIT_OUT ? " OUT" : "",
 	      events & SU_WAIT_HUP ? " HUP" : "",
@@ -2617,7 +2635,7 @@
  */
 void tport_hup_event(tport_t *self)
 {
-  SU_DEBUG_7(("%s(%p)\n", __func__, self));
+	SU_DEBUG_7(("%s(%p)\n", __func__, (void *)self));
 
   if (self->tp_msg) {
     su_time_t now = su_now();
@@ -2650,8 +2668,8 @@
 {
   su_time_t now;
   int again;
-
-  SU_DEBUG_7(("%s(%p)\n", "tport_recv_event", self));
+  
+  SU_DEBUG_7(("%s(%p)\n", "tport_recv_event", (void *)self));
 
   do {
     now = su_now(); 
@@ -2661,8 +2679,10 @@
 
     self->tp_time = su_time_ms(now);
 
+#if HAVE_SOFIA_STUN
     if (again == 3) /* STUN keepalive */
       return;
+#endif
 
     if (again < 0) {
       int error = su_errno();
@@ -2718,7 +2738,7 @@
 
     if (msg_get_flags(msg, MSG_FLG_TOOLARGE))
       SU_DEBUG_3(("%s(%p): too large message from " TPN_FORMAT "\n",
-		  __func__, self, TPN_ARGS(self->tp_name)));
+				  __func__, (void *)self, TPN_ARGS(self->tp_name)));
 
     /* Do not try to read anymore from this connection? */
     if (tport_is_stream(self) && 
@@ -2806,9 +2826,9 @@
 
   SU_DEBUG_7(("%s(%p): %smsg %p ("MOD_ZU" bytes)"
 	      " from " TPN_FORMAT " next=%p\n", 
-	      __func__, self, error ? "bad " : "",
-	      msg, (size_t)msg_size(msg),
-	      TPN_ARGS(d->d_from), next));
+	      __func__, (void *)self, error ? "bad " : "",
+	      (void *)msg, (size_t)msg_size(msg),
+	      TPN_ARGS(d->d_from), (void *)next));
 
   ref = tport_incref(self);
 
@@ -2895,7 +2915,7 @@
     if (!(*in_out_msg = msg = tport_msg_alloc(self, N))) {
       SU_DEBUG_7(("%s(%p): cannot allocate msg for "MOD_ZU" bytes "
 		  "from (%s/%s:%s)\n", 
-		  __func__, self, N, 
+				  __func__, (void *)self, N, 
 		  self->tp_protoname, self->tp_host, self->tp_port));
       return -1;
     }
@@ -2914,7 +2934,7 @@
     int err = su_errno();
     SU_DEBUG_7(("%s(%p): cannot get msg %p buffer for "MOD_ZU" bytes "
 		"from (%s/%s:%s): %s\n", 
-		__func__, self, msg, N, 
+				__func__, (void *)self, (void *)msg, N, 
 		self->tp_protoname, self->tp_host, self->tp_port,
 		su_strerror(err)));
     su_seterrno(err);
@@ -2925,8 +2945,8 @@
 
   SU_DEBUG_7(("%s(%p) msg %p from (%s/%s:%s) has "MOD_ZU" bytes, "
 	      "veclen = "MOD_ZD"\n",
-              __func__, self, 
-	      msg, self->tp_protoname, self->tp_host, self->tp_port, 
+              __func__, (void *)self, 
+			  (void *)msg, self->tp_protoname, self->tp_host, self->tp_port, 
 	      N, veclen));
 
   for (i = 0; veclen > 1 && i < veclen; i++) {
@@ -2977,8 +2997,9 @@
   }
 
   *tpn = *_tpn;
-
-  SU_DEBUG_7(("tport_tsend(%p) tpn = " TPN_FORMAT "\n", self, TPN_ARGS(tpn)));
+  
+  SU_DEBUG_7(("tport_tsend(%p) tpn = " TPN_FORMAT "\n",
+	      (void *)self, TPN_ARGS(tpn)));
 
   if (tport_is_master(self)) {
     primary = (tport_primary_t *)tport_primary_by_name(self, tpn);
@@ -3030,7 +3051,7 @@
   if (tpn->tpn_comp) {
     ai->ai_flags |= TP_AI_COMPRESSED;
     SU_DEBUG_9(("%s: compressed msg(%p) with %s\n", 
-		__func__, msg, tpn->tpn_comp));
+				__func__, (void *)msg, tpn->tpn_comp));
   } 
 
   if (!tpn->tpn_comp || cc == NONE)
@@ -3140,7 +3161,7 @@
     return -1;
   }
 
-  if (msg_size(msg) > (mtu ? mtu : tport_mtu(self))) {
+  if (msg_size(msg) > (usize_t)(mtu ? mtu : tport_mtu(self))) {
     msg_set_errno(msg, EMSGSIZE);
     return -1;
   }
@@ -3236,9 +3257,9 @@
       }
       else {
 	char const *comp = tpn->tpn_comp;
-
+	
 	SU_DEBUG_1(("tport(%p): send truncated for %s/%s:%s%s%s\n", 
-		    self, tpn->tpn_proto, tpn->tpn_host, tpn->tpn_port,
+				(void *)self, tpn->tpn_proto, tpn->tpn_host, tpn->tpn_port,
 		    comp ? ";comp=" : "", comp ? comp : ""));
 
 	su_seterrno(EIO);
@@ -3252,6 +3273,7 @@
   /* We have sent a complete message */
 
   self->tp_slogged = NULL;
+  self->tp_stats.sent_msgs ++;
 
   ai = msg_addrinfo(msg); assert(ai);
   close_after = (ai->ai_flags & TP_AI_CLOSE) == TP_AI_CLOSE;
@@ -3302,9 +3324,9 @@
 
     if (tpn == NULL || tport_is_connection_oriented(self))
       tpn = self->tp_name;
-
+    
     SU_DEBUG_7(("tport_vsend(%p): "MOD_ZU" bytes of "MOD_ZU" to %s/%s:%s%s\n", 
-		self, n, m, tpn->tpn_proto, tpn->tpn_host, 
+				(void *)self, n, m, tpn->tpn_proto, tpn->tpn_host, 
 		tpn->tpn_port, 
 		(ai->ai_flags & TP_AI_COMPRESSED) ? ";comp=sigcomp" : ""));
   }
@@ -3326,7 +3348,7 @@
 
   if (su_is_blocking(error)) {
     SU_DEBUG_5(("tport_vsend(%p): %s with (s=%d %s/%s:%s%s)\n", 
-		self, "EAGAIN", (int)self->tp_socket, 
+				(void *)self, "EAGAIN", (int)self->tp_socket, 
 		tpn->tpn_proto, tpn->tpn_host, tpn->tpn_port, comp));
     return 0;
   }
@@ -3335,7 +3357,7 @@
 
   if (self->tp_addrinfo->ai_family == AF_INET) {
     SU_DEBUG_3(("tport_vsend(%p): %s with (s=%d %s/%s:%s%s)\n", 
-		self, su_strerror(error), (int)self->tp_socket, 
+				(void *)self, su_strerror(error), (int)self->tp_socket, 
 		tpn->tpn_proto, tpn->tpn_host, tpn->tpn_port, comp));
   }
 #if SU_HAVE_IN6
@@ -3343,7 +3365,7 @@
     su_sockaddr_t const *su = (su_sockaddr_t const *)ai->ai_addr;
     SU_DEBUG_3(("tport_vsend(%p): %s with "
 		"(s=%d, IP6=%s/%s:%s%s (scope=%i) addrlen=%u)\n", 
-		self, su_strerror(error), (int)self->tp_socket, 
+				(void *)self, su_strerror(error), (int)self->tp_socket, 
 		tpn->tpn_proto, tpn->tpn_host, tpn->tpn_port, comp,
 		su->su_scope_id, (unsigned)ai->ai_addrlen));
   }
@@ -3351,7 +3373,7 @@
   else {
     SU_DEBUG_3(("\ttport_vsend(%p): %s with "
 		"(s=%d, AF=%u addrlen=%u)%s\n", 
-		self, su_strerror(error), 
+				(void *)self, su_strerror(error), 
 		(int)self->tp_socket, ai->ai_family, (unsigned)ai->ai_addrlen, comp));
   }
 
@@ -3359,7 +3381,7 @@
   int i;
   for (i = 0; i < iovused; i++)
     SU_DEBUG_7(("\t\tiov[%d] = { %d bytes @ %p }\n", 
-		i, iov[i].siv_len, iov[i].siv_base));
+		i, iov[i].siv_len, (void *)iov[i].siv_base));
 #endif
 
   if (tport_is_connection_oriented(self)) {
@@ -3480,9 +3502,9 @@
 {
   unsigned short qhead = self->tp_qhead;
   unsigned short N = self->tp_params->tpp_qsize;
-
+  
   SU_DEBUG_7(("tport_queue(%p): queueing %p for %s/%s:%s\n", 
-	      self, msg, self->tp_protoname, self->tp_host, self->tp_port));
+			  (void *)self, (void *)msg, self->tp_protoname, self->tp_host, self->tp_port));
 
   if (self->tp_queue == NULL) {
     assert(N > 0);
@@ -3618,9 +3640,9 @@
 void tport_send_event(tport_t *self)
 {
   assert(tport_is_connection_oriented(self));
-
+  
   SU_DEBUG_7(("tport_send_event(%p) - ready to send to (%s/%s:%s)\n", 
-	      self, self->tp_protoname, self->tp_host, self->tp_port));
+			  (void *)self, self->tp_protoname, self->tp_host, self->tp_port));
   tport_send_queue(self);
 }
 
@@ -3671,8 +3693,11 @@
     }
     assert(total == n);
 
+    /* We have sent a complete message */
+    
     self->tp_queue[qhead] = NULL;
     msg_destroy(msg);
+    self->tp_stats.sent_msgs++;
     self->tp_slogged = NULL;
 
     qhead = (qhead + 1) % N;
@@ -3773,11 +3798,15 @@
       continue;
 #endif
 
+    if (ai->ai_protocol == 0)
+      continue;
     if (ai->ai_addrlen > sizeof(su_sockaddr_t))
       continue;
+
     mai->ai_family = ai->ai_family;
     mai->ai_socktype = ai->ai_socktype;
     mai->ai_protocol = ai->ai_protocol;
+
     if (ai->ai_addrlen < sizeof(su_sockaddr_t))
       memset(su, 0, sizeof(su_sockaddr_t));
     memcpy(su, ai->ai_addr, ai->ai_addrlen);
@@ -3847,9 +3876,9 @@
 
   if (self == NULL || msg == NULL || callback == NULL || client == NULL)
     return -1;
-
+  
   SU_DEBUG_7(("tport_pend(%p): pending %p for %s/%s:%s (already %u)\n", 
-	      self, msg, 
+			  (void *)self, (void *)msg, 
 	      self->tp_protoname, self->tp_host, self->tp_port,
 	      self->tp_pused));
 
@@ -3904,13 +3933,13 @@
 
   if (pending->p_client != client || 
       pending->p_msg != msg) {
-    SU_DEBUG_1(("tport_release(%p): %u %p by %p not pending\n", self, 
-		pendd, msg, client));
+	  SU_DEBUG_1(("tport_release(%p): %u %p by %p not pending\n", (void *)self, 
+				  pendd, (void *)msg, (void *)client));
     return su_seterrno(EINVAL), -1;
   }
-
+  
   SU_DEBUG_7(("tport_release(%p): %p by %p with %p%s\n", 
-	      self, msg, client, reply,
+			  (void *)self, (void *)msg, (void *)client, (void *)reply,
 	      still_pending ? " (preliminary)" : ""));
 
   /* sigcomp can here associate request (msg) with response (reply) */
@@ -4249,7 +4278,7 @@
     }
     else {
       SU_DEBUG_7(("tport(%p): EXPENSIVE unresolved " TPN_FORMAT "\n",
-		  self, TPN_ARGS(tpn)));
+				  (void *)self, TPN_ARGS(tpn)));
 
       sub = tprb_first(sub);
     }
@@ -4269,11 +4298,11 @@
 	if ((socklen_t)sub->tp_addrlen != sulen ||
 	    memcmp(sub->tp_addr, su, sulen)) {
 	  SU_DEBUG_7(("tport(%p): not found by name " TPN_FORMAT "\n",
-		      self, TPN_ARGS(tpn)));
+				  (void *)self, TPN_ARGS(tpn)));
 	  break;
 	}
 	SU_DEBUG_7(("tport(%p): found %p by name " TPN_FORMAT "\n",
-		    self, sub, TPN_ARGS(tpn)));
+				(void *)self, (void *)sub, TPN_ARGS(tpn)));
       }
       else if ((strcasecmp(canon, sub->tp_canon) &&
 		strcasecmp(host, sub->tp_host)) ||
@@ -4354,10 +4383,10 @@
 
   if (sub)
     SU_DEBUG_7(("%s(%p): found %p by name " TPN_FORMAT "\n",
-		__func__, pri, sub, TPN_ARGS(tpn)));
+				__func__, (void *)pri, (void *)sub, TPN_ARGS(tpn)));
   else
     SU_DEBUG_7(("%s(%p): not found by name " TPN_FORMAT "\n",
-		__func__, pri, TPN_ARGS(tpn)));
+				__func__, (void *)pri, TPN_ARGS(tpn)));
 
   return (tport_t *)sub;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_internal.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_internal.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_internal.h	Tue Apr 24 10:14:28 2007
@@ -91,7 +91,7 @@
 
 /** Transport parameters */
 typedef struct {
-  usize_t  tpp_mtu;		/**< Maximum packet size */
+  unsigned tpp_mtu;		/**< Maximum packet size */
   unsigned tpp_idle;		/**< Allowed connection idle time. */
   unsigned tpp_timeout;		/**< Allowed idle time for message. */
   unsigned tpp_sigcomp_lifetime;  /**< SigComp compartment lifetime  */

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_logging.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_logging.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_logging.c	Tue Apr 24 10:14:28 2007
@@ -52,7 +52,9 @@
  * 
  * @sa TPORT_DUMP, TPORT_DEBUG, tport_log
  */
+#ifdef DOXYGEN
 extern char const TPORT_LOG[];	/* dummy declaration for Doxygen */
+#endif
 
 /**@var TPORT_DUMP
  *
@@ -64,7 +66,9 @@
  * 
  * @sa TPORT_LOG, TPORT_DEBUG, tport_log
  */
+#ifdef DOXYGEN
 extern char const TPORT_DUMP[];	/* dummy declaration for Doxygen */
+#endif
 
 /**@var TPORT_DEBUG
  *
@@ -75,7 +79,9 @@
  * 
  * @sa <su_debug.h>, tport_log, SOFIA_DEBUG
  */
+#ifdef DOXYGEN
 extern char const TPORT_DEBUG[]; /* dummy declaration for Doxygen */
+#endif
 
 /**Debug log for @b tport module. 
  * 
@@ -221,17 +227,17 @@
       n = strncspn(s, end - s, "\r\n");
 
       if (linelen + n > MAX_LINELEN) {
-	n = MAX_LINELEN - n - linelen;
+	n = MAX_LINELEN - linelen;
 	truncated = logged + n;
       }
 
-      su_log("%s%.*s", linelen > n ? "" : "   ", (int)n, s);
+      su_log("%s%.*s", linelen > 0 ? "" : "   ", (int)n, s);
       s += n, linelen += n, logged += n;
 
       if (truncated)
 	break;
       if (s == end)
-	continue;
+	break;
 
       linelen = 0;
       su_log("\n");

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_stub_stun.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_stub_stun.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_stub_stun.c	Tue Apr 24 10:14:28 2007
@@ -155,7 +155,7 @@
     }
     else
       SU_DEBUG_7(("tport(%p): recv_stun_dgram(): "
-		  "ignoring request with "MOD_ZU" bytes\n", self, n));
+		  "ignoring request with "MOD_ZU" bytes\n", (void *)self, n));
   }
   else if (request[0] == 0 && self->tp_master->mr_stun_server) {
     tport_stun_server_vtable_t const *vst = tport_stun_server_vtable;
@@ -178,7 +178,7 @@
     elen = (elen + 3) & -4;	/* Round up to 4 */
 
     SU_DEBUG_7(("tport(%p): recv_stun_dgram(): "
-		"responding %u %s\n", self, status, error));
+		"responding %u %s\n", (void *)self, status, error));
   /*
      0                   1                   2                   3
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
@@ -237,7 +237,7 @@
 #undef set16
   }
   else {
-    SU_DEBUG_0(("tport(%p): recv_stun_dgram(): internal error\n", self));
+    SU_DEBUG_0(("tport(%p): recv_stun_dgram(): internal error\n", (void *)self));
     su_seterrno(EBADMSG);
     retval = -1;
   }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_tls.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_tls.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_tls.c	Tue Apr 24 10:14:28 2007
@@ -55,7 +55,10 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+
+#if HAVE_SIGPIPE
 #include <signal.h>
+#endif
 
 #include "tport_tls.h"
 
@@ -162,8 +165,10 @@
     }
   }
 
+#if HAVE_SIGPIPE
   /* Avoid possible SIGPIPE when sending close_notify */
   signal(SIGPIPE, SIG_IGN);
+#endif
 
   if (tls->bio_err == NULL)
     tls->bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
@@ -295,7 +300,9 @@
   unsigned char sessionId[32] = "sofia/tls"; 
   tls_t *tls;
 
+#if HAVE_SIGPIPE
   signal(SIGPIPE, SIG_IGN);  /* Ignore spurios SIGPIPE from OpenSSL */
+#endif
 
   tls_set_default(ti);
 
@@ -420,6 +427,7 @@
     SSL_set_connect_state(tls->con);
   SSL_set_mode(tls->con, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
 
+  su_setblocking(sock, 0);
   tls_read(tls); /* XXX - works only with non-blocking sockets */
 
   return tls;
@@ -611,7 +619,7 @@
   }
 
   if (0)
-    fprintf(stderr, "tls_read(%p) called on %s (events %u)\n", tls,
+    fprintf(stderr, "tls_read(%p) called on %s (events %u)\n", (void *)tls,
 	    tls->type == tls_slave ? "server" : "client",
 	    tls->read_events);
 
@@ -674,7 +682,7 @@
 
   if (0) 
     fprintf(stderr, "tls_write(%p, %p, "MOD_ZU") called on %s\n", 
-	    tls, buf, size,
+	    (void *)tls, buf, size,
 	    tls && tls->type == tls_slave ? "server" : "client");
 
   if (tls == NULL || buf == NULL) {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_sctp.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_sctp.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_sctp.c	Tue Apr 24 10:14:28 2007
@@ -37,8 +37,6 @@
 
 #include "config.h"
 
-#if HAVE_SCTP
-
 #include "tport_internal.h"
 
 #if HAVE_NETINET_SCTP_H
@@ -59,6 +57,12 @@
 #undef MAX_STREAMS
 #define MAX_STREAMS MAX_STREAMS
 
+/* Missing socket symbols */
+#ifndef SOL_SCTP
+#define SOL_SCTP IPPROTO_SCTP
+#endif
+
+
 enum { MAX_STREAMS = 1 };
 typedef struct tport_sctp_t
 {
@@ -76,6 +80,8 @@
 
 #define TP_SCTP_MSG_MAX (65536)
 
+#if HAVE_SCTP
+
 static int tport_sctp_init_primary(tport_primary_t *, 
 				   tp_name_t tpn[1], 
 				   su_addrinfo_t *, tagi_t const *,
@@ -90,8 +96,8 @@
 				  int socket,
 				  char const **return_reason);
 static int tport_recv_sctp(tport_t *self);
-static int tport_send_sctp(tport_t const *self, msg_t *msg,
-			   msg_iovec_t iov[], int iovused);
+static ssize_t tport_send_sctp(tport_t const *self, msg_t *msg,
+			       msg_iovec_t iov[], size_t iovused);
 
 tport_vtable_t const tport_sctp_client_vtable =
 {
@@ -174,9 +180,6 @@
 {
   self->tp_has_connection = 1;
 
-  if (su_setblocking(socket, 0) < 0)
-    return *return_reason = "su_setblocking", -1;
-
   if (accepted) {
     /* Accepted socket inherit the init information from listen socket */
     return 0;
@@ -251,8 +254,8 @@
   return 2;
 }
 
-static int tport_send_sctp(tport_t const *self, msg_t *msg,
-			   msg_iovec_t iov[], int iovused)
+static ssize_t tport_send_sctp(tport_t const *self, msg_t *msg,
+			       msg_iovec_t iov[], size_t iovused)
 {
   
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_tcp.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_tcp.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_tcp.c	Tue Apr 24 10:14:28 2007
@@ -175,8 +175,6 @@
 
   if (setsockopt(socket, SOL_TCP, TCP_NODELAY, (void *)&one, sizeof one) == -1)
     return *return_reason = "TCP_NODELAY", -1;
-  if (su_setblocking(socket, 0) < 0)
-    return *return_reason = "su_setblocking", -1;
 
   if (!accepted)
     tport_tcp_setsndbuf(socket, 64 * 1024);
@@ -230,7 +228,7 @@
   }
   if (N == -1) {
     err = su_errno();
-    SU_DEBUG_1(("%s(%p): su_getmsgsize(): %s (%d)\n", __func__, self,
+    SU_DEBUG_1(("%s(%p): su_getmsgsize(): %s (%d)\n", __func__, (void *)self,
 		su_strerror(err), err));
     return -1;
   }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_tls.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_tls.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_tls.c	Tue Apr 24 10:14:28 2007
@@ -187,7 +187,7 @@
     ti.CAfile = su_sprintf(autohome, "%s/%s", path, "cafile.pem");
     ti.version = tls_version;
 
-    SU_DEBUG_9(("%s(%p): tls key = %s\n", __func__, pri, ti.key));
+    SU_DEBUG_9(("%s(%p): tls key = %s\n", __func__, (void *)pri, ti.key));
 
     if (ti.key && ti.CAfile && ti.randFile) {
       tlspri->tlspri_master = tls_init_master(&ti);
@@ -271,7 +271,7 @@
   int mask = tls_events(tlstp->tlstp_context, self->tp_events);
 
   SU_DEBUG_7(("%s(%p): logical events%s%s real%s%s\n",
-	      "tport_tls_set_events", self, 
+	      "tport_tls_set_events", (void *)self, 
 	      (self->tp_events & SU_WAIT_IN) ? " IN" : "",
 	      (self->tp_events & SU_WAIT_OUT) ? " OUT" : "",
 	      (mask & SU_WAIT_IN) ? " IN" : "",
@@ -325,7 +325,7 @@
     return 0;
 
   SU_DEBUG_7(("%s(%p): logical events%s%s real%s%s\n",
-	      "tport_tls_events", self, 
+	      "tport_tls_events", (void *)self, 
 	      (events & SU_WAIT_IN) ? " IN" : "",
 	      (events & SU_WAIT_OUT) ? " OUT" : "",
 	      (mask & SU_WAIT_IN) ? " IN" : "",
@@ -358,7 +358,7 @@
 
   N = tls_read(tlstp->tlstp_context);
 
-  SU_DEBUG_7(("%s(%p): tls_read() returned "MOD_ZD"\n", __func__, self, N));
+  SU_DEBUG_7(("%s(%p): tls_read() returned "MOD_ZD"\n", __func__, (void *)self, N));
 
   if (N == 0) /* End-of-stream */
     return 0;
@@ -462,7 +462,7 @@
 #endif
 
     SU_DEBUG_9(("tport_tls_writevec: vec %p %p %lu ("MOD_ZD")\n",  
-		tlstp->tlstp_context, iov[i].siv_base, (LU)iov[i].siv_len, 
+		(void *)tlstp->tlstp_context, (void *)iov[i].siv_base, (LU)iov[i].siv_len, 
 		nerror));
 
     if (nerror == -1) {

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_udp.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_udp.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/tport/tport_type_udp.c	Tue Apr 24 10:14:28 2007
@@ -166,7 +166,9 @@
 
   tport_check_trunc(pri->pri_primary, ai);
 
+#if HAVE_SOFIA_STUN
   tport_stun_server_add_socket(pri->pri_primary);
+#endif
 
   return 0;
 }
@@ -233,7 +235,7 @@
   if (self->tp_params->tpp_drop && 
       (unsigned)su_randint(0, 1000) < self->tp_params->tpp_drop) {
     su_recv(self->tp_socket, sample, 1, 0);
-    SU_DEBUG_3(("tport(%p): simulated packet loss!\n", self));
+    SU_DEBUG_3(("tport(%p): simulated packet loss!\n", (void *)self));
     return 0;
   }
 
@@ -246,10 +248,15 @@
   N = (ssize_t)su_getmsgsize(self->tp_socket);
   if (N == -1) {
     int err = su_errno();
-    SU_DEBUG_1(("%s(%p): su_getmsgsize(): %s (%d)\n", __func__, self,
+    SU_DEBUG_1(("%s(%p): su_getmsgsize(): %s (%d)\n", __func__, (void *)self,
 		su_strerror(err), err));
     return -1;
   }
+  if (N == 0) {
+    su_recv(self->tp_socket, sample, 1, 0);
+    SU_DEBUG_3(("tport(%p): zero length packet", (void *)self));
+    return 0;
+  }
 #endif
 
   veclen = tport_recv_iovec(self, &self->tp_msg, iovec, N, 1);
@@ -276,7 +283,8 @@
       return -1;
   }
   else if (n <= 1) {
-    SU_DEBUG_1(("%s(%p): runt of "MOD_ZD" bytes\n", "tport_recv_dgram", self, n));
+    SU_DEBUG_1(("%s(%p): runt of "MOD_ZD" bytes\n",
+		"tport_recv_dgram", (void *)self, n));
     msg_destroy(msg), self->tp_msg = NULL;
     return 0;
   }
@@ -295,9 +303,11 @@
     /* SigComp */
     return tport_recv_comp_dgram(self, self->tp_comp, &self->tp_msg, 
 				 from, fromlen);
+#if HAVE_SOFIA_STUN
   else if (sample[0] == 0 || sample[0] == 1)
     /* STUN request or response */
     return tport_recv_stun_dgram(self, &self->tp_msg, from, fromlen);
+#endif
   else
     return 0;
 }

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -34,6 +34,7 @@
 
 LDADD = 		liburl.la \
 			../bnf/libbnf.la \
+			../ipt/libipt.la \
 			../su/libsu.la
 
 test_urlmap_SOURCES = 	urlmap.c urlmap.h
@@ -42,7 +43,7 @@
 # ----------------------------------------------------------------------
 # Install and distribution rules
 
-EXTRA_DIST =		Doxyfile url.docs $(BUILT_SOURCES)
+EXTRA_DIST =		url.docs $(BUILT_SOURCES)
 
 # ----------------------------------------------------------------------
 # Tests
@@ -52,6 +53,6 @@
 # ----------------------------------------------------------------------
 # Sofia specific rules
 
-include ../sofia.am
+include $(top_srcdir)/rules/sofia.am
 
 TAG_DLL_FLAGS = 	DLLREF=1

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/sofia-sip/url.h
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/sofia-sip/url.h	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/sofia-sip/url.h	Tue Apr 24 10:14:28 2007
@@ -34,29 +34,32 @@
 #ifndef URL_H_TYPES
 #define URL_H_TYPES
 
-/** Recognized URL schemes (value of url_t.url_type). */
+/** Recognized URL schemes (value of url_t.url_type). 
+ *
+ * @sa &lt;<a href="http://www.iana.org/assignments/uri-schemes.html">http://www.iana.org/assignments/uri-schemes.html</a>&gt;
+ */
 enum url_type_e {
-  url_invalid = -2,		/**< Invalid url. */
-  url_unknown = -1,		/**< Unknown scheme. */
-  url_any = 0,			/**< @c "*" */
-  url_sip,			/**< @c "sip:" */
-  url_sips,			/**< @c "sips:" */
-  url_tel,			/**< @c "tel:" */
-  url_fax,			/**< @c "fax:" */
-  url_modem,			/**< @c "modem:" */
-  url_http,			/**< @c "http:" */
-  url_https,			/**< @c "https:" */
-  url_ftp,			/**< @c "ftp:" */
-  url_file,			/**< @c "file:" */
-  url_rtsp,			/**< @c "rtsp:" */
-  url_rtspu,			/**< @c "rtspu:" */
-  url_mailto,			/**< @c "mailto:" */
-  url_im,			/**< @c "im:" (simple instant messaging) */
-  url_pres,			/**< @c "pres:" (simple presence) */
-  url_cid,			/**< @c "cid:" (Content-ID) */
-  url_msrp,			/**< @c "msrp:" (message session relay)  */
-  url_msrps,			/**< @c "msrps:" (new in @VERSION_1_12_2) */
-  url_wv,			/**< @c "wv:" (Wireless village) */
+  url_invalid = -2,	/**< Invalid url. */
+  url_unknown = -1,	/**< Unknown scheme. */
+  url_any = 0,		/**< "*" */
+  url_sip,		/**< "sip:". @sa @RFC3261 */
+  url_sips,		/**< "sips:". @sa @RFC3261 */
+  url_tel,		/**< "tel:" @sa RFC3966 */
+  url_fax,		/**< "fax:". @note Obsolete. @sa @RFC2806 */
+  url_modem,		/**< "modem:". @note Obsolete. @sa @RFC2806  */
+  url_http,		/**< "http:". @sa @RFC2616, @RFC3986 */
+  url_https,		/**< "https:". @sa @RFC2618, @RFC3986 */
+  url_ftp,		/**< "ftp:". @sa @RFC1738 */
+  url_file,		/**< "file:" @sa @RFC1738 */
+  url_rtsp,		/**< "rtsp:" @sa @RFC2326 */
+  url_rtspu,		/**< "rtspu:" @sa @RFC2326 */
+  url_mailto,		/**< "mailto:" @sa @RFC2368 */
+  url_im,		/**< "im:" (simple instant messaging). @sa @RFC3860 */
+  url_pres,		/**< "pres:" (simple presence). @sa @RFC3859  */
+  url_cid,		/**< "cid:" (Content-ID). @sa @RFC2392 */
+  url_msrp,		/**< "msrp:" (message session relay)  */
+  url_msrps,		/**< "msrps:" (new in @VERSION_1_12_2) */
+  url_wv,		/**< "wv:" (Wireless village) */
   _url_none
 };
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/torture_url.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/torture_url.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/torture_url.c	Tue Apr 24 10:14:28 2007
@@ -49,11 +49,6 @@
 
 char const name[] = "torture_url";
 
-void usage(void)
-{
-  fprintf(stderr, "usage: %s [-v]\n", name);
-}
-
 unsigned char hash1[16], hash2[16];
 
 /* test unquoting and canonizing */
@@ -108,7 +103,7 @@
   TEST_S(url_escape(unreserved, UNRESERVED, NULL), UNRESERVED);
   TEST_S(url_unescape(unreserved, UNRESERVED), UNRESERVED);
 
-  d = "%73ip:%55@%68";
+  d = "%53ip:%75@%48";		/* Sip:u at H */
   u = url_hdup(home, (url_t *)d); TEST_1(u);
   url_digest(hash1, sizeof(hash1), u, NULL);
   url_digest(hash2, sizeof(hash2), (url_t const *)d, NULL);
@@ -125,9 +120,11 @@
   d = url_as_string(home, u); TEST_1(d);
   TEST_S(d, c);
 
-  d = "sip:&=+$,;?/:&=+$, at host:56001;param=+$,/:@&;another=@"
+  d = "sip:&=+$,;?/:&=+$,@[::1]:56001;param=+$,/:@&;another=@"
     "?header=" RESERVED "&%3b%2f%3f%3a%40%26%3d%2b%24%2c";
   u = url_hdup(home, (url_t *)d); TEST_1(u);
+  TEST_S(u->url_user, "&=+$,;?/");
+  TEST_S(u->url_host, "[::1]");
   TEST_S(u->url_headers, "header=" RESERVED "&%3B%2F%3F%3A%40%26%3D%2B%24%2C");
   url_digest(hash1, sizeof(hash1), u, NULL);
   url_digest(hash2, sizeof(hash2), (url_t const *)d, NULL);
@@ -137,8 +134,10 @@
   d = url_as_string(home, u); TEST_1(d);
   TEST_S(d, c);
 
-  d = "http://&=+$,;:&=+$,;@host:8080/foo;param=+$,/:@&;another=@?query=" RESERVED;
+  d = "http://&=+$,;:&=+$,;@host:8080/foo;param=+$,/:@&;another=@"
+    "?query=" RESERVED;
   u = url_hdup(home, (url_t *)d); TEST_1(u);
+  TEST_S(u->url_user, "&=+$,;"); TEST_S(u->url_password, "&=+$,;");
   url_digest(hash1, sizeof(hash1), u, NULL);
   url_digest(hash2, sizeof(hash2), (url_t const *)d, NULL);
   TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);
@@ -333,6 +332,13 @@
   TEST_P(url_hdup(home, (url_t*)"sip:test at 127.0.0.1:55:"), NULL);
   TEST_P(url_hdup(home, (url_t*)"sip:test at 127.0.0.1:sip"), NULL);
 
+  u = url_hdup(home, (url_t*)"SIP:#**00**#;foo=/bar at 127.0.0.1"); TEST_1(u);
+  TEST(u->url_type, url_sip);
+  TEST_S(u->url_user, "#**00**#;foo=/bar");
+
+  TEST_1(!url_hdup(home, (url_t*)"SIP:#**00**#;foo=/bar@#127.0.0.1"));
+  TEST_1(!url_hdup(home, (url_t*)"SIP:#**00**#;foo=/bar;127.0.0.1"));
+
   for (i = 32; i <= 256; i++) {
     char pu[512];
     char param[512];
@@ -397,6 +403,10 @@
   TEST_S(u->url_params, "isfocus");
   TEST_1(!url_have_transport(u));
 
+  u = url_hdup(home, (void *)"sip:%22foo%22 at 172.21.55.55:5060");
+  TEST_1(u);
+  TEST_S(u->url_user, "%22foo%22");
+
   a = url_hdup(home, (void *)"sip:172.21.55.55:5060");
   b = url_hdup(home, (void *)"sip:172.21.55.55");
   TEST_1(a); TEST_1(b);
@@ -628,7 +638,7 @@
 int test_file(void)
 {
   /* Test a url with path like file:/foo/bar  */
-  char fileurl[] = "file:/foo/bar";
+  char fileurl[] = "file:///foo/bar";
   url_t file[1] = { URL_INIT_AS(file) };
   su_home_t home[1] = { SU_HOME_INIT(home) };
   char *tst;
@@ -642,7 +652,9 @@
 
   TEST_1(tst = su_strdup(home, fileurl));
   TEST(url_d(url, tst), 0);
+  TEST_S(url->url_host, "");
   file->url_root = '/';
+  file->url_host = "";
   file->url_path = "foo/bar";
   TEST(url_cmp(file, url), 0);
   TEST(url->url_type, url_file);
@@ -827,6 +839,16 @@
   TEST_S(url->url_host, "some.host");
   TEST_S(url->url_headers, "query");
   TEST_S(url->url_params, NULL);
+
+  TEST_1(u = url_hdup(home, (void *)"http://[::1]/test;ing?here"));
+  TEST_S(u->url_host, "[::1]");
+  TEST_S(u->url_path, "test;ing");
+  TEST_S(u->url_headers, "here");
+
+  url_digest(hash1, sizeof(hash1), u, NULL);
+  url_digest(hash2, sizeof(hash2), (url_t *)"http://[::1]/test;ing?here", 
+	     NULL);
+  TEST(memcmp(hash1, hash2, sizeof(hash1)), 0);
     
   su_home_deinit(home);
 
@@ -1026,7 +1048,11 @@
   END();
 }
 
-
+void usage(int exitcode)
+{
+  fprintf(stderr, "usage: %s [-v] [-a]\n", name);
+  exit(exitcode);
+}
 
 int main(int argc, char *argv[])
 {
@@ -1036,8 +1062,10 @@
   for (i = 1; argv[i]; i++) {
     if (strcmp(argv[i], "-v") == 0)
       tstflags |= tst_verbatim;
+    else if (strcmp(argv[i], "-a") == 0)
+      tstflags |= tst_abort;
     else
-      usage();
+      usage(1);
   }
 
   retval |= test_quote(); fflush(stdout);

Modified: freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/url.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/url.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/libsofia-sip-ua/url/url.c	Tue Apr 24 10:14:28 2007
@@ -556,8 +556,8 @@
 int _url_d(url_t *url, char *s)
 {
   size_t n, p;
-  char *s0, rest_c, *host;
-  int net_path = 1;
+  char *s0, rest_c, *host, *user;
+  int have_authority = 1;
 
   memset(url, 0, sizeof(*url));
   
@@ -582,112 +582,131 @@
 
     url->url_type = url_get_type(url->url_scheme, n);
 
-    net_path = !url_type_is_opaque(url->url_type);
+    have_authority = !url_type_is_opaque(url->url_type);
   }
   else {
     url->url_type = url_unknown;
   }
 
-  host = s;
+  user = NULL, host = s;
 
   if (url->url_type == url_sip || url->url_type == url_sips) {
-    /* SIP URL may have /; in user part */
-	n = strcspn(s, "@#");   /* Opaque part */
-	if ((p = strcspn(s, "#")) == n) {
-	  n = strcspn(s, "@");
-      if (s[n] != '@')
-        n = 0;
-	}
+    /* SIP URL may have /;? in user part but no path */
+    /* user-unreserved  =  "&" / "=" / "+" / "$" / "," / ";" / "?" / "/" */
+    /* Some #*@#* phones include unescaped # there, too */
+    n = strcspn(s, "@/;?#");
+    p = strcspn(s + n, "@");
+    if (s[n + p] == '@') {
+      n += p;
+      user = s;
+      host = s + n + 1;
+    }
+
     n += strcspn(s + n, "/;?#");
   }
-  else if (url->url_type == url_wv) {
-    /* WV URL may have / in user part */
-    n = strcspn(s, "@#?;");
-    if (s[n] == '@')
-      n += strcspn(s + n, ";?#");
-  }
-  else if (url->url_type == url_invalid) {
-    n = strcspn(s, "#");
-  }
-  else if (net_path && host[0] == '/') {
-    url->url_root = host[0];	/* Absolute path */
+  else if (have_authority) {
+    if (url->url_type == url_wv) {
+      /* WV URL may have / in user part */
+      n = strcspn(s, "@#?;");
+      if (s[n] == '@') {
+	user = s;
+	host = s + n + 1;
+	n += strcspn(s + n, ";?#");
+      }
+    }
+    else if (host[0] == '/' && host[1] != '/') {
+      /* foo:/bar or /bar - no authority, just path */
+      url->url_root = '/';	/* Absolute path */
+      host = NULL, n = 0;
+    }
+    else {
+      if (host[0] == '/' && host[1] == '/') {
+	/* We have authority, / / foo or foo */
+	host += 2; s += 2, url->url_root = '/';
+	n = strcspn(s, "/?#@[]");
+      }
+      else 
+	n = strcspn(s, "@;/?#");
+
+      if (s[n] == '@')
+	user = host, host = user + n + 1;
 
-    if (host[1] == '/') {	/* We have host-part */
-      host += 2; s += 2;
+      n += strcspn(s + n, ";/?#");	/* Find path, query and/or fragment */
     }
-    else 
-      host = NULL;
-    n = strcspn(s, "/;?#");	/* Find path, query and/or fragment */
   }
-  else {
-    n = strcspn(s, "/;?#");	/* Find params, query and/or fragment */
+  else /* !have_authority */ {
+    user = host, host = NULL;
+    if (url->url_type != url_invalid)
+      n = strcspn(s, "/;?#");	/* Find params, query and/or fragment */
+    else
+      n = strcspn(s, "#");
   }
 
   rest_c = s[n]; s[n] = 0; s = rest_c ? s + n + 1 : NULL;
 
-  if (host) {
-    char *atsign, *port;
-
-    if (!net_path) {
-      url->url_user = host;
-      host = NULL;
-    }
-    else if ((atsign = strchr(host, '@'))) {
-      char *user;
-
-      url->url_user = user = host;
-
-      if (atsign)
-	*atsign++ = '\0';
-      host = atsign;
-
-      if (url->url_type != url_unknown) {
-	char *colon = strchr(user, ':');
-	if (colon)
-	  *colon++ = '\0';
-	url->url_password = colon;
+  if (user) {
+    if (host) host[-1] = '\0';
+    url->url_user = user;
+    if (url->url_type != url_unknown) {
+      n = strcspn(user, ":");
+      if (user[n]) {
+	user[n] = '\0';
+	url->url_password = user + n + 1;
       }
     }
+  }
+
+  if (host) {
+    url->url_host = host;
+    /* IPv6 (and in some cases, IPv4) addresses are quoted with [] */
+    if (host[0] == '[') {
+      n = strcspn(host, "]");
+      if (host[n] && (host[n + 1] == '\0' || host[n + 1] == ':'))
+	n++;
+      else
+	n = 0;
+    }
+    else {
+      n = strcspn(host, ":");
+    }
 
-    if ((url->url_host = host)) {
-      /* IPv6 (and in some cases, IPv4) addresses are quoted with [] */
-      if (host[0] == '[') {
-	port = strchr(host, ']');
-	if (!port)
+    /* We allow empty host by default */
+    if (n == 0) switch (url->url_type) {
+    case url_sip:
+    case url_sips:
+    case url_im:
+    case url_pres:
+      return -1;
+    default:
+      break;
+    }
+    
+    if (host[n] == ':') {
+      char *port = host + n + 1;
+      url->url_port = port;
+      switch (url->url_type) {
+      case url_any:
+      case url_sip:
+      case url_sips:
+      case url_http:
+      case url_https:
+      case url_ftp:
+      case url_file:
+      case url_rtsp:
+      case url_rtspu:
+	if (!url_canonize2(port, port, SIZE_MAX, RESERVED_MASK))
 	  return -1;
-	port = strchr(port + 1, ':');
-      }
-      else 
-	port = strchr(host, ':');
 
-      if (port) {
-	*port++ = '\0';
-	url->url_port = port;
-	switch (url->url_type) {
-	case url_any:
-	case url_sip:
-	case url_sips:
-	case url_http:
-	case url_https:
-	case url_ftp:
-	case url_file:
-	case url_rtsp:
-	case url_rtspu:
-	  
-	  if (!url_canonize2(port, port, SIZE_MAX, RESERVED_MASK))
-	    return -1;
-
-	  /* Check that port is really numeric or wildcard */
-	  /* Port can be *digit, empty string or "*" */
-	  while (*port >= '0' && *port <= '9')
-	    port++;
-	  if (port != url->url_port 
-	      ? port[0] != '\0' 
-	      : port[0] != '\0'
-	      && (port[0] != '*' || port[1] != '\0'))
-	    return -1;
-	}
+	/* Check that port is really numeric or wildcard */
+	/* Port can be *digit, empty string or "*" */
+	while (*port >= '0' && *port <= '9')
+	  port++;
+	
+	if (port != url->url_port ? port[0] != '\0' 
+	    : (port[0] != '*' || port[1] != '\0'))
+	  return -1;
       }
+      host[n] = 0;
     }
   }
 
@@ -742,12 +761,15 @@
     if (s && !url_canonize(s, s, SIZE_MAX, SIP_USER_UNRESERVED))
       return -1;
 
+    /* Having different charset in user and password does not make sense */
+    /* but that is how it is defined in RFC 3261 */
 #   define SIP_PASS_UNRESERVED "&=+$,"
     s = (char *)url->url_password;
     if (s && !url_canonize(s, s, SIZE_MAX, SIP_PASS_UNRESERVED))
       return -1;
 
-  } else {
+  }
+  else {
 
 #   define USER_UNRESERVED "&=+$,;"
     s = (char *)url->url_user;
@@ -943,7 +965,7 @@
 }
 
 
-/** Calculate the lengh of URL when encoded. 
+/** Calculate the length of URL when encoded. 
  *
  */
 isize_t url_len(url_t const * url)
@@ -1588,7 +1610,7 @@
 static
 int url_tel_cmp_numbers(char const *A, char const *B)
 {
-  char a, b;
+  short a, b;
   int rv;
 
   while (*A && *B) {
@@ -1889,8 +1911,8 @@
 static
 void url_string_update(su_md5_t *md5, char const *s)
 {
-  size_t n;
-  int hostpart = 1;
+  size_t n, p;
+  int have_authority = 1;
   enum url_type_e type = url_any;
   char const *at, *colon;
   char schema[48];
@@ -1910,7 +1932,7 @@
     type = url_get_type(schema, at - schema);
     su_md5_iupdate(md5, schema, at - schema);
 
-    hostpart = !url_type_is_opaque(type);
+    have_authority = !url_type_is_opaque(type);
     s += n + 1;
   }
   else {
@@ -1918,62 +1940,71 @@
   }
   
   if (type == url_sip || type == url_sips) {
-    n = strcspn(s, "@#");	/* Opaque part */
-    if (s[n] != '@')
-      n = 0;
+    /* SIP URL may have /;? in user part but no path */
+    /* user-unreserved  =  "&" / "=" / "+" / "$" / "," / ";" / "?" / "/" */
+    /* Some #*@#* phones include unescaped # there, too */
+    n = strcspn(s, "@/;?#");
+    p = strcspn(s + n, "@");
+    if (s[n + p] == '@') {
+      n += p;
+      /* Ignore password in hash */
+      colon = memchr(s, ':', n);
+      p = colon ? (size_t)(colon - s) : n;
+      canon_update(md5, s, p, SIP_USER_UNRESERVED);
+      s += n + 1; n = 0;
+    }
+    else
+      su_md5_iupdate(md5, "", 1);	/* user */
     n += strcspn(s + n, "/;?#");
   }
-  else if (type == url_wv) {    /* WV URL may have / in user part */
-    n = strcspn(s, "@#?;");
-    if (s[n] == '@')
-      n += strcspn(s + n, ";?#");
-  }
-  else if (!hostpart || s[0] != '/') {
-    n = strcspn(s, "/;?#");	/* Opaque part */
-  }
-  else if (s[1] == '/') {
-    s += 2;
-    n = strcspn(s, "/;?#");	/* Until host, path, query or fragment */
-  }
-  else {
-    /* foo:/bar */
-    su_md5_update(md5, "\0\0", 2); /* user, host */
-    su_md5_striupdate(md5, url_port_default(type));
-    return;
+  else if (have_authority) {
+    if (type == url_wv) {    /* WV URL may have / in user part */
+      n = strcspn(s, "@;?#");
+    }
+    else if (type != url_wv && s[0] == '/' && s[1] != '/') {
+      /* foo:/bar */
+      su_md5_update(md5, "\0\0", 2); /* user, host */
+      su_md5_striupdate(md5, url_port_default(type));
+      return;
+    }
+    else if (s[0] == '/' && s[1] == '/') {
+      /* We have authority, / / foo or foo */
+      s += 2;
+      n = strcspn(s, "/?#@[]");
+    }
+    else 
+      n = strcspn(s, "@;/?#");
+
+    if (s[n] == '@') {
+      /* Ignore password in hash */
+      colon = type != url_unknown ? memchr(s, ':', n) : NULL;
+      p = colon ? (size_t)(colon - s) : n;
+      canon_update(md5, s, p, SIP_USER_UNRESERVED);
+      s += n + 1;
+      n = strcspn(s, "/;?#");	/* Until path, query or fragment */
+    }
+    else {
+      su_md5_iupdate(md5, "", 1);	/* user */
+      n += strcspn(s + n, "/;?#");	/* Until path, query or fragment */
+    }
   }
-  
-  if (!hostpart) {
-    char const *colon = memchr(s, ':', n);
+  else /* if (!have_authority) */ {
+    n = strcspn(s, ":/;?#");	/* Until pass, path, query or fragment */
     
-    if (colon) n = colon - s;
     canon_update(md5, s, n, ""); /* user */
     su_md5_update(md5, "\0", 1); /* host, no port */
     su_md5_striupdate(md5, url_port_default(type));
     return;
   }
 
-  at = memchr(s, '@', n);
-
-  if (at) {
-    char const *allow = 
-      (type == url_sip || type == url_sips) 
-      ? SIP_USER_UNRESERVED
-      : USER_UNRESERVED;
-
-    colon = type == url_unknown ? NULL : memchr(s, ':', at - s);
-
-    /* Updated only user part */
-    if (colon)
-      canon_update(md5, s, colon - s, allow);
-    else
-      canon_update(md5, s, at - s, allow);
-    n = n - (at + 1 - s);
-    s = at + 1;
+  if (n > 0 && s[0] == '[') {	/* IPv6reference */
+    colon = memchr(s, ']', n);
+    if (colon == NULL || ++colon == s + n || *colon != ':')
+      colon = NULL;
   }
-  else
-    su_md5_iupdate(md5, "", 1);	/* user */
+  else 
+    colon = memchr(s, ':', n);
 
-  colon = memchr(s, ':', n);	/* XXX - IPv6! */
   if (colon) {
     canon_update(md5, s, colon - s, ""); /* host */
     canon_update(md5, colon + 1, (s + n) - (colon + 1), "");

Modified: freeswitch/branches/cparker/libs/sofia-sip/m4/sac-general.m4
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/m4/sac-general.m4	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/m4/sac-general.m4	Tue Apr 24 10:14:28 2007
@@ -113,7 +113,7 @@
   *gcc*) ac_cv_cwflag=-Wall;;
   *)	case "$host" in
     *irix*)	ac_cv_cwflag=-fullwarn ;;
-    *solaris*)  ac_cv_cwflag="-erroff=%none,E_END_OF_LOOP_CODE_NOT_REACHED -xCC"
+    *solaris*)  ac_cv_cwflag="-erroff=%none,E_END_OF_LOOP_CODE_NOT_REACHED,E_BAD_PTR_INT_COMBINATION -errtags"
 	        ;;
     *)		ac_cv_cwflag=;;
 		esac 
@@ -127,7 +127,7 @@
 # GCoverage
 #
 AC_ARG_ENABLE(coverage,
-[  --enable-coverage       compile test-coverage (disabled)],
+[  --enable-coverage       compile test-coverage [[disabled]]],
  , enable_coverage=no)
 
 if test X$enable_coverage != Xno ; then
@@ -341,7 +341,7 @@
 AC_DEFUN([SAC_ENABLE_NDEBUG],[
 AC_REQUIRE([SAC_TOOL_CC])
 AC_ARG_ENABLE(ndebug,
-[  --enable-ndebug             compile with NDEBUG (disabled)],
+[  --enable-ndebug         compile with NDEBUG [[disabled]]],
  , enable_ndebug=no)
 AM_CONDITIONAL(NDEBUG, test x$enable_ndebug = yes)
 ])
@@ -351,7 +351,8 @@
 dnl ======================================================================
 AC_DEFUN([SAC_ENABLE_EXPENSIVE_CHECKS],[
 AC_ARG_ENABLE(expensive-checks,
-[  --enable-expensive-checks   run also expensive checks (disabled)],
+[  --enable-expensive-checks
+                          run also expensive checks [[disabled]]],
  , enable_expensive_checks=no)
 if test $enable_expensive_checks != no; then
 AC_SUBST([TESTS_ENVIRONMENT], [EXPENSIVE_CHECKS=1])

Modified: freeswitch/branches/cparker/libs/sofia-sip/m4/sac-openssl.m4
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/m4/sac-openssl.m4	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/m4/sac-openssl.m4	Tue Apr 24 10:14:28 2007
@@ -4,32 +4,45 @@
 AC_DEFUN([SAC_OPENSSL], [
 
 AC_ARG_WITH(openssl,
-[  --with-openssl          use OpenSSL (enabled)],, with_openssl=yes)
+[  --with-openssl          use OpenSSL [[enabled]]],, with_openssl=pkg-config)
 
 dnl SOSXXX:SAC_ASSERT_DEF([openssl libraries])
 
-if test "$with_openssl" != no  ;then
-  AC_CHECK_HEADERS(openssl/tls1.h, [
 
-    HAVE_OPENSSL=1 HAVE_TLS=1
-
-    AC_CHECK_LIB(crypto, BIO_new,, 
-    	HAVE_OPENSSL=0
-    	AC_MSG_WARN(OpenSSL crypto library was not found))
-
-    AC_CHECK_LIB(ssl, TLSv1_method,, 
-    	HAVE_TLS=0
-    	AC_MSG_WARN(OpenSSL protocol library was not found))
-
-    if test x$HAVE_OPENSSL = x1; then
-      AC_DEFINE([HAVE_OPENSSL], 1, [Define to 1 if you have OpenSSL])
-    fi
-
-    if test x$HAVE_TLS = x1; then
-      AC_DEFINE([HAVE_TLS], 1, [Define to 1 if you have TLS])
-    fi
-  ],
-  AC_MSG_WARN(OpenSSL include files were not found))
+if test "$with_openssl" = no  ;then
+  : # No openssl
+else
+
+  if test "$with_openssl" = "pkg-config" ; then 
+    PKG_CHECK_MODULES(openssl, openssl,
+	[HAVE_TLS=1 HAVE_OPENSSL=1 LIBS="$openssl_LIBS $LIBS"],
+	[HAVE_OPENSSL=0])
+  fi
+
+  if test $HAVE_OPENSSL = 1 ; then
+     AC_DEFINE([HAVE_LIBCRYPTO], 1, [Define to 1 if you have the `crypto' library (-lcrypto).])
+     AC_DEFINE([HAVE_LIBSSL], 1, [Define to 1 if you have the `ssl' library (-lssl).])
+  else
+    AC_CHECK_HEADERS([openssl/tls1.h], [
+      HAVE_OPENSSL=1 HAVE_TLS=1
+
+      AC_CHECK_LIB(crypto, BIO_new,, 
+      	HAVE_OPENSSL=0
+      	AC_MSG_WARN(OpenSSL crypto library was not found))
+
+      AC_CHECK_LIB(ssl, TLSv1_method,, 
+      	HAVE_TLS=0
+      	AC_MSG_WARN(OpenSSL protocol library was not found))
+     ],[AC_MSG_WARN(OpenSSL include files were not found)])
+  fi
+  
+  if test x$HAVE_OPENSSL = x1; then
+     AC_DEFINE([HAVE_OPENSSL], 1, [Define to 1 if you have OpenSSL])
+  fi
+
+  if test x$HAVE_TLS = x1; then
+    AC_DEFINE([HAVE_TLS], 1, [Define to 1 if you have TLS])
+  fi
 fi
 
 AM_CONDITIONAL(HAVE_TLS, test x$HAVE_TLS = x1)

Modified: freeswitch/branches/cparker/libs/sofia-sip/m4/sac-su.m4
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/m4/sac-su.m4	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/m4/sac-su.m4	Tue Apr 24 10:14:28 2007
@@ -13,7 +13,7 @@
 dnl ======================================================================
 AC_DEFUN([SAC_WITH_RT],[
 AC_ARG_WITH(rt,  
-[  --with-rt               use POSIX realtime library (used by default)])
+[  --with-rt               use POSIX realtime library [[used by default]]])
 ])
 
 dnl ======================================================================

Modified: freeswitch/branches/cparker/libs/sofia-sip/m4/sac-su2.m4
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/m4/sac-su2.m4	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/m4/sac-su2.m4	Tue Apr 24 10:14:28 2007
@@ -46,6 +46,14 @@
   SAC_SU_DEFINE([SU_HAVE_PTHREADS], 1, [Sofia SU uses pthreads])
 fi
 
+AC_ARG_ENABLE(experimental,
+[  --enable-experimental   enable experimental features [[disabled]]],
+ , enable_experimental=no)
+
+if test $enable_experimental = yes ; then
+  SAC_SU_DEFINE([SU_HAVE_EXPERIMENTAL], 1, [Enable experimental features])
+fi
+
 dnl ===========================================================================
 dnl Checks for typedefs, headers, structures, and compiler characteristics.
 dnl ===========================================================================
@@ -69,9 +77,10 @@
 		Define to 1 if you have inline functions.
 	])dnl
   ;;
-  no)  SAC_SU_DEFINE(su_inline, static)dnl
-       SAC_SU_DEFINE(SU_INLINE)dnl
-       SAC_SU_DEFINE(SU_HAVE_INLINE)dnl
+  no | "" )
+       SAC_SU_DEFINE(su_inline, static)dnl
+       SAC_SU_DEFINE(SU_INLINE, /*inline*/)dnl
+       SAC_SU_DEFINE(SU_HAVE_INLINE, 0)dnl
   ;;
   *)   SAC_SU_DEFINE_UNQUOTED(su_inline, static $ac_cv_c_inline)dnl
        SAC_SU_DEFINE_UNQUOTED(SU_INLINE, $ac_cv_c_inline)dnl
@@ -80,7 +89,7 @@
 esac
 
 AC_ARG_ENABLE(size-compat,
-[  --disable-size-compat            use compatibility size_t types (enabled)],
+[  --disable-size-compat   use compatibility size_t types [[enabled]]],
  , enable_size_compat=yes)
 
 if test X$enable_size_compat != Xyes; then
@@ -104,7 +113,8 @@
 dnl SAC_ENABLE_COREFOUNDATION
 dnl ======================================================================
 AC_ARG_ENABLE(corefoundation,
-[  --enable-corefoundation     compile with OSX COREFOUNDATION (disabled)],
+[  --enable-corefoundation 
+                          compile with OSX COREFOUNDATION [[disabled]]],
  , enable_corefoundation=no)
 AM_CONDITIONAL(COREFOUNDATION, test $enable_corefoundation = yes)
 
@@ -119,21 +129,17 @@
 ### Test if we have stack suitable for handling tags directly
 ###
 
-test -z "$ac_cv_tagstack" && 
-case "$target" in 
-i?86-*-* ) ac_cv_tagstack=yes ;;
-esac
-
 AC_CACHE_CHECK([for stack suitable for tags],[ac_cv_tagstack],[
 ac_cv_tagstack=no
 
-AC_RUN_IFELSE([
+AC_RUN_IFELSE([AC_LANG_SOURCE([[
 #if HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
 #if HAVE_STDINT_H
 #include <stdint.h>
 #endif
+
 #include <stdarg.h>
 
 typedef void *tp;
@@ -169,7 +175,12 @@
 	       (tv)1, (tv)2, (tv)3, (tv)4, (tv)5,
 	       (tv)6, (tv)7, (tv)8, (tv)9, (tv)10);
 }
-],[ac_cv_tagstack=yes],[ac_cv_tagstack=no],[ac_cv_tagstack=no])])
+]])],[ac_cv_tagstack=yes],[ac_cv_tagstack=no],[
+case "$target" in 
+i?86-*-* ) ac_cv_tagstack=yes ;;
+* ) ac_cv_tagstack=no ;;
+esac
+])])
 
 if test $ac_cv_tagstack = yes ; then
 SAC_SU_DEFINE([SU_HAVE_TAGSTACK], 1, [
@@ -185,13 +196,18 @@
 	        [Define to 1 if you have sa_len in struct sockaddr])
 fi
 
-AC_REQUIRE([AC_STRUCT_SIN6])
+AC_ARG_ENABLE([ip6],
+[  --disable-ip6          disable IPv6 functionality [[enabled]]],,enable_ip6=yes)
+
+if ! test no$enable_ip6 = nono ; then
+AC_STRUCT_SIN6
 case $ac_cv_sin6 in 
 yes) SAC_SU_DEFINE(SU_HAVE_IN6, 1, [
 	Define to 1 if you have struct sockaddr_in6]) ;;
  no) ;;
   *) AC_MSG_ERROR([Inconsistent struct sockaddr_sin6 test]) ;;
 esac
+fi
 
 AC_CHECK_HEADERS([unistd.h sys/time.h])
 
@@ -227,9 +243,10 @@
      GetSystemTimeAsFileTime().])
 ],[
 dnl no winsock2
+
 SAC_SU_DEFINE([SU_HAVE_BSDSOCK], 1, [Define to 1 if you have BSD socket interface])
 AC_CHECK_HEADERS([sys/socket.h sys/ioctl.h sys/filio.h sys/sockio.h \
-		  sys/select.h])
+		  sys/select.h sys/epoll.h sys/devpoll.h])
 AC_CHECK_HEADERS([netinet/in.h arpa/inet.h netdb.h \
                   net/if.h net/if_types.h ifaddr.h netpacket/packet.h],,,
 		[
@@ -429,9 +446,12 @@
 AC_SEARCH_LIBS(gethostbyname, xnet nsl)
 AC_SEARCH_LIBS(getaddrinfo, xnet socket nsl)
 
-AC_CHECK_FUNCS([gettimeofday strerror random initstate tcsetattr flock alarm \
+AC_FUNC_ALLOCA
+
+AC_CHECK_FUNCS([gettimeofday strerror random initstate tcsetattr flock \
                 socketpair gethostname gethostbyname getipnodebyname \
-                poll epoll_create select if_nameindex \
+                poll epoll_create kqueue select if_nameindex \
+		signal alarm \
 	        getaddrinfo getnameinfo freeaddrinfo gai_strerror getifaddrs \
                 getline getdelim getpass])
 # getline getdelim getpass are _GNU_SOURCE stuff
@@ -440,7 +460,8 @@
   SAC_SU_DEFINE([SU_HAVE_POLL], 1, [Define to 1 if you have poll().])
 fi
 
-if test $ac_cv_func_epoll_create = yes ; then
+if test $ac_cv_func_epoll_create = yes && test $ac_cv_header_sys_epoll_h = yes
+then
   AC_DEFINE([HAVE_EPOLL], 1, [Define to 1 if you have epoll interface.])
 fi
 
@@ -455,8 +476,32 @@
 fi
 
 SAC_REPLACE_FUNCS([memmem memccpy memspn memcspn strcasestr strtoull \
-		   inet_ntop inet_pton])
+		   inet_ntop inet_pton poll])
+
+if test $ac_cv_func_signal = yes ; then
+AC_CHECK_DECL([SIGPIPE], [
+AC_DEFINE([HAVE_SIGPIPE], 1, [Define to 1 if you have SIGPIPE])],,[
+#include <signal.h>
+])
+dnl add SIGHUP SIGQUIT if needed
+fi
+
+# ===========================================================================
+# Check how to implement su_port
+# ===========================================================================
 
+AC_ARG_ENABLE(poll-port,
+[  --disable-poll-port     disable su_poll_port [[enabled]]
+                          Use this option in systems emulating poll with select],
+ , enable_poll_port=maybe)
+
+if test $enable_poll_port = maybe ; then
+  if test $ac_cv_func_poll = yes ; then
+    AC_DEFINE([HAVE_POLL_PORT], 1, [Define to 1 if you use poll in su_port.])
+  fi
+elif test $enable_poll_port = yes ; then
+    AC_DEFINE([HAVE_POLL_PORT], 1, [Define to 1 if you use poll in su_port.])
+fi
 
 # ===========================================================================
 # Check pthread_rwlock_unlock()

Modified: freeswitch/branches/cparker/libs/sofia-sip/m4/sac-tport.m4
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/m4/sac-tport.m4	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/m4/sac-tport.m4	Tue Apr 24 10:14:28 2007
@@ -4,7 +4,7 @@
 AC_DEFUN([SAC_TPORT], [
 
 AC_ARG_WITH(sigcomp,
-[  --with-sigcomp=dir      use Sofia SigComp package (not used by default)],,
+[  --with-sigcomp=dir      use Sofia SigComp package [[not used]]],,
 	with_sigcomp=no)
 
 if test -n "${with_sigcomp}" && test "${with_sigcomp}" != no ; then
@@ -27,10 +27,12 @@
 AC_SYS_IP_RECVERR
 AC_SYS_IPV6_RECVERR
 
-AC_CHECK_HEADERS(netinet/tcp.h netinet/sctp.h)
+AC_CHECK_HEADERS([netinet/tcp.h netinet/sctp.h],[],[],[
+#include <sys/socket.h>
+])
 
-AC_ARG_WITH(sctp,
-[  --enable-sctp          use LK-SCTP (not used by default)],,
+AC_ARG_ENABLE(sctp,
+[  --enable-sctp           use SCTP [[disabled]]],,
  enable_sigcomp=no)
 
 if test x$enable_sctp = xyes; then

Modified: freeswitch/branches/cparker/libs/sofia-sip/packages/sofia-sip.spec.in
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/packages/sofia-sip.spec.in	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/packages/sofia-sip.spec.in	Tue Apr 24 10:14:28 2007
@@ -12,15 +12,15 @@
 
 BuildRequires: pkgconfig
 
-%{!?bcond_with:%define bcond_with() %{expand:%%{?_with_%{1}:%%global with_%{1} 1}}}
-%{!?bcond_without:%define bcond_without() %{expand:%%{!?_without_%{1}:%%global with_%{1} 1}}}
+%define opt_with() %{expand:%%global with_%{1} %%{?_with_%{1}:1}%%{?!_with_%{1}:0}}
+%define opt_without() %{expand:%%global with_%{1} %%{!?_without_%{1}:1}%%{?_without_%{1}:0}}
 
 # Options: 
-%bcond_with doxygen	- Generate documents using doxygen and dot
-%bcond_with check	- Run tests
-%bcond_with openssl	- Always use OpenSSL (TLS)
-%bcond_with glib	- Always use glib-2.0 (>= 2.2)
-%bcond_with sctp	- Include SCTP transport
+%opt_with doxygen	- Generate documents using doxygen and dot
+%opt_with check		- Run tests
+%opt_with openssl	- Always use OpenSSL (TLS)
+%opt_with glib		- Always use glib-2.0 (>= 2.2)
+%opt_with sctp		- Include SCTP transport
 
 %define have_doxygen %{?_with_doxygen:1}%{!?_with_doxygen:0}
 %define have_openssl %(%{?!_with_openssl:pkg-config 'openssl >= 0.9.7'&&}echo 1||echo 0)
@@ -49,7 +49,7 @@
 %if !%{have_glib}
 options="$options --without-glib"
 %endif
-%if %{with sctp}
+%if %{with_sctp}
 options="$options --enable-sctp"
 %endif
 
@@ -62,7 +62,7 @@
 
 # XXX comment next line to build with non-check aware rpmbuild.
 %check
-%if %{with check}
+%if %{with_check}
 make check
 %endif
 
@@ -126,7 +126,7 @@
 Development package for Sofia SIP UA library. This package includes 
 static libraries and include files.
 
-%if %{without doxygen}
+%if !%{with_doxygen}
 The reference documentation for Sofia SIP UA library is available at 
 <http://sofia-sip.sourceforge.net/development.html>
 %endif

Modified: freeswitch/branches/cparker/libs/sofia-sip/utils/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/utils/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/utils/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -44,5 +44,3 @@
 bin_PROGRAMS =		sip-options sip-date sip-dig
 
 LDADD =			../libsofia-sip-ua/libsofia-sip-ua.la $(GLIB_LIBS)
-
-EXTRA_DIST =		Doxyfile

Modified: freeswitch/branches/cparker/libs/sofia-sip/utils/sip-options.c
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/utils/sip-options.c	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/utils/sip-options.c	Tue Apr 24 10:14:28 2007
@@ -331,7 +331,7 @@
   return context->c_retval;
 }
 
-/** Handle responses to registration request */
+/** Handle responses to OPTIONS request */
 static
 int response_to_options(context_t *context,
 			nta_outgoing_t *oreq,
@@ -355,12 +355,16 @@
 	    sip_is_content_length(h))
 	  continue;
       }
-      if (h->sh_class->hc_name) {
-	snprintf(hname, sizeof hname, "%s: %%s\n", h->sh_class->hc_name);
-	sl_header_print(stdout, hname, h); 
+
+      if (h->sh_class->hc_name == NULL) {
+	sl_header_print(stdout, NULL, h);
+      } 
+      else if (h->sh_class->hc_name[0] == '\0') {
+	sl_header_print(stdout, "%s\n", h); 
       }
       else {
-	sl_header_print(stdout, NULL, h); 
+	snprintf(hname, sizeof hname, "%s: %%s\n", h->sh_class->hc_name);
+	sl_header_print(stdout, hname, h); 
       }
     }
   }

Modified: freeswitch/branches/cparker/libs/sofia-sip/win32/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/win32/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/win32/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -44,6 +44,31 @@
 	autogen.cmd build_sources.cmd version_files.cmd version.awk \
 	install.cmd check.cmd
 
+# VC2005 Project files
+EXTRA_DIST += SofiaSIP.sln \
+    libsofia-sip-ua-static/libsofia_sip_ua_static.vcproj \
+    libsofia-sip-ua/libsofia_sip_ua.vcproj \
+    tests/test_htable/test_htable.vcproj \
+    tests/test_memmem/test_memmem.vcproj \
+    tests/test_nta/test_nta.vcproj \
+    tests/test_nua/test_nua.vcproj \
+    tests/test_su/test_su.vcproj \
+    tests/test_tport/test_tport.vcproj \
+    tests/torture_rbtree/torture_rbtree.vcproj \
+    tests/torture_su/torture_su.vcproj \
+    tests/torture_su_alloc/torture_su_alloc.vcproj \
+    tests/torture_su_bm/torture_su_bm.vcproj \
+    tests/torture_su_port/torture_su_port.vcproj \
+    tests/torture_su_root/torture_su_root.vcproj \
+    tests/torture_su_tag/torture_su_tag.vcproj \
+    tests/torture_su_time/torture_su_time.vcproj \
+    tests/torture_su_timer/torture_su_timer.vcproj \
+    utils/localinfo/localinfo.vcproj \
+    utils/sip_dig/sip_dig.vcproj \
+    utils/sip_options/sip_options.vcproj \
+    utils/sip_options_static/sip_options_static.vcproj \
+    utils/stunc/stunc.vcproj
+
 PTHREAD_DIST = \
 	pthread/ChangeLog \
 	pthread/md5.sum.txt \

Modified: freeswitch/branches/cparker/libs/sofia-sip/win32/SofiaSIP.dsw
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/win32/SofiaSIP.dsw	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/win32/SofiaSIP.dsw	Tue Apr 24 10:14:28 2007
@@ -252,21 +252,6 @@
 
 ###############################################################################
 
-Project: "torture_su_port"=".\tests\torture_su_port\torture_su_port.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-    Begin Project Dependency
-    Project_Dep_Name libsofia_sip_ua_static
-    End Project Dependency
-}}}
-
-###############################################################################
-
 Project: "torture_su_root"=".\tests\torture_su_root\torture_su_root.dsp" - Package Owner=<4>
 
 Package=<5>

Modified: freeswitch/branches/cparker/libs/sofia-sip/win32/build_sources.cmd
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/win32/build_sources.cmd	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/win32/build_sources.cmd	Tue Apr 24 10:14:28 2007
@@ -3,21 +3,22 @@
 ::
 
 @setlocal
- at if x%AWK%==x set AWK=gawk
+ at if x%AWK%==x set AWK=mawk
 @set CHECK=@IF errorlevel 1 GOTO failed
 
 :: Check that we really have awk
 @%AWK% "{ exit(0); }" < NUL >NUL
 @if not errorlevel 9009 goto have_awk
- at echo *** install %AWK% (GNU awk) into your PATH ***
+ at echo *** install %AWK% (mawk or GNU awk) into your PATH ***
+ at echo *** see http://gnuwin32.sourceforge.net/packages/mawk.htm ***
 @goto failed
 :have_awk
 
- at set MSG_AWK=gawk -v BINMODE=rw -f ../libsofia-sip-ua/msg/msg_parser.awk
+ at set MSG_AWK=%AWK% -v BINMODE=rw -f ../libsofia-sip-ua/msg/msg_parser.awk
 :: in Win32 exit 0; from gawk 3.1.3 gets converted to errorlevel 1
 :: If you have gawk 3.1.3 uncomment the following line
-:: @set MSG_AWK=gawk -v BINMODE=rw -f ../libsofia-sip-ua/msg/msg_parser.awk success=-1
- at set TAG_AWK=gawk -f ../libsofia-sip-ua/su/tag_dll.awk BINMODE=rw
+:: @set MSG_AWK=%AWK% -v BINMODE=rw -f ../libsofia-sip-ua/msg/msg_parser.awk success=-1
+ at set TAG_AWK=%AWK% -f ../libsofia-sip-ua/su/tag_dll.awk BINMODE=rw
 
 @set IN=../libsofia-sip-ua/msg/test_class.h
 @set PR=../libsofia-sip-ua/msg/test_protos.h

Modified: freeswitch/branches/cparker/libs/sofia-sip/win32/check.cmd
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/win32/check.cmd	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/win32/check.cmd	Tue Apr 24 10:14:28 2007
@@ -63,5 +63,5 @@
 tests\torture_su_bm\Debug\torture_su_bm.exe
 @if errorlevel 1 ( echo torture_su_bm: FAIL ) else echo torture_su_bm: PASS
 
-tests\torture_su_port\Debug\torture_su_port.exe
- at if errorlevel 1 ( echo torture_su_port: FAIL ) else echo torture_su_port: PASS
+:: tests\torture_su_port\Debug\torture_su_port.exe
+:: @if errorlevel 1 ( echo torture_su_port: FAIL ) else echo torture_su_port: PASS

Modified: freeswitch/branches/cparker/libs/sofia-sip/win32/config.h.in
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/win32/config.h.in	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/win32/config.h.in	Tue Apr 24 10:14:28 2007
@@ -32,10 +32,10 @@
  * @date Created: Tue Sep 12 19:22:54 2000 ppessi
  */
 
-/* Define this as the random number source name. */
+/* Define to as the random number source name. */
 #undef DEV_URANDOM
 
-/* Define this as 1 if you have addrinfo structure. */
+/* Define to 1 if you have addrinfo structure. */
 #define HAVE_ADDRINFO 1
 
 /* Define to 1 if you have the `alarm' function. */
@@ -50,15 +50,21 @@
 /* Define to 1 if you have the `clock_gettime' function. */
 #undef HAVE_CLOCK_GETTIME
 
-/* Define this as 1 if you have /dev/urandom. */
+/* Define to 1 if you have /dev/urandom. */
 #undef HAVE_DEV_URANDOM
 
+/* Define to 1 if you have the <dirent.h> header file. */
+#undef HAVE_DIRENT_H
+
 /* Define to 1 if you have the <dlfcn.h> header file. */
 #undef HAVE_DLFCN_H
 
-/* Define to 1 if you have the `epoll' function. */
+/* Define to 1 if you have epoll interface. */
 #undef HAVE_EPOLL
 
+/* Define to 1 if you have the <fcntl.h> header file. */
+#undef HAVE_FCNTL_H
+
 /* Define this as 1 if you have WIN32 FILETIME type and
    GetSystemTimeAsFileTime(). */
 #define HAVE_FILETIME 1
@@ -69,10 +75,10 @@
 /* Define to 1 if you have the `freeaddrinfo' function. */
 #define HAVE_FREEADDRINFO 1
 
-/* Define as 1 if the C compiler supports __func__ */
+/* Define to 1 if the C compiler supports __func__ */
 #undef HAVE_FUNC
 
-/* Define as 1 if the C compiler supports __FUNCTION__ */
+/* Define to 1 if the C compiler supports __FUNCTION__ */
 #undef HAVE_FUNCTION
 
 /* Define to 1 if you have the `gai_strerror' function. */
@@ -111,16 +117,16 @@
 /* Define to 1 if you have the <ifaddr.h> header file. */
 #undef HAVE_IFADDR_H
 
-/* Define this as 1 if you have SIOCGIFCONF */
+/* Define to 1 if you have SIOCGIFCONF */
 #undef HAVE_IFCONF
 
-/* Define this as 1 if you have SIOCGIFNUM ioctl */
+/* Define to 1 if you have SIOCGIFNUM ioctl */
 #undef HAVE_IFNUM
 
-/* Define this as 1 if you have ifr_ifindex in <net/if.h> */
+/* Define to 1 if you have ifr_ifindex in <net/if.h> */
 #undef HAVE_IFR_IFINDEX
 
-/* Define this as 1 if you have ifr_index in <net/if.h> */
+/* Define to 1 if you have ifr_index in <net/if.h> */
 #undef HAVE_IFR_INDEX
 
 /* Define to 1 if you have the `if_nameindex' function. */
@@ -135,23 +141,27 @@
 /* Define to 1 if you have the `initstate' function. */
 #undef HAVE_INITSTATE
 
-/* Define this as 1 if you have inlining compiler */
+/* Define to 1 if you have inlining compiler */
 #define HAVE_INLINE 1
 
-/* Define this as 1 if you have WIN32 INTERFACE_INFO_EX type. */
+/* Define to 1 if you have WIN32 INTERFACE_INFO_EX type. */
 #undef HAVE_INTERFACE_INFO_EX
 
 /* Define to 1 if you have the <inttypes.h> header file. */
 #undef HAVE_INTTYPES_H
 
-/* Define as 1 you have WIN32 <iphlpapi.h> */
-// XXX: vehmanek-win32-fix:
+/* Define to 1 if you have the <iphlpapi.h> header file. */
+#if _MSC_VER > 1200 
+#define HAVE_IPHLPAPI_H 1
+#else
+// XXX: vehmanek-win32-fix for VC6
 #undef HAVE_IPHLPAPI_H
+#endif
 
-/* Define this as 1 if you have IPV6_RECVERR in <netinet/in6.h> */
+/* Define to 1 if you have IPV6_RECVERR in <netinet/in6.h> */
 #undef HAVE_IPV6_RECVERR
 
-/* Define this as 1 if you have IP_RECVERR in <netinet/in.h> */
+/* Define to 1 if you have IP_RECVERR in <netinet/in.h> */
 #undef HAVE_IP_RECVERR
 
 /* Define to 1 if you have the `crypto' library (-lcrypto). */
@@ -181,9 +191,12 @@
 /* Define to 1 if you have the `memspn' function. */
 #undef HAVE_MEMSPN
 
-/* Define this as 1 if you are compiling in MinGW environment */
+/* Define to 1 if you are compiling in MinGW environment */
 #undef HAVE_MINGW
 
+/* Define to 1 if you have MSG_TRUNC flag */
+#undef HAVE_MSG_TRUNC
+
 /* Define to 1 if you have the <netdb.h> header file. */
 #undef HAVE_NETDB_H
 
@@ -205,7 +218,7 @@
 /* Define to 1 if you have the <net/if_types.h> header file. */
 #undef HAVE_NET_IF_TYPES_H
 
-/* Define this as 1 if you have OpenSSL */
+/* Define to 1 if you have OpenSSL */
 #undef HAVE_OPENSSL
 
 /* Define to 1 if you have the <openssl/tls1.h> header file. */
@@ -214,9 +227,19 @@
 /* Define to 1 if you have the `poll' function. */
 #undef HAVE_POLL
 
-/* Define this as 1 if you have /proc/net/if_inet6 control file */
+/* Define to 1 if you use poll in su_port. */
+#undef HAVE_POLL_PORT
+
+/* Define to 1 if you have /proc/net/if_inet6 control file */
 #undef HAVE_PROC_NET_IF_INET6
 
+/* Define to 1 if you have working pthread_rwlock_t implementation. A thread
+   may hold multiple concurrent read locks on rwlock - that is, successfully
+   call the pthread_rwlock_rdlock() function n times. If so, the application
+   shall ensure that the thread performs matching unlocks - that is, it calls
+   the pthread_rwlock_unlock() function n times. */
+#undef HAVE_PTHREAD_RWLOCK
+
 /* Define to 1 if you have the <pthread.h> header file. */
 #define HAVE_PTHREAD_H 1
 
@@ -224,52 +247,61 @@
 /* See later */
 #define HAVE_RANDOM 1
 
-/* Define this as 1 if you have sa_len in struct sockaddr */
+/* Define to 1 if you have sa_len in struct sockaddr */
 #undef HAVE_SA_LEN
 
-/* Define this a 1 if you have SCTP */
+/* Define to 1 if you have SCTP */
 #undef HAVE_SCTP
 
 /* Define to 1 if you have the `select' function. */
 #undef HAVE_SELECT
 
-/* Define this as 1 if you have Sofia sigcomp >= 2.5 */
+/* Define to 1 if you have Sofia sigcomp >= 2.5 */
 #undef HAVE_SIGCOMP
 
 /* Define to 1 if you have the <sigcomp.h> header file. */
 #undef HAVE_SIGCOMP_H
 
-/* Define as 1 if you have SIGPIPE */
+/* Define to 1 if you have the `signal' function. */
+#define HAVE_SIGNAL 1
+
+/* Define to 1 if you have SIGPIPE */
 #undef HAVE_SIGPIPE
 
-/* Define this as 1 if you have IPv6 structures and constants */
+/* Define to 1 if you have IPv6 structures and constants */
 #define HAVE_SIN6 1
 
-/* Define this as 1 if you have WIN32 WSAIoctl SIO_ADDRESS_LIST_QUERY. */
+/* Define to 1 if you have WIN32 WSAIoctl SIO_ADDRESS_LIST_QUERY. */
 #define HAVE_SIO_ADDRESS_LIST_QUERY 1
 
 /* Define to 1 if you have the `socketpair' function. */
 #undef HAVE_SOCKETPAIR
 
-/* Define this as 1 if you have Sofia sigcomp >= 2.5 */
+/* Define to 1 if we use NTH library */
+#define HAVE_SOFIA_NTH 1
+
+/* Define to 1 if we use NTLM library */
+#undef HAVE_SOFIA_NTLM
+
+/* Define to 1 if you have Sofia sigcomp >= 2.5 */
 #undef HAVE_SOFIA_SIGCOMP
 
-/* Define as 1 always */
+/* Define to 1 always */
 #define HAVE_SOFIA_SIP 1
 
-/* Define as 1 if we use S/MIME library */
+/* Define to 1 if we use S/MIME library */
 #undef HAVE_SOFIA_SMIME
 
-/* Define as 1 if we use DNS library */
+/* Define to 1 if we use DNS library */
 #define HAVE_SOFIA_SRESOLV 1
 
-/* Define as 1 if we use STUN library */
+/* Define to 1 if we use STUN library */
 #undef HAVE_SOFIA_STUN
 
-/* Define as 1 always */
+/* Define to 1 always */
 #define HAVE_SOFIA_SU 1
 
-/* Define as 1 if we use SRTP */
+/* Define to 1 if we use SRTP */
 #undef HAVE_SRTP
 
 /* Define to 1 if you have the <stdint.h> header file. */
@@ -293,15 +325,21 @@
 /* Define to 1 if you have the `strtoull' function. */
 #undef HAVE_STRTOULL
 
-/* Define this as 1 if your CC supports C99 struct initialization */
+/* Define to 1 if your CC supports C99 struct initialization */
 #undef HAVE_STRUCT_KEYWORDS
 
 /* Define to 1 if you have the <sofia-sip/su_wait.h> header file. */
 #define HAVE_SU_WAIT_H 1
 
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+#undef HAVE_SYS_EPOLL_H
+
 /* Define to 1 if you have the <sys/filio.h> header file. */
 #undef HAVE_SYS_FILIO_H
 
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#undef HAVE_SYS_IOCTL_H
+
 /* Define to 1 if you have the <sys/select.h> header file. */
 #undef HAVE_SYS_SELECT_H
 
@@ -323,16 +361,16 @@
 /* Define to 1 if you have the `tcsetattr' function. */
 #undef HAVE_TCSETATTR
 
-/* Define this as 1 if you have TLS */
+/* Define to 1 if you have TLS */
 #undef HAVE_TLS
 
 /* Define to 1 if you have the <unistd.h> header file. */
 #undef HAVE_UNISTD_H
 
-/* Define as 1 if we use UPnP */
+/* Define to 1 if we use UPnP */
 #undef HAVE_UPNP
 
-/* Define as 1 you have WIN32 */
+/* Define to 1 you have WIN32 */
 #define HAVE_WIN32 1
 
 /* Define to 1 if you have the <windef.h> header file. */
@@ -344,13 +382,13 @@
 /* Define to 1 if you have the <ws2tcpip.h> header file. */
 #define HAVE_WS2TCPIP_H 1
 
-/* Define as format (%lli) for long long */
+/* Define to format (%lli) for long long */
 #define LLI "%I64i"
 
-/* Define as format (%llu) for unsigned long long */
+/* Define to format (%llu) for unsigned long long */
 #define LLU "%I64u"
 
-/* Define as format (%llx) for long long hex */
+/* Define to format (%llx) for long long hex */
 #define LLX "%I64x"
 
 /* Name of package */
@@ -427,20 +465,20 @@
 /* This is GCC magic  */
 #define __attribute__(x)
 
-/* Define this as 1 if you have TimeGetTime() */
+/* Define to 1 if you have TimeGetTime() */
 #define HAVE_TIMEGETTIME     1
 
 #define PATH_MAX _MAX_PATH
 
 #define HAVE_WINMM 1
 
-/* Define this as 1 if you have FILETIME */
+/* Define to 1 if you have FILETIME */
 #define HAVE_FILETIME 1
 
-/* Define this as 1 if you have WinSock2 ioctl SIO_ADDRESS_LIST_QUERY */
+/* Define to 1 if you have WinSock2 ioctl SIO_ADDRESS_LIST_QUERY */
 #define HAVE_SIO_ADDRESS_LIST_QUERY 1
 
-/* Define this as 1 if you have INTERFACE_INFO ioctl */
+/* Define to 1 if you have INTERFACE_INFO ioctl */
 #define HAVE_INTERFACE_INFO 	   (1) 
 
 /* Ignore certain warnings */

Modified: freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua-static/libsofia_sip_ua_static.dsp
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua-static/libsofia_sip_ua_static.dsp	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua-static/libsofia_sip_ua_static.dsp	Tue Apr 24 10:14:28 2007
@@ -113,6 +113,10 @@
 # End Source File
 # Begin Source File
 
+SOURCE="..\..\libsofia-sip-ua\su\su_base_port.c"
+# End Source File
+# Begin Source File
+
 SOURCE="..\..\libsofia-sip-ua\su\su_bm.c"
 # End Source File
 # Begin Source File
@@ -149,10 +153,18 @@
 # End Source File
 # Begin Source File
 
+SOURCE="..\..\libsofia-sip-ua\su\su_pthread_port.c"
+# End Source File
+# Begin Source File
+
 SOURCE="..\..\libsofia-sip-ua\su\su_root.c"
 # End Source File
 # Begin Source File
 
+SOURCE="..\..\libsofia-sip-ua\su\su_socket_port.c"
+# End Source File
+# Begin Source File
+
 SOURCE="..\..\libsofia-sip-ua\su\su_sprintf.c"
 # End Source File
 # Begin Source File
@@ -199,6 +211,10 @@
 
 SOURCE="..\..\libsofia-sip-ua\su\su_wait.c"
 # End Source File
+# Begin Source File
+
+SOURCE="..\..\libsofia-sip-ua\su\su_win32_port.c"
+# End Source File
 # End Group
 # Begin Group "ipt"
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua/libsofia_sip_ua.dsp
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua/libsofia_sip_ua.dsp	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/win32/libsofia-sip-ua/libsofia_sip_ua.dsp	Tue Apr 24 10:14:28 2007
@@ -125,6 +125,10 @@
 # End Source File
 # Begin Source File
 
+SOURCE="..\..\libsofia-sip-ua\su\su_base_port.c"
+# End Source File
+# Begin Source File
+
 SOURCE="..\..\libsofia-sip-ua\su\su_bm.c"
 # End Source File
 # Begin Source File
@@ -161,10 +165,18 @@
 # End Source File
 # Begin Source File
 
+SOURCE="..\..\libsofia-sip-ua\su\su_pthread_port.c"
+# End Source File
+# Begin Source File
+
 SOURCE="..\..\libsofia-sip-ua\su\su_root.c"
 # End Source File
 # Begin Source File
 
+SOURCE="..\..\libsofia-sip-ua\su\su_socket_port.c"
+# End Source File
+# Begin Source File
+
 SOURCE="..\..\libsofia-sip-ua\su\su_sprintf.c"
 # End Source File
 # Begin Source File
@@ -211,6 +223,10 @@
 
 SOURCE="..\..\libsofia-sip-ua\su\su_wait.c"
 # End Source File
+# Begin Source File
+
+SOURCE="..\..\libsofia-sip-ua\su\su_win32_port.c"
+# End Source File
 # End Group
 # Begin Group "ipt"
 

Modified: freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_nua/test_nua.dsp
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_nua/test_nua.dsp	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/win32/tests/test_nua/test_nua.dsp	Tue Apr 24 10:14:28 2007
@@ -145,6 +145,10 @@
 # End Source File
 # Begin Source File
 
+SOURCE="..\..\..\libsofia-sip-ua\nua\test_offer_answer.c"
+# End Source File
+# Begin Source File
+
 SOURCE="..\..\..\libsofia-sip-ua\nua\test_ops.c"
 # End Source File
 # Begin Source File

Modified: freeswitch/branches/cparker/libs/sofia-sip/win32/version_files.cmd
==============================================================================
--- freeswitch/branches/cparker/libs/sofia-sip/win32/version_files.cmd	(original)
+++ freeswitch/branches/cparker/libs/sofia-sip/win32/version_files.cmd	Tue Apr 24 10:14:28 2007
@@ -26,14 +26,15 @@
 ::
 
 @setlocal
- at if x%AWK%==x set AWK=gawk
+ at if x%AWK%==x set AWK=mawk
 @set VERSION=%AWK% -v BINMODE="rw" -f version.awk
 @set AC=..\configure.ac
 
 :: Check that we really have awk
 @%AWK% "{ exit(0); }" < NUL >NUL
 @if not errorlevel 9009 goto have_awk
- at echo *** install %AWK% (GNU awk) into your PATH ***
+ at echo *** install %AWK% (mawk or GNU awk) into your PATH ***
+ at echo *** see http://gnuwin32.sourceforge.net/packages/mawk.htm ***
 @goto end
 :have_awk
 

Modified: freeswitch/branches/cparker/libs/speex/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/speex/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/speex/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -2,7 +2,7 @@
 
 # To disable automatic dependency tracking if using other tools than
 # gcc and gmake, add the option 'no-dependencies'
-AUTOMAKE_OPTIONS = 1.8
+AUTOMAKE_OPTIONS = 1.7
 
 m4datadir = $(datadir)/aclocal
 m4data_DATA = speex.m4

Modified: freeswitch/branches/cparker/libs/sqlite/configure.ac
==============================================================================
--- freeswitch/branches/cparker/libs/sqlite/configure.ac	(original)
+++ freeswitch/branches/cparker/libs/sqlite/configure.ac	Tue Apr 24 10:14:28 2007
@@ -394,7 +394,10 @@
   AC_MSG_RESULT(unknown)
 fi
 if test "$CYGWIN" != "yes"; then
-  AC_CYGWIN
+  case $host_os in
+    *cygwin* ) CYGWIN=yes;;
+    * ) CYGWIN=no;;
+  esac
 fi
 if test "$CYGWIN" = "yes"; then
   BUILD_EXEEXT=.exe

Modified: freeswitch/branches/cparker/libs/srtp/Makefile.am
==============================================================================
--- freeswitch/branches/cparker/libs/srtp/Makefile.am	(original)
+++ freeswitch/branches/cparker/libs/srtp/Makefile.am	Tue Apr 24 10:14:28 2007
@@ -1,5 +1,3 @@
-_DIST =
-SUBDIRS = test
 AUTOMAKE_OPTS= gnu
 NAME=srtp
 
@@ -46,7 +44,7 @@
 
 noinst_PROGRAMS = aes_tables
 aes_tables_SOURCES = tables/aes_tables.c
-aes_tables_LDFLAGS = -lcryptomath
+aes_tables_LDADD = libcryptomath.la
 
 pkgconfigdir = $(libdir)/pkgconfig
 pkgconfig_DATA = srtp-1.42.pc

Modified: freeswitch/branches/cparker/libs/srtp/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/srtp/configure.in	(original)
+++ freeswitch/branches/cparker/libs/srtp/configure.in	Tue Apr 24 10:14:28 2007
@@ -134,7 +134,6 @@
 AC_HEADER_STDC
 AC_CHECK_HEADERS(stdlib.h)
 AC_CHECK_HEADERS(unistd.h)
-AC_CHECK_HEADERS(byteswap.h)
 AC_CHECK_HEADERS(stdint.h)
 AC_CHECK_HEADERS(sys/uio.h)
 AC_CHECK_HEADERS(inttypes.h)
@@ -142,6 +141,18 @@
 AC_CHECK_HEADERS(machine/types.h)
 AC_CHECK_HEADERS(sys/int_types.h)
 
+AC_LINK_IFELSE(AC_LANG_PROGRAM([
+#include <inttypes.h>
+#include <byteswap.h>
+],[
+uint64_t y = 0x1122334455667788LL;
+bswap_64(y);
+]),byteswap_cv_bswap_64_usable=yes,byteswap_cv_bswap_64_usable=no)
+
+if test "x${byteswap_cv_bswap_64_usable}" = "xyes" ; then
+AC_DEFINE([HAVE_BYTESWAP_H],1,[define if you have a usable bswap_64 in byteswap.h])
+fi
+
 dnl socket() and friends
 AC_CHECK_HEADERS(sys/socket.h netinet/in.h arpa/inet.h)
 AC_CHECK_HEADERS(windows.h, [AC_CHECK_HEADERS(winsock2.h)])
@@ -269,7 +280,7 @@
 AC_MSG_RESULT($enable_gdoi)
 AM_CONDITIONAL([GDOI],[test "SRTP_GDOI" = "1"])
 
-AC_CONFIG_HEADER(crypto/include/config.h:config_in.h)
+AC_CONFIG_HEADERS(crypto/include/config.h:config_in.h)
 
 AC_OUTPUT(Makefile crypto/Makefile doc/Makefile test/Makefile srtp-1.42.pc)
 

Modified: freeswitch/branches/cparker/libs/srtp/crypto/rng/prng.c
==============================================================================
--- freeswitch/branches/cparker/libs/srtp/crypto/rng/prng.c	(original)
+++ freeswitch/branches/cparker/libs/srtp/crypto/rng/prng.c	Tue Apr 24 10:14:28 2007
@@ -47,7 +47,7 @@
 
 /* single, global prng structure */
 
-x917_prng_t x917_prng;
+static x917_prng_t x917_prng;
 
 err_status_t
 x917_prng_init(rand_source_func_t random_source) {

Modified: freeswitch/branches/cparker/libs/udns/udns.h
==============================================================================
--- freeswitch/branches/cparker/libs/udns/udns.h	(original)
+++ freeswitch/branches/cparker/libs/udns/udns.h	Tue Apr 24 10:14:28 2007
@@ -35,6 +35,10 @@
 #   define UDNS_DATA_API __declspec(dllimport)
 #  endif
 # endif
+#ifdef _MSC_VER
+#undef inline
+#define inline __inline
+#endif
 #endif
 
 #ifndef UDNS_API
@@ -236,17 +240,17 @@
   DNS_R_BADTIME		= 18
 };
 
-static __inline unsigned dns_get16(dnscc_t *s) {
+static inline unsigned dns_get16(dnscc_t *s) {
   return ((unsigned)s[0]<<8) | s[1];
 }
-static __inline unsigned dns_get32(dnscc_t *s) {
+static inline unsigned dns_get32(dnscc_t *s) {
   return ((unsigned)s[0]<<24) | ((unsigned)s[1]<<16)
         | ((unsigned)s[2]<<8) | s[3];
 }
-static __inline dnsc_t *dns_put16(dnsc_t *d, unsigned n) {
+static inline dnsc_t *dns_put16(dnsc_t *d, unsigned n) {
   *d++ = (dnsc_t)((n >> 8) & 255); *d++ = (dnsc_t)(n & 255); return d;
 }
-static __inline dnsc_t *dns_put32(dnsc_t *d, unsigned n) {
+static inline dnsc_t *dns_put32(dnsc_t *d, unsigned n) {
   *d++ = (dnsc_t)((n >> 24) & 255); *d++ = (dnsc_t)((n >> 16) & 255);
   *d++ = (dnsc_t)((n >>  8) & 255); *d++ = (dnsc_t)(n & 255);
   return d;

Modified: freeswitch/branches/cparker/libs/udns/udns_resolver.c
==============================================================================
--- freeswitch/branches/cparker/libs/udns/udns_resolver.c	(original)
+++ freeswitch/branches/cparker/libs/udns/udns_resolver.c	Tue Apr 24 10:14:28 2007
@@ -23,6 +23,9 @@
 
 #ifdef WIN32
 #ifdef _MSC_VER
+#undef inline
+#define inline __inline
+#pragma warning(disable:4133)
 #if (_MSC_VER >= 1400) // VC8+
 #ifndef _CRT_SECURE_NO_DEPRECATE
 #define _CRT_SECURE_NO_DEPRECATE
@@ -46,9 +49,6 @@
 # include <unistd.h>
 # include <fcntl.h>
 # include <sys/time.h>
-# ifdef HAVE_CONFIG_H
-#  include <config.h>
-# endif
 # ifdef HAVE_POLL
 #  include <sys/poll.h>
 # endif
@@ -77,7 +77,7 @@
 # define EAFNOSUPPORT EINVAL
 #endif
 
-union sockaddr_ns {
+union usockaddr_ns {
   struct sockaddr sa;
   struct sockaddr_in sin;
 #if HAVE_INET6
@@ -113,24 +113,24 @@
 
 /* working with dns_query lists */
 
-static __inline void qlist_init(struct dns_qlink *list) {
+static inline void qlist_init(struct dns_qlink *list) {
   list->next = list->prev = (struct dns_query *)list;
 }
 
-static __inline int qlist_empty(const struct dns_qlink *list) {
+static inline int qlist_empty(const struct dns_qlink *list) {
   return list->next == (const struct dns_query *)list ? 1 : 0;
 }
 
-static __inline struct dns_query *qlist_first(struct dns_qlink *list) {
+static inline struct dns_query *qlist_first(struct dns_qlink *list) {
   return list->next == (struct dns_query *)list ? 0 : list->next;
 }
 
-static __inline void qlist_remove(struct dns_query *q) {
+static inline void qlist_remove(struct dns_query *q) {
   q->dnsq_link.next->dnsq_link.prev = q->dnsq_link.prev;
   q->dnsq_link.prev->dnsq_link.next = q->dnsq_link.next;
 }
 
-static __inline struct dns_query *qlist_pop(struct dns_qlink *list) {
+static inline struct dns_query *qlist_pop(struct dns_qlink *list) {
   struct dns_query *q = list->next;
   if (q == (struct dns_query *)list)
     return NULL;
@@ -139,7 +139,7 @@
 }
 
 /* insert q between prev and next */
-static __inline void
+static inline void
 qlist_insert(struct dns_query *q,
              struct dns_query *prev, struct dns_query *next) {
   q->dnsq_link.next = next;
@@ -147,22 +147,22 @@
   prev->dnsq_link.next = next->dnsq_link.prev = q;
 }
 
-static __inline void
+static inline void
 qlist_insert_after(struct dns_query *q, struct dns_query *prev) {
   qlist_insert(q, prev, prev->dnsq_link.next);
 }
 
-static __inline void
+static inline void
 qlist_insert_before(struct dns_query *q, struct dns_query *next) {
   qlist_insert(q, next->dnsq_link.prev, next);
 }
 
-static __inline void
+static inline void
 qlist_add_tail(struct dns_query *q, struct dns_qlink *top) {
   qlist_insert_before(q, (struct dns_query *)top);
 }
 
-static __inline void
+static inline void
 qlist_add_head(struct dns_query *q, struct dns_qlink *top) {
   qlist_insert_after(q, (struct dns_query *)top);
 }
@@ -184,7 +184,7 @@
   unsigned dnsc_port;			/* default port (DNS_PORT) */
   unsigned dnsc_udpbuf;			/* size of UDP buffer */
   /* array of nameserver addresses */
-  union sockaddr_ns dnsc_serv[DNS_MAXSERV];
+  union usockaddr_ns dnsc_serv[DNS_MAXSERV];
   unsigned dnsc_nserv;			/* number of nameservers */
   unsigned dnsc_salen;			/* length of socket addresses */
   /* search list for unqualified names */
@@ -272,7 +272,7 @@
 };
 
 static int dns_add_serv_internal(struct dns_ctx *ctx, const char *serv) {
-  union sockaddr_ns *sns;
+  union usockaddr_ns *sns;
   if (!serv)
     return (ctx->dnsc_nserv = 0);
   if (ctx->dnsc_nserv >= DNS_MAXSERV)
@@ -688,7 +688,7 @@
   dns_socket sock;
   unsigned i;
   int port;
-  union sockaddr_ns *sns;
+  union usockaddr_ns *sns;
 #if HAVE_INET6
   unsigned have_inet6 = 0;
 #endif
@@ -922,7 +922,7 @@
     return;
   }
   DNS_DBGQ(ctx, q, 1,
-           &ctx->dnsc_serv[q->dnsq_servi].sa, sizeof(union sockaddr_ns),
+           &ctx->dnsc_serv[q->dnsq_servi].sa, sizeof(union usockaddr_ns),
            q->dnsq_buf, q->dnsq_len);
   q->dnsq_servwait |= 1 << q->dnsq_servi;	/* expect reply from this ns */
 
@@ -1045,7 +1045,7 @@
   dnsc_t *pbuf;
   dnscc_t *pend, *pcur;
   void *result;
-  union sockaddr_ns sns;
+  union usockaddr_ns sns;
   socklen_t slen;
 
   SETCTX(ctx);

Modified: freeswitch/branches/cparker/libs/win32/js/js.vcproj
==============================================================================
--- freeswitch/branches/cparker/libs/win32/js/js.vcproj	(original)
+++ freeswitch/branches/cparker/libs/win32/js/js.vcproj	Tue Apr 24 10:14:28 2007
@@ -693,84 +693,107 @@
 			Name="NSPR Source"
 			>
 			<File
-				RelativePath="..\..\js\nsprpub\pr\src\md\windows\ntgc.c"
-				>
-			</File>
-			<File
 				RelativePath="..\..\js\nsprpub\pr\src\md\windows\ntinrval.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\md\windows\ntio.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\md\windows\ntmisc.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\md\windows\ntsec.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\md\windows\ntsem.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\md\windows\ntthread.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\pralarm.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\misc\pratom.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\threads\prcmon.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prcountr.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\threads\prcthr.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\prdir.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prdtoa.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\threads\prdump.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prenv.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prerr.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\misc\prerror.c"
 				>
 			</File>
 			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prerrortable.c"
-				>
-			</File>
-			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\prfdcach.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\prfile.c"
@@ -779,78 +802,101 @@
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\misc\prinit.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\misc\prinrval.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\prio.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\priometh.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\pripc.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\pripcsem.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\io\pripv6.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\prlayer.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\linking\prlink.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\prlog.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prlog2.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prlong.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\malloc\prmalloc.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\io\prmapopt.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\malloc\prmem.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\prmmap.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\threads\prmon.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\prmwait.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prnetdb.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\misc\prolock.c"
@@ -859,82 +905,79 @@
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\md\prosdep.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\io\prpolevt.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\io\prprf.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prrng.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\threads\prrwlock.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\io\prscanf.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\memory\prseg.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\threads\prsem.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\memory\prshm.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\memory\prshma.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\io\prsocket.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\io\prstdio.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prsystem.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prthinfo.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\misc\prtime.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\threads\prtpd.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prtpool.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\misc\prtrace.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\threads\combined\prucpu.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\threads\combined\prucv.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\threads\combined\prulock.c"
@@ -943,26 +986,35 @@
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\threads\combined\prustack.c"
 				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\threads\combined\pruthr.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\md\windows\w32ipcsem.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\md\windows\w32poll.c"
 				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\md\windows\w32rng.c"
-				>
-			</File>
-			<File
-				RelativePath="..\..\js\nsprpub\pr\src\md\windows\w32shm.c"
-				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCLCompilerTool"
+					/>
+				</FileConfiguration>
 			</File>
 			<File
 				RelativePath="..\..\js\nsprpub\pr\src\md\windows\win32_errors.c"

Modified: freeswitch/branches/cparker/libs/win32/pcre/libpcre.vcproj
==============================================================================
--- freeswitch/branches/cparker/libs/win32/pcre/libpcre.vcproj	(original)
+++ freeswitch/branches/cparker/libs/win32/pcre/libpcre.vcproj	Tue Apr 24 10:14:28 2007
@@ -53,7 +53,7 @@
 				Name="VCCLCompilerTool"
 				Optimization="0"
 				AdditionalIncludeDirectories="./"
-				PreprocessorDefinitions="_WIN32;WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBPCRE_EXPORTS;SUPPORT_UTF8;SUPPORT_UCP;POSIX_MALLOC_THRESHOLD=10;NO_RECURSE;DEBUG;PCRE_DEFINITION;DLL_EXPORT"
+				PreprocessorDefinitions="_WIN32;WIN32;_DEBUG;_WINDOWS;LIBPCRE_EXPORTS;SUPPORT_UTF8;SUPPORT_UCP;POSIX_MALLOC_THRESHOLD=10;NO_RECURSE;DEBUG;PCRE_DEFINITION;PCRE_STATIC"
 				MinimalRebuild="true"
 				BasicRuntimeChecks="3"
 				RuntimeLibrary="3"
@@ -97,7 +97,7 @@
 			/>
 			<Tool
 				Name="VCPostBuildEventTool"
-				CommandLine="if not exist &quot;$(ProjectDir)..\..\include\&quot; md  &quot;$(ProjectDir)..\..\include\&quot;&#x0D;&#x0A;xcopy &quot;$(ProjectDir)..\..\pcre\pcre.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;"
+				CommandLine=""
 			/>
 		</Configuration>
 		<Configuration
@@ -140,7 +140,7 @@
 				Optimization="2"
 				InlineFunctionExpansion="1"
 				AdditionalIncludeDirectories="./"
-				PreprocessorDefinitions="_WIN32;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBPCRE_EXPORTS;SUPPORT_UTF8;SUPPORT_UCP;POSIX_MALLOC_THRESHOLD=10;NO_RECURSE;PCRE_DEFINITION;DLL_EXPORT"
+				PreprocessorDefinitions="_WIN32;WIN32;NDEBUG;_WINDOWS;LIBPCRE_EXPORTS;SUPPORT_UTF8;SUPPORT_UCP;POSIX_MALLOC_THRESHOLD=10;NO_RECURSE;PCRE_DEFINITION;PCRE_STATIC"
 				StringPooling="true"
 				RuntimeLibrary="2"
 				EnableFunctionLevelLinking="true"
@@ -183,7 +183,7 @@
 			/>
 			<Tool
 				Name="VCPostBuildEventTool"
-				CommandLine="if not exist &quot;$(ProjectDir)..\..\include\&quot; md  &quot;$(ProjectDir)..\..\include\&quot;&#x0D;&#x0A;xcopy &quot;$(ProjectDir)..\..\pcre\pcre.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;"
+				CommandLine=""
 			/>
 		</Configuration>
 		<Configuration
@@ -285,7 +285,7 @@
 			/>
 			<Tool
 				Name="VCPostBuildEventTool"
-				CommandLine="if not exist &quot;$(ProjectDir)..\..\include\&quot; md  &quot;$(ProjectDir)..\..\include\&quot;&#x0D;&#x0A;xcopy &quot;$(ProjectDir)..\..\pcre\pcre.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;"
+				CommandLine=""
 			/>
 		</Configuration>
 		<Configuration
@@ -386,7 +386,7 @@
 			/>
 			<Tool
 				Name="VCPostBuildEventTool"
-				CommandLine="if not exist &quot;$(ProjectDir)..\..\include\&quot; md  &quot;$(ProjectDir)..\..\include\&quot;&#x0D;&#x0A;xcopy &quot;$(ProjectDir)..\..\pcre\pcre.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;"
+				CommandLine=""
 			/>
 		</Configuration>
 	</Configurations>

Modified: freeswitch/branches/cparker/libs/win32/sofia/libsofia_sip_ua_static.vcproj
==============================================================================
--- freeswitch/branches/cparker/libs/win32/sofia/libsofia_sip_ua_static.vcproj	(original)
+++ freeswitch/branches/cparker/libs/win32/sofia/libsofia_sip_ua_static.vcproj	Tue Apr 24 10:14:28 2007
@@ -44,7 +44,7 @@
 				Name="VCCLCompilerTool"
 				Optimization="0"
 				AdditionalIncludeDirectories="&quot;..\..\sofia-sip\win32&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\su&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\ipt&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\sresolv&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\bnf&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\url&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\msg&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\sip&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\nta&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\nua&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\iptsec&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\http&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\nth&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\nea&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\sdp&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\soa&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\stun&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\tport&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\features&quot;;&quot;..\..\pthreads-w32-2-7-0-release&quot;;."
-				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;IN_LIBSOFIA_SIP_UA_STATIC;LIBSOFIA_SIP_UA_STATIC;LIBSRES_STATIC;PTW32_STATIC_LIB"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;IN_LIBSOFIA_SIP_UA_STATIC;LIBSOFIA_SIP_UA_STATIC;LIBSRES_STATIC;PTW32_STATIC_LIB;HAVE_IPHLPAPI_H"
 				MinimalRebuild="true"
 				BasicRuntimeChecks="3"
 				RuntimeLibrary="3"
@@ -54,6 +54,7 @@
 				ProgramDataBaseFileName=".\Debug/"
 				BrowseInformation="1"
 				WarningLevel="4"
+				WarnAsError="true"
 				SuppressStartupBanner="true"
 				Detect64BitPortabilityProblems="true"
 				DebugInformationFormat="3"
@@ -123,7 +124,7 @@
 				Optimization="2"
 				InlineFunctionExpansion="1"
 				AdditionalIncludeDirectories="&quot;..\..\sofia-sip\win32&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\su&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\ipt&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\sresolv&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\bnf&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\url&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\msg&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\sip&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\nta&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\nua&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\iptsec&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\http&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\nth&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\nea&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\sdp&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\soa&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\stun&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\tport&quot;;&quot;..\..\sofia-sip\libsofia-sip-ua\features&quot;;&quot;..\..\pthreads-w32-2-7-0-release&quot;;."
-				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;IN_LIBSOFIA_SIP_UA_STATIC;LIBSOFIA_SIP_UA_STATIC;LIBSRES_STATIC;PTW32_STATIC_LIB"
+				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;IN_LIBSOFIA_SIP_UA_STATIC;LIBSOFIA_SIP_UA_STATIC;LIBSRES_STATIC;PTW32_STATIC_LIB;HAVE_IPHLPAPI_H"
 				StringPooling="true"
 				RuntimeLibrary="2"
 				EnableFunctionLevelLinking="true"
@@ -133,6 +134,7 @@
 				ProgramDataBaseFileName=".\Release/"
 				BrowseInformation="1"
 				WarningLevel="4"
+				WarnAsError="true"
 				SuppressStartupBanner="true"
 				Detect64BitPortabilityProblems="true"
 			/>
@@ -182,247 +184,758 @@
 				Name="su"
 				Filter="su*.c"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\inet_ntop.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\inet_pton.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_addrinfo.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_alloc.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_alloc_lock.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_bm.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_default_log.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_errno.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_global_log.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_localinfo.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_log.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_md5.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_os_nw.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_port.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_root.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_sprintf.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_strdup.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_strlst.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_tag_io.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_taglist.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_time.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_time0.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_timer.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_uniqueid.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_vector.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_wait.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\inet_ntop.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\inet_pton.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_addrinfo.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_alloc.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_alloc_lock.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_base_port.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_bm.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_default_log.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_errno.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_global_log.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_localinfo.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_log.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_md5.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_os_nw.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_port.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_pthread_port.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_root.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_socket_port.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_sprintf.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_strdup.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_strlst.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_tag_io.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_taglist.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_time.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_time0.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_timer.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_uniqueid.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_vector.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_wait.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_win32_port.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="ipt"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\base64.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\rc4.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\string0.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\token64.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\base64.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\rc4.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\string0.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\token64.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="url"
 				Filter="url*.c"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\url.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\url_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\url_tag_ref.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\url.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\url_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\url_tag_ref.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="features"
 				Filter="features*.c"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\features\features.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\features\features.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="bnf"
 				Filter="bnf*.c"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\bnf\bnf.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\bnf\bnf.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="msg"
 				Filter="msg*.c"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_auth.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_basic.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_date.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_generic.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_header_copy.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_header_make.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_mclass.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_mime.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_mime_table.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_parser.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_parser_util.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_tag.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_auth.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_basic.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_date.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_generic.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_header_copy.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_header_make.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_mclass.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_mime.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_mime_table.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_parser.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_parser_util.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_tag.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="clib replacement"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\memcspn.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\memmem.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\memspn.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\strcasestr.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\strtoull.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\memcspn.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\memmem.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\memspn.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\strcasestr.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\strtoull.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="sip"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_basic.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_caller_prefs.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_event.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_extra.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_feature.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_header.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_mime.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_parser.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_parser_table.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_prack.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_pref_util.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_reason.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_refer.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_security.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_session.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_status.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_tag_class.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_tag_ref.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_time.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_util.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_basic.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_caller_prefs.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_event.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_extra.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_feature.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_header.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_mime.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_parser.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_parser_table.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_prack.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_pref_util.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_reason.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_refer.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_security.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_session.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_status.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_tag_class.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_tag_ref.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_time.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_util.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="http"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_basic.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_extra.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_header.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_parser.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_parser_table.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_status.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_tag_class.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_tag_ref.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_basic.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_extra.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_header.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_parser.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_parser_table.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_status.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_tag_class.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\http_tag_ref.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="nth"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\nth_client.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\nth_server.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\nth_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\nth_tag_ref.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\nth_client.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\nth_server.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\nth_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\nth_tag_ref.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="sresolv"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sres.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sres_blocking.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sres_cache.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sresolv.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sres.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sres_blocking.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sres_cache.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sresolv.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="nea"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_debug.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_event.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_server.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_tag_ref.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_debug.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_event.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_server.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_tag_ref.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="iptsec"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_client.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_common.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_digest.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_module.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_module_http.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_module_sip.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_plugin.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_plugin_delayed.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_tag_ref.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\iptsec_debug.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_client.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_common.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_digest.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_module.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_module_http.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_module_sip.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_plugin.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_plugin_delayed.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\auth_tag_ref.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\iptsec_debug.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="stun"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_common.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_dns.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_internal.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_mini.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_tag_ref.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_common.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_dns.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_internal.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_mini.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\stun_tag_ref.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="nua"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_common.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_dialog.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_dialog.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_event_server.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_extension.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_message.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_notifier.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_options.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_params.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_params.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_publish.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_register.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_registrar.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_session.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_stack.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_stack.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_subnotref.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_tag_ref.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\outbound.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_common.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_dialog.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_dialog.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_event_server.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_extension.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_message.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_notifier.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_options.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_params.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_params.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_publish.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_register.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_registrar.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_session.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_stack.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_stack.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_subnotref.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\nua_tag_ref.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\outbound.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="nta"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta_check.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta_tag_ref.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sl_read_payload.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sl_utils_log.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sl_utils_print.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta_check.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta_tag_ref.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sl_read_payload.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sl_utils_log.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sl_utils_print.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="tport"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_internal.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_logging.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_stub_sigcomp.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_stub_stun.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_tag_ref.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_type_connect.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_type_tcp.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_type_udp.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_internal.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_logging.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_stub_sigcomp.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_stub_stun.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_tag_ref.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_type_connect.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_type_tcp.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_type_udp.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="sdp"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp_parse.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp_print.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp_tag_ref.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp_parse.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp_print.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sdp_tag_ref.c"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="soa"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\soa.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\sofia-sip\soa_session.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\soa_static.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\soa_tag.c"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\soa_tag_ref.c"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\soa.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\sofia-sip\soa_session.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\soa_static.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\soa_tag.c"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\soa_tag_ref.c"
+					>
+				</File>
 			</Filter>
 		</Filter>
 		<Filter
@@ -433,194 +946,533 @@
 				Name="su headers"
 				Filter="su*.h"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\htable.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\htable2.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\rbtree.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_addrinfo.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_alloc.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_alloc_stat.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_bm.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_config.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_debug.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_errno.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_localinfo.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_log.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_md5.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_module_debug.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_os_nw.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_port.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_source.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_strlst.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tag.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tag_class.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tag_inline.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tag_io.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tagarg.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_time.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_types.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_uniqueid.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_vector.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_wait.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\tstdef.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\htable.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\htable2.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\rbtree.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_addrinfo.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_alloc.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_alloc_stat.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_bm.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_config.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_debug.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_errno.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_localinfo.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_log.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_md5.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_module_debug.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_os_nw.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\su_port.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_source.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_strlst.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tag.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tag_class.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tag_inline.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tag_io.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_tagarg.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_time.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_types.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_uniqueid.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_vector.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\su_wait.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\su\sofia-sip\tstdef.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="win32 headers"
 				>
-				<File RelativePath="..\config.h"></File>
-				<File RelativePath="..\sofia-sip\su_configure.h"></File>
-				<File RelativePath="..\unistd.h"></File>
+				<File
+					RelativePath="..\config.h"
+					>
+				</File>
+				<File
+					RelativePath="..\sofia-sip\su_configure.h"
+					>
+				</File>
+				<File
+					RelativePath="..\unistd.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="ipt headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\sofia-sip\base64.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\sofia-sip\rc4.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\sofia-sip\string0.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\sofia-sip\token64.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\sofia-sip\base64.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\sofia-sip\rc4.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\sofia-sip\string0.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\ipt\sofia-sip\token64.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="url headers"
 				Filter="url*.h"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\sofia-sip\url.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\sofia-sip\url_tag.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\sofia-sip\url_tag_class.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\sofia-sip\url.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\sofia-sip\url_tag.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\url\sofia-sip\url_tag_class.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="features headers"
 				Filter="features*.h"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\features\sofia-sip\sofia_features.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\features\sofia-sip\sofia_features.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="bnf headers"
 				Filter="bnf*.h"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\bnf\sofia-sip\bnf.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\bnf\sofia-sip\hostdomain.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\bnf\sofia-sip\bnf.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\bnf\sofia-sip\hostdomain.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="msg headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_addr.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_bnf.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_buffer.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_date.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_header.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_internal.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_mclass.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_mclass_hash.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_mime.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_mime_protos.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_parser.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_protos.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_tag_class.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_types.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_addr.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_bnf.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_buffer.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_date.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_header.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\msg_internal.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_mclass.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_mclass_hash.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_mime.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_mime_protos.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_parser.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_protos.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_tag_class.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\msg\sofia-sip\msg_types.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="sip headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_extensions.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_hclasses.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_header.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_internal.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_parser.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_protos.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_status.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_tag.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_tag_class.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_util.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_extensions.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_hclasses.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_header.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sip_internal.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_parser.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_protos.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_status.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_tag.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_tag_class.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sip\sofia-sip\sip_util.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="http headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_hclasses.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_header.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_parser.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_protos.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_status.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_tag.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_tag_class.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_hclasses.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_header.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_parser.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_protos.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_status.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_tag.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\http\sofia-sip\http_tag_class.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="nth headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\sofia-sip\nth.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\sofia-sip\nth_tag.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\sofia-sip\nth.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nth\sofia-sip\nth_tag.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="sresolv headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-resolv\sres.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-resolv\sres_async.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-resolv\sres_cache.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-resolv\sres_record.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-sip\sresolv.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-resolv\sres.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-resolv\sres_async.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-resolv\sres_cache.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-resolv\sres_record.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sresolv\sofia-sip\sresolv.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="nea headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\sofia-sip\nea.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_debug.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\sofia-sip\nea_tag.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\sofia-sip\nea.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\nea_debug.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nea\sofia-sip\nea_tag.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="iptsec headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_client.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_digest.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_module.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_ntlm.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_plugin.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\iptsec_debug.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_client.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_digest.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_module.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_ntlm.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\sofia-sip\auth_plugin.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\iptsec\iptsec_debug.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="stun headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\sofia-sip\stun.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\sofia-sip\stun_common.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\sofia-sip\stun_tag.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\sofia-sip\stun.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\sofia-sip\stun_common.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\stun\sofia-sip\stun_tag.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="nua headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\sofia-sip\nua.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\sofia-sip\nua_tag.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\sofia-sip\nua.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nua\sofia-sip\nua_tag.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="nta headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\nta.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta_internal.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\nta_stateless.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\nta_tag.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\nta_tport.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\sl_utils.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\nta.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\nta_internal.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\nta_stateless.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\nta_tag.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\nta_tport.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\nta\sofia-sip\sl_utils.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="tport headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\sofia-sip\tport.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\sofia-sip\tport_plugins.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\sofia-sip\tport_tag.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_tls.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\sofia-sip\tport.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\sofia-sip\tport_plugins.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\sofia-sip\tport_tag.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\tport\tport_tls.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="sdp headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sofia-sip\sdp.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sofia-sip\sdp_tag.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sofia-sip\sdp.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\sdp\sofia-sip\sdp_tag.h"
+					>
+				</File>
 			</Filter>
 			<Filter
 				Name="soa headers"
 				>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\sofia-sip\soa.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\sofia-sip\soa_add.h"></File>
-				<File RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\sofia-sip\soa_tag.h"></File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\sofia-sip\soa.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\sofia-sip\soa_add.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\sofia-sip\libsofia-sip-ua\soa\sofia-sip\soa_tag.h"
+					>
+				</File>
 			</Filter>
 		</Filter>
 	</Files>

Modified: freeswitch/branches/cparker/libs/win32/sqlite/sqlite.vcproj
==============================================================================
--- freeswitch/branches/cparker/libs/win32/sqlite/sqlite.vcproj	(original)
+++ freeswitch/branches/cparker/libs/win32/sqlite/sqlite.vcproj	Tue Apr 24 10:14:28 2007
@@ -78,7 +78,7 @@
 			/>
 			<Tool
 				Name="VCPostBuildEventTool"
-				CommandLine="if not exist &quot;$(ProjectDir)..\..\include\&quot; md  &quot;$(ProjectDir)..\..\include\&quot;&#x0D;&#x0A;xcopy &quot;$(ProjectDir)..\..\sqlite\src\*.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;xcopy &quot;$(ProjectDir)*.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;&#x0D;&#x0A;"
+				CommandLine="&#x0D;&#x0A;"
 			/>
 		</Configuration>
 		<Configuration
@@ -142,7 +142,7 @@
 			/>
 			<Tool
 				Name="VCPostBuildEventTool"
-				CommandLine="if not exist &quot;$(ProjectDir)..\..\include\&quot; md  &quot;$(ProjectDir)..\..\include\&quot;&#x0D;&#x0A;xcopy &quot;$(ProjectDir)..\..\sqlite\src\*.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;xcopy &quot;$(ProjectDir)*.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;&#x0D;&#x0A;"
+				CommandLine="&#x0D;&#x0A;"
 			/>
 		</Configuration>
 		<Configuration
@@ -224,7 +224,7 @@
 			/>
 			<Tool
 				Name="VCPostBuildEventTool"
-				CommandLine="if not exist &quot;$(ProjectDir)..\..\include\&quot; md  &quot;$(ProjectDir)..\..\include\&quot;&#x0D;&#x0A;xcopy &quot;$(ProjectDir)..\..\sqlite\src\*.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;xcopy &quot;$(ProjectDir)*.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;&#x0D;&#x0A;"
+				CommandLine="&#x0D;&#x0A;"
 			/>
 		</Configuration>
 		<Configuration
@@ -299,7 +299,7 @@
 			/>
 			<Tool
 				Name="VCPostBuildEventTool"
-				CommandLine="if not exist &quot;$(ProjectDir)..\..\include\&quot; md  &quot;$(ProjectDir)..\..\include\&quot;&#x0D;&#x0A;xcopy &quot;$(ProjectDir)..\..\sqlite\src\*.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;xcopy &quot;$(ProjectDir)*.h&quot; &quot;$(ProjectDir)..\..\include\&quot; /C /D /Y&#x0D;&#x0A;&#x0D;&#x0A;"
+				CommandLine="&#x0D;&#x0A;"
 			/>
 		</Configuration>
 	</Configurations>

Modified: freeswitch/branches/cparker/libs/win32/xmlrpc/xmlrpc.vcproj
==============================================================================
--- freeswitch/branches/cparker/libs/win32/xmlrpc/xmlrpc.vcproj	(original)
+++ freeswitch/branches/cparker/libs/win32/xmlrpc/xmlrpc.vcproj	Tue Apr 24 10:14:28 2007
@@ -26,7 +26,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="if not exist $(ProjectDir)..\..\xmlrpc-c\transport_config.h copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\transport_config_win32.h&quot; $(ProjectDir)..\..\xmlrpc-c\transport_config.h&#x0D;&#x0A;if not exist $(ProjectDir)..\..\xmlrpc-c\config.h copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\xmlrpc_win32_config.h&quot; $(ProjectDir)..\..\xmlrpc-c\config.h&#x0D;&#x0A;if not exist $(ProjectDir)..\..\xmlrpc-c\xmlrpc_config.h copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\xmlrpc_win32_config.h&quot; $(ProjectDir)..\..\xmlrpc-c\xmlrpc_config.h&#x0D;&#x0A;"
+				CommandLine="if not exist &quot;$(ProjectDir)..\..\xmlrpc-c\transport_config.h&quot; copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\transport_config_win32.h&quot; &quot;$(ProjectDir)..\..\xmlrpc-c\transport_config.h&quot;&#x0D;&#x0A;if not exist &quot;$(ProjectDir)..\..\xmlrpc-c\config.h&quot; copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\xmlrpc_win32_config.h&quot; &quot;$(ProjectDir)..\..\xmlrpc-c\config.h&quot;&#x0D;&#x0A;if not exist &quot;$(ProjectDir)..\..\xmlrpc-c\xmlrpc_config.h&quot; copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\xmlrpc_win32_config.h&quot; &quot;$(ProjectDir)..\..\xmlrpc-c\xmlrpc_config.h&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"
@@ -102,7 +102,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="if not exist $(ProjectDir)..\..\xmlrpc-c\transport_config.h copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\transport_config_win32.h&quot; $(ProjectDir)..\..\xmlrpc-c\transport_config.h&#x0D;&#x0A;if not exist $(ProjectDir)..\..\xmlrpc-c\config.h copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\xmlrpc_win32_config.h&quot; $(ProjectDir)..\..\xmlrpc-c\config.h&#x0D;&#x0A;if not exist $(ProjectDir)..\..\xmlrpc-c\xmlrpc_config.h copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\xmlrpc_win32_config.h&quot; $(ProjectDir)..\..\xmlrpc-c\xmlrpc_config.h&#x0D;&#x0A;"
+				CommandLine="if not exist &quot;$(ProjectDir)..\..\xmlrpc-c\transport_config.h&quot; copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\transport_config_win32.h&quot; &quot;$(ProjectDir)..\..\xmlrpc-c\transport_config.h&quot;&#x0D;&#x0A;if not exist &quot;$(ProjectDir)..\..\xmlrpc-c\config.h&quot; copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\xmlrpc_win32_config.h&quot; &quot;$(ProjectDir)..\..\xmlrpc-c\config.h&quot;&#x0D;&#x0A;if not exist &quot;$(ProjectDir)..\..\xmlrpc-c\xmlrpc_config.h&quot; copy &quot;$(ProjectDir)..\..\xmlrpc-c\Windows\xmlrpc_win32_config.h&quot; &quot;$(ProjectDir)..\..\xmlrpc-c\xmlrpc_config.h&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"

Modified: freeswitch/branches/cparker/libs/xmlrpc-c/GNUmakefile
==============================================================================
--- freeswitch/branches/cparker/libs/xmlrpc-c/GNUmakefile	(original)
+++ freeswitch/branches/cparker/libs/xmlrpc-c/GNUmakefile	Tue Apr 24 10:14:28 2007
@@ -7,7 +7,7 @@
 
 include $(SRCDIR)/Makefile.config
 
-SUBDIRS = include src lib tools examples
+SUBDIRS = include src lib tools
 
 PROGRAMS_TO_INSTALL = xmlrpc-c-config
 

Modified: freeswitch/branches/cparker/libs/xmlrpc-c/configure.in
==============================================================================
--- freeswitch/branches/cparker/libs/xmlrpc-c/configure.in	(original)
+++ freeswitch/branches/cparker/libs/xmlrpc-c/configure.in	Tue Apr 24 10:14:28 2007
@@ -240,9 +240,7 @@
 dnl =======================================================================
 
 AC_PROG_CC
-if test x"$enable_cplusplus" != xno; then
-    AC_PROG_CXX
-fi
+AC_PROG_CXX
 AC_PROG_INSTALL
 
 

Modified: freeswitch/branches/cparker/libs/xmlrpc-c/src/Makefile
==============================================================================
--- freeswitch/branches/cparker/libs/xmlrpc-c/src/Makefile	(original)
+++ freeswitch/branches/cparker/libs/xmlrpc-c/src/Makefile	Tue Apr 24 10:14:28 2007
@@ -10,9 +10,11 @@
 default: all
 
 SUBDIRS =
+CPPCLEAN = 
 
 ifeq ($(ENABLE_CPLUSPLUS),yes)
   SUBDIRS += cpp
+  CPPCLEAN += cpp/clean
 endif
 
 WININET_TRANSPORT_DIR = $(SRCDIR)/lib/wininet_transport
@@ -131,7 +133,7 @@
 
 .PHONY: clean clean-local distclean
 clean: clean-common clean-local
-clean-local: cpp/clean
+clean-local: $(CPPCLEAN)
 
 distclean: clean distclean-common
 

Modified: freeswitch/branches/cparker/scripts/socket/FreeSWITCH/Client.pm
==============================================================================
--- freeswitch/branches/cparker/scripts/socket/FreeSWITCH/Client.pm	(original)
+++ freeswitch/branches/cparker/scripts/socket/FreeSWITCH/Client.pm	Tue Apr 24 10:14:28 2007
@@ -208,6 +208,22 @@
   return $self->sendmsg($hash);
 }
 
+sub unicast($$$$$$) {
+  my $self = shift;
+
+  my $hash = {
+	      'command' => "sendmsg",
+	      'call-command' => "unicast",
+	      'local_ip' => $_[0],
+	      'local_port' => $_[1],
+	      'remote_ip' => $_[2],
+	      'remote_port' => $_[3],
+	      'transport' => $_[4]
+	     };
+
+  return $self->sendmsg($hash);
+}
+
 sub call_data($) {
   my $self = shift;
 

Modified: freeswitch/branches/cparker/src/include/switch.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch.h	(original)
+++ freeswitch/branches/cparker/src/include/switch.h	Tue Apr 24 10:14:28 2007
@@ -47,18 +47,40 @@
 #include <switch_am_config.h>
 #endif
 
-#include <switch_platform.h>
+#define FREESWITCH_PEN "27880"
+#define FREESWITCH_OID_PREFIX ".1.3.6.1.4.1." FREESWITCH_PEN
+#define FREESWITCH_ITAD "543"
+#define __EXTENSIONS__ 1
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <stddef.h>
 #include <assert.h>
 #include <setjmp.h>
-#include <switch_apr.h>
-#include <switch_sqlite.h>
+#include <ctype.h>
+#include <fcntl.h>
+#ifndef _MSC_VER
+#include <strings.h>
+#endif
+#include <string.h>
+#include <sys/stat.h>
+#include <limits.h>
+#include <sys/types.h>
+#include <time.h>
+#include <signal.h>
+#include <errno.h>
+
+#include <switch_platform.h>
 #include <switch_types.h>
+#include <switch_apr.h>
+
+#include <switch_core_db.h>
+#include <switch_regex.h>
 #include <switch_core.h>
 #include <switch_loadable_module.h>
 #include <switch_console.h>
 #include <switch_utils.h>
 #include <switch_caller.h>
-#include <switch_config.h>
 #include <switch_frame.h>
 #include <switch_module_interfaces.h>
 #include <switch_channel.h>
@@ -70,8 +92,9 @@
 #include <switch_stun.h>
 #include <switch_log.h>
 #include <switch_xml.h>
-#include <pcre.h>
-
+#include <switch_core_event_hook.h>
+#include <switch_scheduler.h>
+#include <libteletone.h>
 
 /** \mainpage FreeSWITCH
  * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application

Modified: freeswitch/branches/cparker/src/include/switch_am_config.h.in
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_am_config.h.in	(original)
+++ freeswitch/branches/cparker/src/include/switch_am_config.h.in	Tue Apr 24 10:14:28 2007
@@ -1,131 +1,19 @@
-/* src/include/switch_am_config.h.in.  Generated from configure.in by autoheader.  */
+#ifndef SWITCH_AM_CONFIG_H
+#define SWITCH_AM_CONFIG_H
 
-/* Enable extra debugging. */
-#undef DEBUG
 
-/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
-   */
-#undef HAVE_DIRENT_H
+#define SWITCH_INT_16  @short_value@
+#define SWITCH_INT_32  @int_value@
+#define SWITCH_INT_64  @long_value@
+#define SWITCH_SIZE_T  @size_t_value@
+#define SWITCH_SSIZE_T @ssize_t_value@
+
+#define SWITCH_SIZEOF_VOIDP @voidp_size@
+#define SWITCH_PREFIX_DIR "@prefix@"
+
+ at ssize_t_fmt@
+ at size_t_fmt@
+ at int64_t_fmt@
+ at uint64_t_fmt@
 
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#undef HAVE_DLFCN_H
-
-/* Define to 1 if you have the `gethostname' function. */
-#undef HAVE_GETHOSTNAME
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#undef HAVE_INTTYPES_H
-
-/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
-   to 0 otherwise. */
-#undef HAVE_MALLOC
-
-/* Define to 1 if you have the <memory.h> header file. */
-#undef HAVE_MEMORY_H
-
-/* Define to 1 if you have the `mlock' function. */
-#undef HAVE_MLOCK
-
-/* Define to 1 if you have the `mlockall' function. */
-#undef HAVE_MLOCKALL
-
-/* Define to 1 if you have the `mmap' function. */
-#undef HAVE_MMAP
-
-/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
-#undef HAVE_NDIR_H
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#undef HAVE_STDINT_H
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#undef HAVE_STDLIB_H
-
-/* Define to 1 if you have the `strftime' function. */
-#undef HAVE_STRFTIME
-
-/* Define to 1 if you have the <strings.h> header file. */
-#undef HAVE_STRINGS_H
-
-/* Define to 1 if you have the <string.h> header file. */
-#undef HAVE_STRING_H
-
-/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
-   */
-#undef HAVE_SYS_DIR_H
-
-/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
-   */
-#undef HAVE_SYS_NDIR_H
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#undef HAVE_SYS_STAT_H
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#undef HAVE_SYS_TYPES_H
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#undef HAVE_UNISTD_H
-
-/* Define to 1 if you have the `usleep' function. */
-#undef HAVE_USLEEP
-
-/* Define to 1 if you have the `vasprintf' function. */
-#undef HAVE_VASPRINTF
-
-/* Enable Optimization. */
-#undef OPTIMZER
-
-/* Name of package */
-#undef PACKAGE
-
-/* Define to the address where bug reports for this package should be sent. */
-#undef PACKAGE_BUGREPORT
-
-/* Define to the full name of this package. */
-#undef PACKAGE_NAME
-
-/* Define to the full name and version of this package. */
-#undef PACKAGE_STRING
-
-/* Define to the one symbol short name of this package. */
-#undef PACKAGE_TARNAME
-
-/* Define to the version of this package. */
-#undef PACKAGE_VERSION
-
-/* Define as the return type of signal handlers (`int' or `void'). */
-#undef RETSIGTYPE
-
-/* Define to 1 if you have the ANSI C header files. */
-#undef STDC_HEADERS
-
-/* Little Endian */
-#undef SWITCH_BYTE_ORDER
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#undef TIME_WITH_SYS_TIME
-
-/* Define to 1 if your <sys/time.h> declares `struct tm'. */
-#undef TM_IN_SYS_TIME
-
-/* Version number of package */
-#undef VERSION
-
-/* sunpro is bad at inline */
-#undef __inline__
-
-/* Define to empty if `const' does not conform to ANSI C. */
-#undef const
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef __cplusplus
-#undef inline
 #endif
-
-/* Define to rpl_malloc if the replacement function should be used. */
-#undef malloc
-
-/* Define to `unsigned' if <sys/types.h> does not define. */
-#undef size_t

Modified: freeswitch/branches/cparker/src/include/switch_apr.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_apr.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_apr.h	Tue Apr 24 10:14:28 2007
@@ -39,1450 +39,1110 @@
 #ifndef SWITCH_APR_H
 #define SWITCH_APR_H
 
-#include <apr.h>
-#include <apr_network_io.h>
-#include <apr_errno.h>
-#include <apr_general.h>
-#include <apr_thread_proc.h>
-#include <apr_portable.h>
-#include <apr_thread_mutex.h>
-#include <apr_thread_cond.h>
-#include <apr_thread_rwlock.h>
-#include <apr_file_io.h>
-#include <apr_poll.h>
-#include <apr_dso.h>
-#include <apr_hash.h>
-#include <apr_strings.h>
-#include <apr_network_io.h>
-#include <apr_poll.h>
-#include <apr_queue.h>
-#include <apr_uuid.h>
-#include <apr_strmatch.h>
-#define APR_WANT_STDIO
-#define APR_WANT_STRFUNC
-#include <apr_want.h>
-#include <apr_env.h>
-
 SWITCH_BEGIN_EXTERN_C
-
 /*
    The pieces of apr we allow ppl to pass around between modules we typedef into our namespace and wrap all the functions
    any other apr code should be as hidden as possible.
 */
-
 /**
  * @defgroup switch_apr Brought To You By APR
  * @ingroup FREESWITCH
  * @{
- */	
-
-typedef apr_size_t swtich_size_t;
-typedef apr_int16_t switch_int16_t;
-
+ */
 /**
- * @defgroup switch_file_io File I/O Handling Functions
+ * @defgroup switch_memory_pool Memory Pool Functions
  * @ingroup switch_apr 
  * @{
  */
+/** The fundamental pool type */
+	typedef struct apr_pool_t switch_memory_pool_t;
 
-typedef apr_size_t switch_size_t;
-
-/** Structure for referencing files. */
-typedef apr_file_t switch_file_t;
-
-#define SWITCH_SO_LINGER APR_SO_LINGER
-#define SWITCH_SO_KEEPALIVE APR_SO_KEEPALIVE
-#define SWITCH_SO_DEBUG APR_SO_DEBUG
-#define SWITCH_SO_NONBLOCK APR_SO_NONBLOCK
-#define SWITCH_SO_REUSEADDR APR_SO_REUSEADDR
-#define SWITCH_SO_SNDBUF APR_SO_SNDBUF
-#define SWITCH_SO_RCVBUF APR_SO_RCVBUF
-#define SWITCH_SO_DISCONNECTED APR_SO_DISCONNECTED
 
 /**
- * @defgroup switch_file_permissions File Permissions flags 
- * @ingroup switch_file_io
- * @{
+ * Clear all memory in the pool and run all the cleanups. This also destroys all
+ * subpools.
+ * @param p The pool to clear
+ * @remark This does not actually free the memory, it just allows the pool
+ *         to re-use this memory for the next allocation.
+ * @see apr_pool_destroy()
  */
-    
-#define SWITCH_FPROT_USETID APR_FPROT_USETID		/**< Set user id */
-#define SWITCH_FPROT_UREAD APR_FPROT_UREAD			/**< Read by user */
-#define SWITCH_FPROT_UWRITE APR_FPROT_UWRITE		/**< Write by user */
-#define SWITCH_FPROT_UEXECUTE APR_FPROT_UEXECUTE	/**< Execute by user */
-
-#define SWITCH_FPROT_GSETID APR_FPROT_GSETID		/**< Set group id */
-#define SWITCH_FPROT_GREAD APR_FPROT_GREAD			/**< Read by group */
-#define SWITCH_FPROT_GWRITE APR_FPROT_GWRITE		/**< Write by group */
-#define SWITCH_FPROT_GEXECUTE APR_FPROT_GEXECUTE	/**< Execute by group */
-
-#define SWITCH_FPROT_WSETID APR_FPROT_U WSETID
-#define SWITCH_FPROT_WREAD APR_FPROT_WREAD			/**< Read by others */
-#define SWITCH_FPROT_WWRITE APR_FPROT_WWRITE		/**< Write by others */
-#define SWITCH_FPROT_WEXECUTE APR_FPROT_WEXECUTE	/**< Execute by others */
-
-#define SWITCH_FPROT_OS_DEFAULT APR_FPROT_OS_DEFAULT	/**< use OS's default permissions */
+SWITCH_DECLARE(void) switch_pool_clear(switch_memory_pool_t *p);
 
-/* additional permission flags for apr_file_copy  and apr_file_append */
-#define SWITCH_FPROT_FILE_SOURCE_PERMS APR_FPROT_FILE_SOURCE_PERMS	/**< Copy source file's permissions */
 /** @} */
 
 /**
- * @defgroup switch_file_open_flags File Open Flags/Routines
- * @ingroup switch_file_io
+ * @defgroup switch_dso Dynamic Object Handling Routines
+ * @ingroup switch_apr 
  * @{
  */
-#define SWITCH_FOPEN_READ APR_FOPEN_READ							/**< Open the file for reading */
-#define SWITCH_FOPEN_WRITE APR_FOPEN_WRITE							/**< Open the file for writing */
-#define SWITCH_FOPEN_CREATE APR_FOPEN_CREATE						/**< Create the file if not there */
-#define SWITCH_FOPEN_APPEND APR_FOPEN_APPEND						/**< Append to the end of the file */
-#define SWITCH_FOPEN_TRUNCATE APR_FOPEN_TRUNCATE					/**< Open the file and truncate to 0 length */
-#define SWITCH_FOPEN_BINARY APR_FOPEN_BINARY						/**< Open the file in binary mode */
-#define SWITCH_FOPEN_EXCL APR_FOPEN_EXCL							/**< Open should fail if APR_CREATE and file exists. */
-#define SWITCH_FOPEN_BUFFERED APR_FOPEN_BUFFERED					/**< Open the file for buffered I/O */
-#define SWITCH_FOPEN_DELONCLOSE APR_FOPEN_DELONCLOSE				/**< Delete the file after close */
-#define SWITCH_FOPEN_XTHREAD APR_FOPEN_XTHREAD						/**< Platform dependent tag to open the file for use across multiple threads */
-#define SWITCH_FOPEN_SHARELOCK APR_FOPEN_SHARELOCK					/**< Platform dependent support for higher level locked read/write access to support writes across process/machines */
-#define SWITCH_FOPEN_NOCLEANUP APR_FOPEN_NOCLEANUP					/**< Do not register a cleanup when the file is opened */
-#define SWITCH_FOPEN_SENDFILE_ENABLED APR_FOPEN_SENDFILE_ENABLED	/**< Advisory flag that this file should support apr_socket_sendfile operation */
-#define SWITCH_FOPEN_LARGEFILE APR_FOPEN_LAREFILE					/**< Platform dependent flag to enable large file support */
-/** @} */
-
-/**
- * Open the specified file.
- * @param newf The opened file descriptor.
- * @param fname The full path to the file (using / on all systems)
- * @param flag Or'ed value of:
- * <PRE>
- *         SWITCH_FOPEN_READ				open for reading
- *         SWITCH_FOPEN_WRITE				open for writing
- *         SWITCH_FOPEN_CREATE				create the file if not there
- *         SWITCH_FOPEN_APPEND				file ptr is set to end prior to all writes
- *         SWITCH_FOPEN_TRUNCATE			set length to zero if file exists
- *         SWITCH_FOPEN_BINARY				not a text file (This flag is ignored on 
- *											UNIX because it has no meaning)
- *         SWITCH_FOPEN_BUFFERED			buffer the data.  Default is non-buffered
- *         SWITCH_FOPEN_EXCL				return error if APR_CREATE and file exists
- *         SWITCH_FOPEN_DELONCLOSE			delete the file after closing.
- *         SWITCH_FOPEN_XTHREAD				Platform dependent tag to open the file
- *											for use across multiple threads
- *         SWITCH_FOPEN_SHARELOCK			Platform dependent support for higher
- *											level locked read/write access to support
- *											writes across process/machines
- *         SWITCH_FOPEN_NOCLEANUP			Do not register a cleanup with the pool 
- *											passed in on the <EM>pool</EM> argument (see below).
- *											The apr_os_file_t handle in apr_file_t will not
- *											be closed when the pool is destroyed.
- *         SWITCH_FOPEN_SENDFILE_ENABLED	Open with appropriate platform semantics
- *											for sendfile operations.  Advisory only,
- *											apr_socket_sendfile does not check this flag.
- * </PRE>
- * @param perm Access permissions for file.
- * @param pool The pool to use.
- * @remark If perm is SWITCH_FPROT_OS_DEFAULT and the file is being created,
- * appropriate default permissions will be used.
- */
-DoxyDefine(apr_status_t switch_file_open(switch_file_t **newf, const char *fname, apr_int32_t flag, switch_fileperms_t perm, switch_pool_t *pool);)
-#define switch_file_open apr_file_open
-#define switch_file_seek apr_file_seek
-
 /**
- * Close the specified file.
- * @param file The file descriptor to close.
+ * Structure for referencing dynamic objects
  */
-DoxyDefine(apr_status_t switch_file_close(switch_file_t *file);)
-#define switch_file_close apr_file_close
+	 typedef struct apr_dso_handle_t switch_dso_handle_t;
 
 /**
- * Establish a lock on the specified, open file. The lock may be advisory
- * or mandatory, at the discretion of the platform. The lock applies to
- * the file as a whole, rather than a specific range. Locks are established
- * on a per-thread/process basis; a second lock by the same thread will not
- * block.
- * @param thefile The file to lock.
- * @param type The type of lock to establish on the file.
+ * Structure for referencing symbols from dynamic objects
  */
-DoxyDefine(apr_status_t apr_file_lock(switch_file_t *thefile, int type);)
-#define switch_file_lock apr_file_lock
+	 typedef void *switch_dso_handle_sym_t;
 
 /**
- * Remove any outstanding locks on the file.
- * @param thefile The file to unlock.
+ * Load a DSO library.
+ * @param res_handle Location to store new handle for the DSO.
+ * @param path Path to the DSO library
+ * @param ctx Pool to use.
+ * @bug We aught to provide an alternative to RTLD_GLOBAL, which
+ * is the only supported method of loading DSOs today.
  */
-DoxyDefine(apr_status_t apr_file_unlock(switch_file_t *thefile);)
-#define switch_file_unlock apr_file_unlock
+SWITCH_DECLARE(switch_status_t) switch_dso_load(switch_dso_handle_t ** res_handle, const char *path, switch_memory_pool_t *ctx);
 
 /**
- * Delete the specified file.
- * @param path The full path to the file (using / on all systems)
- * @param pool The pool to use.
- * @remark If the file is open, it won't be removed until all
- * instances are closed.
+ * Close a DSO library.
+ * @param handle handle to close.
  */
-DoxyDefine(apr_status_t apr_file_remove(const char *path, apr_pool_t *pool);)
-#define switch_file_remove apr_file_remove
+SWITCH_DECLARE(switch_status_t) switch_dso_unload(switch_dso_handle_t * handle);
 
 /**
- * Read data from the specified file.
- * @param thefile The file descriptor to read from.
- * @param buf The buffer to store the data to.
- * @param nbytes On entry, the number of bytes to read; on exit, the number
- * of bytes read.
- *
- * @remark apr_file_read will read up to the specified number of
- * bytes, but never more.  If there isn't enough data to fill that
- * number of bytes, all of the available data is read.  The third
- * argument is modified to reflect the number of bytes read.  If a
- * char was put back into the stream via ungetc, it will be the first
- * character returned.
- *
- * @remark It is not possible for both bytes to be read and an APR_EOF
- * or other error to be returned.  APR_EINTR is never returned.
+ * Load a symbol from a DSO handle.
+ * @param ressym Location to store the loaded symbol
+ * @param handle handle to load the symbol from.
+ * @param symname Name of the symbol to load.
  */
-DoxyDefine(apr_status_t switch_file_read(switch_file_t *thefile, void *buf, switch_size_t *nbytes);)
-#define switch_file_read apr_file_read
+SWITCH_DECLARE(switch_status_t) switch_dso_sym(switch_dso_handle_sym_t * ressym, switch_dso_handle_t * handle, const char *symname);
 
 /**
- * Write data to the specified file.
- * @param thefile The file descriptor to write to.
- * @param buf The buffer which contains the data.
- * @param nbytes On entry, the number of bytes to write; on exit, the number 
- *               of bytes written.
- *
- * @remark apr_file_write will write up to the specified number of
- * bytes, but never more.  If the OS cannot write that many bytes, it
- * will write as many as it can.  The third argument is modified to
- * reflect the * number of bytes written.
- *
- * @remark It is possible for both bytes to be written and an error to
- * be returned.  APR_EINTR is never returned.
+ * Report more information when a DSO function fails.
+ * @param dso The dso handle that has been opened
+ * @param buf Location to store the dso error
+ * @param bufsize The size of the provided buffer
  */
-DoxyDefine(apr_status_t switch_file_write(switch_file_t *thefile, const void *buf, switch_size_t *nbytes);)
-#define switch_file_write apr_file_write
+SWITCH_DECLARE(const char *) switch_dso_error(switch_dso_handle_t * dso, char *buf, size_t bufsize);
 
 /** @} */
 
 /**
- * @defgroup switch_thread_cond Condition Variable Routines
- * @ingroup switch_apr 
+ * @defgroup switch_string String Handling funcions
+ * @ingroup switch_apr
  * @{
  */
 
-/**
- * Note: destroying a condition variable (or likewise, destroying or
- * clearing the pool from which a condition variable was allocated) if
- * any threads are blocked waiting on it gives undefined results.
- */
+SWITCH_DECLARE(int) switch_snprintf(char *buf, switch_size_t len, const char *format, ...);
 
-/** Opaque structure for thread condition variables */
-typedef apr_thread_cond_t switch_thread_cond_t;
+SWITCH_DECLARE(int) switch_vasprintf(char **buf, const char *format, va_list ap);
+
+SWITCH_DECLARE(char *) switch_copy_string(char *dst, const char *src, switch_size_t dst_size);
+
+/** @} */
 
 /**
- * Create and initialize a condition variable that can be used to signal
- * and schedule threads in a single process.
- * @param cond the memory address where the newly created condition variable
- *        will be stored.
- * @param pool the pool from which to allocate the mutex.
+ * @defgroup apr_hash Hash Tables
+ * @ingroup switch_apr
+ * @{
  */
-DoxyDefine(apr_status_t switch_thread_cond_create(switch_thread_cond_t **cond, switch_pool_t *pool);)
-#define switch_thread_cond_create apr_thread_cond_create
 
-typedef apr_os_thread_t switch_thread_id_t;
-
-#define switch_thread_data_set apr_thread_data_set
-#define switch_thread_data_get apr_thread_data_get
-#define switch_thread_self apr_os_thread_current
-#define switch_time_make(sec, usec) ((apr_time_t)(sec) * APR_USEC_PER_SEC \
-                                     + (apr_time_t)(usec))
+/** Abstract type for hash tables. */
+	 typedef struct apr_hash_t switch_hash_t;
 
+/** Abstract type for scanning hash tables. */
+	 typedef struct apr_hash_index_t switch_hash_index_t;
 
 /**
- * Put the active calling thread to sleep until signaled to wake up. Each
- * condition variable must be associated with a mutex, and that mutex must
- * be locked before  calling this function, or the behavior will be
- * undefined. As the calling thread is put to sleep, the given mutex
- * will be simultaneously released; and as this thread wakes up the lock
- * is again simultaneously acquired.
- * @param cond the condition variable on which to block.
- * @param mutex the mutex that must be locked upon entering this function,
- *        is released while the thread is asleep, and is again acquired before
- *        returning from this function.
+ * When passing a key to switch_hashfunc_default, this value can be
+ * passed to indicate a string-valued key, and have the length compute automatically.
+ *
  */
-DoxyDefine(apr_status_t switch_thread_cond_wait(switch_thread_cond_t *cond, switch_thread_mutex_t *mutex);)
-#define switch_thread_cond_wait apr_thread_cond_wait
+#define SWITCH_HASH_KEY_STRING     (-1)
 
 /**
- * Put the active calling thread to sleep until signaled to wake up or
- * the timeout is reached. Each condition variable must be associated
- * with a mutex, and that mutex must be locked before calling this
- * function, or the behavior will be undefined. As the calling thread
- * is put to sleep, the given mutex will be simultaneously released;
- * and as this thread wakes up the lock is again simultaneously acquired.
- * @param cond the condition variable on which to block.
- * @param mutex the mutex that must be locked upon entering this function,
- *        is released while the thread is asleep, and is again acquired before
- *        returning from this function.
- * @param timeout The amount of time in microseconds to wait. This is 
- *        a maximum, not a minimum. If the condition is signaled, we 
- *        will wake up before this time, otherwise the error APR_TIMEUP
- *        is returned.
+ * Start iterating over the entries in a hash table.
+ * @param p The pool to allocate the switch_hash_index_t iterator. If this
+ *          pool is NULL, then an internal, non-thread-safe iterator is used.
+ * @param ht The hash table
+ * @remark  There is no restriction on adding or deleting hash entries during
+ * an iteration (although the results may be unpredictable unless all you do
+ * is delete the current entry) and multiple iterations can be in
+ * progress at the same time.
+
  */
-DoxyDefine(apr_status_t switch_thread_cond_timedwait(switch_thread_cond_t *cond, switch_thread_mutex_t *mutex, switch_interval_time_t timeout);)
-#define switch_thread_cond_timedwait apr_thread_cond_timedwait
+SWITCH_DECLARE(switch_hash_index_t *) switch_hash_first(switch_memory_pool_t *p, switch_hash_t * ht);
 
 /**
- * Signals a single thread, if one exists, that is blocking on the given
- * condition variable. That thread is then scheduled to wake up and acquire
- * the associated mutex. Although it is not required, if predictable scheduling
- * is desired, that mutex must be locked while calling this function.
- * @param cond the condition variable on which to produce the signal.
+ * Continue iterating over the entries in a hash table.
+ * @param hi The iteration state
+ * @return a pointer to the updated iteration state.  NULL if there are no more  
+ *         entries.
  */
-DoxyDefine(apr_status_t switch_thread_cond_signal(switch_thread_cond_t *cond);)
-#define switch_thread_cond_signal apr_thread_cond_signal
+SWITCH_DECLARE(switch_hash_index_t *) switch_hash_next(switch_hash_index_t * ht);
 
 /**
- * Signals all threads blocking on the given condition variable.
- * Each thread that was signaled is then scheduled to wake up and acquire
- * the associated mutex. This will happen in a serialized manner.
- * @param cond the condition variable on which to produce the broadcast.
+ * Get the current entry's details from the iteration state.
+ * @param hi The iteration state
+ * @param key Return pointer for the pointer to the key.
+ * @param klen Return pointer for the key length.
+ * @param val Return pointer for the associated value.
+ * @remark The return pointers should point to a variable that will be set to the
+ *         corresponding data, or they may be NULL if the data isn't interesting.
  */
-DoxyDefine(apr_status_t switch_thread_cond_broadcast(switch_thread_cond_t *cond);)
-#define switch_thread_cond_broadcast apr_thread_cond_broadcast
+SWITCH_DECLARE(void) switch_hash_this(switch_hash_index_t * hi, const void **key, switch_ssize_t *klen, void **val);
 
 /**
- * Destroy the condition variable and free the associated memory.
- * @param cond the condition variable to destroy.
+ * The default hash function.
+ * @param key pointer to the key.
+ * @param klen the key length.
+ * 
  */
-DoxyDefine(apr_status_t switch_thread_cond_destroy(switch_thread_cond_t *cond);)
-#define switch_thread_cond_destroy apr_thread_cond_destroy
+SWITCH_DECLARE(unsigned int) switch_hashfunc_default(const char *key, switch_ssize_t *klen);
 
-/** @} */
+SWITCH_DECLARE(switch_memory_pool_t *) switch_hash_pool_get(switch_hash_t * ht);
 
-/**
- * @defgroup switch_thread_proc Threads and Process Functions
+/** @} */
+ /**
+ * @defgroup switch_time Time Routines
  * @ingroup switch_apr 
  * @{
  */
 
-/** Opaque Thread structure. */
-typedef apr_thread_t switch_thread_t;
+ /** number of microseconds since 00:00:00 january 1, 1970 UTC */
+	 typedef int64_t switch_time_t;
 
-/** Opaque Thread attributes structure. */
-typedef apr_threadattr_t switch_threadattr_t;
+ /** number of microseconds in the interval */
+	 typedef int64_t switch_interval_time_t;
 
 /**
- * The prototype for any APR thread worker functions.
- * typedef void *(SWITCH_THREAD_FUNC *switch_thread_start_t)(switch_thread_t*, void*);
+ * a structure similar to ANSI struct tm with the following differences:
+ *  - tm_usec isn't an ANSI field
+ *  - tm_gmtoff isn't an ANSI field (it's a bsdism)
  */
-#define SWITCH_THREAD_FUNC APR_THREAD_FUNC
-typedef apr_thread_start_t switch_thread_start_t;
+	 typedef struct switch_time_exp_t {
+	/** microseconds past tm_sec */
+		 int32_t tm_usec;
+	/** (0-61) seconds past tm_min */
+		 int32_t tm_sec;
+	/** (0-59) minutes past tm_hour */
+		 int32_t tm_min;
+	/** (0-23) hours past midnight */
+		 int32_t tm_hour;
+	/** (1-31) day of the month */
+		 int32_t tm_mday;
+	/** (0-11) month of the year */
+		 int32_t tm_mon;
+	/** year since 1900 */
+		 int32_t tm_year;
+	/** (0-6) days since sunday */
+		 int32_t tm_wday;
+	/** (0-365) days since jan 1 */
+		 int32_t tm_yday;
+	/** daylight saving time */
+		 int32_t tm_isdst;
+	/** seconds east of UTC */
+		 int32_t tm_gmtoff;
+	 } switch_time_exp_t;
 
-#define switch_threadattr_stacksize_set apr_threadattr_stacksize_set
+SWITCH_DECLARE(switch_time_t) switch_time_make(switch_time_t sec, int32_t usec);
 
 /**
- * Create and initialize a new threadattr variable
- * @param new_attr The newly created threadattr.
- * @param cont The pool to use
+ * @return the current time
  */
-DoxyDefine(apr_status_t switch_threadattr_create(switch_threadattr_t **new_attr, switch_pool_t *cont);)
-#define switch_threadattr_create apr_threadattr_create
+SWITCH_DECLARE(switch_time_t) switch_time_now(void);
 
 /**
- * Set if newly created threads should be created in detached state.
- * @param attr The threadattr to affect 
- * @param on Non-zero if detached threads should be created.
+ * Convert time value from human readable format to a numeric apr_time_t that
+ * always represents GMT
+ * @param result the resulting imploded time
+ * @param input the input exploded time
  */
-DoxyDefine(apr_status_t switch_threadattr_detach_set(switch_threadattr_t *attr, switch_int32_t on);)
-#define switch_threadattr_detach_set apr_threadattr_detach_set
+SWITCH_DECLARE(switch_status_t) switch_time_exp_gmt_get(switch_time_t * result, switch_time_exp_t * input);
 
 /**
- * Create a new thread of execution
- * @param new_thread The newly created thread handle.
- * @param attr The threadattr to use to determine how to create the thread
- * @param func The function to start the new thread in
- * @param data Any data to be passed to the starting function
- * @param cont The pool to use
+ * formats the exploded time according to the format specified
+ * @param s string to write to
+ * @param retsize The length of the returned string
+ * @param max The maximum length of the string
+ * @param format The format for the time string
+ * @param tm The time to convert
  */
-DoxyDefine(apr_status_t switch_thread_create(switch_thread_t **new_thread, switch_threadattr_t *attr, switch_thread_start_t func, void *data, switch_pool_t *cont);)
-#define switch_thread_create apr_thread_create
-
-/** @} */
+SWITCH_DECLARE(switch_status_t) switch_strftime(char *s, switch_size_t *retsize, switch_size_t max, const char *format, switch_time_exp_t * tm);
 
 /**
- * @defgroup switch_network_io Network Routines
- * @ingroup switch_apr 
- * @{
+ * switch_rfc822_date formats dates in the RFC822
+ * format in an efficient manner.  It is a fixed length
+ * format which requires the indicated amount of storage,
+ * including the trailing NUL terminator.
+ * @param date_str String to write to.
+ * @param t the time to convert 
  */
+SWITCH_DECLARE(switch_status_t) switch_rfc822_date(char *date_str, switch_time_t t);
 
-/** descriptor refers to a socket */
-#define SWITCH_POLL_SOCKET APR_POLL_SOCKET
-
-/** @def SWITCH_UNSPEC
- * Let the system decide which address family to use
+/**
+ * convert a time to its human readable components in GMT timezone
+ * @param result the exploded time
+ * @param input the time to explode
  */
-#define SWITCH_UNSPEC APR_UNSPEC 
-
-/** A structure to represent sockets */
-typedef apr_socket_t switch_socket_t;
-
-/** Freeswitch's socket address type, used to ensure protocol independence */
-typedef apr_sockaddr_t switch_sockaddr_t;
-
-typedef apr_port_t switch_port_t;
-/* function definitions */
+SWITCH_DECLARE(switch_status_t) switch_time_exp_gmt(switch_time_exp_t * result, switch_time_t input);
 
 /**
- * Create a socket.
- * @param new_sock The new socket that has been set up.
- * @param family The address family of the socket (e.g., APR_INET).
- * @param type The type of the socket (e.g., SOCK_STREAM).
- * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP).
- * @param cont The pool to use
+ * Convert time value from human readable format to a numeric apr_time_t 
+ * e.g. elapsed usec since epoch
+ * @param result the resulting imploded time
+ * @param input the input exploded time
  */
-DoxyDefine(apr_status_t switch_socket_create(switch_socket_t **new_sock, int family, int type, int protocol, switch_pool_t *cont);)
-#define switch_socket_create apr_socket_create
+SWITCH_DECLARE(switch_status_t) switch_time_exp_get(switch_time_t * result, switch_time_exp_t * input);
 
 /**
- * Shutdown either reading, writing, or both sides of a socket.
- * @param thesocket The socket to close 
- * @param how How to shutdown the socket.  One of:
- * <PRE>
- *            APR_SHUTDOWN_READ         no longer allow read requests
- *            APR_SHUTDOWN_WRITE        no longer allow write requests
- *            APR_SHUTDOWN_READWRITE    no longer allow read or write requests 
- * </PRE>
- * @see apr_shutdown_how_e
- * @remark This does not actually close the socket descriptor, it just
- *      controls which calls are still valid on the socket.
+ * convert a time to its human readable components in local timezone
+ * @param result the exploded time
+ * @param input the time to explode
  */
-DoxyDefine(apr_status_t switch_socket_shutdown(switch_socket_t *thesocket, switch_shutdown_how_e how);)
-#define switch_socket_shutdown apr_socket_shutdown
+SWITCH_DECLARE(switch_status_t) switch_time_exp_lt(switch_time_exp_t * result, switch_time_t input);
 
 /**
- * Close a socket.
- * @param thesocket The socket to close 
+ * Sleep for the specified number of micro-seconds.
+ * @param t desired amount of time to sleep.
+ * @warning May sleep for longer than the specified time. 
  */
-DoxyDefine(apr_status_t switch_socket_close(switch_socket_t *thesocket);)
-#define switch_socket_close apr_socket_close
+SWITCH_DECLARE(void) switch_sleep(switch_interval_time_t t);
 
-/**
- * Bind the socket to its associated port
- * @param sock The socket to bind 
- * @param sa The socket address to bind to
- * @remark This may be where we will find out if there is any other process
- *      using the selected port.
- */
-DoxyDefine(apr_status_t switch_socket_bind(switch_socket_t *sock, switch_sockaddr_t *sa);)
-#define switch_socket_bind apr_socket_bind
+/** @} */
 
 /**
- * Listen to a bound socket for connections.
- * @param sock The socket to listen on 
- * @param backlog The number of outstanding connections allowed in the sockets
- *                listen queue.  If this value is less than zero, the listen
- *                queue size is set to zero.  
+ * @defgroup switch_thread_mutex Thread Mutex Routines
+ * @ingroup switch_apr
+ * @{
  */
-DoxyDefine(apr_status_t switch_socket_listen(switch_socket_t *sock, switch_int32_t backlog);)
-#define switch_socket_listen apr_socket_listen
 
-/**
- * Accept a new connection request
- * @param new_sock A copy of the socket that is connected to the socket that
- *                 made the connection request.  This is the socket which should
- *                 be used for all future communication.
- * @param sock The socket we are listening on.
- * @param connection_pool The pool for the new socket.
- */
-DoxyDefine(apr_status_t switch_socket_accept(switch_socket_t **new_sock, switch_socket_t *sock, switch_pool_t *connection_pool);)
-#define switch_socket_accept apr_socket_accept
+/** Opaque thread-local mutex structure */
+	 typedef struct apr_thread_mutex_t switch_mutex_t;
 
-/**
- * Issue a connection request to a socket either on the same machine 
- * or a different one.
- * @param sock The socket we wish to use for our side of the connection 
- * @param sa The address of the machine we wish to connect to.
- */
-DoxyDefine(apr_status_t switch_socket_connect(switch_socket_t *sock, switch_sockaddr_t *sa);)
-#define switch_socket_connect apr_socket_connect
+/** Lock Flags */
+#define SWITCH_MUTEX_DEFAULT	0x0	/**< platform-optimal lock behavior */
+#define SWITCH_MUTEX_NESTED		0x1	/**< enable nested (recursive) locks */
+#define	SWITCH_MUTEX_UNNESTED	0x2	/**< disable nested locks */
 
 /**
- * Create apr_sockaddr_t from hostname, address family, and port.
- * @param sa The new apr_sockaddr_t.
- * @param hostname The hostname or numeric address string to resolve/parse, or
- *               NULL to build an address that corresponds to 0.0.0.0 or ::
- * @param family The address family to use, or APR_UNSPEC if the system should 
- *               decide.
- * @param port The port number.
- * @param flags Special processing flags:
+ * Create and initialize a mutex that can be used to synchronize threads.
+ * @param lock the memory address where the newly created mutex will be
+ *        stored.
+ * @param flags Or'ed value of:
  * <PRE>
- *       APR_IPV4_ADDR_OK          first query for IPv4 addresses; only look
- *                                 for IPv6 addresses if the first query failed;
- *                                 only valid if family is APR_UNSPEC and hostname
- *                                 isn't NULL; mutually exclusive with
- *                                 APR_IPV6_ADDR_OK
- *       APR_IPV6_ADDR_OK          first query for IPv6 addresses; only look
- *                                 for IPv4 addresses if the first query failed;
- *                                 only valid if family is APR_UNSPEC and hostname
- *                                 isn't NULL and APR_HAVE_IPV6; mutually exclusive
- *                                 with APR_IPV4_ADDR_OK
+ *           SWITCH_THREAD_MUTEX_DEFAULT   platform-optimal lock behavior.
+ *           SWITCH_THREAD_MUTEX_NESTED    enable nested (recursive) locks.
+ *           SWITCH_THREAD_MUTEX_UNNESTED  disable nested locks (non-recursive).
  * </PRE>
- * @param p The pool for the apr_sockaddr_t and associated storage.
- */
-DoxyDefine(apr_status_t switch_sockaddr_info_get(switch_sockaddr_t **sa,
-									  const char *hostname,
-									  switch_int32_t family,
-									  switch_port_t port,
-									  switch_int32_t flags,
-									  switch_pool_t *p);)
-#define switch_sockaddr_info_get apr_sockaddr_info_get
-
-/**
- * Look up the host name from an apr_sockaddr_t.
- * @param hostname The hostname.
- * @param sa The apr_sockaddr_t.
- * @param flags Special processing flags.
- */
-DoxyDefine(apr_status_t switch_getnameinfo(char **hostname,
-									switch_sockaddr_t *sa,
-									switch_int32_t flags);)
-#define switch_getnameinfo apr_getnameinfo
-
-/**
- * Parse hostname/IP address with scope id and port.
- *
- * Any of the following strings are accepted:
- *   8080                  (just the port number)
- *   www.apache.org        (just the hostname)
- *   www.apache.org:8080   (hostname and port number)
- *   [fe80::1]:80          (IPv6 numeric address string only)
- *   [fe80::1%eth0]        (IPv6 numeric address string and scope id)
- *
- * Invalid strings:
- *                         (empty string)
- *   [abc]                 (not valid IPv6 numeric address string)
- *   abc:65536             (invalid port number)
+ * @param pool the pool from which to allocate the mutex.
+ * @warning Be cautious in using SWITCH_THREAD_MUTEX_DEFAULT.  While this is the
+ * most optimial mutex based on a given platform's performance charateristics,
+ * it will behave as either a nested or an unnested lock.
  *
- * @param addr The new buffer containing just the hostname.  On output, *addr 
- *             will be NULL if no hostname/IP address was specfied.
- * @param scope_id The new buffer containing just the scope id.  On output, 
- *                 *scope_id will be NULL if no scope id was specified.
- * @param port The port number.  On output, *port will be 0 if no port was 
- *             specified.
- *             ### FIXME: 0 is a legal port (per RFC 1700). this should
- *             ### return something besides zero if the port is missing.
- * @param str The input string to be parsed.
- * @param p The pool from which *addr and *scope_id are allocated.
- * @remark If scope id shouldn't be allowed, check for scope_id != NULL in 
- *         addition to checking the return code.  If addr/hostname should be 
- *         required, check for addr == NULL in addition to checking the 
- *         return code.
- */
-DoxyDefine(apr_status_t switch_parse_addr_port(char **addr,
-									char **scope_id,
-									switch_port_t *port,
-									const char *str,
-									switch_pool_t *p);)
-#define switch_parse_addr_port apr_parse_addr_port
-
-/**
- * Get name of the current machine
- * @param buf A buffer to store the hostname in.
- * @param len The maximum length of the hostname that can be stored in the
- *            buffer provided.  The suggested length is APRMAXHOSTLEN + 1.
- * @param cont The pool to use.
- * @remark If the buffer was not large enough, an error will be returned.
- */
-DoxyDefine(apr_status_t switch_gethostname(char *buf, int len, switch_pool_t *cont);)
-#define switch_gethostname apr_gethostname
-
-/**
- * Return the data associated with the current socket
- * @param data The user data associated with the socket.
- * @param key The key to associate with the user data.
- * @param sock The currently open socket.
- */
-DoxyDefine(apr_status_t switch_socket_data_get(void **data, const char *key,
-										switch_socket_t *sock);)
-#define switch_socket_data_get apr_socket_data_get
-
-/**
- * Set the data associated with the current socket.
- * @param sock The currently open socket.
- * @param data The user data to associate with the socket.
- * @param key The key to associate with the data.
- * @param cleanup The cleanup to call when the socket is destroyed.
- */
-DoxyDefine(apr_status_t switch_socket_data_set(switch_socket_t *sock, 
-									void *data,
-									const char *key,
-									switch_status_t (*cleanup)(void*));)
-#define switch_socket_data_set apr_socket_data_set
+*/
+SWITCH_DECLARE(switch_status_t) switch_mutex_init(switch_mutex_t ** lock, unsigned int flags, switch_memory_pool_t *pool);
 
-/**
- * Send data over a network.
- * @param sock The socket to send the data over.
- * @param buf The buffer which contains the data to be sent. 
- * @param len On entry, the number of bytes to send; on exit, the number
- *            of bytes sent.
- * @remark
- * <PRE>
- * This functions acts like a blocking write by default.  To change 
- * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
- * socket option.
- *
- * It is possible for both bytes to be sent and an error to be returned.
- *
- * APR_EINTR is never returned.
- * </PRE>
- */
-DoxyDefine(apr_status_t switch_socket_send(switch_socket_t *sock,
-								const char *buf,
-								apr_size_t *len);)
-#define switch_socket_send apr_socket_send
 
 /**
- * Send multiple packets of data over a network.
- * @param sock The socket to send the data over.
- * @param vec The array of iovec structs containing the data to send 
- * @param nvec The number of iovec structs in the array
- * @param len Receives the number of bytes actually written
- * @remark
- * <PRE>
- * This functions acts like a blocking write by default.  To change 
- * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
- * socket option.
- * The number of bytes actually sent is stored in argument 3.
- *
- * It is possible for both bytes to be sent and an error to be returned.
- *
- * APR_EINTR is never returned.
- * </PRE>
+ * Destroy the mutex and free the memory associated with the lock.
+ * @param lock the mutex to destroy.
  */
-DoxyDefine(apr_status_t switch_socket_sendv(switch_socket_t *sock, 
-                                           const struct iovec *vec,
-                                           apr_int32_t nvec, apr_size_t *len);)
-#define switch_socket_sendv apr_socket_sendv
+SWITCH_DECLARE(switch_status_t) switch_mutex_destroy(switch_mutex_t * lock);
 
 /**
- * @param sock The socket to send from
- * @param where The apr_sockaddr_t describing where to send the data
- * @param flags The flags to use
- * @param buf  The data to send
- * @param len  The length of the data to send
+ * Acquire the lock for the given mutex. If the mutex is already locked,
+ * the current thread will be put to sleep until the lock becomes available.
+ * @param lock the mutex on which to acquire the lock.
  */
-DoxyDefine(apr_status_t switch_socket_sendto(switcj_socket_t *sock, 
-								  apr_sockaddr_t *where,
-								  apr_int32_t flags,
-								  const char *buf, 
-								  apr_size_t *len);)
-#define switch_socket_sendto apr_socket_sendto
-
-/**
- * @param from The apr_sockaddr_t to fill in the recipient info
- * @param sock The socket to use
- * @param flags The flags to use
- * @param buf  The buffer to use
- * @param len  The length of the available buffer
- *
-
-DoxyDefine(apr_status_t switch_socket_recvfrom(switch_sockaddr_t *from, 
-									switch_socket_t *sock,
-									apr_int32_t flags, 
-									char *buf, 
-									apr_size_t *len);)
-#define switch_socket_recvfrom apr_socket_recvfrom
-*/
-
-/**
- * Send a file from an open file descriptor to a socket, along with 
- * optional headers and trailers
- * @param sock The socket to which we're writing
- * @param file The open file from which to read
- * @param hdtr A structure containing the headers and trailers to send
- * @param offset Offset into the file where we should begin writing
- * @param len (input)  - Number of bytes to send from the file 
- *            (output) - Number of bytes actually sent, 
- *                       including headers, file, and trailers
- * @param flags APR flags that are mapped to OS specific flags
- * @remark This functions acts like a blocking write by default.  To change 
- *         this behavior, use apr_socket_timeout_set() or the
- *         APR_SO_NONBLOCK socket option.
- * The number of bytes actually sent is stored in the len parameter.
- * The offset parameter is passed by reference for no reason; its
- * value will never be modified by the apr_socket_sendfile() function.
- */
-DoxyDefine(apr_status_t switch_socket_sendfile(apr_socket_t *sock, 
-                                              switch_file_t *file,
-                                              apr_hdtr_t *hdtr,
-                                              apr_off_t *offset,
-                                              apr_size_t *len,
-                                              apr_int32_t flags);)
-#define switch_socket_sendfile apr_socket_sendfile
+SWITCH_DECLARE(switch_status_t) switch_mutex_lock(switch_mutex_t * lock);
 
 /**
- * Read data from a network.
- * @param sock The socket to read the data from.
- * @param buf The buffer to store the data in. 
- * @param len On entry, the number of bytes to receive; on exit, the number
- *            of bytes received.
- * @remark
- * <PRE>
- * This functions acts like a blocking read by default.  To change 
- * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
- * socket option.
- * The number of bytes actually received is stored in argument 3.
- *
- * It is possible for both bytes to be received and an APR_EOF or
- * other error to be returned.
- *
- * APR_EINTR is never returned.
- * </PRE>
+ * Release the lock for the given mutex.
+ * @param lock the mutex from which to release the lock.
  */
-DoxyDefine(apr_status_t switch_socket_recv(switch_socket_t *sock, 
-								char *buf, 
-								apr_size_t *len);)
-#define switch_socket_recv apr_socket_recv
+SWITCH_DECLARE(switch_status_t) switch_mutex_unlock(switch_mutex_t * lock);
 
 /**
- * Setup socket options for the specified socket
- * @param sock The socket to set up.
- * @param opt The option we would like to configure.  One of:
- * <PRE>
- *            APR_SO_DEBUG      --  turn on debugging information 
- *            APR_SO_KEEPALIVE  --  keep connections active
- *            APR_SO_LINGER     --  lingers on close if data is present
- *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
- *                                  When this option is enabled, use
- *                                  the APR_STATUS_IS_EAGAIN() macro to
- *                                  see if a send or receive function
- *                                  could not transfer data without
- *                                  blocking.
- *            APR_SO_REUSEADDR  --  The rules used in validating addresses
- *                                  supplied to bind should allow reuse
- *                                  of local addresses.
- *            APR_SO_SNDBUF     --  Set the SendBufferSize
- *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
- * </PRE>
- * @param on Value for the option.
+ * Attempt to acquire the lock for the given mutex. If the mutex has already
+ * been acquired, the call returns immediately with APR_EBUSY. Note: it
+ * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine
+ * if the return value was APR_EBUSY, for portability reasons.
+ * @param lock the mutex on which to attempt the lock acquiring.
  */
-DoxyDefine(apr_status_t switch_socket_opt_set(switch_socket_t *sock,
-								   apr_int32_t opt, 
-								   apr_int32_t on);)
-#define switch_socket_opt_set apr_socket_opt_set
+SWITCH_DECLARE(switch_status_t) switch_mutex_trylock(switch_mutex_t * lock);
 
-/**
- * Setup socket timeout for the specified socket
- * @param sock The socket to set up.
- * @param t Value for the timeout.
- * <PRE>
- *   t > 0  -- read and write calls return APR_TIMEUP if specified time
- *             elapsess with no data read or written
- *   t == 0 -- read and write calls never block
- *   t < 0  -- read and write calls block
- * </PRE>
- */
-DoxyDefine(apr_status_t switch_socket_timeout_set(switch_socket_t *sock,
-									   apr_interval_time_t t);)
-#define switch_socket_timeout_set apr_socket_timeout_set
+/** @} */
 
 /**
- * Query socket options for the specified socket
- * @param sock The socket to query
- * @param opt The option we would like to query.  One of:
- * <PRE>
- *            APR_SO_DEBUG      --  turn on debugging information 
- *            APR_SO_KEEPALIVE  --  keep connections active
- *            APR_SO_LINGER     --  lingers on close if data is present
- *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
- *            APR_SO_REUSEADDR  --  The rules used in validating addresses
- *                                  supplied to bind should allow reuse
- *                                  of local addresses.
- *            APR_SO_SNDBUF     --  Set the SendBufferSize
- *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
- *            APR_SO_DISCONNECTED -- Query the disconnected state of the socket.
- *                                  (Currently only used on Windows)
- * </PRE>
- * @param on Socket option returned on the call.
+ * @defgroup switch_thread_rwlock Thread Read/Write lock Routines
+ * @ingroup switch_apr
+ * @{
  */
-DoxyDefine(apr_status_t switch_socket_opt_get(switch_socket_t *sock, 
-									apr_int32_t opt, apr_int32_t *on);)
-#define switch_socket_opt_get apr_socket_opt_get
 
-/**
- * Query socket timeout for the specified socket
- * @param sock The socket to query
- * @param t Socket timeout returned from the query.
- */
-DoxyDefine(apr_status_t switch_socket_timeout_get(switch_socket_t *sock, 
-                                                 apr_interval_time_t *t);)
-#define switch_socket_timeout_get apr_socket_timeout_get
+/** Opaque structure used for the rwlock */
+	 typedef struct apr_thread_rwlock_t switch_thread_rwlock_t;
+
+SWITCH_DECLARE(switch_status_t) switch_thread_rwlock_create(switch_thread_rwlock_t ** rwlock, switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_status_t) switch_thread_rwlock_destroy(switch_thread_rwlock_t * rwlock);
+SWITCH_DECLARE(switch_memory_pool_t *) switch_thread_rwlock_pool_get(switch_thread_rwlock_t * rwlock);
+SWITCH_DECLARE(switch_status_t) switch_thread_rwlock_rdlock(switch_thread_rwlock_t * rwlock);
+SWITCH_DECLARE(switch_status_t) switch_thread_rwlock_tryrdlock(switch_thread_rwlock_t * rwlock);
+SWITCH_DECLARE(switch_status_t) switch_thread_rwlock_wrlock(switch_thread_rwlock_t * rwlock);
+SWITCH_DECLARE(switch_status_t) switch_thread_rwlock_trywrlock(switch_thread_rwlock_t * rwlock);
+SWITCH_DECLARE(switch_status_t) switch_thread_rwlock_unlock(switch_thread_rwlock_t * rwlock);
+
+/** @} */
 
 /**
- * Query the specified socket if at the OOB/Urgent data mark
- * @param sock The socket to query
- * @param atmark Is set to true if socket is at the OOB/urgent mark,
- *               otherwise is set to false.
+ * @defgroup switch_thread_cond Condition Variable Routines
+ * @ingroup switch_apr 
+ * @{
  */
-DoxyDefine(apr_status_t switch_socket_atmark(switch_socket_t *sock, 
-								  int *atmark);)
-#define switch_socket_atmark apr_socket_atmark
 
 /**
- * Return an apr_sockaddr_t from an apr_socket_t
- * @param sa The returned apr_sockaddr_t.
- * @param which Which interface do we want the apr_sockaddr_t for?
- * @param sock The socket to use
+ * Note: destroying a condition variable (or likewise, destroying or
+ * clearing the pool from which a condition variable was allocated) if
+ * any threads are blocked waiting on it gives undefined results.
  */
-DoxyDefine(apr_status_t switch_socket_addr_get(switch_sockaddr_t **sa,
-									apr_interface_e which,
-									switch_socket_t *sock);)
-#define switch_socket_addr_get apr_socket_addr_get
-
-/**
- * Return the IP address (in numeric address string format) in
- * an APR socket address.  APR will allocate storage for the IP address 
- * string from the pool of the apr_sockaddr_t.
- * @param addr The IP address.
- * @param sockaddr The socket address to reference.
- */
-DoxyDefine(apr_status_t switch_sockaddr_ip_get(char **addr, 
-									switch_sockaddr_t *sockaddr);)
-#define switch_sockaddr_ip_get apr_sockaddr_ip_get
-
-/**
- * See if the IP addresses in two APR socket addresses are
- * equivalent.  Appropriate logic is present for comparing
- * IPv4-mapped IPv6 addresses with IPv4 addresses.
- *
- * @param addr1 One of the APR socket addresses.
- * @param addr2 The other APR socket address.
- * @remark The return value will be non-zero if the addresses
- * are equivalent.
- */
-DoxyDefine(int switch_sockaddr_equal(const switch_sockaddr_t *addr1, 
-						  const switch_sockaddr_t *addr2);)
-#define switch_sockaddr_equal apr_sockaddr_equal
 
-/**
-* Return the type of the socket.
-* @param sock The socket to query.
-* @param type The returned type (e.g., SOCK_STREAM).
-*/
-DoxyDefine(apr_status_t switch_socket_type_get(switch_socket_t *sock, 
-									int *type);)
-#define switch_socket_type_get apr_socket_type_get
+/** Opaque structure for thread condition variables */
+	 typedef struct apr_thread_cond_t switch_thread_cond_t;
 
 /**
- * Given an switch_sockaddr_t and a service name, set the port for the service
- * @param sockaddr The switch_sockaddr_t that will have its port set
- * @param servname The name of the service you wish to use
+ * Create and initialize a condition variable that can be used to signal
+ * and schedule threads in a single process.
+ * @param cond the memory address where the newly created condition variable
+ *        will be stored.
+ * @param pool the pool from which to allocate the mutex.
  */
-DoxyDefine(apr_status_t switch_getservbyname(switch_sockaddr_t *sockaddr, 
-								  const char *servname);)
-#define switch_getservbyname apr_getservbyname
+SWITCH_DECLARE(switch_status_t) switch_thread_cond_create(switch_thread_cond_t ** cond, switch_memory_pool_t *pool);
 
 /**
- * Build an ip-subnet representation from an IP address and optional netmask or
- * number-of-bits.
- * @param ipsub The new ip-subnet representation
- * @param ipstr The input IP address string
- * @param mask_or_numbits The input netmask or number-of-bits string, or NULL
- * @param p The pool to allocate from
+ * Put the active calling thread to sleep until signaled to wake up. Each
+ * condition variable must be associated with a mutex, and that mutex must
+ * be locked before  calling this function, or the behavior will be
+ * undefined. As the calling thread is put to sleep, the given mutex
+ * will be simultaneously released; and as this thread wakes up the lock
+ * is again simultaneously acquired.
+ * @param cond the condition variable on which to block.
+ * @param mutex the mutex that must be locked upon entering this function,
+ *        is released while the thread is asleep, and is again acquired before
+ *        returning from this function.
  */
-DoxyDefine(apr_status_t switch_ipsubnet_create(apr_ipsubnet_t **ipsub, 
-									const char *ipstr, 
-									const char *mask_or_numbits, 
-									switch_pool_t *p);)
-#define switch_ipsubnet_create apr_ipsubnet_create
+SWITCH_DECLARE(switch_status_t) switch_thread_cond_wait(switch_thread_cond_t * cond, switch_mutex_t * mutex);
 
 /**
- * Test the IP address in an apr_sockaddr_t against a pre-built ip-subnet
- * representation.
- * @param ipsub The ip-subnet representation
- * @param sa The socket address to test
- * @return non-zero if the socket address is within the subnet, 0 otherwise
+ * Put the active calling thread to sleep until signaled to wake up or
+ * the timeout is reached. Each condition variable must be associated
+ * with a mutex, and that mutex must be locked before calling this
+ * function, or the behavior will be undefined. As the calling thread
+ * is put to sleep, the given mutex will be simultaneously released;
+ * and as this thread wakes up the lock is again simultaneously acquired.
+ * @param cond the condition variable on which to block.
+ * @param mutex the mutex that must be locked upon entering this function,
+ *        is released while the thread is asleep, and is again acquired before
+ *        returning from this function.
+ * @param timeout The amount of time in microseconds to wait. This is 
+ *        a maximum, not a minimum. If the condition is signaled, we 
+ *        will wake up before this time, otherwise the error APR_TIMEUP
+ *        is returned.
  */
-DoxyDefine(int switch_ipsubnet_test(apr_ipsubnet_t *ipsub, switch_sockaddr_t *sa);)
-#define switch_ipsubnet_test apr_ipsubnet_test
+SWITCH_DECLARE(switch_status_t) switch_thread_cond_timedwait(switch_thread_cond_t * cond, switch_mutex_t * mutex, switch_interval_time_t timeout);
 
 /**
- * Return the protocol of the socket.
- * @param sock The socket to query.
- * @param protocol The returned protocol (e.g., APR_PROTO_TCP).
+ * Signals a single thread, if one exists, that is blocking on the given
+ * condition variable. That thread is then scheduled to wake up and acquire
+ * the associated mutex. Although it is not required, if predictable scheduling
+ * is desired, that mutex must be locked while calling this function.
+ * @param cond the condition variable on which to produce the signal.
  */
-DoxyDefine(apr_status_t switch_socket_protocol_get(switch_socket_t *sock,
-										int *protocol);)
-#define switch_socket_protocol_get apr_socket_protocol_get
+SWITCH_DECLARE(switch_status_t) switch_thread_cond_signal(switch_thread_cond_t * cond);
 
 /**
- * Join a Multicast Group
- * @param sock The socket to join a multicast group
- * @param join The address of the multicast group to join
- * @param iface Address of the interface to use.  If NULL is passed, the 
- *              default multicast interface will be used. (OS Dependent)
- * @param source Source Address to accept transmissions from (non-NULL 
- *               implies Source-Specific Multicast)
+ * Signals all threads blocking on the given condition variable.
+ * Each thread that was signaled is then scheduled to wake up and acquire
+ * the associated mutex. This will happen in a serialized manner.
+ * @param cond the condition variable on which to produce the broadcast.
  */
-DoxyDefine(apr_status_t switch_mcast_join(switch_socket_t *sock,
-							   switch_sockaddr_t *join,
-							   switch_sockaddr_t *iface,
-							   switch_sockaddr_t *source);)
-#define switch_mcast_join apr_mcast_join
+SWITCH_DECLARE(switch_status_t) switch_thread_cond_broadcast(switch_thread_cond_t * cond);
 
 /**
- * Leave a Multicast Group.  All arguments must be the same as
- * switch_mcast_join.
- * @param sock The socket to leave a multicast group
- * @param addr The address of the multicast group to leave
- * @param iface Address of the interface to use.  If NULL is passed, the 
- *              default multicast interface will be used. (OS Dependent)
- * @param source Source Address to accept transmissions from (non-NULL 
- *               implies Source-Specific Multicast)
+ * Destroy the condition variable and free the associated memory.
+ * @param cond the condition variable to destroy.
  */
-DoxyDefine(apr_status_t switch_mcast_leave(switch_socket_t *sock,
-								switch_sockaddr_t *addr,
-								switch_sockaddr_t *iface,
-								switch_sockaddr_t *source);)
-#define switch_mcast_leave apr_mcast_leave
+SWITCH_DECLARE(switch_status_t) switch_thread_cond_destroy(switch_thread_cond_t * cond);
 
-/**
- * Set the Multicast Time to Live (ttl) for a multicast transmission.
- * @param sock The socket to set the multicast ttl
- * @param ttl Time to live to Assign. 0-255, default=1
- * @remark If the TTL is 0, packets will only be seen by sockets on 
- * the local machine, and only when multicast loopback is enabled.
- */
-DoxyDefine(apr_status_t switch_mcast_hops(switch_socket_t *sock,
-							   apr_byte_t ttl);)
-#define switch_mcast_hops apr_mcast_hops
+/** @} */
 
 /**
- * Toggle IP Multicast Loopback
- * @param sock The socket to set multicast loopback
- * @param opt 0=disable, 1=enable
+ * @defgroup switch_UUID UUID Handling
+ * @ingroup switch_apr
+ * @{
  */
-DoxyDefine(apr_status_t switch_mcast_loopback(switch_socket_t *sock,
-								   apr_byte_t opt);)
-#define switch_mcast_loopback apr_mcast_loopback
 
-/**
- * Set the Interface to be used for outgoing Multicast Transmissions.
- * @param sock The socket to set the multicast interface on
- * @param iface Address of the interface to use for Multicast
- */
-DoxyDefine(apr_status_t switch_mcast_interface(switch_socket_t *sock,
-									switch_sockaddr_t *iface);)
-#define switch_mcast_interface apr_mcast_interface
+/** we represent a UUID as a block of 16 bytes. */
 
-/** @} */
+	 typedef struct {
+		 unsigned char data[16];
+							/**< the actual UUID */
+	 } switch_uuid_t;
+
+/** UUIDs are formatted as: 00112233-4455-6677-8899-AABBCCDDEEFF */
+#define SWITCH_UUID_FORMATTED_LENGTH 36
 
 /**
- * @defgroup switch_memory_pool Memory Pool Functions
- * @ingroup switch_apr 
- * @{
+ * Format a UUID into a string, following the standard format
+ * @param buffer The buffer to place the formatted UUID string into. It must
+ *               be at least APR_UUID_FORMATTED_LENGTH + 1 bytes long to hold
+ *               the formatted UUID and a null terminator
+ * @param uuid The UUID to format
  */
-/** The fundamental pool type */
-typedef apr_pool_t switch_memory_pool_t;
+SWITCH_DECLARE(void) switch_uuid_format(char *buffer, const switch_uuid_t * uuid);
 
+/**
+ * Generate and return a (new) UUID
+ * @param uuid The resulting UUID
+ */
+SWITCH_DECLARE(void) switch_uuid_get(switch_uuid_t * uuid);
 
 /**
- * Clear all memory in the pool and run all the cleanups. This also destroys all
- * subpools.
- * @param p The pool to clear
- * @remark This does not actually free the memory, it just allows the pool
- *         to re-use this memory for the next allocation.
- * @see apr_pool_destroy()
+ * Parse a standard-format string into a UUID
+ * @param uuid The resulting UUID
+ * @param uuid_str The formatted UUID
  */
-DoxyDefine(void switch_pool_clear(switch_memory_pool_t *p);)
-#define switch_pool_clear apr_pool_clear
+SWITCH_DECLARE(switch_status_t) switch_uuid_parse(switch_uuid_t * uuid, const char *uuid_str);
+
 /** @} */
 
 /**
- * @defgroup apr_poll Poll Routines
+ * @defgroup switch_FIFO Thread Safe FIFO bounded queue
  * @ingroup switch_apr
  * @{
  */
-/** Poll descriptor set. */
-typedef apr_pollfd_t switch_pollfd_t;
 
-/** Opaque structure used for pollset API */
-typedef apr_pollset_t switch_pollset_t;
+/** Opaque structure used for queue API */
+	 typedef struct apr_queue_t switch_queue_t;
+
+/** 
+ * create a FIFO queue
+ * @param queue The new queue
+ * @param queue_capacity maximum size of the queue
+ * @param a pool to allocate queue from
+ */
+SWITCH_DECLARE(switch_status_t) switch_queue_create(switch_queue_t ** queue, unsigned int queue_capacity, switch_memory_pool_t *pool);
 
 /**
- * Poll options
+ * pop/get an object from the queue, blocking if the queue is already empty
+ *
+ * @param queue the queue
+ * @param data the data
+ * @returns APR_EINTR the blocking was interrupted (try again)
+ * @returns APR_EOF if the queue has been terminated
+ * @returns APR_SUCCESS on a successfull pop
  */
-#define SWITCH_POLLIN APR_POLLIN			/**< Can read without blocking */
-#define SWITCH_POLLPRI APR_POLLPRI			/**< Priority data available */
-#define SWITCH_POLLOUT APR_POLLOUT			/**< Can write without blocking */
-#define SWITCH_POLLERR APR_POLLERR			/**< Pending error */
-#define SWITCH_POLLHUP APR_POLLHUP			/**< Hangup occurred */
-#define SWITCH_POLLNVAL APR_POLLNVAL		/**< Descriptior invalid */
+SWITCH_DECLARE(switch_status_t) switch_queue_pop(switch_queue_t * queue, void **data);
 
 /**
- * Setup a pollset object
- * @param pollset  The pointer in which to return the newly created object 
- * @param size The maximum number of descriptors that this pollset can hold
- * @param p The pool from which to allocate the pollset
- * @param flags Optional flags to modify the operation of the pollset.
+ * push/add a object to the queue, blocking if the queue is already full
  *
- * @remark If flags equals APR_POLLSET_THREADSAFE, then a pollset is
- * created on which it is safe to make concurrent calls to
- * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() from
- * separate threads.  This feature is only supported on some
- * platforms; the apr_pollset_create() call will fail with
- * APR_ENOTIMPL on platforms where it is not supported.
+ * @param queue the queue
+ * @param data the data
+ * @returns APR_EINTR the blocking was interrupted (try again)
+ * @returns APR_EOF the queue has been terminated
+ * @returns APR_SUCCESS on a successfull push
  */
-DoxyDefine(apr_status_t switch_pollset_create(switch_pollset_t **pollset,
-                                             apr_uint32_t size,
-                                             switch_memory_pool_t *p,
-                                             apr_uint32_t flags);)
-#define switch_pollset_create apr_pollset_create
+SWITCH_DECLARE(switch_status_t) switch_queue_push(switch_queue_t * queue, void *data);
 
 /**
- * Add a socket or file descriptor to a pollset
- * @param pollset The pollset to which to add the descriptor
- * @param descriptor The descriptor to add
- * @remark If you set client_data in the descriptor, that value
- *         will be returned in the client_data field whenever this
- *         descriptor is signalled in apr_pollset_poll().
- * @remark If the pollset has been created with APR_POLLSET_THREADSAFE
- *         and thread T1 is blocked in a call to apr_pollset_poll() for
- *         this same pollset that is being modified via apr_pollset_add()
- *         in thread T2, the currently executing apr_pollset_poll() call in
- *         T1 will either: (1) automatically include the newly added descriptor
- *         in the set of descriptors it is watching or (2) return immediately
- *         with APR_EINTR.  Option (1) is recommended, but option (2) is
- *         allowed for implementations where option (1) is impossible
- *         or impractical.
+ * returns the size of the queue.
+ *
+ * @warning this is not threadsafe, and is intended for reporting/monitoring
+ * of the queue.
+ * @param queue the queue
+ * @returns the size of the queue
  */
-DoxyDefine(apr_status_t switch_pollset_add(switch_pollset_t *pollset,
-                                          const switch_pollfd_t *descriptor);)
-#define switch_pollset_add apr_pollset_add
+SWITCH_DECLARE(unsigned int) switch_queue_size(switch_queue_t * queue);
 
 /**
- * Poll the sockets in the poll structure
- * @param aprset The poll structure we will be using. 
- * @param numsock The number of sockets we are polling
- * @param nsds The number of sockets signalled.
- * @param timeout The amount of time in microseconds to wait.  This is 
- *                a maximum, not a minimum.  If a socket is signalled, we 
- *                will wake up before this time.  A negative number means 
- *                wait until a socket is signalled.
- * @remark The number of sockets signalled is returned in the third argument. 
- *         This is a blocking call, and it will not return until either a 
- *         socket has been signalled, or the timeout has expired. 
+ * pop/get an object to the queue, returning immediatly if the queue is empty
+ *
+ * @param queue the queue
+ * @param data the data
+ * @returns APR_EINTR the blocking operation was interrupted (try again)
+ * @returns APR_EAGAIN the queue is empty
+ * @returns APR_EOF the queue has been terminated
+ * @returns APR_SUCCESS on a successfull push
  */
-DoxyDefine(apr_status_t switch_poll(switch_pollfd_t *aprset, apr_int32_t numsock,
-                                   apr_int32_t *nsds, 
-                                   apr_interval_time_t timeout);)
-#define switch_poll apr_poll
- 
- /** @} */
+SWITCH_DECLARE(switch_status_t) switch_queue_trypop(switch_queue_t * queue, void **data);
 
- /**
- * @defgroup switch_time Time Routines
+/**
+ * push/add a object to the queue, returning immediatly if the queue is full
+ *
+ * @param queue the queue
+ * @param data the data
+ * @returns APR_EINTR the blocking operation was interrupted (try again)
+ * @returns APR_EAGAIN the queue is full
+ * @returns APR_EOF the queue has been terminated
+ * @returns APR_SUCCESS on a successfull push
+ */
+SWITCH_DECLARE(switch_status_t) switch_queue_trypush(switch_queue_t * queue, void *data);
+
+/** @} */
+
+/**
+ * @defgroup switch_file_io File I/O Handling Functions
  * @ingroup switch_apr 
  * @{
  */
 
- /** number of microseconds since 00:00:00 january 1, 1970 UTC */
-typedef apr_time_t switch_time_t;
+/** Structure for referencing files. */
+	 typedef struct apr_file_t switch_file_t;
 
- /** number of microseconds in the interval */
-typedef apr_interval_time_t switch_interval_time_t;
+	 typedef int32_t switch_fileperms_t;
+	 typedef int switch_seek_where_t;
 
 /**
- * a structure similar to ANSI struct tm with the following differences:
- *  - tm_usec isn't an ANSI field
- *  - tm_gmtoff isn't an ANSI field (it's a bsdism)
+ * @defgroup switch_file_permissions File Permissions flags 
+ * @ingroup switch_file_io
+ * @{
  */
-typedef apr_time_exp_t switch_time_exp_t;
 
-/**
- * @return the current time
- */
-DoxyDefine(switch_time_t switch_time_now(void);)
-#define switch_time_now apr_time_now
+#define SWITCH_FPROT_USETID 0x8000			/**< Set user id */
+#define SWITCH_FPROT_UREAD 0x0400			/**< Read by user */
+#define SWITCH_FPROT_UWRITE 0x0200			/**< Write by user */
+#define SWITCH_FPROT_UEXECUTE 0x0100		/**< Execute by user */
+
+#define SWITCH_FPROT_GSETID 0x4000			/**< Set group id */
+#define SWITCH_FPROT_GREAD 0x0040			/**< Read by group */
+#define SWITCH_FPROT_GWRITE 0x0020			/**< Write by group */
+#define SWITCH_FPROT_GEXECUTE 0x0010		/**< Execute by group */
+
+#define SWITCH_FPROT_WSTICKY 0x2000
+#define SWITCH_FPROT_WREAD 0x0004			/**< Read by others */
+#define SWITCH_FPROT_WWRITE 0x0002			/**< Write by others */
+#define SWITCH_FPROT_WEXECUTE 0x0001		/**< Execute by others */
 
-/**
- * Convert time value from human readable format to a numeric apr_time_t that
- * always represents GMT
- * @param result the resulting imploded time
- * @param input the input exploded time
- */
-DoxyDefine(switch_status_t switch_time_exp_gmt_get(switch_time_t *result, switch_time_exp_t *input);)
-#define switch_time_exp_gmt_get apr_time_exp_gmt_get
+#define SWITCH_FPROT_OS_DEFAULT 0x0FFF		/**< use OS's default permissions */
+
+/* additional permission flags for apr_file_copy  and apr_file_append */
+#define SWITCH_FPROT_FILE_SOURCE_PERMS 0x1000	/**< Copy source file's permissions */
+/** @} */
 
 /**
- * formats the exploded time according to the format specified
- * @param s string to write to
- * @param retsize The length of the returned string
- * @param max The maximum length of the string
- * @param format The format for the time string
- * @param tm The time to convert
+ * @defgroup switch_file_open_flags File Open Flags/Routines
+ * @ingroup switch_file_io
+ * @{
  */
-DoxyDefine(apr_status_t switch_strftime(char *s, apr_size_t *retsize, 
-                                       apr_size_t max, const char *format, 
-                                       switch_time_exp_t *tm);)
-#define switch_strftime apr_strftime
+#define SWITCH_FOPEN_READ				0x00001		/**< Open the file for reading */
+#define SWITCH_FOPEN_WRITE				0x00002		/**< Open the file for writing */
+#define SWITCH_FOPEN_CREATE				0x00004		/**< Create the file if not there */
+#define SWITCH_FOPEN_APPEND				0x00008		/**< Append to the end of the file */
+#define SWITCH_FOPEN_TRUNCATE			0x00010		/**< Open the file and truncate to 0 length */
+#define SWITCH_FOPEN_BINARY				0x00020		/**< Open the file in binary mode */
+#define SWITCH_FOPEN_EXCL				0x00040		/**< Open should fail if APR_CREATE and file exists. */
+#define SWITCH_FOPEN_BUFFERED			0x00080		/**< Open the file for buffered I/O */
+#define SWITCH_FOPEN_DELONCLOSE			0x00100		/**< Delete the file after close */
+#define SWITCH_FOPEN_XTHREAD			0x00200		/**< Platform dependent tag to open the file for use across multiple threads */
+#define SWITCH_FOPEN_SHARELOCK			0x00400		/**< Platform dependent support for higher level locked read/write access to support writes across process/machines */
+#define SWITCH_FOPEN_NOCLEANUP			0x00800		/**< Do not register a cleanup when the file is opened */
+#define SWITCH_FOPEN_SENDFILE_ENABLED	0x01000		/**< Advisory flag that this file should support apr_socket_sendfile operation */
+#define SWITCH_FOPEN_LARGEFILE			0x04000		/**< Platform dependent flag to enable large file support */
+/** @} */
 
 /**
- * switch_rfc822_date formats dates in the RFC822
- * format in an efficient manner.  It is a fixed length
- * format which requires the indicated amount of storage,
- * including the trailing NUL terminator.
- * @param date_str String to write to.
- * @param t the time to convert 
+ * Open the specified file.
+ * @param newf The opened file descriptor.
+ * @param fname The full path to the file (using / on all systems)
+ * @param flag Or'ed value of:
+ * <PRE>
+ *         SWITCH_FOPEN_READ				open for reading
+ *         SWITCH_FOPEN_WRITE				open for writing
+ *         SWITCH_FOPEN_CREATE				create the file if not there
+ *         SWITCH_FOPEN_APPEND				file ptr is set to end prior to all writes
+ *         SWITCH_FOPEN_TRUNCATE			set length to zero if file exists
+ *         SWITCH_FOPEN_BINARY				not a text file (This flag is ignored on 
+ *											UNIX because it has no meaning)
+ *         SWITCH_FOPEN_BUFFERED			buffer the data.  Default is non-buffered
+ *         SWITCH_FOPEN_EXCL				return error if APR_CREATE and file exists
+ *         SWITCH_FOPEN_DELONCLOSE			delete the file after closing.
+ *         SWITCH_FOPEN_XTHREAD				Platform dependent tag to open the file
+ *											for use across multiple threads
+ *         SWITCH_FOPEN_SHARELOCK			Platform dependent support for higher
+ *											level locked read/write access to support
+ *											writes across process/machines
+ *         SWITCH_FOPEN_NOCLEANUP			Do not register a cleanup with the pool 
+ *											passed in on the <EM>pool</EM> argument (see below).
+ *											The apr_os_file_t handle in apr_file_t will not
+ *											be closed when the pool is destroyed.
+ *         SWITCH_FOPEN_SENDFILE_ENABLED	Open with appropriate platform semantics
+ *											for sendfile operations.  Advisory only,
+ *											apr_socket_sendfile does not check this flag.
+ * </PRE>
+ * @param perm Access permissions for file.
+ * @param pool The pool to use.
+ * @remark If perm is SWITCH_FPROT_OS_DEFAULT and the file is being created,
+ * appropriate default permissions will be used.
  */
-DoxyDefine(apr_status_t switch_rfc822_date(char *date_str, switch_time_t t);)
-#define switch_rfc822_date apr_rfc822_date
+SWITCH_DECLARE(switch_status_t) switch_file_open(switch_file_t ** newf, const char *fname, int32_t flag, switch_fileperms_t perm,
+												 switch_memory_pool_t *pool);
+
+
+SWITCH_DECLARE(switch_status_t) switch_file_seek(switch_file_t * thefile, switch_seek_where_t where, int64_t *offset);
 
 /**
- * convert a time to its human readable components in GMT timezone
- * @param result the exploded time
- * @param input the time to explode
+ * Close the specified file.
+ * @param file The file descriptor to close.
  */
-DoxyDefine(apr_status_t switch_time_exp_gmt(switch_time_exp_t *result, 
-                                           switch_time_t input);)
-#define switch_time_exp_gmt apr_time_exp_gmt
+SWITCH_DECLARE(switch_status_t) switch_file_close(switch_file_t * thefile);
 
 /**
- * Convert time value from human readable format to a numeric apr_time_t 
- * e.g. elapsed usec since epoch
- * @param result the resulting imploded time
- * @param input the input exploded time
+ * Delete the specified file.
+ * @param path The full path to the file (using / on all systems)
+ * @param pool The pool to use.
+ * @remark If the file is open, it won't be removed until all
+ * instances are closed.
  */
-DoxyDefine(apr_status_t switch_time_exp_get(switch_time_t *result, 
-											switch_time_exp_t *input);)
-#define switch_time_exp_get apr_time_exp_get
+SWITCH_DECLARE(switch_status_t) switch_file_remove(const char *path, switch_memory_pool_t *pool);
 
 /**
- * convert a time to its human readable components in local timezone
- * @param result the exploded time
- * @param input the time to explode
+ * Read data from the specified file.
+ * @param thefile The file descriptor to read from.
+ * @param buf The buffer to store the data to.
+ * @param nbytes On entry, the number of bytes to read; on exit, the number
+ * of bytes read.
+ *
+ * @remark apr_file_read will read up to the specified number of
+ * bytes, but never more.  If there isn't enough data to fill that
+ * number of bytes, all of the available data is read.  The third
+ * argument is modified to reflect the number of bytes read.  If a
+ * char was put back into the stream via ungetc, it will be the first
+ * character returned.
+ *
+ * @remark It is not possible for both bytes to be read and an APR_EOF
+ * or other error to be returned.  APR_EINTR is never returned.
  */
-DoxyDefine(apr_status_t switch_time_exp_lt(switch_time_exp_t *result, 
-											switch_time_t input);)
-#define switch_time_exp_lt apr_time_exp_lt
+SWITCH_DECLARE(switch_status_t) switch_file_read(switch_file_t * thefile, void *buf, switch_size_t *nbytes);
 
 /**
- * Sleep for the specified number of micro-seconds.
- * @param t desired amount of time to sleep.
- * @warning May sleep for longer than the specified time. 
+ * Write data to the specified file.
+ * @param thefile The file descriptor to write to.
+ * @param buf The buffer which contains the data.
+ * @param nbytes On entry, the number of bytes to write; on exit, the number 
+ *               of bytes written.
+ *
+ * @remark apr_file_write will write up to the specified number of
+ * bytes, but never more.  If the OS cannot write that many bytes, it
+ * will write as many as it can.  The third argument is modified to
+ * reflect the * number of bytes written.
+ *
+ * @remark It is possible for both bytes to be written and an error to
+ * be returned.  APR_EINTR is never returned.
  */
-DoxyDefine(void switch_sleep(apr_interval_time_t t);)
-#define switch_sleep apr_sleep
+SWITCH_DECLARE(switch_status_t) switch_file_write(switch_file_t * thefile, const void *buf, switch_size_t *nbytes);
+
+SWITCH_DECLARE(switch_status_t) switch_file_exists(const char *filename, switch_memory_pool_t *pool);
 
 /** @} */
 
 /**
- * @defgroup apr_hash Hash Tables
- * @ingroup switch_apr
+ * @defgroup switch_thread_proc Threads and Process Functions
+ * @ingroup switch_apr 
  * @{
  */
 
-/** Abstract type for hash tables. */
-typedef apr_hash_t switch_hash_t;
+/** Opaque Thread structure. */
+	 typedef struct apr_thread_t switch_thread_t;
 
-/** Abstract type for scanning hash tables. */
-typedef apr_hash_index_t switch_hash_index_t;
+/** Opaque Thread attributes structure. */
+	 typedef struct apr_threadattr_t switch_threadattr_t;
 
 /**
- * Start iterating over the entries in a hash table.
- * @param p The pool to allocate the switch_hash_index_t iterator. If this
- *          pool is NULL, then an internal, non-thread-safe iterator is used.
- * @param ht The hash table
- * @remark  There is no restriction on adding or deleting hash entries during
- * an iteration (although the results may be unpredictable unless all you do
- * is delete the current entry) and multiple iterations can be in
- * progress at the same time.
+ * The prototype for any APR thread worker functions.
+ * typedef void *(SWITCH_THREAD_FUNC *switch_thread_start_t)(switch_thread_t*, void*);
+ */
+	 typedef void *(SWITCH_THREAD_FUNC * switch_thread_start_t) (switch_thread_t *, void *);
+
+//APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, switch_size_t stacksize)
+SWITCH_DECLARE(switch_status_t) switch_threadattr_stacksize_set(switch_threadattr_t * attr, switch_size_t stacksize);
 
+/**
+ * Create and initialize a new threadattr variable
+ * @param new_attr The newly created threadattr.
+ * @param cont The pool to use
  */
-DoxyDefine(switch_hash_index_t * switch_hash_first(switch_memory_pool_t *p, switch_hash_t *ht);)
-#define switch_hash_first apr_hash_first
+SWITCH_DECLARE(switch_status_t) switch_threadattr_create(switch_threadattr_t ** new_attr, switch_memory_pool_t *pool);
 
 /**
- * Continue iterating over the entries in a hash table.
- * @param hi The iteration state
- * @return a pointer to the updated iteration state.  NULL if there are no more  
- *         entries.
+ * Set if newly created threads should be created in detached state.
+ * @param attr The threadattr to affect 
+ * @param on Non-zero if detached threads should be created.
  */
-DoxyDefine(switch_hash_index_t * switch_hash_next(switch_hash_index_t *hi);)
-#define switch_hash_next apr_hash_next
+SWITCH_DECLARE(switch_status_t) switch_threadattr_detach_set(switch_threadattr_t * attr, int32_t on);
 
 /**
- * Get the current entry's details from the iteration state.
- * @param hi The iteration state
- * @param key Return pointer for the pointer to the key.
- * @param klen Return pointer for the key length.
- * @param val Return pointer for the associated value.
- * @remark The return pointers should point to a variable that will be set to the
- *         corresponding data, or they may be NULL if the data isn't interesting.
+ * Create a new thread of execution
+ * @param new_thread The newly created thread handle.
+ * @param attr The threadattr to use to determine how to create the thread
+ * @param func The function to start the new thread in
+ * @param data Any data to be passed to the starting function
+ * @param cont The pool to use
  */
-DoxyDefine(void switch_hash_this(switch_hash_index_t *hi, const void **key, 
-                                apr_ssize_t *klen, void **val);)
-#define switch_hash_this apr_hash_this
+SWITCH_DECLARE(switch_status_t) switch_thread_create(switch_thread_t ** new_thread, switch_threadattr_t * attr,
+													 switch_thread_start_t func, void *data, switch_memory_pool_t *cont);
 
 /** @} */
 
 /**
- * @defgroup switch_StrMatch String matching routines
- * @ingroup switch_apr
+ * @defgroup switch_network_io Network Routines
+ * @ingroup switch_apr 
  * @{
  */
 
-/** Precompiled search pattern */
-typedef apr_strmatch_pattern switch_strmatch_pattern;
+#define SWITCH_SO_LINGER 1
+#define SWITCH_SO_KEEPALIVE 2
+#define SWITCH_SO_DEBUG 4
+#define SWITCH_SO_NONBLOCK 8
+#define SWITCH_SO_REUSEADDR 16
+#define SWITCH_SO_SNDBUF 64
+#define SWITCH_SO_RCVBUF 128
+#define SWITCH_SO_DISCONNECTED 256
 
-/**
- * Precompile a pattern for matching using the Boyer-Moore-Horspool algorithm
- * @param p The pool from which to allocate the pattern
- * @param s The pattern string
- * @param case_sensitive Whether the matching should be case-sensitive
- * @return a pointer to the compiled pattern, or NULL if compilation fails
- */
-DoxyDefine(const switch_strmatch_pattern * switch_strmatch_precompile(switch_memory_pool_t *p, const char *s, int case_sensitive);)
-#define switch_strmatch_precompile apr_strmatch_precompile
-
-/**
- * Search for a precompiled pattern within a string
- * @param pattern The pattern
- * @param s The string in which to search for the pattern
- * @param slen The length of s (excluding null terminator)
- * @return A pointer to the first instance of the pattern in s, or
- *         NULL if not found
- */
-DoxyDefine(const char * switch_strmatch(const switch_strmatch_pattern *pattern,
-                                       const char *s, apr_size_t slen);)
-#define switch_strmatch apr_strmatch
-/** @} */
+ /**
+ * @def SWITCH_INET
+ * Not all platforms have these defined, so we'll define them here
+ * The default values come from FreeBSD 4.1.1
+ */
+#define SWITCH_INET     AF_INET
+
+/** @def SWITCH_UNSPEC
+ * Let the system decide which address family to use
+ */
+#ifdef AF_UNSPEC
+#define SWITCH_UNSPEC   AF_UNSPEC
+#else
+#define SWITCH_UNSPEC   0
+#endif
+
+/** A structure to represent sockets */
+	 typedef struct apr_socket_t switch_socket_t;
+
+/** Freeswitch's socket address type, used to ensure protocol independence */
+	 typedef struct apr_sockaddr_t switch_sockaddr_t;
+
+	 typedef enum {
+		 SWITCH_SHUTDOWN_READ,	   /**< no longer allow read request */
+		 SWITCH_SHUTDOWN_WRITE,	   /**< no longer allow write requests */
+		 SWITCH_SHUTDOWN_READWRITE /**< no longer allow read or write requests */
+	 } switch_shutdown_how_e;
 
 /**
- * @defgroup switch_UUID UUID Handling
- * @ingroup switch_apr
+ * @defgroup IP_Proto IP Protocol Definitions for use when creating sockets
  * @{
  */
+#define SWITCH_PROTO_TCP       6   /**< TCP  */
+#define SWITCH_PROTO_UDP      17   /**< UDP  */
+#define SWITCH_PROTO_SCTP    132   /**< SCTP */
+/** @} */
 
-/** we represent a UUID as a block of 16 bytes. */
+/* function definitions */
 
-typedef apr_uuid_t switch_uuid_t;
+/**
+ * Create a socket.
+ * @param new_sock The new socket that has been set up.
+ * @param family The address family of the socket (e.g., SWITCH_INET).
+ * @param type The type of the socket (e.g., SOCK_STREAM).
+ * @param protocol The protocol of the socket (e.g., SWITCH_PROTO_TCP).
+ * @param pool The pool to use
+ */
+SWITCH_DECLARE(switch_status_t) switch_socket_create(switch_socket_t ** new_sock, int family, int type, int protocol, switch_memory_pool_t *pool);
 
-/** UUIDs are formatted as: 00112233-4455-6677-8899-AABBCCDDEEFF */
+/**
+ * Shutdown either reading, writing, or both sides of a socket.
+ * @param sock The socket to close 
+ * @param how How to shutdown the socket.  One of:
+ * <PRE>
+ *            SWITCH_SHUTDOWN_READ         no longer allow read requests
+ *            SWITCH_SHUTDOWN_WRITE        no longer allow write requests
+ *            SWITCH_SHUTDOWN_READWRITE    no longer allow read or write requests 
+ * </PRE>
+ * @see switch_shutdown_how_e
+ * @remark This does not actually close the socket descriptor, it just
+ *      controls which calls are still valid on the socket.
+ */
+SWITCH_DECLARE(switch_status_t) switch_socket_shutdown(switch_socket_t * sock, switch_shutdown_how_e how);
 
 /**
- * Format a UUID into a string, following the standard format
- * @param buffer The buffer to place the formatted UUID string into. It must
- *               be at least APR_UUID_FORMATTED_LENGTH + 1 bytes long to hold
- *               the formatted UUID and a null terminator
- * @param uuid The UUID to format
- */ 
-DoxyDefine(void switch_uuid_format(char *buffer, const switch_uuid_t *uuid);)
-#define switch_uuid_format apr_uuid_format
+ * Close a socket.
+ * @param sock The socket to close 
+ */
+SWITCH_DECLARE(switch_status_t) switch_socket_close(switch_socket_t * sock);
 
 /**
- * Generate and return a (new) UUID
- * @param uuid The resulting UUID
- */ 
-DoxyDefine(void switch_uuid_get(switch_uuid_t *uuid);)
-#define switch_uuid_get apr_uuid_get
+ * Bind the socket to its associated port
+ * @param sock The socket to bind 
+ * @param sa The socket address to bind to
+ * @remark This may be where we will find out if there is any other process
+ *      using the selected port.
+ */
+SWITCH_DECLARE(switch_status_t) switch_socket_bind(switch_socket_t * sock, switch_sockaddr_t * sa);
+
+/**
+ * Listen to a bound socket for connections.
+ * @param sock The socket to listen on 
+ * @param backlog The number of outstanding connections allowed in the sockets
+ *                listen queue.  If this value is less than zero, the listen
+ *                queue size is set to zero.  
+ */
+SWITCH_DECLARE(switch_status_t) switch_socket_listen(switch_socket_t * sock, int32_t backlog);
 
 /**
- * Parse a standard-format string into a UUID
- * @param uuid The resulting UUID
- * @param uuid_str The formatted UUID
- */ 
-DoxyDefine(apr_status_t switch_uuid_parse(switch_uuid_t *uuid, const char *uuid_str);)
-#define switch_uuid_parse apr_uuid_parse
-
-/** @} */
+ * Accept a new connection request
+ * @param new_sock A copy of the socket that is connected to the socket that
+ *                 made the connection request.  This is the socket which should
+ *                 be used for all future communication.
+ * @param sock The socket we are listening on.
+ * @param connection_pool The pool for the new socket.
+ */
+SWITCH_DECLARE(switch_status_t) switch_socket_accept(switch_socket_t ** new_sock, switch_socket_t * sock, switch_memory_pool_t *pool);
 
 /**
- * @defgroup switch_FIFO Thread Safe FIFO bounded queue
- * @ingroup switch_apr
- * @{
+ * Issue a connection request to a socket either on the same machine 
+ * or a different one.
+ * @param sock The socket we wish to use for our side of the connection 
+ * @param sa The address of the machine we wish to connect to.
  */
+SWITCH_DECLARE(switch_status_t) switch_socket_connect(switch_socket_t * sock, switch_sockaddr_t * sa);
 
-/** Opaque structure used for queue API */
-typedef apr_queue_t switch_queue_t;
+SWITCH_DECLARE(uint16_t) switch_sockaddr_get_port(switch_sockaddr_t * sa);
+SWITCH_DECLARE(char *) switch_get_addr(char *buf, switch_size_t len, switch_sockaddr_t * in);
+SWITCH_DECLARE(int32_t) switch_sockaddr_get_family(switch_sockaddr_t * sa);
+SWITCH_DECLARE(switch_status_t) switch_sockaddr_ip_get(char **addr, switch_sockaddr_t * sa);
 
-/** 
- * create a FIFO queue
- * @param queue The new queue
- * @param queue_capacity maximum size of the queue
- * @param a pool to allocate queue from
- */
-DoxyDefine(apr_status_t switch_queue_create(switch_queue_t **queue, 
-                                           unsigned int queue_capacity, 
-                                           switch_memory_pool_t *a);)
-#define switch_queue_create apr_queue_create
 
 /**
- * interrupt all the threads blocking on this queue.
- *
- * @param queue the queue
+ * Create apr_sockaddr_t from hostname, address family, and port.
+ * @param sa The new apr_sockaddr_t.
+ * @param hostname The hostname or numeric address string to resolve/parse, or
+ *               NULL to build an address that corresponds to 0.0.0.0 or ::
+ * @param family The address family to use, or SWITCH_UNSPEC if the system should 
+ *               decide.
+ * @param port The port number.
+ * @param flags Special processing flags:
+ * <PRE>
+ *       APR_IPV4_ADDR_OK          first query for IPv4 addresses; only look
+ *                                 for IPv6 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL; mutually exclusive with
+ *                                 APR_IPV6_ADDR_OK
+ *       APR_IPV6_ADDR_OK          first query for IPv6 addresses; only look
+ *                                 for IPv4 addresses if the first query failed;
+ *                                 only valid if family is APR_UNSPEC and hostname
+ *                                 isn't NULL and APR_HAVE_IPV6; mutually exclusive
+ *                                 with APR_IPV4_ADDR_OK
+ * </PRE>
+ * @param p The pool for the apr_sockaddr_t and associated storage.
  */
-DoxyDefine(apr_status_t switch_queue_interrupt_all(switch_queue_t *queue);)
-#define switch_queue_interrupt_all apr_queue_interrupt_all
+SWITCH_DECLARE(switch_status_t) switch_sockaddr_info_get(switch_sockaddr_t ** sa, const char *hostname,
+														 int32_t family, switch_port_t port, int32_t flags, switch_memory_pool_t *pool);
 
 /**
- * pop/get an object from the queue, blocking if the queue is already empty
+ * Send data over a network.
+ * @param sock The socket to send the data over.
+ * @param buf The buffer which contains the data to be sent. 
+ * @param len On entry, the number of bytes to send; on exit, the number
+ *            of bytes sent.
+ * @remark
+ * <PRE>
+ * This functions acts like a blocking write by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
  *
- * @param queue the queue
- * @param data the data
- * @returns APR_EINTR the blocking was interrupted (try again)
- * @returns APR_EOF if the queue has been terminated
- * @returns APR_SUCCESS on a successfull pop
+ * It is possible for both bytes to be sent and an error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * </PRE>
  */
-DoxyDefine(apr_status_t switch_queue_pop(switch_queue_t *queue, void **data);)
-#define switch_queue_pop apr_queue_pop
+SWITCH_DECLARE(switch_status_t) switch_socket_send(switch_socket_t * sock, const char *buf, switch_size_t *len);
 
 /**
- * push/add a object to the queue, blocking if the queue is already full
- *
- * @param queue the queue
- * @param data the data
- * @returns APR_EINTR the blocking was interrupted (try again)
- * @returns APR_EOF the queue has been terminated
- * @returns APR_SUCCESS on a successfull push
+ * @param sock The socket to send from
+ * @param where The apr_sockaddr_t describing where to send the data
+ * @param flags The flags to use
+ * @param buf  The data to send
+ * @param len  The length of the data to send
  */
-DoxyDefine(apr_status_t switch_queue_push(switch_queue_t *queue, void *data);)
-#define switch_queue_push apr_queue_push
+SWITCH_DECLARE(switch_status_t) switch_socket_sendto(switch_socket_t * sock, switch_sockaddr_t * where, int32_t flags, const char *buf,
+													 switch_size_t *len);
 
 /**
- * returns the size of the queue.
+ * @param from The apr_sockaddr_t to fill in the recipient info
+ * @param sock The socket to use
+ * @param flags The flags to use
+ * @param buf  The buffer to use
+ * @param len  The length of the available buffer
  *
- * @warning this is not threadsafe, and is intended for reporting/monitoring
- * of the queue.
- * @param queue the queue
- * @returns the size of the queue
  */
-DoxyDefine(unsigned int switch_queue_size(switch_queue_t *queue);)
-#define switch_queue_size apr_queue_size
+SWITCH_DECLARE(switch_status_t) switch_socket_recvfrom(switch_sockaddr_t * from, switch_socket_t * sock, int32_t flags, char *buf, size_t *len);
+
 
 /**
- * terminate all queue, sendinging a interupt to all the
- * blocking threads
+ * Read data from a network.
+ * @param sock The socket to read the data from.
+ * @param buf The buffer to store the data in. 
+ * @param len On entry, the number of bytes to receive; on exit, the number
+ *            of bytes received.
+ * @remark
+ * <PRE>
+ * This functions acts like a blocking read by default.  To change 
+ * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK
+ * socket option.
+ * The number of bytes actually received is stored in argument 3.
  *
- * @param queue the queue
+ * It is possible for both bytes to be received and an APR_EOF or
+ * other error to be returned.
+ *
+ * APR_EINTR is never returned.
+ * </PRE>
  */
-DoxyDefine(apr_status_t switch_queue_term(switch_queue_t *queue);)
-#define switch_queue_term apr_queue_term
+SWITCH_DECLARE(switch_status_t) switch_socket_recv(switch_socket_t * sock, char *buf, switch_size_t *len);
 
 /**
- * pop/get an object to the queue, returning immediatly if the queue is empty
- *
- * @param queue the queue
- * @param data the data
- * @returns APR_EINTR the blocking operation was interrupted (try again)
- * @returns APR_EAGAIN the queue is empty
- * @returns APR_EOF the queue has been terminated
- * @returns APR_SUCCESS on a successfull push
+ * Setup socket options for the specified socket
+ * @param sock The socket to set up.
+ * @param opt The option we would like to configure.  One of:
+ * <PRE>
+ *            APR_SO_DEBUG      --  turn on debugging information 
+ *            APR_SO_KEEPALIVE  --  keep connections active
+ *            APR_SO_LINGER     --  lingers on close if data is present
+ *            APR_SO_NONBLOCK   --  Turns blocking on/off for socket
+ *                                  When this option is enabled, use
+ *                                  the APR_STATUS_IS_EAGAIN() macro to
+ *                                  see if a send or receive function
+ *                                  could not transfer data without
+ *                                  blocking.
+ *            APR_SO_REUSEADDR  --  The rules used in validating addresses
+ *                                  supplied to bind should allow reuse
+ *                                  of local addresses.
+ *            APR_SO_SNDBUF     --  Set the SendBufferSize
+ *            APR_SO_RCVBUF     --  Set the ReceiveBufferSize
+ * </PRE>
+ * @param on Value for the option.
  */
-DoxyDefine(apr_status_t switch_queue_trypop(switch_queue_t *queue, void **data);)
-#define switch_queue_trypop apr_queue_trypop
+SWITCH_DECLARE(switch_status_t) switch_socket_opt_set(switch_socket_t * sock, int32_t opt, int32_t on);
 
 /**
- * push/add a object to the queue, returning immediatly if the queue is full
- *
- * @param queue the queue
- * @param data the data
- * @returns APR_EINTR the blocking operation was interrupted (try again)
- * @returns APR_EAGAIN the queue is full
- * @returns APR_EOF the queue has been terminated
- * @returns APR_SUCCESS on a successfull push
+ * Setup socket timeout for the specified socket
+ * @param sock The socket to set up.
+ * @param t Value for the timeout.
+ * <PRE>
+ *   t > 0  -- read and write calls return APR_TIMEUP if specified time
+ *             elapsess with no data read or written
+ *   t == 0 -- read and write calls never block
+ *   t < 0  -- read and write calls block
+ * </PRE>
  */
-DoxyDefine(apr_status_t switch_queue_trypush(switch_queue_t *queue, void *data);)
-#define switch_queue_trypush apr_queue_trypush
+SWITCH_DECLARE(switch_status_t) switch_socket_timeout_set(switch_socket_t * sock, switch_interval_time_t t);
 
-/** @} */
+/**
+ * Join a Multicast Group
+ * @param sock The socket to join a multicast group
+ * @param join The address of the multicast group to join
+ * @param iface Address of the interface to use.  If NULL is passed, the 
+ *              default multicast interface will be used. (OS Dependent)
+ * @param source Source Address to accept transmissions from (non-NULL 
+ *               implies Source-Specific Multicast)
+ */
+SWITCH_DECLARE(switch_status_t) switch_mcast_join(switch_socket_t * sock, switch_sockaddr_t * join, switch_sockaddr_t * iface, switch_sockaddr_t * source);
 
 
-typedef apr_thread_rwlock_t switch_thread_rwlock_t;
 
-#define switch_thread_rwlock_create apr_thread_rwlock_create
-#define switch_thread_rwlock_destroy apr_thread_rwlock_destroy
-#define switch_thread_rwlock_pool_get apr_thread_rwlock_pool_get
-#define switch_thread_rwlock_rdlock apr_thread_rwlock_rdlock
-#define switch_thread_rwlock_tryrdlock apr_thread_rwlock_tryrdlock
-#define switch_thread_rwlock_trywrlock apr_thread_rwlock_trywrlock
-#define switch_thread_rwlock_unlock apr_thread_rwlock_unlock
-#define switch_thread_rwlock_wrlock apr_thread_rwlock_wrlock
+/** @} */
 
 /**
- * @defgroup switch_thread_mutex Thread Mutex Routines
+ * @defgroup apr_poll Poll Routines
  * @ingroup switch_apr
  * @{
  */
+/** Poll descriptor set. */
+	 typedef struct apr_pollfd_t switch_pollfd_t;
 
-/** Opaque thread-local mutex structure */
-typedef apr_thread_mutex_t switch_mutex_t;
-
-/** Lock Flags */
-
-#define SWITCH_MUTEX_DEFAULT APR_THREAD_MUTEX_DEFAULT	/**< platform-optimal lock behavior */
-#define SWITCH_MUTEX_NESTED APR_THREAD_MUTEX_NESTED	/**< enable nested (recursive) locks */
-#define	SWITCH_MUTEX_UNNESTED APR_THREAD_MUTEX_UNNESTED	/**< disable nested locks */
-
+/** Opaque structure used for pollset API */
+	 typedef struct apr_pollset_t switch_pollset_t;
 
 /**
- * Create and initialize a mutex that can be used to synchronize threads.
- * @param lock the memory address where the newly created mutex will be
- *        stored.
- * @param flags Or'ed value of:
- * <PRE>
- *           SWITCH_THREAD_MUTEX_DEFAULT   platform-optimal lock behavior.
- *           SWITCH_THREAD_MUTEX_NESTED    enable nested (recursive) locks.
- *           SWITCH_THREAD_MUTEX_UNNESTED  disable nested locks (non-recursive).
- * </PRE>
- * @param pool the pool from which to allocate the mutex.
- * @warning Be cautious in using SWITCH_THREAD_MUTEX_DEFAULT.  While this is the
- * most optimial mutex based on a given platform's performance charateristics,
- * it will behave as either a nested or an unnested lock.
- *
-SWITCH_DECLARE(switch_status_t) switch_mutex_init(switch_mutex_t **lock,
-												switch_lock_flag flags,
-												switch_memory_pool_t *pool);
-*/
-#define switch_mutex_init apr_thread_mutex_create
-/**
- * Destroy the mutex and free the memory associated with the lock.
- * @param lock the mutex to destroy.
+ * Poll options
  */
-//SWITCH_DECLARE(switch_status_t) switch_mutex_destroy(switch_mutex_t *lock);
-#define switch_mutex_destroy apr_thread_mutex_destroy
+#define SWITCH_POLLIN 0x001			/**< Can read without blocking */
+#define SWITCH_POLLPRI 0x002			/**< Priority data available */
+#define SWITCH_POLLOUT 0x004			/**< Can write without blocking */
+#define SWITCH_POLLERR 0x010			/**< Pending error */
+#define SWITCH_POLLHUP 0x020			/**< Hangup occurred */
+#define SWITCH_POLLNVAL 0x040		/**< Descriptior invalid */
 
 /**
- * Acquire the lock for the given mutex. If the mutex is already locked,
- * the current thread will be put to sleep until the lock becomes available.
- * @param lock the mutex on which to acquire the lock.
+ * Setup a pollset object
+ * @param pollset  The pointer in which to return the newly created object 
+ * @param size The maximum number of descriptors that this pollset can hold
+ * @param p The pool from which to allocate the pollset
+ * @param flags Optional flags to modify the operation of the pollset.
+ *
+ * @remark If flags equals APR_POLLSET_THREADSAFE, then a pollset is
+ * created on which it is safe to make concurrent calls to
+ * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() from
+ * separate threads.  This feature is only supported on some
+ * platforms; the apr_pollset_create() call will fail with
+ * APR_ENOTIMPL on platforms where it is not supported.
  */
-//SWITCH_DECLARE(switch_status_t) switch_mutex_lock(switch_mutex_t *lock);
-#define switch_mutex_lock apr_thread_mutex_lock
+SWITCH_DECLARE(switch_status_t) switch_pollset_create(switch_pollset_t ** pollset, uint32_t size, switch_memory_pool_t *p, uint32_t flags);
 
 /**
- * Release the lock for the given mutex.
- * @param lock the mutex from which to release the lock.
+ * Add a socket or file descriptor to a pollset
+ * @param pollset The pollset to which to add the descriptor
+ * @param descriptor The descriptor to add
+ * @remark If you set client_data in the descriptor, that value
+ *         will be returned in the client_data field whenever this
+ *         descriptor is signalled in apr_pollset_poll().
+ * @remark If the pollset has been created with APR_POLLSET_THREADSAFE
+ *         and thread T1 is blocked in a call to apr_pollset_poll() for
+ *         this same pollset that is being modified via apr_pollset_add()
+ *         in thread T2, the currently executing apr_pollset_poll() call in
+ *         T1 will either: (1) automatically include the newly added descriptor
+ *         in the set of descriptors it is watching or (2) return immediately
+ *         with APR_EINTR.  Option (1) is recommended, but option (2) is
+ *         allowed for implementations where option (1) is impossible
+ *         or impractical.
  */
-//SWITCH_DECLARE(switch_status_t) switch_mutex_unlock(switch_mutex_t *lock);
-#define switch_mutex_unlock apr_thread_mutex_unlock
+SWITCH_DECLARE(switch_status_t) switch_pollset_add(switch_pollset_t * pollset, const switch_pollfd_t * descriptor);
 
 /**
- * Attempt to acquire the lock for the given mutex. If the mutex has already
- * been acquired, the call returns immediately with APR_EBUSY. Note: it
- * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine
- * if the return value was APR_EBUSY, for portability reasons.
- * @param lock the mutex on which to attempt the lock acquiring.
+ * Poll the sockets in the poll structure
+ * @param aprset The poll structure we will be using. 
+ * @param numsock The number of sockets we are polling
+ * @param nsds The number of sockets signalled.
+ * @param timeout The amount of time in microseconds to wait.  This is 
+ *                a maximum, not a minimum.  If a socket is signalled, we 
+ *                will wake up before this time.  A negative number means 
+ *                wait until a socket is signalled.
+ * @remark The number of sockets signalled is returned in the third argument. 
+ *         This is a blocking call, and it will not return until either a 
+ *         socket has been signalled, or the timeout has expired. 
  */
-//SWITCH_DECLARE(switch_status_t) switch_mutex_trylock(switch_mutex_t *lock);
-#define switch_mutex_trylock apr_thread_mutex_trylock
+SWITCH_DECLARE(switch_status_t) switch_poll(switch_pollfd_t * aprset, int32_t numsock, int32_t *nsds, switch_interval_time_t timeout);
+
+/*!
+  \brief Create a set of file descriptors to poll
+  \param poll the polfd to create
+  \param sock the socket to add
+  \param flags the flags to modify the behaviour
+  \param pool the memory pool to use
+  \return SWITCH_STATUS_SUCCESS when successful
+*/
+SWITCH_DECLARE(switch_status_t) switch_socket_create_pollfd(switch_pollfd_t ** poll, switch_socket_t * sock, int16_t flags, switch_memory_pool_t *pool);
+
+
+ /** @} */
+
+
+
 
-/** @} */
 /** @} */
 /** @} */
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_bitpack.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_bitpack.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_bitpack.h	Tue Apr 24 10:14:28 2007
@@ -36,22 +36,20 @@
 #ifndef SWITCH_BITPACK_H
 #define SWITCH_BITPACK_H
 SWITCH_BEGIN_EXTERN_C
-
 #include <switch.h>
-
 #ifdef DEBUG_BITS
 static char bb[80] = "";
 static inline char *print_bits(switch_byte_t byte, char *x)
 {
 
-    int i,j = 0;
-    x[j++] = '[';
-    for (i=7;i>=0;i--) {
-        x[j++] = (byte & (1 << i)) ? '1' : '0';
-    }
-    x[j++] = ']';
-    x[j++] = '\0';
-    return x;
+	int i, j = 0;
+	x[j++] = '[';
+	for (i = 7; i >= 0; i--) {
+		x[j++] = (byte & (1 << i)) ? '1' : '0';
+	}
+	x[j++] = ']';
+	x[j++] = '\0';
+	return x;
 }
 #endif
 
@@ -63,8 +61,8 @@
   \{ 
 */
 
-static const int8_t SWITCH_BITPACKED_MASKS[] = {0, 1, 3, 7, 15, 31, 63, 127, 255};
-static const int8_t SWITCH_REVERSE_BITPACKED_MASKS[] = {255, 254, 252, 248, 240, 224, 192, 128};
+static const uint8_t SWITCH_BITPACKED_MASKS[] = { 0, 1, 3, 7, 15, 31, 63, 127, 255 };
+static const uint8_t SWITCH_REVERSE_BITPACKED_MASKS[] = { 255, 254, 252, 248, 240, 224, 192, 128 };
 
 /*!
   \brief Initialize a bitpack object
@@ -75,7 +73,8 @@
   \param mode RFC3551 or AAL2 mode (curse you backwards folks) 
 */
 DoxyDefine(void switch_bitpack_init(switch_bitpack_t *pack, int32_t bitlen, switch_byte_t *buf, uint32_t buflen, switch_bitpack_mode_t mode))
-static inline int8_t switch_bitpack_init(switch_bitpack_t *pack, switch_byte_t bitlen, switch_byte_t *buf, uint32_t buflen, switch_bitpack_mode_t mode)
+	 static inline int8_t switch_bitpack_init(switch_bitpack_t *pack, switch_byte_t bitlen, switch_byte_t *buf, uint32_t buflen,
+											  switch_bitpack_mode_t mode)
 {
 	if (!pack || (bitlen > SWITCH_BITS_PER_BYTE) || !buf || !buflen) {
 		return -1;
@@ -94,7 +93,7 @@
 
 static inline void pack_check_over(switch_bitpack_t *pack)
 {
-	switch_byte_t this_byte = pack->this_byte;	
+	switch_byte_t this_byte = pack->this_byte;
 
 	if (pack->over) {
 		pack->bits_cur = pack->over;
@@ -117,7 +116,7 @@
 
 		pack->bytes++;
 		pack->over = pack->under = 0;
-	}	
+	}
 }
 
 /*!
@@ -125,14 +124,14 @@
   \param pack the pack/unpack object
 */
 DoxyDefine(int8_t switch_bitpack_done(switch_bitpack_t *pack))
-static inline int8_t switch_bitpack_done(switch_bitpack_t *pack)
+	 static inline int8_t switch_bitpack_done(switch_bitpack_t *pack)
 {
 
 	if (pack->bits_cur && pack->bits_cur < SWITCH_BITS_PER_BYTE) {
 		pack->bytes++;
 		if (pack->mode == SWITCH_BITPACK_MODE_AAL2) {
-            *pack->cur <<= SWITCH_BITS_PER_BYTE - pack->bits_cur;
-        }
+			*pack->cur <<= SWITCH_BITS_PER_BYTE - pack->bits_cur;
+		}
 	}
 
 	if (pack->over) {
@@ -149,11 +148,11 @@
   \return -1 if the buffer is full otherwise 0
 */
 DoxyDefine(int8_t switch_bitpack_out(switch_bitpack_t *unpack, switch_byte_t in))
-static inline int8_t switch_bitpack_out(switch_bitpack_t *unpack, switch_byte_t in)
+	 static inline int8_t switch_bitpack_out(switch_bitpack_t *unpack, switch_byte_t in)
 {
 	switch_byte_t this_byte;
 
-	if ((uint32_t)(unpack->cur - unpack->buf) > unpack->buflen) {
+	if ((uint32_t) (unpack->cur - unpack->buf) > unpack->buflen) {
 		return -1;
 	}
 
@@ -163,7 +162,7 @@
 
 
 	pack_check_over(unpack);
-	while(unpack->bits_cur <= SWITCH_BITS_PER_BYTE) {
+	while (unpack->bits_cur <= SWITCH_BITS_PER_BYTE) {
 		switch_byte_t next = unpack->bits_cur + unpack->frame_bits;
 		switch_byte_t under_in;
 		switch_byte_t mask;
@@ -220,20 +219,20 @@
   \return -1 if the buffer is full otherwise 0
 */
 DoxyDefine(int8_t switch_bitpack_in(switch_bitpack_t *pack, switch_byte_t in))
-static inline int8_t switch_bitpack_in(switch_bitpack_t *pack, switch_byte_t in)
+	 static inline int8_t switch_bitpack_in(switch_bitpack_t *pack, switch_byte_t in)
 {
 	int next = pack->bits_cur + pack->frame_bits;
 
-	if ((uint32_t)(pack->cur - pack->buf) > pack->buflen) {
+	if ((uint32_t) (pack->cur - pack->buf) > pack->buflen) {
 		return -1;
-	} 
+	}
 
 	pack->bits_tot += pack->frame_bits;
 
 	if (next > SWITCH_BITS_PER_BYTE) {
 		switch_byte_t a = 0, b = 0, rem, nxt;
 		rem = SWITCH_BITS_PER_BYTE - pack->bits_cur;
-		nxt = pack->frame_bits - rem ;
+		nxt = pack->frame_bits - rem;
 		if (pack->mode == SWITCH_BITPACK_MODE_RFC3551) {
 			a = in & SWITCH_BITPACKED_MASKS[rem];
 			b = in >> rem;
@@ -250,7 +249,7 @@
 			pack->cur++;
 			*pack->cur |= b;
 			pack->bits_cur = nxt;
-			
+
 		}
 		pack->bytes++;
 
@@ -259,14 +258,14 @@
 		if (pack->mode == SWITCH_BITPACK_MODE_RFC3551) {
 			in <<= pack->shiftby;
 			*pack->cur |= in;
-			pack->shiftby = (switch_byte_t)(pack->shiftby + pack->frame_bits);
+			pack->shiftby = (switch_byte_t) (pack->shiftby + pack->frame_bits);
 		} else {
 			*pack->cur <<= pack->frame_bits;
 			*pack->cur |= in;
 		}
 
 		if (next == SWITCH_BITS_PER_BYTE) {
-			pack->cur++;			
+			pack->cur++;
 			pack->bytes++;
 			pack->bits_cur = pack->shiftby = 0;
 		} else {
@@ -276,11 +275,11 @@
 
 	return 0;
 }
+
 ///\}
 
 SWITCH_END_EXTERN_C
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_buffer.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_buffer.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_buffer.h	Tue Apr 24 10:14:28 2007
@@ -41,7 +41,6 @@
 #include <switch.h>
 
 SWITCH_BEGIN_EXTERN_C
-
 /**
  * @defgroup switch_buffer Buffer Routines
  * @ingroup core1
@@ -50,8 +49,7 @@
  * and I think it can be optimized under the hood as we go using bucket brigades and/or ring buffering techniques.
  * @{
  */
-
-struct switch_buffer;
+	struct switch_buffer;
 
 
 /*! \brief Allocate a new switch_buffer 
@@ -69,9 +67,7 @@
  * \param max_len length the buffer is allowed to grow to
  * \return status
  */
-SWITCH_DECLARE(switch_status_t) switch_buffer_create_dynamic(switch_buffer_t **buffer,
-															 switch_size_t blocksize,
-															 switch_size_t start_len,
+SWITCH_DECLARE(switch_status_t) switch_buffer_create_dynamic(switch_buffer_t **buffer, switch_size_t blocksize, switch_size_t start_len,
 															 switch_size_t max_len);
 
 /*! \brief Get the length of a switch_buffer_t 
@@ -100,6 +96,21 @@
  */
 SWITCH_DECLARE(switch_size_t) switch_buffer_read(switch_buffer_t *buffer, void *data, switch_size_t datalen);
 
+/*! \brief Read data endlessly from a switch_buffer_t 
+ * \param buffer any buffer of type switch_buffer_t
+ * \param data pointer to the read data to be returned
+ * \param datalen amount of data to be returned
+ * \return int ammount of data actually read
+ * \note Once you have read all the data from the buffer it will loop around.
+ */
+SWITCH_DECLARE(switch_size_t) switch_buffer_read_loop(switch_buffer_t *buffer, void *data, switch_size_t datalen);
+
+/*! \brief Assign a number of loops to read
+ * \param buffer any buffer of type switch_buffer_t
+ * \param loops the number of loops (-1 for infinite)
+ */
+SWITCH_DECLARE(void) switch_buffer_set_loops(switch_buffer_t *buffer, int32_t loops);
+
 /*! \brief Write data into a switch_buffer_t up to the length of datalen
  * \param buffer any buffer of type switch_buffer_t
  * \param data pointer to the data to be written
@@ -129,9 +140,7 @@
 /** @} */
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_caller.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_caller.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_caller.h	Tue Apr 24 10:14:28 2007
@@ -56,10 +56,9 @@
 #include <switch.h>
 
 SWITCH_BEGIN_EXTERN_C
-
 /*! \brief Call Specific Data
  */
-struct switch_caller_profile {
+	struct switch_caller_profile {
 	/*! The Call's User Name */
 	char *username;
 	/*! The name of the dialplan */
@@ -118,6 +117,7 @@
 	switch_caller_application_t *last_application;
 	/*! Pointer to the entire stack of applications for this extension */
 	switch_caller_application_t *applications;
+	struct switch_caller_profile *children;
 	struct switch_caller_extension *next;
 };
 
@@ -128,10 +128,7 @@
   \param extension_number extension number
   \return a new extension object allocated from the session's memory pool
 */
-SWITCH_DECLARE(switch_caller_extension_t *) switch_caller_extension_new(switch_core_session_t *session,
-																	  char *extension_name,
-																	  char *extension_number
-																	  );
+SWITCH_DECLARE(switch_caller_extension_t *) switch_caller_extension_new(switch_core_session_t *session, char *extension_name, char *extension_number);
 
 /*!
   \brief Add an application (instruction) to the given extension
@@ -141,9 +138,7 @@
   \param extra_data optional argument to the application
 */
 SWITCH_DECLARE(void) switch_caller_extension_add_application(switch_core_session_t *session,
-															 switch_caller_extension_t *caller_extension,
-															 char *application_name,
-															 char *extra_data);
+															 switch_caller_extension_t *caller_extension, char *application_name, char *extra_data);
 
 
 /*!
@@ -178,9 +173,7 @@
 																	const char *network_addr,
 																	const char *ani,
 																	const char *aniii,
-																	const char *rdnis,
-																	const char *source,
-																	const char *context,
+																	const char *rdnis, const char *source, const char *context,
 																	const char *destination_number);
 
 /*!
@@ -188,9 +181,8 @@
   \param session session associated with the profile (bound by scope)
   \param tocopy the existing profile
 */
-	
-SWITCH_DECLARE(switch_caller_profile_t *) switch_caller_profile_clone(switch_core_session_t *session,
-																	switch_caller_profile_t *tocopy);
+
+SWITCH_DECLARE(switch_caller_profile_t *) switch_caller_profile_clone(switch_core_session_t *session, switch_caller_profile_t *tocopy);
 
 /*!
   \brief Add headers to an existing event in regards to a specific profile
@@ -202,11 +194,8 @@
 SWITCH_DECLARE(void) switch_caller_profile_event_set_data(switch_caller_profile_t *caller_profile, char *prefix, switch_event_t *event);
 
 SWITCH_END_EXTERN_C
-
 /** @} */
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_channel.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_channel.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_channel.h	Tue Apr 24 10:14:28 2007
@@ -40,9 +40,7 @@
 
 #include <switch.h>
 
-SWITCH_BEGIN_EXTERN_C
-
-struct switch_channel_timetable {
+SWITCH_BEGIN_EXTERN_C struct switch_channel_timetable {
 	switch_time_t created;
 	switch_time_t answered;
 	switch_time_t hungup;
@@ -76,17 +74,14 @@
 
 
 SWITCH_DECLARE(switch_channel_state_t) switch_channel_perform_set_state(switch_channel_t *channel,
-                                                                        const char *file,
-                                                                        const char *func,
-                                                                        int line,
-                                                                        switch_channel_state_t state);
+																		const char *file, const char *func, int line, switch_channel_state_t state);
 
 /*!
   \brief Set the current state of a channel
   \param channel channel to set state of
   \param state new state
   \return current state of channel after application of new state
-*/	
+*/
 #define switch_channel_set_state(channel, state) switch_channel_perform_set_state(channel, __FILE__, __SWITCH_FUNC__, __LINE__, state)
 
 /*!
@@ -132,10 +127,8 @@
   \param state the initial state of the channel
   \param flags the initial channel flags
 */
-SWITCH_DECLARE(switch_status_t) switch_channel_init(switch_channel_t *channel,
-								switch_core_session_t *session,
-								switch_channel_state_t state,
-								uint32_t flags);
+SWITCH_DECLARE(switch_status_t) switch_channel_init(switch_channel_t *channel, switch_core_session_t *session, switch_channel_state_t state,
+													uint32_t flags);
 
 /*!
   \brief Fire A presence event for the channel
@@ -266,6 +259,22 @@
 SWITCH_DECLARE(void) switch_channel_set_flag(switch_channel_t *channel, switch_channel_flag_t flags);
 
 /*!
+  \brief Set given flag(s) on a given channel's bridge partner
+  \param channel channel to derive the partner channel to set flag(s) on
+  \param flags or'd list of flags to set
+  \return true if the flag was set
+*/
+SWITCH_DECLARE(switch_bool_t) switch_channel_set_flag_partner(switch_channel_t *channel, switch_channel_flag_t flags);
+
+/*!
+  \brief Clears given flag(s) on a given channel's bridge partner
+  \param channel channel to derive the partner channel to clear flag(s) from
+  \param flags the flags to clear
+  \return true if the flag was cleared
+*/
+SWITCH_DECLARE(switch_bool_t) switch_channel_clear_flag_partner(switch_channel_t *channel, switch_channel_flag_t flags);
+
+/*!
   \brief Set given flag(s) on a given channel to be applied on the next state change
   \param channel channel on which to set flag(s)
   \param flags or'd list of flags to set
@@ -279,15 +288,9 @@
 */
 SWITCH_DECLARE(void) switch_channel_clear_flag(switch_channel_t *channel, switch_channel_flag_t flags);
 
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_answer(switch_channel_t *channel,
-                                                              const char *file,
-                                                              const char *func,
-                                                              int line);
-
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_answered(switch_channel_t *channel,
-                                                                     const char *file,
-                                                                     const char *func,
-                                                                     int line);
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_answer(switch_channel_t *channel, const char *file, const char *func, int line);
+
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_answered(switch_channel_t *channel, const char *file, const char *func, int line);
 
 /*!
   \brief Answer a channel (initiate/acknowledge a successful connection)
@@ -310,10 +313,7 @@
 */
 #define switch_channel_mark_pre_answered(channel) switch_channel_perform_mark_pre_answered(channel, __FILE__, __SWITCH_FUNC__, __LINE__)
 
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_ring_ready(switch_channel_t *channel,
-																  const char *file,
-																  const char *func,
-																  int line);
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_ring_ready(switch_channel_t *channel, const char *file, const char *func, int line);
 /*!
   \brief Send Ringing message to a channel
   \param channel channel to ring
@@ -322,33 +322,24 @@
 #define switch_channel_ring_ready(channel) switch_channel_perform_ring_ready(channel, __FILE__, __SWITCH_FUNC__, __LINE__)
 
 
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_pre_answer(switch_channel_t *channel,
-                                                                  const char *file,
-                                                                  const char *func,
-                                                                  int line);
-
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_pre_answered(switch_channel_t *channel,
-                                                                       const char *file,
-                                                                       const char *func,
-                                                                       int line);
-
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_ring_ready(switch_channel_t *channel,
-																	   const char *file,
-																	   const char *func,
-																	   int line);
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_pre_answer(switch_channel_t *channel, const char *file, const char *func, int line);
+
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_pre_answered(switch_channel_t *channel, const char *file, const char *func, int line);
+
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_ring_ready(switch_channel_t *channel, const char *file, const char *func, int line);
 
 /*!
   \brief Indicate progress on a channel to attempt early media
   \param channel channel to pre-answer
   \return SWITCH_STATUS_SUCCESS
-*/								
+*/
 #define switch_channel_pre_answer(channel) switch_channel_perform_pre_answer(channel, __FILE__, __SWITCH_FUNC__, __LINE__)
 
 /*!
   \brief Indicate a channel is ready to provide ringback
   \param channel channel
   \return SWITCH_STATUS_SUCCESS
-*/								
+*/
 #define switch_channel_mark_ring_ready(channel) switch_channel_perform_mark_ring_ready(channel, __FILE__, __SWITCH_FUNC__, __LINE__)
 
 /*!
@@ -407,11 +398,8 @@
 SWITCH_DECLARE(char *) switch_channel_get_name(switch_channel_t *channel);
 
 
-SWITCH_DECLARE(switch_channel_state_t) switch_channel_perform_hangup(switch_channel_t *channel, 
-                                                                     const char *file,
-                                                                     const char *func,
-                                                                     int line,
-                                                                     switch_call_cause_t hangup_cause);
+SWITCH_DECLARE(switch_channel_state_t) switch_channel_perform_hangup(switch_channel_t *channel,
+																	 const char *file, const char *func, int line, switch_call_cause_t hangup_cause);
 
 /*!
   \brief Hangup a channel flagging it's state machine to end
@@ -478,9 +466,7 @@
 /** @} */
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_config.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_config.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_config.h	Tue Apr 24 10:14:28 2007
@@ -58,22 +58,22 @@
 
 #include <switch.h>
 
-SWITCH_BEGIN_EXTERN_C
+SWITCH_BEGIN_EXTERN_C typedef struct switch_config switch_config_t;
 
 /*! \brief A simple file handle representing an open configuration file **/
 struct switch_config {
 	/*! FILE stream buffer to the opened file */
-    FILE *file;
+	FILE *file;
 	/*! path to the file */
-    char *path;
+	char *path;
 	/*! current category */
-    char category[256];
+	char category[256];
 	/*! current section */
-    char section[256];
+	char section[256];
 	/*! buffer of current line being read */
-    char buf[1024];
+	char buf[1024];
 	/*! current line number in file */
-    int lineno;
+	int lineno;
 	/*! current category number in file */
 	int catno;
 	/*! current section number in file */
@@ -88,13 +88,13 @@
   \param file_path path to the file
   \return 1 (true) on success 0 (false) on failure
 */
-SWITCH_DECLARE(int) switch_config_open_file(switch_config_t *cfg, char *file_path);
+SWITCH_DECLARE(int) switch_config_open_file(switch_config_t * cfg, char *file_path);
 
 /*!
   \brief Close a previously opened configuration file
   \param cfg (switch_config_t *) config handle to use
 */
-SWITCH_DECLARE(void) switch_config_close_file(switch_config_t *cfg);
+SWITCH_DECLARE(void) switch_config_close_file(switch_config_t * cfg);
 
 /*!
   \brief Retrieve next name/value pair from configuration file
@@ -102,14 +102,11 @@
   \param var pointer to aim at the new variable name
   \param val pointer to aim at the new value
 */
-SWITCH_DECLARE(int) switch_config_next_pair(switch_config_t *cfg, char **var, char **val);
+SWITCH_DECLARE(int) switch_config_next_pair(switch_config_t * cfg, char **var, char **val);
 
 SWITCH_END_EXTERN_C
-
 /** @} */
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_console.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_console.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_console.h	Tue Apr 24 10:14:28 2007
@@ -51,9 +51,6 @@
 		s.alloc_len = SWITCH_CMD_CHUNK_LEN;\
 		s.alloc_chunk = SWITCH_CMD_CHUNK_LEN;\
 	}
-
- 
-
 /*!
   \brief A simple comand loop that reads input from the terminal
 */
@@ -62,16 +59,15 @@
 /*!
   \brief A method akin to printf that allows you to redirect output to a specific console "channel"
 */
-SWITCH_DECLARE(void) switch_console_printf(switch_text_channel_t channel, const char *file, const char *func, int line, const char *fmt, ...) PRINTF_FUNCTION(5,6);
+SWITCH_DECLARE(void) switch_console_printf(switch_text_channel_t channel, const char *file, const char *func, int line,
+										   const char *fmt, ...) PRINTF_FUNCTION(5, 6);
 
 /*!
   \brief A method akin to printf for dealing with api streams
 */
-SWITCH_DECLARE(switch_status_t) switch_console_stream_write(switch_stream_handle_t *handle, const char *fmt, ...) PRINTF_FUNCTION(2,3);
+SWITCH_DECLARE(switch_status_t) switch_console_stream_write(switch_stream_handle_t *handle, const char *fmt, ...) PRINTF_FUNCTION(2, 3);
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_core.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_core.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_core.h	Tue Apr 24 10:14:28 2007
@@ -41,43 +41,47 @@
 #include <switch.h>
 
 SWITCH_BEGIN_EXTERN_C
-
 #define SWITCH_MAX_CORE_THREAD_SESSION_OBJS 128
 #define SWITCH_MAX_STREAMS 128
-
 struct switch_core_time_duration {
-    uint32_t mms;
-    uint32_t ms;
-    uint32_t sec;
-    uint32_t min;
-    uint32_t hr;
+	uint32_t mms;
+	uint32_t ms;
+	uint32_t sec;
+	uint32_t min;
+	uint32_t hr;
 	uint32_t day;
 	uint32_t yr;
 };
 
+struct switch_app_log {
+	char *app;
+	char *arg;
+	struct switch_app_log *next;
+};
+
 /*! \brief A message object designed to allow unlike technologies to exchange data */
 struct switch_core_session_message {
-	/*! uuid of the sender (for replies)*/
+	/*! uuid of the sender (for replies) */
 	char *from;
 	/*! enumeration of the type of message */
 	switch_core_session_message_types_t message_id;
 
-	/*! optional numeric arg*/
+	/*! optional numeric arg */
 	int numeric_arg;
-	/*! optional string arg*/
+	/*! optional string arg */
 	char *string_arg;
-	/*! optional string arg*/
+	/*! optional string arg */
 	switch_size_t string_arg_size;
 	/*! optional arbitrary pointer arg */
 	void *pointer_arg;
 	/*! optional arbitrary pointer arg's size */
 	switch_size_t pointer_arg_size;
 
-	/*! optional numeric reply*/
+	/*! optional numeric reply */
 	int numeric_reply;
-	/*! optional string reply*/
+	/*! optional string reply */
 	char *string_reply;
-	/*! optional string reply*/
+	/*! optional string reply */
 	switch_size_t string_reply_size;
 	/*! optional arbitrary pointer reply */
 	void *pointer_reply;
@@ -96,7 +100,7 @@
 	/*! array of void pointers to pass mutiple data objects */
 	void *objs[SWITCH_MAX_CORE_THREAD_SESSION_OBJS];
 	/*! a pointer to a memory pool if the thread has it's own pool */
-    switch_input_callback_function_t input_callback;
+	switch_input_callback_function_t input_callback;
 	switch_memory_pool_t *pool;
 };
 
@@ -110,11 +114,11 @@
   \{ 
 */
 
-
 ///\defgroup mb1 Media Bugs
 ///\ingroup core1
 ///\{
 
+
 /*!
   \brief Add a media bug to the session
   \param session the session to add the bug to
@@ -126,9 +130,7 @@
 */
 SWITCH_DECLARE(switch_status_t) switch_core_media_bug_add(switch_core_session_t *session,
 														  switch_media_bug_callback_t callback,
-														  void *user_data,
-														  switch_media_bug_flag_t flags,
-														  switch_media_bug_t **new_bug);
+														  void *user_data, switch_media_bug_flag_t flags, switch_media_bug_t **new_bug);
 /*!
   \brief Obtain private data from a media bug
   \param bug the bug to get the data from
@@ -158,6 +160,12 @@
 SWITCH_DECLARE(switch_status_t) switch_core_media_bug_remove(switch_core_session_t *session, switch_media_bug_t **bug);
 
 /*!
+  \brief Close and destroy a media bug
+  \param bug bug to remove
+  \return SWITCH_STATUS_SUCCESS if the operation was a success
+*/
+SWITCH_DECLARE(switch_status_t) switch_core_media_bug_close(switch_media_bug_t **bug);
+/*!
   \brief Remove all media bugs from the session
   \param session the session to remove the bugs from
   \return SWITCH_STATUS_SUCCESS if the operation was a success
@@ -187,9 +195,7 @@
   \return SWITCH_STATUS_SUCCESS if the operation was a success
 */
 SWITCH_DECLARE(switch_status_t) switch_core_port_allocator_new(switch_port_t start,
-															   switch_port_t end,
-															   uint8_t inc,
-															   switch_core_port_allocator_t **new_allocator);
+															   switch_port_t end, uint8_t inc, switch_core_port_allocator_t **new_allocator);
 
 /*!
   \brief Get a port from the port allocator
@@ -244,10 +250,7 @@
 ///\{
 
 #ifdef SWITCH_DEBUG_RWLOCKS
-SWITCH_DECLARE(switch_status_t) switch_core_session_perform_read_lock(switch_core_session_t *session,
-                                                                      const char *file,
-                                                                      const char *func,
-                                                                      int line);
+SWITCH_DECLARE(switch_status_t) switch_core_session_perform_read_lock(switch_core_session_t *session, const char *file, const char *func, int line);
 #endif
 
 /*! 
@@ -263,10 +266,7 @@
 
 
 #ifdef SWITCH_DEBUG_RWLOCKS
-SWITCH_DECLARE(void) switch_core_session_perform_write_lock(switch_core_session_t *session,
-                                                            const char *file,
-                                                            const char *func,
-                                                            int line);
+SWITCH_DECLARE(void) switch_core_session_perform_write_lock(switch_core_session_t *session, const char *file, const char *func, int line);
 #endif
 
 /*! 
@@ -280,10 +280,7 @@
 #endif
 
 #ifdef SWITCH_DEBUG_RWLOCKS
-SWITCH_DECLARE(void) switch_core_session_perform_rwunlock(switch_core_session_t *session,
-                                                          const char *file,
-                                                          const char *func,
-                                                          int line);
+SWITCH_DECLARE(void) switch_core_session_perform_rwunlock(switch_core_session_t *session, const char *file, const char *func, int line);
 #endif
 
 /*! 
@@ -428,7 +425,8 @@
   \param pool the pool to use for the allocation (a new one will be used if NULL)
   \return the newly created session
 */
-SWITCH_DECLARE(switch_core_session_t *) switch_core_session_request(const switch_endpoint_interface_t *endpoint_interface, switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_core_session_t *) switch_core_session_request(const switch_endpoint_interface_t
+																	*endpoint_interface, switch_memory_pool_t **pool);
 
 /*! 
   \brief Destroy a session and return the memory pool to the core
@@ -444,12 +442,18 @@
 SWITCH_DECLARE(uint32_t) switch_core_session_count(void);
 
 /*! 
+  \brief Provide the current session_id
+  \return the total number of allocated sessions since core startup
+*/
+SWITCH_DECLARE(switch_size_t) switch_core_session_id(void);
+
+/*! 
   \brief Allocate and return a new session from the core based on a given endpoint module name
   \param endpoint_name the name of the endpoint module
   \param pool the pool to use
   \return the newly created session
 */
-SWITCH_DECLARE(switch_core_session_t *) switch_core_session_request_by_name(char *endpoint_name, switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_core_session_t *) switch_core_session_request_by_name(char *endpoint_name, switch_memory_pool_t **pool);
 
 /*! 
   \brief Launch the session thread (state machine) on a given session
@@ -483,10 +487,7 @@
 SWITCH_DECLARE(char *) switch_core_get_uuid(void);
 
 #ifdef SWITCH_DEBUG_RWLOCKS
-SWITCH_DECLARE(switch_core_session_t *) switch_core_session_perform_locate(char *uuid_str,
-                                                                           const char *file,
-                                                                           const char *func,
-                                                                           int line);
+SWITCH_DECLARE(switch_core_session_t *) switch_core_session_perform_locate(char *uuid_str, const char *file, const char *func, int line);
 #endif
 
 /*! 
@@ -527,7 +528,7 @@
   \param message the switch_core_session_message_t object to send
   \return the status returned by the message handler
 */
-SWITCH_DECLARE (switch_status_t) switch_core_session_message_send(char *uuid_str, switch_core_session_message_t *message);
+SWITCH_DECLARE(switch_status_t) switch_core_session_message_send(char *uuid_str, switch_core_session_message_t *message);
 
 /*! 
   \brief Queue a message on a session
@@ -538,6 +539,14 @@
 SWITCH_DECLARE(switch_status_t) switch_core_session_queue_message(switch_core_session_t *session, switch_core_session_message_t *message);
 
 /*! 
+  \brief pass an indication message on a session
+  \param session the session to pass the message across
+  \param indication the indication message to pass
+  \return SWITCH_STATUS_SUCCESS if the message was passed
+*/
+SWITCH_DECLARE(switch_status_t) switch_core_session_pass_indication(switch_core_session_t *session, switch_core_session_message_types_t indication);
+
+/*! 
   \brief Queue an indication message on a session
   \param session the session to queue the message to
   \param indication the indication message to queue
@@ -568,6 +577,11 @@
 */
 SWITCH_DECLARE(switch_status_t) switch_core_session_event_send(char *uuid_str, switch_event_t **event);
 
+SWITCH_DECLARE(switch_app_log_t *) switch_core_session_get_app_log(switch_core_session_t *session);
+SWITCH_DECLARE(switch_status_t) switch_core_session_exec(switch_core_session_t *session,
+														 const switch_application_interface_t *application_interface, char *arg);
+SWITCH_DECLARE(switch_status_t) switch_core_session_execute_exten(switch_core_session_t *session, char *exten, char *dialplan, char *context);
+
 /*! 
   \brief Send an event to a session translating it to it's native message format
   \param session the session to receive the event
@@ -620,7 +634,7 @@
   \param func a function to execute in the thread
   \param obj an arguement
 */
-SWITCH_DECLARE(void) switch_core_session_launch_thread(switch_core_session_t *session, void *(*func)(switch_thread_t *, void *), void *obj);
+SWITCH_DECLARE(void) switch_core_session_launch_thread(switch_core_session_t *session, void *(*func) (switch_thread_t *, void *), void *obj);
 
 /*! 
   \brief Signal a thread using a thread session to terminate
@@ -648,15 +662,7 @@
 SWITCH_DECLARE(switch_call_cause_t) switch_core_session_outgoing_channel(switch_core_session_t *session,
 																		 char *endpoint_name,
 																		 switch_caller_profile_t *caller_profile,
-																		 switch_core_session_t **new_session,
-																		 switch_memory_pool_t *pool);
-
-/*! 
-  \brief Answer the channel of a given session
-  \param session the session to answer the channel of
-  \return SWITCH_STATUS_SUCCESS if the channel was answered
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_answer_channel(switch_core_session_t *session);
+																		 switch_core_session_t **new_session, switch_memory_pool_t **pool);
 
 /*! 
   \brief Receive a message on a given session
@@ -725,6 +731,9 @@
 */
 SWITCH_DECLARE(switch_status_t) switch_core_session_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, int stream_id);
 
+SWITCH_DECLARE(switch_status_t) switch_core_session_read_video_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, int stream_id);
+SWITCH_DECLARE(switch_status_t) switch_core_session_write_video_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, int stream_id);
+
 /*! 
   \brief Reset the buffers and resampler on a session
   \param session the session to reset
@@ -742,11 +751,8 @@
 SWITCH_DECLARE(switch_status_t) switch_core_session_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, int stream_id);
 
 
-SWITCH_DECLARE(switch_status_t) switch_core_session_perform_kill_channel(switch_core_session_t *session, 
-                                                                         const char *file, 
-                                                                         const char *func, 
-                                                                         int line, 
-                                                                         switch_signal_t sig);
+SWITCH_DECLARE(switch_status_t) switch_core_session_perform_kill_channel(switch_core_session_t *session,
+																		 const char *file, const char *func, int line, switch_signal_t sig);
 /*! 
   \brief Send a signal to a channel
   \param session session to send signal to
@@ -781,82 +787,8 @@
 */
 SWITCH_DECLARE(switch_status_t) switch_core_session_send_dtmf(switch_core_session_t *session, char *dtmf);
 
-/*! 
-  \brief Add an event hook to be executed when a session requests an outgoing extension
-  \param session session to bind hook to
-  \param outgoing_channel hook to bind
-  \return SWITCH_STATUS_SUCCESS on suceess
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_outgoing(switch_core_session_t *session, switch_outgoing_channel_hook_t outgoing_channel);
 ///\}
 
-///\defgroup shooks Session Hook Callbacks
-///\ingroup core1
-///\{
-/*! 
-  \brief Add an event hook to be executed when a session answers a channel
-  \param session session to bind hook to
-  \param answer_channel hook to bind
-  \return SWITCH_STATUS_SUCCESS on suceess
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_answer_channel(switch_core_session_t *session, switch_answer_channel_hook_t answer_channel);
-
-/*! 
-  \brief Add an event hook to be executed when a session sends a message
-  \param session session to bind hook to
-  \param receive_message hook to bind
-  \return SWITCH_STATUS_SUCCESS on suceess
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_receive_message(switch_core_session_t *session, switch_receive_message_hook_t receive_message);
-
-/*! 
-  \brief Add an event hook to be executed when a session reads a frame
-  \param session session to bind hook to
-  \param  read_frame hook to bind
-  \return SWITCH_STATUS_SUCCESS on suceess
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_read_frame(switch_core_session_t *session, switch_read_frame_hook_t read_frame);
-
-/*! 
-  \brief Add an event hook to be executed when a session writes a frame
-  \param session session to bind hook to
-  \param write_frame hook to bind
-  \return SWITCH_STATUS_SUCCESS on suceess
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_write_frame(switch_core_session_t *session, switch_write_frame_hook_t write_frame);
-
-/*! 
-  \brief Add an event hook to be executed when a session kills a channel
-  \param session session to bind hook to
-  \param kill_channel hook to bind
-  \return SWITCH_STATUS_SUCCESS on suceess
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_kill_channel(switch_core_session_t *session, switch_kill_channel_hook_t kill_channel);
-
-/*! 
-  \brief Add an event hook to be executed when a session waits for a read event
-  \param session session to bind hook to
-  \param waitfor_read hook to bind
-  \return SWITCH_STATUS_SUCCESS on suceess
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_waitfor_read(switch_core_session_t *session, switch_waitfor_read_hook_t waitfor_read);
-
-/*! 
-  \brief Add an event hook to be executed when a session waits for a write event
-  \param session session to bind hook to
-  \param waitfor_write hook to bind
-  \return SWITCH_STATUS_SUCCESS on suceess
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_waitfor_write(switch_core_session_t *session, switch_waitfor_write_hook_t waitfor_write);
-
-/*! 
-  \brief Add an event hook to be executed when a session sends dtmf
-  \param session session to bind hook to
-  \param send_dtmf hook to bind
-  \return SWITCH_STATUS_SUCCESS on suceess
-*/
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_send_dtmf(switch_core_session_t *session, switch_send_dtmf_hook_t send_dtmf);
-///\}
 
 ///\defgroup hashf Hash Functions
 ///\ingroup core1
@@ -867,14 +799,14 @@
   \param pool the pool to use for the new hash
   \return SWITCH_STATUS_SUCCESS if the hash is created
 */
-SWITCH_DECLARE(switch_status_t) switch_core_hash_init(switch_hash_t **hash, switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_status_t) switch_core_hash_init(switch_hash_t ** hash, switch_memory_pool_t *pool);
 
 /*! 
   \brief Destroy an existing hash table
   \param hash the hash to destroy
   \return SWITCH_STATUS_SUCCESS if the hash is destroyed
 */
-SWITCH_DECLARE(switch_status_t) switch_core_hash_destroy(switch_hash_t *hash);
+SWITCH_DECLARE(switch_status_t) switch_core_hash_destroy(switch_hash_t * hash);
 
 /*! 
   \brief Insert data into a hash
@@ -884,7 +816,7 @@
   \return SWITCH_STATUS_SUCCESS if the data is added
   \note the string key must be a constant or a dynamic string
 */
-SWITCH_DECLARE(switch_status_t) switch_core_hash_insert(switch_hash_t *hash, const char *key, const void *data);
+SWITCH_DECLARE(switch_status_t) switch_core_hash_insert(switch_hash_t * hash, const char *key, const void *data);
 
 /*! 
   \brief Insert data into a hash with dynamicly allocated key name
@@ -893,7 +825,7 @@
   \param data the data to add
   \return SWITCH_STATUS_SUCCESS if the data is added
 */
-SWITCH_DECLARE(switch_status_t) switch_core_hash_insert_dup(switch_hash_t *hash, const char *key, const void *data);
+SWITCH_DECLARE(switch_status_t) switch_core_hash_insert_dup(switch_hash_t * hash, const char *key, const void *data);
 
 /*! 
   \brief Delete data from a hash based on desired key
@@ -901,7 +833,7 @@
   \param key the key from which to delete the data
   \return SWITCH_STATUS_SUCCESS if the data is deleted
 */
-SWITCH_DECLARE(switch_status_t) switch_core_hash_delete(switch_hash_t *hash, const char *key);
+SWITCH_DECLARE(switch_status_t) switch_core_hash_delete(switch_hash_t * hash, const char *key);
 
 /*! 
   \brief Retrieve data from a given hash
@@ -909,7 +841,7 @@
   \param key the key to retrieve
   \return a pointer to the data held in the key
 */
-SWITCH_DECLARE(void *) switch_core_hash_find(switch_hash_t *hash, const char *key);
+SWITCH_DECLARE(void *) switch_core_hash_find(switch_hash_t * hash, const char *key);
 ///\}
 
 ///\defgroup timer Timer Functions
@@ -931,7 +863,7 @@
   \param timer the timer to wait on
   \return the newest sample count
 */
-SWITCH_DECLARE(int) switch_core_timer_next(switch_timer_t *timer);
+SWITCH_DECLARE(switch_status_t) switch_core_timer_next(switch_timer_t *timer);
 
 /*! 
   \brief Step the timer one step
@@ -971,15 +903,13 @@
   \param pool the memory pool to use
   \return SWITCH_STATUS_SUCCESS if the handle is allocated
 */
-SWITCH_DECLARE(switch_status_t) switch_core_codec_init(switch_codec_t *codec, 
-													   char *codec_name, 
+SWITCH_DECLARE(switch_status_t) switch_core_codec_init(switch_codec_t *codec,
+													   char *codec_name,
 													   char *fmtp,
-													   uint32_t rate, 
-													   int ms, 
-													   int channels, 
-													   uint32_t flags,
-													   const switch_codec_settings_t *codec_settings, 
-													   switch_memory_pool_t *pool);
+													   uint32_t rate,
+													   int ms,
+													   int channels,
+													   uint32_t flags, const switch_codec_settings_t *codec_settings, switch_memory_pool_t *pool);
 
 /*! 
   \brief Encode data using a codec handle
@@ -996,14 +926,11 @@
   \note encoded_data_len will be rewritten to the in-use size of encoded_data
 */
 SWITCH_DECLARE(switch_status_t) switch_core_codec_encode(switch_codec_t *codec,
-													   switch_codec_t *other_codec,
-													   void *decoded_data,
-													   uint32_t decoded_data_len,
-													   uint32_t decoded_rate,
-													   void *encoded_data,
-													   uint32_t *encoded_data_len,
-													   uint32_t *encoded_rate,
-													   unsigned int *flag);
+														 switch_codec_t *other_codec,
+														 void *decoded_data,
+														 uint32_t decoded_data_len,
+														 uint32_t decoded_rate,
+														 void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate, unsigned int *flag);
 
 /*! 
   \brief Decode data using a codec handle
@@ -1020,14 +947,11 @@
   \note decoded_data_len will be rewritten to the in-use size of decoded_data
 */
 SWITCH_DECLARE(switch_status_t) switch_core_codec_decode(switch_codec_t *codec,
-													   switch_codec_t *other_codec,
-													   void *encoded_data,
-													   uint32_t encoded_data_len,
-													   uint32_t encoded_rate,
-													   void *decoded_data,
-													   uint32_t *decoded_data_len,
-													   uint32_t *decoded_rate,
-													   unsigned int *flag);
+														 switch_codec_t *other_codec,
+														 void *encoded_data,
+														 uint32_t encoded_data_len,
+														 uint32_t encoded_rate,
+														 void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate, unsigned int *flag);
 
 /*! 
   \brief Destroy an initalized codec handle
@@ -1109,14 +1033,16 @@
 /*! 
   \brief Open a media file using file format modules
   \param fh a file handle to use
+  \param channels the number of channels
+  \param rate the sample rate
   \param file_path the path to the file
   \param flags read/write flags
   \param pool the pool to use (NULL for new pool)
   \return SWITCH_STATUS_SUCCESS if the file is opened
   \note the loadable module used is chosen based on the file extension
 */
-SWITCH_DECLARE(switch_status_t) switch_core_file_open(switch_file_handle_t *fh, char *file_path, unsigned int flags, switch_memory_pool_t *pool);
-
+SWITCH_DECLARE(switch_status_t) switch_core_file_open(switch_file_handle_t *fh,
+													  char *file_path, uint8_t channels, uint32_t rate, unsigned int flags, switch_memory_pool_t *pool);
 /*! 
   \brief Read media from a file handle
   \param fh the file handle to read from (must be initilized by you memset all 0 for read, fill in channels and rate for write)
@@ -1185,12 +1111,9 @@
   \param pool the pool to use (NULL for new pool)
   \return SWITCH_STATUS_SUCCESS if the handle is opened
 */
-SWITCH_DECLARE(switch_status_t) switch_core_speech_open(switch_speech_handle_t *sh, 
-													  char *module_name,
-													  char *voice_name,
-													  unsigned int rate,
-													  switch_speech_flag_t *flags,
-													  switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_status_t) switch_core_speech_open(switch_speech_handle_t *sh,
+														char *module_name,
+														char *voice_name, unsigned int rate, switch_speech_flag_t *flags, switch_memory_pool_t *pool);
 /*! 
   \brief Feed text to the TTS module
   \param sh the speech handle to feed
@@ -1239,11 +1162,8 @@
   \param flags flags in/out for fine tuning
   \return SWITCH_STATUS_SUCCESS with len adjusted to the bytes written if successful
 */
-SWITCH_DECLARE(switch_status_t) switch_core_speech_read_tts(switch_speech_handle_t *sh, 
-														  void *data,
-														  switch_size_t *datalen,
-														  uint32_t *rate,
-														  switch_speech_flag_t *flags);
+SWITCH_DECLARE(switch_status_t) switch_core_speech_read_tts(switch_speech_handle_t *sh,
+															void *data, switch_size_t *datalen, uint32_t * rate, switch_speech_flag_t *flags);
 /*! 
   \brief Close an open speech handle
   \param sh the speech handle to close
@@ -1266,11 +1186,7 @@
 */
 SWITCH_DECLARE(switch_status_t) switch_core_asr_open(switch_asr_handle_t *ah,
 													 char *module_name,
-													 char *codec,
-													 int rate,
-													 char *dest,
-													 switch_asr_flag_t *flags,
-													 switch_memory_pool_t *pool);
+													 char *codec, int rate, char *dest, switch_asr_flag_t *flags, switch_memory_pool_t *pool);
 
 /*!
   \brief Close an asr handle
@@ -1354,12 +1270,8 @@
   \param pool the pool to use (NULL for new pool)
   \return SWITCH_STATUS_SUCCESS if the handle is opened
 */
-SWITCH_DECLARE(switch_status_t) switch_core_directory_open(switch_directory_handle_t *dh, 
-														 char *module_name, 
-														 char *source,
-														 char *dsn,
-														 char *passwd,
-														 switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_status_t) switch_core_directory_open(switch_directory_handle_t *dh,
+														   char *module_name, char *source, char *dsn, char *passwd, switch_memory_pool_t *pool);
 
 /*! 
   \brief Query a directory handle
@@ -1405,6 +1317,22 @@
 */
 SWITCH_DECLARE(FILE *) switch_core_data_channel(switch_text_channel_t channel);
 
+/*! 
+  \brief Determines if the core is ready to take calls
+  \return SWITCH_TRUE or SWITCH_FALSE
+*/
+SWITCH_DECLARE(switch_bool_t) switch_core_ready(void);
+
+/*! 
+  \brief Execute a management operation.
+  \param relative_oid the relative oid of the operation.
+  \param action the action to perform.
+  \param data input/output string.
+  \param datalen size in bytes of data.
+  \return SUCCESS on sucess.
+*/
+SWITCH_DECLARE(switch_status_t) switch_core_management_exec(char *relative_oid, switch_management_action_t action, char *data, switch_size_t datalen);
+
 
 /*! 
   \brief Set the maximum priority the process can obtain
@@ -1443,7 +1371,7 @@
   \param val the command arguement (if needed)
   \return 0 on success nonzero on error
 */
-SWITCH_DECLARE(int32_t) switch_core_session_ctl(switch_session_ctl_t cmd, uint32_t *val);
+SWITCH_DECLARE(int32_t) switch_core_session_ctl(switch_session_ctl_t cmd, uint32_t * val);
 
 /*!
   \brief Get the output console
@@ -1453,7 +1381,7 @@
 /*! 
   \brief Launch a thread
 */
-SWITCH_DECLARE(void) switch_core_launch_thread(void *(*func)(switch_thread_t *, void*), void *obj, switch_memory_pool_t *pool);
+SWITCH_DECLARE(void) switch_core_launch_thread(void *(*func) (switch_thread_t *, void *), void *obj, switch_memory_pool_t *pool);
 
 /*!
   \brief Initiate Globals
@@ -1474,9 +1402,7 @@
 */
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_event.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_event.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_event.h	Tue Apr 24 10:14:28 2007
@@ -61,9 +61,8 @@
 #include <switch.h>
 
 SWITCH_BEGIN_EXTERN_C
-
 /*! \brief An event Header */
-struct switch_event_header{
+	struct switch_event_header {
 	/*! the header name */
 	char *name;
 	/*! the header value */
@@ -172,7 +171,8 @@
   \param fmt the value of the header (varargs see standard sprintf family)
   \return SWITCH_STATUS_SUCCESS if the header was added
 */
-SWITCH_DECLARE(switch_status_t) switch_event_add_header(switch_event_t *event, switch_stack_t stack, const char *header_name, const char *fmt, ...) PRINTF_FUNCTION(4,5);
+SWITCH_DECLARE(switch_status_t) switch_event_add_header(switch_event_t *event, switch_stack_t stack,
+														const char *header_name, const char *fmt, ...) PRINTF_FUNCTION(4, 5);
 
 /*!
   \brief Destroy an event
@@ -208,7 +208,8 @@
   \param user_data optional user specific data to pass whenever the callback is invoked
   \return SWITCH_STATUS_SUCCESS if the event was binded
 */
-SWITCH_DECLARE(switch_status_t) switch_event_bind(char *id, switch_event_types_t event, char *subclass_name, switch_event_callback_t callback, void *user_data);
+SWITCH_DECLARE(switch_status_t) switch_event_bind(char *id, switch_event_types_t event, char *subclass_name, switch_event_callback_t callback,
+												  void *user_data);
 
 /*!
   \brief Render the name of an event id enumeration
@@ -251,7 +252,7 @@
   \return the xml object if the operation was successful
   \note the body supplied by this function will supersede an existing body the event may have
 */
-SWITCH_DECLARE(switch_xml_t) switch_event_xmlize(switch_event_t *event, const char *fmt, ...) PRINTF_FUNCTION(2,3);
+SWITCH_DECLARE(switch_xml_t) switch_event_xmlize(switch_event_t *event, const char *fmt, ...) PRINTF_FUNCTION(2, 3);
 
 /*!
   \brief Determine if the event system has been initilized
@@ -266,7 +267,7 @@
   \return SWITCH_STATUS_SUCCESS if the body was added to the event
   \note the body parameter can be shadowed by the switch_event_reserve_subclass_detailed function
 */
-SWITCH_DECLARE(switch_status_t) switch_event_add_body(switch_event_t *event, const char *fmt, ...) PRINTF_FUNCTION(2,3);
+SWITCH_DECLARE(switch_status_t) switch_event_add_body(switch_event_t *event, const char *fmt, ...) PRINTF_FUNCTION(2, 3);
 
 
 /*!
@@ -311,9 +312,7 @@
 ///\}
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_frame.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_frame.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_frame.h	Tue Apr 24 10:14:28 2007
@@ -30,7 +30,7 @@
  *
  */
 /*! \file switch_frame.h
-    \brief Media Frame Structure
+  \brief Media Frame Structure
 */
 
 #ifndef SWITCH_FRAME_H
@@ -39,7 +39,6 @@
 #include <switch.h>
 
 SWITCH_BEGIN_EXTERN_C
-
 /*! \brief An abstraction of a data frame */
 struct switch_frame {
 	/*! a pointer to the codec information */
@@ -48,7 +47,7 @@
 	const char *source;
 	/*! the raw packet */
 	void *packet;
-	/*! the size of the raw packet when applicable*/
+	/*! the size of the raw packet when applicable */
 	uint32_t packetlen;
 	/*! the frame data */
 	void *data;
@@ -63,15 +62,16 @@
 	/*! the payload of the frame */
 	switch_payload_t payload;
 	/*! the timestamp of the frame */
-	uint32_t timestamp;
+	switch_size_t timestamp;
+	uint16_t seq;
+	uint32_t ssrc;
+	switch_bool_t m;
 	/*! frame flags */
 	switch_frame_flag_t flags;
 };
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_ivr.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_ivr.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_ivr.h	Tue Apr 24 10:14:28 2007
@@ -43,6 +43,27 @@
 
 SWITCH_BEGIN_EXTERN_C
 
+struct switch_unicast_conninfo {
+	switch_core_session_t *session;
+	switch_codec_t read_codec;
+	switch_frame_t write_frame;
+	switch_byte_t write_frame_data[SWITCH_RECOMMENDED_BUFFER_SIZE];
+	switch_socket_t *socket;
+	char *local_ip;
+	switch_port_t local_port;
+	char *remote_ip;
+	switch_port_t remote_port;
+	switch_sockaddr_t *local_addr;
+	switch_sockaddr_t *remote_addr;
+	switch_mutex_t *flag_mutex;
+	int32_t flags;
+	int type;
+	int transport;
+	int stream_id;
+};
+typedef struct switch_unicast_conninfo switch_unicast_conninfo_t;
+
+
 /**
  * @defgroup switch_ivr IVR Library
  * @ingroup core1
@@ -51,6 +72,14 @@
  * @{
  */
 
+SWITCH_DECLARE(switch_status_t) switch_ivr_deactivate_unicast(switch_core_session_t *session);
+SWITCH_DECLARE(switch_status_t) switch_ivr_activate_unicast(switch_core_session_t *session, 
+															char *local_ip,
+															switch_port_t local_port,
+															char *remote_ip,
+															switch_port_t remote_port,
+															char *transport,
+															char *flags);
 
 /*!
   \brief Generate an XML CDR report.
@@ -59,7 +88,7 @@
   \return SWITCH_STATUS_SUCCESS if successful
   \note on success the xml object must be freed
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_generate_xml_cdr(switch_core_session_t *session, switch_xml_t *xml_cdr);
+SWITCH_DECLARE(switch_status_t) switch_ivr_generate_xml_cdr(switch_core_session_t *session, switch_xml_t * xml_cdr);
 
 /*!
   \brief Parse command from an event
@@ -82,15 +111,11 @@
 /*!
   \brief Wait for DTMF digits calling a pluggable callback function when digits are collected.
   \param session the session to read.
-  \param dtmf_callback code to execute if any dtmf is dialed during the recording
-  \param buf an object to maintain across calls
-  \param buflen the size of buf
+  \param args arguements to pass for callbacks etc
   \param timeout a timeout in milliseconds
   \return SWITCH_STATUS_SUCCESS to keep the collection moving.
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_collect_digits_callback(switch_core_session_t *session,
-                                                                   switch_input_args_t *args,
-																   uint32_t timeout);
+SWITCH_DECLARE(switch_status_t) switch_ivr_collect_digits_callback(switch_core_session_t *session, switch_input_args_t *args, uint32_t timeout);
 
 /*!
   \brief Wait for specified number of DTMF digits, untile terminator is received or until the channel hangs up.
@@ -106,10 +131,7 @@
 SWITCH_DECLARE(switch_status_t) switch_ivr_collect_digits_count(switch_core_session_t *session,
 																char *buf,
 																uint32_t buflen,
-																uint32_t maxdigits,
-																const char *terminators,
-																char *terminator,
-																uint32_t timeout);
+																uint32_t maxdigits, const char *terminators, char *terminator, uint32_t timeout);
 
 /*!
   \brief Engage background Speech detection on a session
@@ -122,11 +144,7 @@
   \return SWITCH_STATUS_SUCCESS if all is well
 */
 SWITCH_DECLARE(switch_status_t) switch_ivr_detect_speech(switch_core_session_t *session,
-														 char *mod_name,
-														 char *grammar,
-														 char *path,
-														 char *dest,
-														 switch_asr_handle_t *ah);
+														 char *mod_name, char *grammar, char *path, char *dest, switch_asr_handle_t *ah);
 
 /*!
   \brief Stop background Speech detection on a session
@@ -173,7 +191,7 @@
   \param fh file handle to use (NULL for builtin one)
   \return SWITCH_STATUS_SUCCESS if all is well
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_record_session(switch_core_session_t *session, char *file,  switch_file_handle_t *fh);
+SWITCH_DECLARE(switch_status_t) switch_ivr_record_session(switch_core_session_t *session, char *file, switch_file_handle_t *fh);
 
 /*!
   \brief Stop Recording a session
@@ -185,22 +203,17 @@
 
 SWITCH_DECLARE(switch_status_t) switch_ivr_inband_dtmf_session(switch_core_session_t *session);
 SWITCH_DECLARE(switch_status_t) switch_ivr_stop_inband_dtmf_session(switch_core_session_t *session);
+SWITCH_DECLARE(void) switch_ivr_session_echo(switch_core_session_t *session);
 
 /*!
   \brief play a file from the disk to the session
   \param session the session to play the file too
   \param fh file handle to use (NULL for builtin one)
   \param file the path to the file
-  \param dtmf_callback code to execute if any dtmf is dialed during the playback
-  \param buf an object to maintain across calls
-  \param buflen the size of buf
-  \return SWITCH_STATUS_SUCCESS if all is well
-  \note passing a NULL dtmf_callback nad a not NULL buf indicates to copy any dtmf to buf and stop playback.
-*/
-SWITCH_DECLARE(switch_status_t) switch_ivr_play_file(switch_core_session_t *session,
-                                                     switch_file_handle_t *fh,
-                                                     char *file,
-                                                     switch_input_args_t *args);
+  \param args arguements to pass for callbacks etc
+  \return SWITCH_STATUS_SUCCESS if all is well
+*/
+SWITCH_DECLARE(switch_status_t) switch_ivr_play_file(switch_core_session_t *session, switch_file_handle_t *fh, char *file, switch_input_args_t *args);
 
 
 /*!
@@ -208,26 +221,13 @@
   \param session the session to record from
   \param fh file handle to use
   \param file the path to the file
-  \param dtmf_callback code to execute if any dtmf is dialed during the recording
-  \param buf an object to maintain across calls
-  \param buflen the size of buf
+  \param args arguements to pass for callbacks etc
   \param limit max limit to record for (0 for infinite)
   \return SWITCH_STATUS_SUCCESS if all is well
-  \note passing a NULL dtmf_callback nad a not NULL buf indicates to copy any dtmf to buf and stop recording.
 */
 SWITCH_DECLARE(switch_status_t) switch_ivr_record_file(switch_core_session_t *session,
-                                                       switch_file_handle_t *fh,
-                                                       char *file,
-                                                       switch_input_args_t *args,
-                                                       uint32_t limit);
+													   switch_file_handle_t *fh, char *file, switch_input_args_t *args, uint32_t limit);
 
-/*!
- \brief Function to evaluate an expression against a string
- \param target The string to find a match in
- \param expression The regular expression to run against the string
- \return Boolean if a match was found or not
-*/
-SWITCH_DECLARE(switch_status_t) switch_regex_match(char *target, char *expression);
 
 /*!
   \brief Play a sound and gather digits with the number of retries specified if the user doesn't give digits in the set time
@@ -246,23 +246,18 @@
   \note to test for digit capture failure look for \\0 in the first position of the buffer
 */
 SWITCH_DECLARE(switch_status_t) switch_play_and_get_digits(switch_core_session_t *session,
-                                                           uint32_t min_digits,
-                                                           uint32_t max_digits,
-                                                           uint32_t max_tries,
-                                                           uint32_t timeout,
-                                                           char* valid_terminators,
-                                                           char* audio_file,
-                                                           char* bad_input_audio_file,
-                                                           void* digit_buffer,
-                                                           uint32_t digit_buffer_length,
-                                                           char* digits_regex);
+														   uint32_t min_digits,
+														   uint32_t max_digits,
+														   uint32_t max_tries,
+														   uint32_t timeout,
+														   char *valid_terminators,
+														   char *audio_file,
+														   char *bad_input_audio_file, void *digit_buffer, uint32_t digit_buffer_length,
+														   char *digits_regex);
 
 SWITCH_DECLARE(switch_status_t) switch_ivr_speak_text_handle(switch_core_session_t *session,
-                                                             switch_speech_handle_t *sh,
-                                                             switch_codec_t *codec,
-                                                             switch_timer_t *timer,
-                                                             char *text,
-                                                             switch_input_args_t *args);
+															 switch_speech_handle_t *sh,
+															 switch_codec_t *codec, switch_timer_t *timer, char *text, switch_input_args_t *args);
 
 /*!
   \brief Speak given text with given tts engine
@@ -270,18 +265,12 @@
   \param tts_name the desired tts module
   \param voice_name the desired voice
   \param rate the sample rate
-  \param dtmf_callback code to execute if any dtmf is dialed during the audio
   \param text the text to speak
-  \param buf an option data pointer to pass to the callback or a string to put encountered digits in
-  \param buflen the len of buf
+  \param args arguements to pass for callbacks etc
   \return SWITCH_STATUS_SUCCESS if all is well
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_speak_text(switch_core_session_t *session, 
-													  char *tts_name,
-													  char *voice_name,
-													  uint32_t rate,
-													  char *text,
-                                                      switch_input_args_t *args);
+SWITCH_DECLARE(switch_status_t) switch_ivr_speak_text(switch_core_session_t *session,
+													  char *tts_name, char *voice_name, uint32_t rate, char *text, switch_input_args_t *args);
 
 /*!
   \brief Make an outgoing call
@@ -295,6 +284,7 @@
   \param cid_num_override override the caller id number
   \param caller_profile_override override the entire calling caller profile
   \return SWITCH_STATUS_SUCCESS if bleg is a running session.
+  \note bleg will be read locked which must be unlocked with switch_core_session_rwunlock() before losing scope
 */
 SWITCH_DECLARE(switch_status_t) switch_ivr_originate(switch_core_session_t *session,
 													 switch_core_session_t **bleg,
@@ -302,23 +292,20 @@
 													 char *bridgeto,
 													 uint32_t timelimit_sec,
 													 const switch_state_handler_table_t *table,
-													 char *cid_name_override,
-													 char *cid_num_override,
-													 switch_caller_profile_t *caller_profile_override);
+													 char *cid_name_override, char *cid_num_override, switch_caller_profile_t *caller_profile_override);
 
 /*!
   \brief Bridge Audio from one session to another
   \param session one session
   \param peer_session the other session
-  \param dtmf_callback code to execute if any dtmf is dialed during the bridge
+  \param dtmf_callback a callback for messages and dtmf
   \param session_data data to pass to the DTMF callback for session
   \param peer_session_data data to pass to the DTMF callback for peer_session
   \return SWITCH_STATUS_SUCCESS if all is well
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_multi_threaded_bridge(switch_core_session_t *session, 
+SWITCH_DECLARE(switch_status_t) switch_ivr_multi_threaded_bridge(switch_core_session_t *session,
 																 switch_core_session_t *peer_session,
-																 switch_input_callback_function_t dtmf_callback,
-																 void *session_data,
+																 switch_input_callback_function_t dtmf_callback, void *session_data,
 																 void *peer_session_data);
 
 /*!
@@ -339,6 +326,28 @@
 SWITCH_DECLARE(switch_status_t) switch_ivr_session_transfer(switch_core_session_t *session, char *extension, char *dialplan, char *context);
 
 /*!
+  \brief Transfer an existing session to another location in the future
+  \param runtime the time (int epoch seconds) to transfer the call
+  \param uuid the uuid of the session to transfer
+  \param extension the new extension
+  \param dialplan the new dialplan (OPTIONAL, may be NULL)
+  \param context the new context (OPTIONAL, may be NULL)
+  \return the id of the task
+*/
+SWITCH_DECLARE(uint32_t) switch_ivr_schedule_transfer(time_t runtime, char *uuid, char *extension, char *dialplan, char *context);
+
+
+/*!
+  \brief Hangup an existing session in the future
+  \param runtime the time (int epoch seconds) to transfer the call
+  \param uuid the uuid of the session to hangup
+  \param cause the hanup cause code
+  \param bleg hangup up the B-Leg if possible
+  \return the id of the task
+*/
+SWITCH_DECLARE(uint32_t) switch_ivr_schedule_hangup(time_t runtime, char *uuid, switch_call_cause_t cause, switch_bool_t bleg);
+
+/*!
   \brief Bridge two existing sessions
   \param originator_uuid the uuid of the originator
   \param originatee_uuid the uuid of the originator
@@ -391,6 +400,16 @@
 SWITCH_DECLARE(switch_status_t) switch_ivr_unhold(switch_core_session_t *session);
 
 /*!
+  \brief Signal the session to broadcast audio in the future
+  \param runtime when (in epoch time) to run the broadcast
+  \param uuid the uuid of the session to broadcast on
+  \param path the path data of the broadcast "/path/to/file.wav [<timer name>]" or "speak:<engine>|<voice>|<Text to say>"
+  \param flags flags to send to the request (SMF_ECHO_BRIDGED to send the broadcast to both sides of the call)
+  \return the id of the task
+*/
+SWITCH_DECLARE(uint32_t) switch_ivr_schedule_broadcast(time_t runtime, char *uuid, char *path, switch_media_flag_t flags);
+
+/*!
   \brief Signal the session to broadcast audio
   \param uuid the uuid of the session to broadcast on
   \param path the path data of the broadcast "/path/to/file.wav [<timer name>]" or "speak:<engine>|<voice>|<Text to say>"
@@ -411,24 +430,24 @@
 
 /******************************************************************************************************/
 
-struct switch_ivr_digit_stream_parser;
-typedef struct switch_ivr_digit_stream_parser switch_ivr_digit_stream_parser_t;
-struct switch_ivr_digit_stream;
-typedef struct switch_ivr_digit_stream switch_ivr_digit_stream_t;
+	 struct switch_ivr_digit_stream_parser;
+	 typedef struct switch_ivr_digit_stream_parser switch_ivr_digit_stream_parser_t;
+	 struct switch_ivr_digit_stream;
+	 typedef struct switch_ivr_digit_stream switch_ivr_digit_stream_t;
 /*!
   \brief Create a digit stream parser object
   \param pool the pool to use for the new hash
   \param parser a pointer to the object pointer
   \return SWITCH_STATUS_SUCCESS if all is well 
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_new(switch_memory_pool_t *pool, switch_ivr_digit_stream_parser_t **parser);
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_new(switch_memory_pool_t *pool, switch_ivr_digit_stream_parser_t ** parser);
 
 /*!
   \brief Destroy a digit stream parser object
   \param parser a pointer to the parser object
   \return SWITCH_STATUS_SUCCESS if all is well 
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_destroy(switch_ivr_digit_stream_parser_t *parser);
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_destroy(switch_ivr_digit_stream_parser_t * parser);
 
 /*!
   \brief Create a new digit stream object
@@ -436,14 +455,14 @@
   \param stream a pointer to the stream object pointer
   \return NULL if no match found or consumer data that was associated with a given digit string when matched
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_new(switch_ivr_digit_stream_parser_t *parser, switch_ivr_digit_stream_t **stream);
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_new(switch_ivr_digit_stream_parser_t * parser, switch_ivr_digit_stream_t ** stream);
 
 /*!
   \brief Destroys a digit stream object
   \param stream a pointer to the stream object
   \return NULL if no match found or consumer data that was associated with a given digit string when matched
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_destroy(switch_ivr_digit_stream_t *stream);
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_destroy(switch_ivr_digit_stream_t * stream);
 
 /*!
   \brief Set a digit string to action mapping
@@ -452,7 +471,7 @@
   \param data consumer data attached to this digit string
   \return SWITCH_STATUS_SUCCESS if all is well 
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_set_event(switch_ivr_digit_stream_parser_t *parser, char *digits, void *data);
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_set_event(switch_ivr_digit_stream_parser_t * parser, char *digits, void *data);
 
 /*!
   \brief Delete a string to action mapping
@@ -460,22 +479,23 @@
   \param digits the digit string to be removed from the map
   \return SWITCH_STATUS_SUCCESS if all is well 
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_del_event(switch_ivr_digit_stream_parser_t *parser, char *digits);
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_del_event(switch_ivr_digit_stream_parser_t * parser, char *digits);
 
 /*!
   \brief Feed digits collected into the stream for event match testing
   \param parser a pointer to the parser object created by switch_ivr_digit_stream_parser_new
+  \param stream a stream to write data to
   \param digit a digit to collect and test against the map of digit strings
   \return NULL if no match found or consumer data that was associated with a given digit string when matched
 */
-SWITCH_DECLARE(void *) switch_ivr_digit_stream_parser_feed(switch_ivr_digit_stream_parser_t *parser, switch_ivr_digit_stream_t *stream, char digit);
+SWITCH_DECLARE(void *) switch_ivr_digit_stream_parser_feed(switch_ivr_digit_stream_parser_t * parser, switch_ivr_digit_stream_t * stream, char digit);
 
 /*!
   \brief Reset the collected digit stream to nothing
   \param stream a pointer to the parser stream object created by switch_ivr_digit_stream_new
   \return SWITCH_STATUS_SUCCESS if all is well 
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_reset(switch_ivr_digit_stream_t *stream);
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_reset(switch_ivr_digit_stream_t * stream);
 
 /*!
   \brief Set a digit string terminator
@@ -483,7 +503,7 @@
   \param digit the terminator digit
   \return SWITCH_STATUS_SUCCESS if all is well 
 */
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_set_terminator(switch_ivr_digit_stream_parser_t *parser, char digit);
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_set_terminator(switch_ivr_digit_stream_parser_t * parser, char digit);
 
 
 /******************************************************************************************************/
@@ -499,28 +519,28 @@
  * @{
  */
 
-typedef enum {
-	SWITCH_IVR_MENU_FLAG_FALLTOMAIN = (1 << 0),
-	SWITCH_IVR_MENU_FLAG_FREEPOOL = (1 << 1),
-	SWITCH_IVR_MENU_FLAG_STACK = (1 << 2),
-} switch_ivr_menu_flags;
+	 typedef enum {
+		 SWITCH_IVR_MENU_FLAG_FALLTOMAIN = (1 << 0),
+		 SWITCH_IVR_MENU_FLAG_FREEPOOL = (1 << 1),
+		 SWITCH_IVR_MENU_FLAG_STACK = (1 << 2),
+	 } switch_ivr_menu_flags;
 /* Actions are either set in switch_ivr_menu_bind_function or returned by a callback */
-typedef enum {
-	SWITCH_IVR_ACTION_DIE, 		/* Exit the menu.                  */
-	SWITCH_IVR_ACTION_EXECMENU,	/* Goto another menu in the stack. */
-	SWITCH_IVR_ACTION_EXECAPP,	/* Execute an application.         */
-	SWITCH_IVR_ACTION_PLAYSOUND,	/* Play a sound.                   */
-	SWITCH_IVR_ACTION_SAYTEXT,	/* say text.                       */
-	SWITCH_IVR_ACTION_SAYPHRASE,	/* say a phrase macro.                       */
-	SWITCH_IVR_ACTION_BACK,		/* Go back 1 menu.                 */
-	SWITCH_IVR_ACTION_TOMAIN,	/* Go back to the top level menu.  */
-	SWITCH_IVR_ACTION_TRANSFER,	/* Transfer caller to another ext. */
-	SWITCH_IVR_ACTION_NOOP,		/* No operation                    */
-} switch_ivr_action_t;
-struct switch_ivr_menu;
-typedef switch_ivr_action_t switch_ivr_menu_action_function_t(struct switch_ivr_menu *, char *, char *, size_t, void *);
-typedef struct switch_ivr_menu switch_ivr_menu_t;
-typedef struct switch_ivr_menu_action switch_ivr_menu_action_t;
+	 typedef enum {
+		 SWITCH_IVR_ACTION_DIE,	/* Exit the menu.                  */
+		 SWITCH_IVR_ACTION_EXECMENU,	/* Goto another menu in the stack. */
+		 SWITCH_IVR_ACTION_EXECAPP,	/* Execute an application.         */
+		 SWITCH_IVR_ACTION_PLAYSOUND,	/* Play a sound.                   */
+		 SWITCH_IVR_ACTION_SAYTEXT,	/* say text.                       */
+		 SWITCH_IVR_ACTION_SAYPHRASE,	/* say a phrase macro.                       */
+		 SWITCH_IVR_ACTION_BACK,	/* Go back 1 menu.                 */
+		 SWITCH_IVR_ACTION_TOMAIN,	/* Go back to the top level menu.  */
+		 SWITCH_IVR_ACTION_TRANSFER,	/* Transfer caller to another ext. */
+		 SWITCH_IVR_ACTION_NOOP,	/* No operation                    */
+	 } switch_ivr_action_t;
+	 struct switch_ivr_menu;
+	 typedef switch_ivr_action_t switch_ivr_menu_action_function_t(struct switch_ivr_menu *, char *, char *, size_t, void *);
+	 typedef struct switch_ivr_menu switch_ivr_menu_t;
+	 typedef struct switch_ivr_menu_action switch_ivr_menu_action_t;
 /******************************************************************************************************/
 
 /*!
@@ -530,28 +550,26 @@
  *\param name A pointer to the name of this menu.
  *\param greeting_sound Optional pointer to a main sound (press 1 for this 2 for that).
  *\param short_greeting_sound Optional pointer to a shorter main sound for subsequent loops.
- *\param exit_sound Optional pointer to a sound to play upon exiting the menu
+ *\param exit_sound Optional pointer to a sound to play upon exiting the menu.
  *\param invalid_sound Optional pointer to a sound to play after invalid input.
- *\param tts_engine Text To Speech engine name
- *\param tts_voice Text To Speech engine voice name
+ *\param tts_engine Text To Speech engine name.
+ *\param tts_voice Text To Speech engine voice name.
+ *\param phrase_lang the language to use for the phrase macros.
  *\param timeout A number of milliseconds to pause before looping.
  *\param max_failures Maximum number of failures to withstand before hangingup This resets everytime you enter the menu.
- *\param pool memory pool (NULL to create one)
- *\return SWITCH_STATUS_SUCCESS if the menu was created
+ *\param pool memory pool (NULL to create one).
+ *\return SWITCH_STATUS_SUCCESS if the menu was created.
  */
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_init(switch_ivr_menu_t **new_menu,
-													 switch_ivr_menu_t *main,
-													 const char *name, 
-													 const char *greeting_sound, 
+SWITCH_DECLARE(switch_status_t) switch_ivr_menu_init(switch_ivr_menu_t ** new_menu,
+													 switch_ivr_menu_t * main,
+													 const char *name,
+													 const char *greeting_sound,
 													 const char *short_greeting_sound,
 													 const char *exit_sound,
-													 const char *invalid_sound, 
+													 const char *invalid_sound,
 													 const char *tts_engine,
 													 const char *tts_voice,
-													 const char *phrase_lang,
-													 int timeout,
-													 int max_failures, 
-													 switch_memory_pool_t *pool);
+													 const char *phrase_lang, int timeout, int max_failures, switch_memory_pool_t *pool);
 
 /*!
  *\brief switch_ivr_menu_bind_action: Bind a keystroke to an action.
@@ -561,7 +579,7 @@
  *\param bind KeyStrokes to bind the action to.
  *\return SWUTCH_STATUS_SUCCESS if the action was binded
  */
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_bind_action(switch_ivr_menu_t *menu, switch_ivr_action_t ivr_action, const char *arg, const char *bind);
+SWITCH_DECLARE(switch_status_t) switch_ivr_menu_bind_action(switch_ivr_menu_t * menu, switch_ivr_action_t ivr_action, const char *arg, const char *bind);
 
 
 /*!
@@ -575,7 +593,8 @@
  *\note The function returns an switch_ivr_action_t enum of what you want to do. and looks to your buffer for args.
  *\return SWUTCH_STATUS_SUCCESS if the function was binded
  */
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_bind_function(switch_ivr_menu_t *menu, switch_ivr_menu_action_function_t *function, const char *arg, const char *bind);
+SWITCH_DECLARE(switch_status_t) switch_ivr_menu_bind_function(switch_ivr_menu_t * menu,
+															  switch_ivr_menu_action_function_t * function, const char *arg, const char *bind);
 
 
 /*!
@@ -586,17 +605,17 @@
  *\param obj A void pointer to an object you want to make avaliable to your callback functions that you may have binded with switch_ivr_menu_bind_function.
  *\return SWITCH_STATUS_SUCCESS if all is well
  */
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_execute(switch_core_session_t *session, switch_ivr_menu_t *stack, char *name, void *obj);
+SWITCH_DECLARE(switch_status_t) switch_ivr_menu_execute(switch_core_session_t *session, switch_ivr_menu_t * stack, char *name, void *obj);
 
 /*!
  *\brief free a stack of menu objects.
  *\param stack The top level menu you wish to destroy.
  *\return SWITCH_STATUS_SUCCESS if the object was a top level menu and it was freed
  */
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_free(switch_ivr_menu_t *stack);
+SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_free(switch_ivr_menu_t * stack);
 
-struct switch_ivr_menu_xml_ctx;
-typedef struct switch_ivr_menu_xml_ctx switch_ivr_menu_xml_ctx_t;
+	 struct switch_ivr_menu_xml_ctx;
+	 typedef struct switch_ivr_menu_xml_ctx switch_ivr_menu_xml_ctx_t;
 /*!
  *\brief Build a menu stack from an xml source
  *\param xml_menu_ctx The XML menu parser context previously created by switch_ivr_menu_stack_xml_init
@@ -605,10 +624,8 @@
  *\param xml_menu The xml Menu source of the menu to be created
  *\return SWITCH_STATUS_SUCCESS if all is well
  */
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_xml_build(switch_ivr_menu_xml_ctx_t *xml_menu_ctx,
-                                                                switch_ivr_menu_t **menu_stack,
-                                                                switch_xml_t xml_menus,
-                                                                switch_xml_t xml_menu);
+SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_xml_build(switch_ivr_menu_xml_ctx_t * xml_menu_ctx,
+																switch_ivr_menu_t ** menu_stack, switch_xml_t xml_menus, switch_xml_t xml_menu);
 
 /*!
  *\param xml_menu_ctx The XML menu parser context previously created by switch_ivr_menu_stack_xml_init
@@ -616,28 +633,22 @@
  *\param function The menu function callback that will be executed when menu digits are bound to this name
  *\return SWITCH_STATUS_SUCCESS if all is well
  */
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_xml_add_custom(switch_ivr_menu_xml_ctx_t *xml_menu_ctx,
-										char *name,
-										switch_ivr_menu_action_function_t *function);
+SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_xml_add_custom(switch_ivr_menu_xml_ctx_t * xml_menu_ctx,
+																	 char *name, switch_ivr_menu_action_function_t * function);
 
 /*!
  *\param xml_menu_ctx A pointer of a XML menu parser context to be created
  *\param pool memory pool (NULL to create one)
  *\return SWITCH_STATUS_SUCCESS if all is well
  */
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_xml_init(switch_ivr_menu_xml_ctx_t **xml_menu_ctx, switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_xml_init(switch_ivr_menu_xml_ctx_t ** xml_menu_ctx, switch_memory_pool_t *pool);
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_phrase_macro(switch_core_session_t *session,
-                                                        char *macro_name,
-                                                        char *data,
-                                                        char *lang,
-                                                        switch_input_args_t *args);
+SWITCH_DECLARE(switch_status_t) switch_ivr_phrase_macro(switch_core_session_t *session, char *macro_name, char *data, char *lang,
+														switch_input_args_t *args);
 /** @} */
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_loadable_module.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_loadable_module.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_loadable_module.h	Tue Apr 24 10:14:28 2007
@@ -44,15 +44,13 @@
 #include <switch.h>
 
 SWITCH_BEGIN_EXTERN_C
-
 /*!
   \defgroup mods Loadable Module Functions
   \ingroup core1
   \{ 
 */
-
 /*! \brief The abstraction of a loadable module */
-struct switch_loadable_module_interface {
+	struct switch_loadable_module_interface {
 	/*! the name of the module */
 	const char *module_name;
 	/*! the table of endpoints the module has implmented */
@@ -79,6 +77,8 @@
 	const switch_say_interface_t *say_interface;
 	/*! the table of asr interfaces the module has implmented */
 	const switch_asr_interface_t *asr_interface;
+	/*! the table of management interfaces the module has implmented */
+	const switch_management_interface_t *management_interface;
 };
 
 /*!
@@ -123,9 +123,9 @@
   \note only use this function if you are making a module that in turn gateways module loading to another technology
  */
 SWITCH_DECLARE(switch_status_t) switch_loadable_module_build_dynamic(char *filename,
-																   switch_module_load_t switch_module_load,
-																   switch_module_runtime_t switch_module_runtime,
-																   switch_module_shutdown_t switch_module_shutdown);
+																	 switch_module_load_t switch_module_load,
+																	 switch_module_runtime_t switch_module_runtime,
+																	 switch_module_shutdown_t switch_module_shutdown);
 
 /*!
   \brief Retrieve the timer interface by it's registered name
@@ -190,6 +190,12 @@
  */
 SWITCH_DECLARE(switch_say_interface_t *) switch_loadable_module_get_say_interface(char *name);
 
+/*!
+  \brief Retrieve the management interface by it's registered name
+  \param relative_oid the relative oid of the management interface
+  \return the desired management interface
+ */
+SWITCH_DECLARE(switch_management_interface_t *) switch_loadable_module_get_management_interface(char *relative_oid);
 
 /*!
   \brief Retrieve the list of loaded codecs into an array
@@ -198,8 +204,7 @@
   \param arraylen the max size in elements of the array
   \return the number of elements added to the array
  */
-SWITCH_DECLARE(int) switch_loadable_module_get_codecs(switch_memory_pool_t *pool, const switch_codec_implementation_t **array,
-													  int arraylen);
+SWITCH_DECLARE(int) switch_loadable_module_get_codecs(switch_memory_pool_t *pool, const switch_codec_implementation_t **array, int arraylen);
 
 
 /*!
@@ -211,8 +216,7 @@
   \return the number of elements added to the array
   \note this function only considers codecs that are listed in the "prefs" array and ignores the rest.
 */
-SWITCH_DECLARE(int) switch_loadable_module_get_codecs_sorted(const switch_codec_implementation_t **array,
-															 int arraylen, char **prefs, int preflen);
+SWITCH_DECLARE(int) switch_loadable_module_get_codecs_sorted(const switch_codec_implementation_t **array, int arraylen, char **prefs, int preflen);
 
 /*!
   \brief Execute a registered API command
@@ -232,7 +236,7 @@
   \param fname the file name of the module
   \return the status
 */
-SWITCH_DECLARE(switch_status_t) switch_loadable_module_load_module(char *dir, char *fname);
+SWITCH_DECLARE(switch_status_t) switch_loadable_module_load_module(char *dir, char *fname, switch_bool_t runtime);
 
 /* Prototypes of module interface functions */
 
@@ -258,9 +262,7 @@
 ///\}
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_log.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_log.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_log.h	Tue Apr 24 10:14:28 2007
@@ -41,32 +41,32 @@
 #include <switch.h>
 
 SWITCH_BEGIN_EXTERN_C
-
 ///\defgroup log Logger Routines
 ///\ingroup core1
 ///\{
-
-
 /*! \brief Log Data
  */
-typedef struct {
+	typedef struct {
 	/*! The complete log message */
 	char *data;
-	/*! The file where the message originated */	
+	/*! The file where the message originated */
 	char *file;
-	/*! The line number where the message originated */	
+	/*! The line number where the message originated */
 	uint32_t line;
-	/*! The function where the message originated */	
+	/*! The function where the message originated */
 	char *func;
-	/*! The log level of the message */	
+	/*! The log level of the message */
 	switch_log_level_t level;
 	/*! The time when the log line was sent */
 	switch_time_t timestamp;
-	/*! A pointer to where the actual content of the message starts (skipping past the preformatted portion) */	
+	/*! A pointer to where the actual content of the message starts (skipping past the preformatted portion) */
 	char *content;
+
+	/* To maintain abi, only add new elements to the end of this struct and do not delete any elements */
+
 } switch_log_node_t;
 
-typedef switch_status_t (*switch_log_function_t)(const switch_log_node_t *node, switch_log_level_t level);
+typedef switch_status_t (*switch_log_function_t) (const switch_log_node_t *node, switch_log_level_t level);
 
 
 /*! 
@@ -94,7 +94,8 @@
   \param ... variable args
   \note there are channel macros to supply the first 4 parameters
 */
-SWITCH_DECLARE(void) switch_log_printf(switch_text_channel_t channel, const char *file, const char *func, int line, switch_log_level_t level, const char *fmt, ...) PRINTF_FUNCTION(6,7);
+SWITCH_DECLARE(void) switch_log_printf(switch_text_channel_t channel, const char *file, const char *func, int line,
+									   switch_log_level_t level, const char *fmt, ...) PRINTF_FUNCTION(6, 7);
 
 /*! 
   \brief Shut down  the logging engine
@@ -118,9 +119,7 @@
 
 ///\}
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_module_interfaces.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_module_interfaces.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_module_interfaces.h	Tue Apr 24 10:14:28 2007
@@ -42,10 +42,9 @@
 #include <switch.h>
 
 SWITCH_BEGIN_EXTERN_C
-
 /*! \brief A table of functions to execute at various states 
 */
-struct switch_state_handler_table {
+	struct switch_state_handler_table {
 	/*! executed when the state changes to init */
 	switch_state_handler_t on_init;
 	/*! executed when the state changes to ring */
@@ -54,13 +53,13 @@
 	switch_state_handler_t on_execute;
 	/*! executed when the state changes to hangup */
 	switch_state_handler_t on_hangup;
-	/*! executed when the state changes to loopback*/
+	/*! executed when the state changes to loopback */
 	switch_state_handler_t on_loopback;
-	/*! executed when the state changes to transmit*/
+	/*! executed when the state changes to transmit */
 	switch_state_handler_t on_transmit;
-	/*! executed when the state changes to hold*/
+	/*! executed when the state changes to hold */
 	switch_state_handler_t on_hold;
-	/*! executed when the state changes to hibernate*/
+	/*! executed when the state changes to hibernate */
 	switch_state_handler_t on_hibernate;
 };
 
@@ -75,122 +74,35 @@
 	switch_event_t *event;
 };
 
-/*! \brief Node in which to store custom outgoing channel callback hooks */
-struct switch_io_event_hook_outgoing_channel {
-	/*! the outgoing channel callback hook*/
-	switch_outgoing_channel_hook_t outgoing_channel;
-	struct switch_io_event_hook_outgoing_channel *next;
-};
-
-/*! \brief Node in which to store custom answer channel callback hooks */
-struct switch_io_event_hook_answer_channel {
-	/*! the answer channel callback hook*/
-	switch_answer_channel_hook_t answer_channel;
-	struct switch_io_event_hook_answer_channel *next;
-};
-
-/*! \brief Node in which to store custom receive message callback hooks */
-struct switch_io_event_hook_receive_message {
-	/*! the answer channel callback hook*/
-	switch_receive_message_hook_t receive_message;
-	struct switch_io_event_hook_receive_message *next;
-};
-
-/*! \brief Node in which to store custom receive message callback hooks */
-struct switch_io_event_hook_receive_event {
-	/*! the answer channel callback hook*/
-	switch_receive_event_hook_t receive_event;
-	struct switch_io_event_hook_receive_event *next;
-};
-
-/*! \brief Node in which to store custom read frame channel callback hooks */
-struct switch_io_event_hook_read_frame {
-	/*! the read frame channel callback hook*/
-	switch_read_frame_hook_t read_frame;
-	struct switch_io_event_hook_read_frame *next;
-};
-
-/*! \brief Node in which to store custom write_frame channel callback hooks */
-struct switch_io_event_hook_write_frame {
-	/*! the write_frame channel callback hook*/
-	switch_write_frame_hook_t write_frame;
-	struct switch_io_event_hook_write_frame *next;
-};
-
-/*! \brief Node in which to store custom kill channel callback hooks */
-struct switch_io_event_hook_kill_channel {
-	/*! the kill channel callback hook*/
-	switch_kill_channel_hook_t kill_channel;
-	struct switch_io_event_hook_kill_channel *next;
-};
-
-/*! \brief Node in which to store custom waitfor read channel callback hooks */
-struct switch_io_event_hook_waitfor_read {
-	/*! the waitfor read channel callback hook*/
-	switch_waitfor_read_hook_t waitfor_read;
-	struct switch_io_event_hook_waitfor_read *next;
-};
-
-/*! \brief Node in which to store custom waitfor write channel callback hooks */
-struct switch_io_event_hook_waitfor_write {
-	/*! the waitfor write channel callback hook*/
-	switch_waitfor_write_hook_t waitfor_write;
-	struct switch_io_event_hook_waitfor_write *next;
-};
-
-/*! \brief Node in which to store custom send dtmf channel callback hooks */
-struct switch_io_event_hook_send_dtmf {
-	/*! the send dtmf channel callback hook*/
-	switch_send_dtmf_hook_t send_dtmf;
-	struct switch_io_event_hook_send_dtmf *next;
-};
-
-/*! \brief A table of lists of io_event_hooks to store the event hooks associated with a session */
-struct switch_io_event_hooks {
-	/*! a list of outgoing channel hooks */
-	switch_io_event_hook_outgoing_channel_t *outgoing_channel;
-	/*! a list of answer channel hooks */
-	switch_io_event_hook_answer_channel_t *answer_channel;
-	/*! a list of receive message hooks */
-	switch_io_event_hook_receive_message_t *receive_message;
-	/*! a list of queue message hooks */
-	switch_io_event_hook_receive_event_t *receive_event;
-	/*! a list of read frame hooks */
-	switch_io_event_hook_read_frame_t *read_frame;
-	/*! a list of write frame hooks */
-	switch_io_event_hook_write_frame_t *write_frame;
-	/*! a list of kill channel hooks */
-	switch_io_event_hook_kill_channel_t *kill_channel;
-	/*! a list of wait for read hooks */
-	switch_io_event_hook_waitfor_read_t *waitfor_read;
-	/*! a list of wait for write hooks */
-	switch_io_event_hook_waitfor_write_t *waitfor_write;
-	/*! a list of send dtmf hooks */
-	switch_io_event_hook_send_dtmf_t *send_dtmf;
-};
+struct switch_io_event_hooks;
+
 
 /*! \brief A table of i/o routines that an endpoint interface can implement */
 struct switch_io_routines {
 	/*! creates an outgoing session from given session, caller profile */
-	switch_call_cause_t (*outgoing_channel)(switch_core_session_t *, switch_caller_profile_t *, switch_core_session_t **, switch_memory_pool_t *);
-	/*! answers the given session's channel */
-	switch_status_t (*answer_channel)(switch_core_session_t *);
+	switch_call_cause_t (*outgoing_channel) (switch_core_session_t *, switch_caller_profile_t *, switch_core_session_t **, switch_memory_pool_t **);
 	/*! read a frame from a session */
-	switch_status_t (*read_frame)(switch_core_session_t *, switch_frame_t **, int, switch_io_flag_t, int);
+	switch_status_t (*read_frame) (switch_core_session_t *, switch_frame_t **, int, switch_io_flag_t, int);
 	/*! write a frame to a session */
-	switch_status_t (*write_frame)(switch_core_session_t *, switch_frame_t *, int, switch_io_flag_t, int);
+	switch_status_t (*write_frame) (switch_core_session_t *, switch_frame_t *, int, switch_io_flag_t, int);
 	/*! send a kill signal to the session's channel */
-	switch_status_t (*kill_channel)(switch_core_session_t *, int);
+	switch_status_t (*kill_channel) (switch_core_session_t *, int);
 	/*! wait for the session's channel to be ready to read audio */
-	switch_status_t (*waitfor_read)(switch_core_session_t *, int, int);
+	switch_status_t (*waitfor_read) (switch_core_session_t *, int, int);
 	/*! wait for the session's channel to be ready to write audio */
-	switch_status_t (*waitfor_write)(switch_core_session_t *, int, int);
+	switch_status_t (*waitfor_write) (switch_core_session_t *, int, int);
 	/*! send a string of DTMF digits to a session's channel */
-	switch_status_t (*send_dtmf)(switch_core_session_t *, char *);
-	/*! receive a message from another session*/
-	switch_status_t (*receive_message)(switch_core_session_t *, switch_core_session_message_t *);
-	/*! queue a message for another session*/
-	switch_status_t (*receive_event)(switch_core_session_t *, switch_event_t *);
+	switch_status_t (*send_dtmf) (switch_core_session_t *, char *);
+	/*! receive a message from another session */
+	switch_status_t (*receive_message) (switch_core_session_t *, switch_core_session_message_t *);
+	/*! queue a message for another session */
+	switch_status_t (*receive_event) (switch_core_session_t *, switch_event_t *);
+	/*! change a sessions channel state */
+	switch_status_t (*state_change) (switch_core_session_t *);
+	/*! read a video frame from a session */
+	switch_status_t (*read_video_frame) (switch_core_session_t *, switch_frame_t **, int, switch_io_flag_t, int);
+	/*! write a video frame to a session */
+	switch_status_t (*write_video_frame) (switch_core_session_t *, switch_frame_t *, int, switch_io_flag_t, int);
 };
 
 /*! \brief Abstraction of an module endpoint interface
@@ -225,7 +137,7 @@
 	/*! sample count to increment by on each cycle */
 	unsigned int samples;
 	/*! current sample count based on samples parameter */
-	unsigned int samplecount;
+	uint32_t samplecount;
 	/*! the timer interface provided from a loadable module */
 	switch_timer_interface_t *timer_interface;
 	/*! the timer's memory pool */
@@ -239,15 +151,15 @@
 	/*! the name of the interface */
 	const char *interface_name;
 	/*! function to allocate the timer */
-	switch_status_t (*timer_init)(switch_timer_t *);
+	switch_status_t (*timer_init) (switch_timer_t *);
 	/*! function to wait for one cycle to pass */
-	switch_status_t (*timer_next)(switch_timer_t *);
+	switch_status_t (*timer_next) (switch_timer_t *);
 	/*! function to step the timer one step */
-	switch_status_t (*timer_step)(switch_timer_t *);
+	switch_status_t (*timer_step) (switch_timer_t *);
 	/*! function to check if the current step has expired */
-	switch_status_t (*timer_check)(switch_timer_t *);
+	switch_status_t (*timer_check) (switch_timer_t *);
 	/*! function to deallocate the timer */
-	switch_status_t (*timer_destroy)(switch_timer_t *);
+	switch_status_t (*timer_destroy) (switch_timer_t *);
 	const struct switch_timer_interface *next;
 };
 
@@ -265,19 +177,19 @@
 	/*! the name of the interface */
 	const char *interface_name;
 	/*! function to open the file */
-	switch_status_t (*file_open)(switch_file_handle_t *, char *file_path);
+	switch_status_t (*file_open) (switch_file_handle_t *, char *file_path);
 	/*! function to close the file */
-	switch_status_t (*file_close)(switch_file_handle_t *);
+	switch_status_t (*file_close) (switch_file_handle_t *);
 	/*! function to read from the file */
-	switch_status_t (*file_read)(switch_file_handle_t *, void *data, switch_size_t *len);
+	switch_status_t (*file_read) (switch_file_handle_t *, void *data, switch_size_t *len);
 	/*! function to write from the file */
-	switch_status_t (*file_write)(switch_file_handle_t *, void *data, switch_size_t *len);
+	switch_status_t (*file_write) (switch_file_handle_t *, void *data, switch_size_t *len);
 	/*! function to seek to a certian position in the file */
-	switch_status_t (*file_seek)(switch_file_handle_t *, unsigned int *cur_pos, int64_t samples, int whence);
+	switch_status_t (*file_seek) (switch_file_handle_t *, unsigned int *cur_pos, int64_t samples, int whence);
 	/*! function to set meta data */
-	switch_status_t (*file_set_string)(switch_file_handle_t *fh, switch_audio_col_t col, const char *string);
+	switch_status_t (*file_set_string) (switch_file_handle_t *fh, switch_audio_col_t col, const char *string);
 	/*! function to get meta data */
-	switch_status_t (*file_get_string)(switch_file_handle_t *fh, switch_audio_col_t col, const char **string);
+	switch_status_t (*file_get_string) (switch_file_handle_t *fh, switch_audio_col_t col, const char **string);
 	/*! list of supported file extensions */
 	char **extens;
 	const struct switch_file_interface *next;
@@ -305,16 +217,17 @@
 	int seekable;
 	/*! the sample count of the file */
 	unsigned int sample_count;
-	/*! the speed of the file playback*/
+	/*! the speed of the file playback */
 	int speed;
 	/*! the handle's memory pool */
 	switch_memory_pool_t *memory_pool;
 	/*! private data for the format module to store handle specific info */
 	void *private_info;
+	char *handler;
 	int64_t pos;
 	switch_buffer_t *audio_buffer;
-    uint32_t thresh;
-    uint32_t silence_hits;
+	uint32_t thresh;
+	uint32_t silence_hits;
 };
 
 /*! \brief Abstract interface to an asr module */
@@ -322,27 +235,23 @@
 	/*! the name of the interface */
 	const char *interface_name;
 	/*! function to open the asr interface */
-	switch_status_t (*asr_open)(switch_asr_handle_t *ah,
-								char *codec,
-								int rate,
-								char *dest,
-								switch_asr_flag_t *flags);
+	switch_status_t (*asr_open) (switch_asr_handle_t *ah, char *codec, int rate, char *dest, switch_asr_flag_t *flags);
 	/*! function to load a grammar to the asr interface */
-	switch_status_t (*asr_load_grammar)(switch_asr_handle_t *ah, char *grammar, char *path);
+	switch_status_t (*asr_load_grammar) (switch_asr_handle_t *ah, char *grammar, char *path);
 	/*! function to unload a grammar to the asr interface */
-	switch_status_t (*asr_unload_grammar)(switch_asr_handle_t *ah, char *grammar);
+	switch_status_t (*asr_unload_grammar) (switch_asr_handle_t *ah, char *grammar);
 	/*! function to close the asr interface */
-	switch_status_t (*asr_close)(switch_asr_handle_t *ah, switch_asr_flag_t *flags);
-	/*! function to feed audio to the ASR*/
-	switch_status_t (*asr_feed)(switch_asr_handle_t *ah, void *data, unsigned int len, switch_asr_flag_t *flags);
-	/*! function to resume the ASR*/
-	switch_status_t (*asr_resume)(switch_asr_handle_t *ah);
-	/*! function to pause the ASR*/
-	switch_status_t (*asr_pause)(switch_asr_handle_t *ah);
-	/*! function to read results from the ASR*/
-	switch_status_t (*asr_check_results)(switch_asr_handle_t *ah, switch_asr_flag_t *flags);
-	/*! function to read results from the ASR*/
-	switch_status_t (*asr_get_results)(switch_asr_handle_t *ah, char **xmlstr, switch_asr_flag_t *flags);
+	switch_status_t (*asr_close) (switch_asr_handle_t *ah, switch_asr_flag_t *flags);
+	/*! function to feed audio to the ASR */
+	switch_status_t (*asr_feed) (switch_asr_handle_t *ah, void *data, unsigned int len, switch_asr_flag_t *flags);
+	/*! function to resume the ASR */
+	switch_status_t (*asr_resume) (switch_asr_handle_t *ah);
+	/*! function to pause the ASR */
+	switch_status_t (*asr_pause) (switch_asr_handle_t *ah);
+	/*! function to read results from the ASR */
+	switch_status_t (*asr_check_results) (switch_asr_handle_t *ah, switch_asr_flag_t *flags);
+	/*! function to read results from the ASR */
+	switch_status_t (*asr_get_results) (switch_asr_handle_t *ah, char **xmlstr, switch_asr_flag_t *flags);
 	const struct switch_asr_interface *next;
 };
 
@@ -352,11 +261,11 @@
 	const switch_asr_interface_t *asr_interface;
 	/*! flags to control behaviour */
 	uint32_t flags;
-	/*! The Name*/
+	/*! The Name */
 	char *name;
-	/*! The Codec*/
+	/*! The Codec */
 	char *codec;
-	/*! The Rate*/
+	/*! The Rate */
 	uint32_t rate;
 	char *grammar;
 	/*! the handle's memory pool */
@@ -370,24 +279,17 @@
 	/*! the name of the interface */
 	const char *interface_name;
 	/*! function to open the speech interface */
-	switch_status_t (*speech_open)(switch_speech_handle_t *sh,
-								 char *voice_name, 
-								 int rate,
-								 switch_speech_flag_t *flags);
+	switch_status_t (*speech_open) (switch_speech_handle_t *sh, char *voice_name, int rate, switch_speech_flag_t *flags);
 	/*! function to close the speech interface */
-	switch_status_t (*speech_close)(switch_speech_handle_t *, switch_speech_flag_t *flags);
-	/*! function to feed audio to the ASR*/
-	switch_status_t (*speech_feed_tts)(switch_speech_handle_t *sh, char *text, switch_speech_flag_t *flags);
-	/*! function to read audio from the TTS*/
-	switch_status_t (*speech_read_tts)(switch_speech_handle_t *sh,
-									 void *data,
-									 switch_size_t *datalen,
-									 uint32_t *rate,
-									 switch_speech_flag_t *flags);
-	void (*speech_flush_tts)(switch_speech_handle_t *sh);
-	void (*speech_text_param_tts)(switch_speech_handle_t *sh, char *param, char *val);
-	void (*speech_numeric_param_tts)(switch_speech_handle_t *sh, char *param, int val);
-	void (*speech_float_param_tts)(switch_speech_handle_t *sh, char *param, double val);
+	switch_status_t (*speech_close) (switch_speech_handle_t *, switch_speech_flag_t *flags);
+	/*! function to feed audio to the ASR */
+	switch_status_t (*speech_feed_tts) (switch_speech_handle_t *sh, char *text, switch_speech_flag_t *flags);
+	/*! function to read audio from the TTS */
+	switch_status_t (*speech_read_tts) (switch_speech_handle_t *sh, void *data, switch_size_t *datalen, uint32_t * rate, switch_speech_flag_t *flags);
+	void (*speech_flush_tts) (switch_speech_handle_t *sh);
+	void (*speech_text_param_tts) (switch_speech_handle_t *sh, char *param, char *val);
+	void (*speech_numeric_param_tts) (switch_speech_handle_t *sh, char *param, int val);
+	void (*speech_float_param_tts) (switch_speech_handle_t *sh, char *param, double val);
 
 	const struct switch_speech_interface *next;
 };
@@ -399,9 +301,9 @@
 	const switch_speech_interface_t *speech_interface;
 	/*! flags to control behaviour */
 	uint32_t flags;
-	/*! The Name*/
+	/*! The Name */
 	char *name;
-	/*! The Rate*/
+	/*! The Rate */
 	uint32_t rate;
 	uint32_t speed;
 	char voice[80];
@@ -417,7 +319,7 @@
 	/*! the name of the interface */
 	const char *interface_name;
 	/*! function to pass down to the module */
-    switch_say_callback_t say_function;
+	switch_say_callback_t say_function;
 	const struct switch_say_interface *next;
 };
 
@@ -426,25 +328,34 @@
 	/*! the name of the interface */
 	const char *interface_name;
 	/*! function to open the directory interface */
-	switch_status_t (*chat_send)(char *proto, char *from, char *to, char *subject, char *body, char *hint);
+	switch_status_t (*chat_send) (char *proto, char *from, char *to, char *subject, char *body, char *hint);
 	const struct switch_chat_interface *next;
 };
 
+/*! \brief Abstract interface to a management module */
+struct switch_management_interface {
+	/*! the name of the interface */
+	const char *relative_oid;
+	/*! function to open the directory interface */
+	switch_status_t (*management_function) (char *relative_oid, switch_management_action_t action, char *data, switch_size_t datalen);
+	const struct switch_management_interface *next;
+};
+
 /*! \brief Abstract interface to a directory module */
 struct switch_directory_interface {
 	/*! the name of the interface */
 	const char *interface_name;
 	/*! function to open the directory interface */
-	switch_status_t (*directory_open)(switch_directory_handle_t *dh, char *source, char *dsn, char *passwd);
+	switch_status_t (*directory_open) (switch_directory_handle_t *dh, char *source, char *dsn, char *passwd);
 	/*! function to close the directory interface */
-	switch_status_t (*directory_close)(switch_directory_handle_t *dh);
+	switch_status_t (*directory_close) (switch_directory_handle_t *dh);
 	/*! function to query the directory interface */
-	switch_status_t (*directory_query)(switch_directory_handle_t *dh, char *base, char *query);
+	switch_status_t (*directory_query) (switch_directory_handle_t *dh, char *base, char *query);
 	/*! function to advance to the next record */
-	switch_status_t (*directory_next)(switch_directory_handle_t *dh);
+	switch_status_t (*directory_next) (switch_directory_handle_t *dh);
 	/*! function to advance to the next name/value pair in the current record */
-	switch_status_t (*directory_next_pair)(switch_directory_handle_t *dh, char **var, char **val);
-	
+	switch_status_t (*directory_next_pair) (switch_directory_handle_t *dh, char **var, char **val);
+
 	const struct switch_directory_interface *next;
 };
 
@@ -513,7 +424,7 @@
 	switch_codec_settings_t codec_settings;
 	/*! flags to modify behaviour */
 	uint32_t flags;
-	/*! the handle's memory pool*/
+	/*! the handle's memory pool */
 	switch_memory_pool_t *memory_pool;
 	/*! private data for the codec module to store handle specific info */
 	void *private_info;
@@ -548,29 +459,21 @@
 	/*! max number of frames to send in one network packet */
 	int max_frames_per_packet;
 	/*! function to initialize a codec handle using this implementation */
-	switch_status_t (*init)(switch_codec_t *, switch_codec_flag_t, const switch_codec_settings_t *codec_settings);
+	switch_status_t (*init) (switch_codec_t *, switch_codec_flag_t, const switch_codec_settings_t *codec_settings);
 	/*! function to encode raw data into encoded data */
-	switch_status_t (*encode)(switch_codec_t *codec,
-						 switch_codec_t *other_codec,
-						 void *decoded_data,
-						 uint32_t decoded_data_len,
-						 uint32_t decoded_rate,
-						 void *encoded_data,
-						 uint32_t *encoded_data_len,
-						 uint32_t *encoded_rate,
-						 unsigned int *flag);
+	switch_status_t (*encode) (switch_codec_t *codec,
+							   switch_codec_t *other_codec,
+							   void *decoded_data,
+							   uint32_t decoded_data_len,
+							   uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate, unsigned int *flag);
 	/*! function to decode encoded data into raw data */
-	switch_status_t (*decode)(switch_codec_t *codec,
-						 switch_codec_t *other_codec,
-						 void *encoded_data,
-						 uint32_t encoded_data_len,
-						 uint32_t encoded_rate,
-						 void *decoded_data,
-						 uint32_t *decoded_data_len,
-						 uint32_t *decoded_rate,
-						 unsigned int *flag);
+	switch_status_t (*decode) (switch_codec_t *codec,
+							   switch_codec_t *other_codec,
+							   void *encoded_data,
+							   uint32_t encoded_data_len,
+							   uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate, unsigned int *flag);
 	/*! deinitalize a codec handle using this implementation */
-	switch_status_t (*destroy)(switch_codec_t *);
+	switch_status_t (*destroy) (switch_codec_t *);
 	const struct switch_codec_implementation *next;
 };
 
@@ -614,9 +517,7 @@
 };
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_platform.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_platform.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_platform.h	Tue Apr 24 10:14:28 2007
@@ -35,22 +35,17 @@
 #define SWITCH_PLATFORM_H
 
 SWITCH_BEGIN_EXTERN_C
-
 #ifdef __ICC
 #pragma warning (disable:810 869 981 279 1469 188)
 #endif
-
 #include <stdio.h>
-
+#define SWITCH_VA_NONE "%s", ""
 #ifdef _MSC_VER
 #define __SWITCH_FUNC__ __FUNCTION__
 #else
 #define __SWITCH_FUNC__ (const char *)__func__
 #endif
-
 #ifdef _MSC_VER
-
-
 /* disable the following warnings 
  * C4100: The formal parameter is not referenced in the body of the function. The unreferenced parameter is ignored. 
  * C4200: Non standard extension C zero sized array
@@ -62,9 +57,19 @@
  * C4512: assignment operator could not be generated
  * C4610: struct  can never be instantiated - user defined constructor required
  */
-#pragma warning(disable:4100 4200 4204 4706 4819 4132 4510 4512 4610)
+#pragma warning(disable:4100 4200 4204 4706 4819 4132 4510 4512 4610 4996)
+
+#define SWITCH_HAVE_ODBC 1
+
+#ifdef _MSC_VER
+#  pragma comment(lib, "odbc32.lib")
+#endif
 
-#if (_MSC_VER >= 1400) // VC8+
+#pragma include_alias(<libteletone.h>,				<../../libs/libteletone/src/libteletone.h>)
+#pragma include_alias(<libteletone_generate.h>,		<../../libs/libteletone/src/libteletone_generate.h>)
+#pragma include_alias(<libteletone_detect.h>,		<../../libs/libteletone/src/libteletone_detect.h>)
+
+#if (_MSC_VER >= 1400)			// VC8+
 #ifndef _CRT_SECURE_NO_DEPRECATE
 #define _CRT_SECURE_NO_DEPRECATE
 #endif
@@ -72,43 +77,46 @@
 #define _CRT_NONSTDC_NO_DEPRECATE
 #endif
 #endif // VC8+
-
 #if  _MSC_VER < 1300
 #ifndef __FUNCTION__
 #define __FUNCTION__ ""
 #endif
 #endif
-
 #undef inline
 #define inline __inline
-
 #ifndef uint32_t
-typedef unsigned __int8		uint8_t;
-typedef unsigned __int16	uint16_t;
-typedef unsigned __int32	uint32_t;
-typedef unsigned __int64    uint64_t;
-typedef __int8		int8_t;
-typedef __int16		int16_t;
-typedef __int32		int32_t;
-typedef __int64		int64_t;
-typedef unsigned long	in_addr_t;
-#endif
+typedef unsigned __int8 uint8_t;
+typedef unsigned __int16 uint16_t;
+typedef unsigned __int32 uint32_t;
+typedef unsigned __int64 uint64_t;
+typedef __int8 int8_t;
+typedef __int16 int16_t;
+typedef __int32 int32_t;
+typedef __int64 int64_t;
+typedef unsigned long in_addr_t;
+#endif
+typedef int pid_t;
+typedef int uid_t;
+typedef int gid_t;
 #define PACKED
 #include <io.h>
+#define strcasecmp(s1, s2) stricmp(s1, s2)
+#define strncasecmp(s1, s2, n) strnicmp(s1, s2, n)
+#ifndef snprintf
+#define snprintf _snprintf
+#endif
+
 #else
 /* packed attribute */
 #ifndef PACKED
 #define PACKED __attribute__ ((__packed__))
 #endif
-#include <limits.h>
-#include <inttypes.h>
-#include <sys/types.h>
 #include <inttypes.h>
 #include <unistd.h>
-#include <stdlib.h>
-#include <time.h>
+#include <arpa/inet.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
 #endif // _MSC_VER
-
 #ifndef __LITTLE_ENDIAN
 #define __LITTLE_ENDIAN 1234
 #endif
@@ -122,7 +130,6 @@
 #define __BYTE_ORDER __LITTLE_ENDIAN
 #endif
 #endif
-
 #ifdef WIN32
 #if defined(SWITCH_CORE_DECLARE_STATIC)
 #define SWITCH_DECLARE(type)			type __stdcall
@@ -137,7 +144,6 @@
 #define SWITCH_DECLARE_NONSTD(type)		__declspec(dllimport) type __cdecl
 #define SWITCH_DECLARE_DATA				__declspec(dllimport)
 #endif
-
 #if defined(SWITCH_MOD_DECLARE_STATIC)
 #define SWITCH_MOD_DECLARE(type)		type __cdecl
 #elif defined(MOD_EXPORTS)
@@ -152,29 +158,129 @@
 #ifndef S_IWUSR
 #define S_IWUSR _S_IWRITE
 #endif
+#define SWITCH_THREAD_FUNC  __stdcall
 #else //not win32
 #define SWITCH_DECLARE(type) type
 #define SWITCH_DECLARE_NONSTD(type) type
 #define SWITCH_MOD_DECLARE(type) type
 #define SWITCH_DECLARE_DATA
+#define SWITCH_THREAD_FUNC
 #endif
-
 #ifdef DOXYGEN
 #define DoxyDefine(x) x
 #else
 #define DoxyDefine(x)
 #endif
-
 #if __GNUC__ >= 3
 #define PRINTF_FUNCTION(fmtstr,vars) __attribute__((format(printf,fmtstr,vars)))
 #else
 #define PRINTF_FUNCTION(fmtstr,vars)
 #endif
+#ifdef SWITCH_INT32
+	typedef SWITCH_INT32 switch_int32_t;
+#else
+	typedef int32_t switch_int32_t;
+#endif
 
-SWITCH_END_EXTERN_C
+#ifdef SWITCH_SIZE_T
+typedef SWITCH_SIZE_T switch_size_t;
+#else
+typedef uintptr_t switch_size_t;
+#endif
+
+#ifdef SWITCH_SSIZE_T
+typedef SWITCH_SSIZE_T switch_ssize_t;
+#else
+typedef intptr_t switch_ssize_t;
+#endif
+
+#ifdef WIN32
+
+#ifdef WIN64
+#define SWITCH_SSIZE_T_FMT          "I64d"
+#define SWITCH_SIZE_T_FMT           "I64d"
+#else
+#define SWITCH_SSIZE_T_FMT          "d"
+#define SWITCH_SIZE_T_FMT           "d"
+#endif
+
+#define SWITCH_INT64_T_FMT          "I64d"
+#define SWITCH_UINT64_T_FMT         "I64u"
+
+#else
+#ifndef SWITCH_SSIZE_T_FMT
+#define SWITCH_SSIZE_T_FMT          (sizeof (switch_ssize_t) == sizeof (long) ? "ld" : sizeof (switch_ssize_t) == sizeof (int) ? "d" : "lld")
+#endif
+
+#ifndef SWITCH_SIZE_T_FMT
+#define SWITCH_SIZE_T_FMT           (sizeof (switch_size_t) == sizeof (long) ? "lu" : sizeof (switch_size_t) == sizeof (int) ? "u" : "llu")
+#endif
+
+#ifndef SWITCH_INT64_T_FMT
+#define SWITCH_INT64_T_FMT          (sizeof (long) == 8 ? "ld" : "lld")
+#endif
+
+#ifndef SWITCH_UINT64_T_FMT
+#define SWITCH_UINT64_T_FMT         (sizeof (long) == 8 ? "lu" : "llu")
+#endif
+
+#ifndef TIME_T_FMT
+#define TIME_T_FMT "ld"
+#endif
 
 #endif
 
+#define SWITCH_TIME_T_FMT SWITCH_INT64_T_FMT
+
+SWITCH_END_EXTERN_C
+/* these includes must be outside the extern "C" block on windows or it will break compatibility with c++ modules*/
+#ifdef WIN32
+/* Has windows.h already been included?  If so, our preferences don't matter,
+ * but we will still need the winsock things no matter what was included.
+ * If not, include a restricted set of windows headers to our tastes.
+ */
+#ifndef _WINDOWS_
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef _WIN32_WINNT
+/* Restrict the server to a subset of Windows NT 4.0 header files by default
+ */
+#define _WIN32_WINNT 0x0400
+#endif
+#ifndef NOUSER
+#define NOUSER
+#endif
+#ifndef NOMCX
+#define NOMCX
+#endif
+#ifndef NOIME
+#define NOIME
+#endif
+#include <windows.h>
+/* 
+ * Add a _very_few_ declarations missing from the restricted set of headers
+ * (If this list becomes extensive, re-enable the required headers above!)
+ * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now
+ */
+#define SW_HIDE             0
+#ifndef _WIN32_WCE
+#include <winsock2.h>
+#include <mswsock.h>
+#include <ws2tcpip.h>
+#else
+#include <winsock.h>
+#endif
+#endif /* !_WINDOWS_ */
+#include <process.h>
+#endif
+#endif
+#ifndef FALSE
+#define FALSE 0
+#endif
+#ifndef TRUE
+#define TRUE (!FALSE)
+#endif
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_resample.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_resample.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_resample.h	Tue Apr 24 10:14:28 2007
@@ -45,16 +45,13 @@
 
 #include <switch.h>
 SWITCH_BEGIN_EXTERN_C
-#include <stdlib.h>
-
 /*!
   \defgroup resamp Audio Resample Functions
   \ingroup core1
   \{ 
 */
-
 /*! \brief An audio resampling handle */
-typedef struct {
+	typedef struct {
 	/*! a pointer to store the resampler object */
 	void *resampler;
 	/*! the rate to resample from in hz */
@@ -88,11 +85,7 @@
   \return SWITCH_STATUS_SUCCESS if the handle was created
  */
 SWITCH_DECLARE(switch_status_t) switch_resample_create(switch_audio_resampler_t **new_resampler,
-													 int from_rate,
-													 switch_size_t from_size,
-													 int to_rate,
-													 uint32_t to_size,
-													 switch_memory_pool_t *pool);
+													   int from_rate, switch_size_t from_size, int to_rate, uint32_t to_size, switch_memory_pool_t *pool);
 
 /*!
   \brief Destroy an existing resampler handle
@@ -156,6 +149,14 @@
 SWITCH_DECLARE(void) switch_swap_linear(int16_t *buf, int len);
 
 /*!
+  \brief Generate static noise
+  \param data the audio data buffer
+  \param samples the number of 2 byte samples
+  \param divisor the volume factor
+ */
+SWITCH_DECLARE(void) switch_generate_sln_silence(int16_t *data, uint32_t samples, uint32_t divisor);
+
+/*!
   \brief Change the volume of a signed linear audio frame
   \param data the audio data
   \param samples the number of 2 byte samples
@@ -165,9 +166,7 @@
 ///\}
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_rtp.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_rtp.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_rtp.h	Tue Apr 24 10:14:28 2007
@@ -27,6 +27,7 @@
  *
  *
  * switch_channel.h -- Media Channel Interface
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  */
 /** 
@@ -39,17 +40,12 @@
 #define SWITCH_RTP_H
 
 SWITCH_BEGIN_EXTERN_C
-
 #define SWITCH_RTP_MAX_BUF_LEN 16384
-
 ///\defgroup rtp RTP (RealTime Transport Protocol)
 ///\ingroup core1
 ///\{
-typedef void (*switch_rtp_invalid_handler_t)(switch_rtp_t *rtp_session,
-										   switch_socket_t *sock,
-										   void *data,
-										   switch_size_t datalen,
-										   switch_sockaddr_t *from_addr);
+typedef void (*switch_rtp_invalid_handler_t) (switch_rtp_t *rtp_session,
+											  switch_socket_t * sock, void *data, switch_size_t datalen, switch_sockaddr_t * from_addr);
 
 /*! 
   \brief Initilize the RTP System
@@ -58,6 +54,20 @@
 */
 SWITCH_DECLARE(void) switch_rtp_init(switch_memory_pool_t *pool);
 
+/*!
+  \brief Set/Get RTP start port
+  \param port new value (if > 0)
+  \return the current RTP start port
+*/
+SWITCH_DECLARE(switch_port_t) switch_rtp_set_start_port(switch_port_t port);
+
+/*!
+  \brief Set/Get RTP end port
+  \param port new value (if > 0)
+  \return the current RTP end port
+*/
+SWITCH_DECLARE(switch_port_t) switch_rtp_set_end_port(switch_port_t port);
+
 /*! 
   \brief Request a new port to be used for media
   \return the new port to use
@@ -68,7 +78,7 @@
   \brief create a new RTP session handle
   \param new_rtp_session a poiter to aim at the new session
   \param payload the IANA payload number
-  \param packet_size the default packet_size
+  \param samples_per_interval the default samples_per_interval
   \param ms_per_packet time in microseconds per packet
   \param flags flags to control behaviour
   \param crypto_key optional crypto key
@@ -77,15 +87,12 @@
   \param pool a memory pool to use for the session
   \return the new RTP session or NULL on failure
 */
-SWITCH_DECLARE(switch_status_t)switch_rtp_create(switch_rtp_t **new_rtp_session,
-												 switch_payload_t payload,
-												 uint32_t packet_size,
-												 uint32_t ms_per_packet,
-												 switch_rtp_flag_t flags,
-												 char *crypto_key,
-												 char *timer_name,
-												 const char **err,
-												 switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_status_t) switch_rtp_create(switch_rtp_t **new_rtp_session,
+												  switch_payload_t payload,
+												  uint32_t samples_per_interval,
+												  uint32_t ms_per_packet,
+												  switch_rtp_flag_t flags, char *crypto_key, char *timer_name, const char **err,
+												  switch_memory_pool_t *pool);
 
 
 /*!
@@ -95,7 +102,7 @@
   \param tx_host the remote address
   \param tx_port the remote port
   \param payload the IANA payload number
-  \param packet_size the default packet_size
+  \param samples_per_interval the default samples_per_interval
   \param ms_per_packet time in microseconds per packet
   \param flags flags to control behaviour
   \param crypto_key optional crypto key
@@ -104,18 +111,14 @@
   \param pool a memory pool to use for the session
   \return the new RTP session or NULL on failure
 */
-SWITCH_DECLARE(switch_rtp_t *)switch_rtp_new(char *rx_host,
-											 switch_port_t rx_port,
-											 char *tx_host,
-											 switch_port_t tx_port,
-											 switch_payload_t payload,
-											 uint32_t packet_size,
-											 uint32_t ms_per_packet,
-											 switch_rtp_flag_t flags,
-											 char *crypto_key,
-											 char *timer_name,
-											 const char **err,
-											 switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_rtp_t *) switch_rtp_new(char *rx_host,
+											  switch_port_t rx_port,
+											  char *tx_host,
+											  switch_port_t tx_port,
+											  switch_payload_t payload,
+											  uint32_t samples_per_interval,
+											  uint32_t ms_per_packet,
+											  switch_rtp_flag_t flags, char *crypto_key, char *timer_name, const char **err, switch_memory_pool_t *pool);
 
 
 /*! 
@@ -189,21 +192,21 @@
   \param rtp_session the RTP session to retrieve the socket from
   \return the socket from the RTP session
 */
-SWITCH_DECLARE(switch_socket_t *)switch_rtp_get_rtp_socket(switch_rtp_t *rtp_session);
+SWITCH_DECLARE(switch_socket_t *) switch_rtp_get_rtp_socket(switch_rtp_t *rtp_session);
 
 /*! 
-  \brief Set the default packet size for a given RTP session
-  \param rtp_session the RTP session to set the packet size on
-  \param packet_size the new default packet size 
+  \brief Set the default samples per interval for a given RTP session
+  \param rtp_session the RTP session to set the samples per interval on
+  \param samples_per_interval the new default samples per interval 
 */
-SWITCH_DECLARE(void) switch_rtp_set_default_packet_size(switch_rtp_t *rtp_session, uint16_t packet_size);
+SWITCH_DECLARE(void) switch_rtp_set_default_samples_per_interval(switch_rtp_t *rtp_session, uint16_t samples_per_interval);
 
 /*! 
-  \brief Get the default packet size for a given RTP session
-  \param rtp_session the RTP session to get the packet size from
-  \return the default packet_size of the RTP session
+  \brief Get the default samples per interval for a given RTP session
+  \param rtp_session the RTP session to get the samples per interval from
+  \return the default samples per interval of the RTP session
 */
-SWITCH_DECLARE(uint32_t) switch_rtp_get_default_packet_size(switch_rtp_t *rtp_session);
+SWITCH_DECLARE(uint32_t) switch_rtp_get_default_samples_per_interval(switch_rtp_t *rtp_session);
 
 /*! 
   \brief Set the default payload number for a given RTP session
@@ -237,7 +240,8 @@
   \param flags flags
   \return the number of bytes read
 */
-SWITCH_DECLARE(switch_status_t) switch_rtp_read(switch_rtp_t *rtp_session, void *data, uint32_t *datalen, switch_payload_t *payload_type, switch_frame_flag_t *flags);
+SWITCH_DECLARE(switch_status_t) switch_rtp_read(switch_rtp_t *rtp_session, void *data, uint32_t * datalen,
+												switch_payload_t *payload_type, switch_frame_flag_t *flags);
 
 /*! 
   \brief Queue RFC2833 DTMF data into an RTP Session
@@ -281,10 +285,7 @@
   \return the number of bytes read
 */
 SWITCH_DECLARE(switch_status_t) switch_rtp_zerocopy_read(switch_rtp_t *rtp_session,
-														 void **data,
-														 uint32_t *datalen,
-														 switch_payload_t *payload_type,
-														 switch_frame_flag_t *flags);
+														 void **data, uint32_t * datalen, switch_payload_t *payload_type, switch_frame_flag_t *flags);
 
 /*! 
   \brief Read data from a given RTP session without copying
@@ -313,7 +314,8 @@
   \param flags flags for control
   \return SWITCH_STAUTS_SUCCESS on success
 */
-SWITCH_DECLARE(switch_status_t) switch_rtp_enable_vad(switch_rtp_t *rtp_session, switch_core_session_t *session, switch_codec_t *codec, switch_vad_flag_t flags);
+SWITCH_DECLARE(switch_status_t) switch_rtp_enable_vad(switch_rtp_t *rtp_session, switch_core_session_t *session,
+													  switch_codec_t *codec, switch_vad_flag_t flags);
 
 /*!
   \brief Disable VAD on an RTP Session
@@ -346,13 +348,8 @@
 */
 SWITCH_DECLARE(int) switch_rtp_write_manual(switch_rtp_t *rtp_session,
 											void *data,
-											uint16_t datalen,
-											uint8_t m,
-											switch_payload_t payload,
-											uint32_t ts,
-											uint16_t mseq,
-											uint32_t ssrc,
-											switch_frame_flag_t *flags);
+											uint32_t datalen,
+											uint8_t m, switch_payload_t payload, uint32_t ts, uint16_t mseq, uint32_t ssrc, switch_frame_flag_t *flags);
 
 /*! 
   \brief Retrieve the SSRC from a given RTP session
@@ -376,20 +373,25 @@
 SWITCH_DECLARE(void) switch_rtp_set_telephony_event(switch_rtp_t *rtp_session, switch_payload_t te);
 
 /*! 
+  \brief Set the payload type for comfort noise
+  \param rtp_session the RTP session to modify
+  \param pt the payload type
+*/
+SWITCH_DECLARE(void) switch_rtp_set_cng_pt(switch_rtp_t *rtp_session, switch_payload_t pt);
+
+/*! 
   \brief Retrieve the private data from a given RTP session
   \param rtp_session the RTP session to retrieve the data from
   \return the pointer to the private data
 */
-SWITCH_DECLARE(void *)switch_rtp_get_private(switch_rtp_t *rtp_session);
+SWITCH_DECLARE(void *) switch_rtp_get_private(switch_rtp_t *rtp_session);
 
 /*!
   \}
 */
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_sqlite.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_sqlite.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_sqlite.h	Tue Apr 24 10:14:28 2007
@@ -36,26 +36,22 @@
 #define SWITCH_SQLITE_H
 
 SWITCH_BEGIN_EXTERN_C
-
 #include <sqlite3.h>
-
 /**
  * @defgroup switch_sqlite_top Brought To You By SQLite
  * @ingroup FREESWITCH
  * @{
  */
-
 /**
  * @defgroup switch_sqlite Database Routines
  * @ingroup switch_sqlite_top 
  * @{
  */
-
 /**
  * Each open sqlite database is represented by an instance of the
  * following opaque structure.
 */
-typedef sqlite3 switch_core_db_t;
+	typedef sqlite3 switch_core_db_t;
 typedef sqlite3_stmt switch_core_db_stmt_t;
 /**
  * Aggregate functions use the following routine to allocate
@@ -67,17 +63,15 @@
  *
  * The buffer allocated is freed automatically by SQLite.
  */
-DoxyDefine(void *switch_core_db_aggregate_context(sqlite3_context*, int nBytes);)
+DoxyDefine(void *switch_core_db_aggregate_context(sqlite3_context *, int nBytes);)
 #define switch_core_db_aggregate_context sqlite3_aggregate_context
-
 /**
  * /return the number of calls to xStep for a particular
  * aggregate function instance.  The current call to xStep counts so this
  * routine always returns at least 1.
  */
-DoxyDefine(int switch_core_db_aggregate_count(sqlite3_context*);)
+DoxyDefine(int switch_core_db_aggregate_count(sqlite3_context *);)
 #define switch_core_db_aggregate_count sqlite3_aggregate_count
-
 /**
  * In the SQL strings input to switch_core_db_prepare(),
  * one or more literals can be replace by parameters "?" or ":AAA" or
@@ -106,9 +100,8 @@
  * an switch_core_db_prepare() or sqlite3_reset().  Unbound parameterss are
  * interpreted as NULL.
  */
-DoxyDefine(int switch_core_db_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));)
+DoxyDefine(int switch_core_db_bind_blob(sqlite3_stmt *, int, const void *, int n, void (*)(void *));)
 #define switch_core_db_bind_blob sqlite3_bind_blob
-
 /**
  * In the SQL strings input to switch_core_db_prepare(),
  * one or more literals can be replace by parameters "?" or ":AAA" or
@@ -129,9 +122,8 @@
  * an switch_core_db_prepare() or sqlite3_reset().  Unbound parameterss are
  * interpreted as NULL.
  */
-DoxyDefine(int switch_core_db_bind_double(sqlite3_stmt*, int, double);)
+DoxyDefine(int switch_core_db_bind_double(sqlite3_stmt *, int, double);)
 #define switch_core_db_bind_double sqlite3_bind_double
-
 /**
  * In the SQL strings input to switch_core_db_prepare(),
  * one or more literals can be replace by parameters "?" or ":AAA" or
@@ -152,9 +144,8 @@
  * an switch_core_db_prepare() or sqlite3_reset().  Unbound parameterss are
  * interpreted as NULL.
  */
-DoxyDefine(int switch_core_db_bind_int(sqlite3_stmt*, int, int);)
+DoxyDefine(int switch_core_db_bind_int(sqlite3_stmt *, int, int);)
 #define switch_core_db_bind_int sqlite3_bind_int
-
 /**
  * In the SQL strings input to switch_core_db_prepare(),
  * one or more literals can be replace by parameters "?" or ":AAA" or
@@ -175,9 +166,8 @@
  * an switch_core_db_prepare() or sqlite3_reset().  Unbound parameterss are
  * interpreted as NULL.
  */
-DoxyDefine(int switch_core_db_bind_int64(sqlite3_stmt*, int, sqlite_int64);)
+DoxyDefine(int switch_core_db_bind_int64(sqlite3_stmt *, int, sqlite_int64);)
 #define switch_core_db_bind_int64 sqlite3_bind_int64
-
 /**
  * In the SQL strings input to switch_core_db_prepare(),
  * one or more literals can be replace by parameters "?" or ":AAA" or
@@ -198,9 +188,8 @@
  * an switch_core_db_prepare() or sqlite3_reset().  Unbound parameterss are
  * interpreted as NULL.
  */
-DoxyDefine(int switch_core_db_bind_null(sqlite3_stmt*, int);)
+DoxyDefine(int switch_core_db_bind_null(sqlite3_stmt *, int);)
 #define switch_core_db_bind_null sqlite3_bind_null
-
 /**
  * In the SQL strings input to switch_core_db_prepare(),
  * one or more literals can be replace by parameters "?" or ":AAA" or
@@ -229,9 +218,8 @@
  * an switch_core_db_prepare() or sqlite3_reset().  Unbound parameterss are
  * interpreted as NULL.
  */
-DoxyDefine(int switch_core_db_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));)
+DoxyDefine(int switch_core_db_bind_text(sqlite3_stmt *, int, const char *, int n, void (*)(void *));)
 #define switch_core_db_bind_text sqlite3_bind_text
-
 /**
  * In the SQL strings input to switch_core_db_prepare(),
  * one or more literals can be replace by parameters "?" or ":AAA" or
@@ -260,9 +248,8 @@
  * an switch_core_db_prepare() or sqlite3_reset().  Unbound parameterss are
  * interpreted as NULL.
  */
-DoxyDefine(int switch_core_db_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));)
+DoxyDefine(int switch_core_db_bind_text16(sqlite3_stmt *, int, const void *, int, void (*)(void *));)
 #define switch_core_db_bind_text16 sqlite3_bind_text16
-
 /**
  * In the SQL strings input to switch_core_db_prepare(),
  * one or more literals can be replace by parameters "?" or ":AAA" or
@@ -283,24 +270,21 @@
  * an switch_core_db_prepare() or sqlite3_reset().  Unbound parameterss are
  * interpreted as NULL.
  */
-DoxyDefine(int switch_core_db_bind_value(sqlite3_stmt*, int, const sqlite3_value*);)
+DoxyDefine(int switch_core_db_bind_value(sqlite3_stmt *, int, const sqlite3_value *);)
 #define switch_core_db_bind_value sqlite3_bind_value
-
 /**
  * @return The number of parameters in a compiled SQL statement.
  * @remark This routine was added to support DBD::SQLite.
  */
-DoxyDefine(int switch_core_db_bind_parameter_count(sqlite3_stmt*);)
+DoxyDefine(int switch_core_db_bind_parameter_count(sqlite3_stmt *);)
 #define switch_core_db_bind_parameter_count sqlite3_bind_parameter_count
-
 /**
  * @return the index of a parameter with the given name.  If no parameter with the 
  * given name is found, return 0.
  * @remark The name must match exactly.
  */
-DoxyDefine(int switch_core_db_bind_parameter_index(sqlite3_stmt*, const char *zName);)
+DoxyDefine(int switch_core_db_bind_parameter_index(sqlite3_stmt *, const char *zName);)
 #define switch_core_db_bind_parameter_index sqlite3_bind_parameter_index
-
 /**
  * @return the name of the i-th parameter.  
  * @remark Ordinary parameters "?" are
@@ -308,9 +292,8 @@
  * $VVV the complete text of the parameter name is returned, including
  * the initial ":" or "$".  NULL is returned if the index is out of range.
  */
-DoxyDefine(const char *switch_core_db_bind_parameter_name(sqlite3_stmt*, int);)
+DoxyDefine(const char *switch_core_db_bind_parameter_name(sqlite3_stmt *, int);)
 #define switch_core_db_bind_parameter_name sqlite3_bind_parameter_name
-
 /**
  * This routine identifies a callback function that is invoked
  * whenever an attempt is made to open a database table that is
@@ -333,9 +316,8 @@
  * data structures out from under the executing query and will 
  * probably result in a coredump.
  */
-DoxyDefine(int switch_core_db_busy_handler(switch_core_db*, int(*)(void*,int), void*);)
+DoxyDefine(int switch_core_db_busy_handler(switch_core_db *, int (*)(void *, int), void *);)
 #define switch_core_db_busy_handler sqlite3_busy_handler
-
 /**
  * This routine sets a busy handler that sleeps for a while when a
  * table is locked.  The handler will sleep multiple times until 
@@ -346,9 +328,8 @@
  * Calling this routine with an argument less than or equal to zero
  * turns off all busy handlers.
  */
-DoxyDefine(int switch_core_db_busy_timeout(switch_core_db*, int ms);)
+DoxyDefine(int switch_core_db_busy_timeout(switch_core_db *, int ms);)
 #define switch_core_db_busy_timeout sqlite3_busy_timeout
-
 /**
  * This function returns the number of database rows that were changed
  * (or inserted or deleted) by the most recent called sqlite3_exec().
@@ -369,9 +350,8 @@
  * table. To get an accurate count of the number of rows deleted, use
  * "DELETE FROM table WHERE 1" instead.
  */
-DoxyDefine(int switch_core_db_changes(switch_core_db*);)
+DoxyDefine(int switch_core_db_changes(switch_core_db *);)
 #define switch_core_db_changes sqlite3_changes
-
 /**
  * A function to close the database.
  *
@@ -385,7 +365,6 @@
  */
 DoxyDefine(int switch_core_db_close(switch_core_db *);)
 #define switch_core_db_close sqlite3_close
-
 /**
  * To avoid having to register all collation sequences before a database
  * can be used, a single callback function may be registered with the
@@ -405,13 +384,9 @@
  * The collation sequence is returned to SQLite by a collation-needed
  * callback using the sqlite3_create_collation() API, described above.
  */
-DoxyDefine(int switch_core_db_collation_needed(
-  switch_core_db*, 
-  void*, 
-  void(*)(void*,switch_core_db*,int eTextRep,const char*)
-);)
+DoxyDefine(int switch_core_db_collation_needed(switch_core_db *, void *, void (*)(void *, switch_core_db *, int eTextRep, const char *)
+		   );)
 #define switch_core_db_collation_needed sqlite3_collation_needed
-
 /**
  * The next group of routines returns information about the information
  * in a single column of the current result row of a query.
@@ -453,9 +428,8 @@
  *
  * @return the value of a BLOB.
  */
-DoxyDefine(const void *switch_core_db_column_blob(sqlite3_stmt *stmt, int iCol);)
+DoxyDefine(const void *switch_core_db_column_blob(sqlite3_stmt * stmt, int iCol);)
 #define switch_core_db_column_blob sqlite3_column_blob
-
 /**
  * The next group of routines returns information about the information
  * in a single column of the current result row of a query.  In every
@@ -497,9 +471,8 @@
  * TEXT value represented as UTF-8.  The "\000" terminator is included in the 
  * byte count for TEXT values.
  */
-DoxyDefine(int switch_core_db_column_bytes(sqlite3_stmt*, int iCol);)
+DoxyDefine(int switch_core_db_column_bytes(sqlite3_stmt *, int iCol);)
 #define switch_core_db_column_bytes sqlite3_column_bytes
-
 /**
  * The next group of routines returns information about the information
  * in a single column of the current result row of a query.  In every
@@ -541,9 +514,8 @@
  * TEXT value represented as UTF-16.  The "\u0000" terminator is included in 
  * the byte count for TEXT values.
  */
-DoxyDefine(int switch_core_db_column_bytes16(sqlite3_stmt*, int iCol);)
+DoxyDefine(int switch_core_db_column_bytes16(sqlite3_stmt *, int iCol);)
 #define switch_core_db_column_bytes16 sqlite3_column_bytes16
-
 /**
  * The next group of routines returns information about the information
  * in a single column of the current result row of a query.  In every
@@ -583,9 +555,8 @@
  *
  *  Return a FLOAT value.
  */
-DoxyDefine(double switch_core_db_column_double(sqlite3_stmt*, int iCol);)
+DoxyDefine(double switch_core_db_column_double(sqlite3_stmt *, int iCol);)
 #define switch_core_db_column_double sqlite3_column_double
-
 /**
  * The next group of routines returns information about the information
  * in a single column of the current result row of a query.  In every
@@ -626,9 +597,8 @@
  *  Return an INTEGER value in the host computer's native integer representation.  
  *  This might be either a 32- or 64-bit integer depending on the host.
  */
-DoxyDefine(int switch_core_db_column_int(sqlite3_stmt*, int iCol);)
+DoxyDefine(int switch_core_db_column_int(sqlite3_stmt *, int iCol);)
 #define switch_core_db_column_int sqlite3_column_int
-
 /**
  * The next group of routines returns information about the information
  * in a single column of the current result row of a query.  In every
@@ -668,9 +638,8 @@
  *
  * Return an INTEGER value as a 64-bit signed integer.
  */
-DoxyDefine(sqlite_int64 switch_core_db_column_int64(sqlite3_stmt*, int iCol);)
+	DoxyDefine(sqlite_int64 switch_core_db_column_int64(sqlite3_stmt *, int iCol);)
 #define switch_core_db_column_int64 sqlite3_column_int64
-
 /**
  * The next group of routines returns information about the information
  * in a single column of the current result row of a query.  In every
@@ -710,9 +679,8 @@
  *
  *  Return the value as UTF-8 text.
  */
-DoxyDefine(const unsigned char *switch_core_db_column_text(sqlite3_stmt*, int iCol);)
+DoxyDefine(const unsigned char *switch_core_db_column_text(sqlite3_stmt *, int iCol);)
 #define switch_core_db_column_text sqlite3_column_text
-
 /**
  * The next group of routines returns information about the information
  * in a single column of the current result row of a query.  In every
@@ -752,9 +720,8 @@
  *
  * Return the value as UTF-16 text.
  */
-DoxyDefine(const void *switch_core_db_column_text16(sqlite3_stmt*, int iCol);)
+DoxyDefine(const void *switch_core_db_column_text16(sqlite3_stmt *, int iCol);)
 #define switch_core_db_column_text16 sqlite3_column_text16
-
 /**
  * The next group of routines returns information about the information
  * in a single column of the current result row of a query.  In every
@@ -795,25 +762,22 @@
  * ReturnS the datatype of the result.  This is one of
  * SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL.
  */
-DoxyDefine(int switch_core_db_column_type(sqlite3_stmt*, int iCol);)
+DoxyDefine(int switch_core_db_column_type(sqlite3_stmt *, int iCol);)
 #define switch_core_db_column_type sqlite3_column_type
-
 /**
  * The first parameter is a compiled SQL statement. This function returns
  * the column heading for the Nth column of that statement, where N is the
  * second function parameter.  The string returned is UTF-8.
  */
-DoxyDefine(const char *switch_core_db_column_name(sqlite3_stmt*,int);)
+DoxyDefine(const char *switch_core_db_column_name(sqlite3_stmt *, int);)
 #define switch_core_db_column_name sqlite3_column_name
-
 /**
  * Return the number of columns in the result set returned by the compiled
  * SQL statement. This routine returns 0 if pStmt is an SQL statement
  * that does not return data (for example an UPDATE).
  */
-DoxyDefine(int switch_core_db_column_count(sqlite3_stmt *pStmt);)
+DoxyDefine(int switch_core_db_column_count(sqlite3_stmt * pStmt);)
 #define switch_core_db_column_count sqlite3_column_count
-
 /**
  * The first parameter is a compiled SQL statement. If this statement
  * is a SELECT statement, the Nth column of the returned result set 
@@ -834,7 +798,6 @@
  */
 DoxyDefine(const char *switch_core_db_column_decltype(sqlite3_stmt *, int i);)
 #define switch_core_db_column_decltype sqlite3_column_decltype
-
 /**
  * The first parameter is a compiled SQL statement. If this statement
  * is a SELECT statement, the Nth column of the returned result set 
@@ -853,9 +816,8 @@
  * result column (i==1), and a NULL pointer for the first result column
  * (i==0).
  */
-DoxyDefine(const void *switch_core_db_column_decltype16(sqlite3_stmt*,int);)
+DoxyDefine(const void *switch_core_db_column_decltype16(sqlite3_stmt *, int);)
 #define switch_core_db_column_decltype16 sqlite3_column_decltype16
-
 /**
  * Register a callback function to be invoked whenever a new transaction
  * is committed.  The pArg argument is passed through to the callback.
@@ -869,9 +831,8 @@
  *
  ****** THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  */
-DoxyDefine(void *switch_core_db_commit_hook(switch_core_db*, int(*)(void*), void*);)
+DoxyDefine(void *switch_core_db_commit_hook(switch_core_db *, int (*)(void *), void *);)
 #define switch_core_db_commit_hook sqlite3_commit_hook
-
 /**
  * This functions return true if the given input string comprises
  * one or more complete SQL statements. The parameter must be a nul-terminated 
@@ -883,7 +844,6 @@
  */
 DoxyDefine(int switch_core_db_complete(const char *sql);)
 #define switch_core_db_complete sqlite3_complete
-
 /**
  * This function is used to add new collation sequences to the
  * sqlite3 handle specified as the first argument. 
@@ -909,15 +869,10 @@
  * the first string is less than, equal to, or greater than the second
  * string. i.e. (STRING1 - STRING2).
  */
-DoxyDefine(int switch_core_db_create_collation(
-  switch_core_db*, 
-  const char *zName, 
-  int eTextRep, 
-  void*,
-  int(*xCompare)(void*,int,const void*,int,const void*)
-);)
+DoxyDefine(int switch_core_db_create_collation(switch_core_db *,
+											   const char *zName, int eTextRep, void *, int (*xCompare) (void *, int, const void *, int, const void *)
+		   );)
 #define switch_core_db_create_collation sqlite3_create_collation
-
 /**
  * The following function is used to add user functions or aggregates
  * implemented in C to the SQL langauge interpreted by SQLite. The
@@ -951,18 +906,15 @@
  * xFunc and an xFinal, or an xStep but no xFinal, SQLITE_ERROR is
  * returned.
  */
-DoxyDefine(int switch_core_db_create_function(
-  switch_core_db *,
-  const char *zFunctionName,
-  int nArg,
-  int eTextRep,
-  void*,
-  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
-  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
-  void (*xFinal)(sqlite3_context*)
-);)
+DoxyDefine(int switch_core_db_create_function(switch_core_db *,
+											  const char *zFunctionName,
+											  int nArg,
+											  int eTextRep,
+											  void *,
+											  void (*xFunc) (sqlite3_context *, int, sqlite3_value **),
+											  void (*xStep) (sqlite3_context *, int, sqlite3_value **), void (*xFinal) (sqlite3_context *)
+		   );)
 #define switch_core_db_create_function sqlite3_create_function
-
 /**
  * Return the number of values in the current row of the result set.
  *
@@ -972,18 +924,16 @@
  * error code, or before switch_core_db_step() has been called on a 
  * compiled SQL statement, this routine returns zero.
  */
-DoxyDefine(int switch_core_db_data_count(sqlite3_stmt *pStmt);)
+DoxyDefine(int switch_core_db_data_count(sqlite3_stmt * pStmt);)
 #define switch_core_db_data_count sqlite3_data_count
-
 /**
  * Return the sqlite3* database handle to which the prepared statement given
  * in the argument belongs.  This is the same database handle that was
  * the first argument to the switch_core_db_prepare() that was used to create
  * the statement in the first place.
  */
-DoxyDefine(switch_core_db *switch_core_db_db_handle(sqlite3_stmt*);)
+	DoxyDefine(switch_core_db * switch_core_db_db_handle(sqlite3_stmt *);)
 #define switch_core_db_db_handle sqlite3_db_handle
-
 /**
 ** Return the error code for the most recent switch_core_db_* API call associated
 ** with switch_core_db handle 'db'. SQLITE_OK is returned if the most recent 
@@ -999,9 +949,8 @@
 ** code returned by this function is associated with the same error as
 ** the strings  returned by sqlite3_errmsg() and sqlite3_errmsg16().
 */
-DoxyDefine(int switch_core_db_errcode(switch_core_db *db);)
+DoxyDefine(int switch_core_db_errcode(switch_core_db * db);)
 #define switch_core_db_errcode sqlite3_errcode
-
 /**
  * Return a pointer to a UTF-8 encoded string describing in english the
  * error condition for the most recent sqlite3_* API call. The returned
@@ -1010,9 +959,8 @@
  * The string "not an error" is returned when the most recent API call was
  * successful.
  */
-DoxyDefine(const char *switch_core_db_errmsg(switch_core_db*);)
+DoxyDefine(const char *switch_core_db_errmsg(switch_core_db *);)
 #define switch_core_db_errmsg sqlite3_errmsg
-
 /**
  * A function to executes one or more statements of SQL.
  *
@@ -1053,15 +1001,13 @@
  * behavior can be modified somewhat using the sswitch_core_db_busy_handler()
  * and switch_core_db_busy_timeout() functions below.)
  */
-DoxyDefine(int switch_core_db_exec(
-  switch_core_db*,                     /* An open database */
-  const char *sql,              /* SQL to be executed */
-  sqlite3_callback,             /* Callback function */
-  void *,                       /* 1st argument to callback function */
-  char **errmsg                 /* Error msg written here */
-);)
+DoxyDefine(int switch_core_db_exec(switch_core_db *,	/* An open database */
+								   const char *sql,	/* SQL to be executed */
+								   sqlite3_callback,	/* Callback function */
+								   void *,	/* 1st argument to callback function */
+								   char **errmsg	/* Error msg written here */
+		   );)
 #define switch_core_db_exec sqlite3_exec
-
 /**
  * Return TRUE (non-zero) if the statement supplied as an argument needs
  * to be recompiled.  A statement needs to be recompiled whenever the
@@ -1071,9 +1017,8 @@
  * added or changed.
  *
  */
-DoxyDefine(int switch_core_db_expired(sqlite3_stmt*);)
+DoxyDefine(int switch_core_db_expired(sqlite3_stmt *);)
 #define switch_core_db_expired sqlite3_expired
-
 /**
  * This function is called to delete a compiled
  * SQL statement obtained by a previous call to switch_core_db_prepare().
@@ -1088,24 +1033,21 @@
  * rolled back and transactions cancelled,  depending on the circumstances,
  * and the result code returned will be SQLITE_ABORT.
  */
-DoxyDefine(int switch_core_db_finalize(sqlite3_stmt *pStmt);)
+DoxyDefine(int switch_core_db_finalize(sqlite3_stmt * pStmt);)
 #define switch_core_db_finalize sqlite3_finalize
-
 /**
  * Call this routine to free the memory that sqlite3_get_table() allocated.
  */
 DoxyDefine(void switch_core_db_free_table(char **result);)
 #define switch_core_db_free_table sqlite3_free_table
-
 /**
  * Test to see whether or not the database connection is in autocommit
  * mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
  * by default.  Autocommit is disabled by a BEGIN statement and reenabled
  * by the next COMMIT or ROLLBACK.
  */
-DoxyDefine(int switch_core_db_get_autocommit(switch_core_db*);)
+DoxyDefine(int switch_core_db_get_autocommit(switch_core_db *);)
 #define switch_core_db_get_autocommit sqlite3_get_autocommit
-
 /**
  * The following function may be used by scalar user functions to
  * associate meta-data with argument values. If the same value is passed to
@@ -1125,9 +1067,8 @@
  * expressions that are constant at compile time. This includes literal
  * values and SQL variables.
  */
-DoxyDefine(void *switch_core_db_get_auxdata(sqlite3_context*, int);)
+DoxyDefine(void *switch_core_db_get_auxdata(sqlite3_context *, int);)
 #define switch_core_db_get_auxdata sqlite3_get_auxdata
-
 /**
  * The following function may be used by scalar user functions to
  * associate meta-data with argument values. If the same value is passed to
@@ -1149,9 +1090,8 @@
  * expressions that are constant at compile time. This includes literal
  * values and SQL variables.
  */
-DoxyDefine(void switch_core_db_set_auxdata(sqlite3_context*, int, void*, void (*)(void*));)
+DoxyDefine(void switch_core_db_set_auxdata(sqlite3_context *, int, void *, void (*)(void *));)
 #define switch_core_db_set_auxdata sqlite3_set_auxdata
-
 /**
  * This next routine is really just a wrapper around sqlite3_exec().
  * Instead of invoking a user-supplied callback for each row of the
@@ -1193,16 +1133,14 @@
  *
  * The return value of this routine is the same as from switch_core_db_exec().
  */
-DoxyDefine(int switch_core_db_get_table(
-  switch_core_db*,       /* An open database */
-  const char *sql,       /* SQL to be executed */
-  char ***resultp,       /* Result written to a char *[]  that this points to */
-  int *nrow,             /* Number of result rows written here */
-  int *ncolumn,          /* Number of result columns written here */
-  char **errmsg          /* Error msg written here */
-);)
+DoxyDefine(int switch_core_db_get_table(switch_core_db *,	/* An open database */
+										const char *sql,	/* SQL to be executed */
+										char ***resultp,	/* Result written to a char *[]  that this points to */
+										int *nrow,	/* Number of result rows written here */
+										int *ncolumn,	/* Number of result columns written here */
+										char **errmsg	/* Error msg written here */
+		   );)
 #define switch_core_db_get_table sqlite3_get_table
-
 /**
  * This function is called to recover from a malloc() failure that occured
  * within the SQLite library. Normally, after a single malloc() fails the 
@@ -1224,16 +1162,14 @@
  */
 DoxyDefine(int switch_core_db_global_recover();)
 #define switch_core_db_global_recover sqlite3_global_recover
-
 /** This function causes any pending database operation to abort and
  * return at its earliest opportunity.  This routine is typically
  * called in response to a user action such as pressing "Cancel"
  * or Ctrl-C where the user wants a long query operation to halt
  * immediately.
  */
-DoxyDefine(void switch_core_db_interrupt(switch_core_db*);)
+DoxyDefine(void switch_core_db_interrupt(switch_core_db *);)
 #define switch_core_db_interrupt sqlite3_interrupt
-
 /**
  * Each entry in an SQLite table has a unique integer key.  (The key is
  * the value of the INTEGER PRIMARY KEY column if there is such a column,
@@ -1243,9 +1179,8 @@
  *
  * This function is similar to the mysql_insert_id() function from MySQL.
  */
-DoxyDefine(sqlite_int64 switch_core_db_last_insert_rowid(switch_core_db*);)
+	DoxyDefine(sqlite_int64 switch_core_db_last_insert_rowid(switch_core_db *);)
 #define switch_core_db_last_insert_rowid sqlite3_last_insert_rowid
-
 /**
  * Open the sqlite database file "filename".  The "filename" is UTF-8
  * encoded.  An sqlite3* handle is returned in *ppDb, even
@@ -1261,12 +1196,10 @@
  * with the switch_core_db* handle should be released by passing it to
  * switch_core_db_close() when it is no longer required.
  */
-DoxyDefine(int switch_core_db_open(
-  const char *filename,   /* Database filename (UTF-8) */
-  switch_core_db **ppDb          /* OUT: SQLite db handle */
-);)
+DoxyDefine(int switch_core_db_open(const char *filename,	/* Database filename (UTF-8) */
+								   switch_core_db ** ppDb	/* OUT: SQLite db handle */
+		   );)
 #define switch_core_db_open sqlite3_open
-
 /**
  * To execute an SQL query, it must first be compiled into a byte-code
  * program using the following routine.
@@ -1289,15 +1222,13 @@
  *
  * On success, SQLITE_OK is returned.  Otherwise an error code is returned.
  */
-DoxyDefine(int switch_core_db_prepare(
-  sqlite3 *db,            /* Database handle */
-  const char *zSql,       /* SQL statement, UTF-8 encoded */
-  int nBytes,             /* Length of zSql in bytes. */
-  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
-  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
-);)
+DoxyDefine(int switch_core_db_prepare(sqlite3 * db,	/* Database handle */
+									  const char *zSql,	/* SQL statement, UTF-8 encoded */
+									  int nBytes,	/* Length of zSql in bytes. */
+									  sqlite3_stmt ** ppStmt,	/* OUT: Statement handle */
+									  const char **pzTail	/* OUT: Pointer to unused portion of zSql */
+		   );)
 #define switch_core_db_prepare sqlite3_prepare
-
 /**
  * Register a function for tracing SQL command evaluation.  The function registered by
  * switch_core_db_profile() runs at the end of each SQL statement and includes
@@ -1306,10 +1237,8 @@
  * The sqlite3_profile() API is currently considered experimental and
  * is subject to change.
  */
-DoxyDefine(void *switch_core_db_profile(switch_core_db*,
-   void(*xProfile)(void*,const char*,sqlite_uint64), void*);)
+DoxyDefine(void *switch_core_db_profile(switch_core_db *, void (*xProfile) (void *, const char *, sqlite_uint64), void *);)
 #define switch_core_db_profile sqlite3_profile
-
 /**
  * This routine configures a callback function - the progress callback - that
  * is invoked periodically during long running calls to switch_core_db_exec(),
@@ -1336,9 +1265,8 @@
  *
  ****** THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  */
-DoxyDefine(void switch_core_db_progress_handler(switch_core_db*, int, int(*)(void*), void*);)
+DoxyDefine(void switch_core_db_progress_handler(switch_core_db *, int, int (*)(void *), void *);)
 #define switch_core_db_progress_handler sqlite3_progress_handler
-
 /**
  * The switch_core_db_reset() function is called to reset a compiled SQL
  * statement obtained by a previous call to switch_core_db_prepare()
@@ -1346,93 +1274,80 @@
  * Any SQL statement variables that had values bound to them using
  * the switch_core_db_bind_*() API retain their values.
  */
-DoxyDefine(int switch_core_db_reset(sqlite3_stmt *pStmt);)
+DoxyDefine(int switch_core_db_reset(sqlite3_stmt * pStmt);)
 #define switch_core_db_reset sqlite3_reset
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_blob(sqlite3_context*, const void*, int, void(*)(void*));)
+DoxyDefine(void switch_core_db_result_blob(sqlite3_context *, const void *, int, void (*)(void *));)
 #define switch_core_db_result_blob sqlite3_result_blob
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_double(sqlite3_context*, double);)
+DoxyDefine(void switch_core_db_result_double(sqlite3_context *, double);)
 #define switch_core_db_result_double sqlite3_result_double
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_error(sqlite3_context*, const char*, int);)
+DoxyDefine(void switch_core_db_result_error(sqlite3_context *, const char *, int);)
 #define switch_core_db_result_error sqlite3_result_error
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_error16(sqlite3_context*, const void*, int);)
+DoxyDefine(void switch_core_db_result_error16(sqlite3_context *, const void *, int);)
 #define switch_core_db_result_error16 sqlite3_result_error16
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_int(sqlite3_context*, int);)
+DoxyDefine(void switch_core_db_result_int(sqlite3_context *, int);)
 #define switch_core_db_result_int sqlite3_result_int
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_int64(sqlite3_context*, sqlite_int64);)
+DoxyDefine(void switch_core_db_result_int64(sqlite3_context *, sqlite_int64);)
 #define switch_core_db_result_int64 sqlite3_result_int64
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_null(sqlite3_context*);)
+DoxyDefine(void switch_core_db_result_null(sqlite3_context *);)
 #define switch_core_db_result_null sqlite3_result_null
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_text(sqlite3_context*, const char*, int, void(*)(void*));)
+DoxyDefine(void switch_core_db_result_text(sqlite3_context *, const char *, int, void (*)(void *));)
 #define switch_core_db_result_text sqlite3_result_text
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_text16(sqlite3_context*, const void*, int, void(*)(void*));)
+DoxyDefine(void switch_core_db_result_text16(sqlite3_context *, const void *, int, void (*)(void *));)
 #define switch_core_db_result_text16 sqlite3_result_text16
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));)
+DoxyDefine(void switch_core_db_result_text16le(sqlite3_context *, const void *, int, void (*)(void *));)
 #define switch_core_db_result_text16le sqlite3_result_text16le
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));)
+DoxyDefine(void switch_core_db_result_text16be(sqlite3_context *, const void *, int, void (*)(void *));)
 #define switch_core_db_result_text16be sqlite3_result_text16be
-
 /**
  * User-defined functions invoke this routine in order to
  * set their return value.
  */
-DoxyDefine(void switch_core_db_result_value(sqlite3_context*, sqlite3_value*);)
+DoxyDefine(void switch_core_db_result_value(sqlite3_context *, sqlite3_value *);)
 #define switch_core_db_result_value sqlite3_result_value
-
 /**
  * This routine registers a callback with the SQLite library.  The
  * callback is invoked (at compile-time, not at run-time) for each
@@ -1441,13 +1356,9 @@
  * SQL statement should be aborted with an error and SQLITE_IGNORE
  * if the column should be treated as a NULL value.
  */
-DoxyDefine(int switch_core_db_set_authorizer(
-  switch_core_db*,
-  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
-  void *pUserData
-);)
+DoxyDefine(int switch_core_db_set_authorizer(switch_core_db *,
+											 int (*xAuth) (void *, int, const char *, const char *, const char *, const char *), void *pUserData);)
 #define switch_core_db_set_authorizer sqlite3_set_authorizer
-
 /** 
  * After an SQL query has been compiled with a call to either
  * switch_core_db_prepare(), then this function must be
@@ -1480,9 +1391,8 @@
  * SQLITE_DONE.  Or it could be the case the the same database connection
  * is being used simulataneously by two or more threads.
  */
-DoxyDefine(int switch_core_db_step(sqlite3_stmt*);)
+DoxyDefine(int switch_core_db_step(sqlite3_stmt *);)
 #define switch_core_db_step sqlite3_step
-
 /**
  * If the following global variable is made to point to a
  * string which is the name of a directory, then all temporary files
@@ -1493,9 +1403,8 @@
  * Once switch_core_db_open() has been called, changing this variable will invalidate
  * the current temporary database, if any.
  */
-DoxyDefine(extern char *switch_core_db_temp_directory;)
+	DoxyDefine(extern char *switch_core_db_temp_directory;)
 #define switch_core_db_temp_directory sqlite3_temp_directory
-
 /**
  * This function returns the number of database rows that have been
  * modified by INSERT, UPDATE or DELETE statements since the database handle
@@ -1512,17 +1421,15 @@
  * table. To get an accurate count of the number of rows deleted, use
  * "DELETE FROM table WHERE 1" instead.
  */
-DoxyDefine(int switch_core_db_total_changes(switch_core_db*);)
+DoxyDefine(int switch_core_db_total_changes(switch_core_db *);)
 #define switch_core_db_total_changes sqlite3_total_changes
-
 /**
  * Register a function for tracing SQL command evaluation.  The function
  * registered is invoked at the first switch_core_db_step()
  * for the evaluation of an SQL statement.
  */
-DoxyDefine(void *switch_core_db_trace(switch_core_db*, void(*xTrace)(void*,const char*), void*);)
+DoxyDefine(void *switch_core_db_trace(switch_core_db *, void (*xTrace) (void *, const char *), void *);)
 #define switch_core_db_trace sqlite3_trace
-
 /**
  * Move all bindings from the first prepared statement over to the second.
  * This routine is useful, for example, if the first prepared statement
@@ -1530,17 +1437,15 @@
  * the second prepared statement then all of the bindings transfered over
  * to the second statement before the first statement is finalized.
  */
-DoxyDefine(int switch_core_db_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);)
+DoxyDefine(int switch_core_db_transfer_bindings(sqlite3_stmt *, sqlite3_stmt *);)
 #define switch_core_db_transfer_bindings sqlite3_transfer_bindings
-
 /**
  * The pUserData parameter to the switch_core_db_create_function()
  * routine used to register user functions is available to
  * the implementation of the function using this call.
  */
-DoxyDefine(void *switch_core_db_user_data(sqlite3_context*);)
+DoxyDefine(void *switch_core_db_user_data(sqlite3_context *);)
 #define switch_core_db_user_data sqlite3_user_data
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1549,9 +1454,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(const void *switch_core_db_value_blob(sqlite3_value*);)
+DoxyDefine(const void *switch_core_db_value_blob(sqlite3_value *);)
 #define switch_core_db_value_blob sqlite3_value_blob
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1560,9 +1464,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(int switch_core_db_value_bytes(sqlite3_value*);)
+DoxyDefine(int switch_core_db_value_bytes(sqlite3_value *);)
 #define switch_core_db_value_bytes sqlite3_value_bytes
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1571,9 +1474,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(int switch_core_db_value_bytes16(sqlite3_value*);)
+DoxyDefine(int switch_core_db_value_bytes16(sqlite3_value *);)
 #define switch_core_db_value_bytes16 sqlite3_value_bytes16
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1582,9 +1484,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(double switch_core_db_value_double(sqlite3_value*);)
+DoxyDefine(double switch_core_db_value_double(sqlite3_value *);)
 #define switch_core_db_value_double sqlite3_value_double
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1593,9 +1494,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(int switch_core_db_value_int(sqlite3_value*);)
+DoxyDefine(int switch_core_db_value_int(sqlite3_value *);)
 #define switch_core_db_value_int sqlite3_value_int
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1604,9 +1504,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(sqlite_int64 switch_core_db_value_int64(sqlite3_value*);)
+	DoxyDefine(sqlite_int64 switch_core_db_value_int64(sqlite3_value *);)
 #define switch_core_db_value_int64 sqlite3_value_int64
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1615,9 +1514,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(const unsigned char *switch_core_db_value_text(sqlite3_value*);)
+DoxyDefine(const unsigned char *switch_core_db_value_text(sqlite3_value *);)
 #define switch_core_db_value_text sqlite3_value_text
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1626,9 +1524,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(const void *switch_core_db_value_text16(sqlite3_value*);)
+DoxyDefine(const void *switch_core_db_value_text16(sqlite3_value *);)
 #define switch_core_db_value_text16 sqlite3_value_text16
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1637,9 +1534,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(const void *switch_core_db_value_text16be(sqlite3_value*);)
+DoxyDefine(const void *switch_core_db_value_text16be(sqlite3_value *);)
 #define switch_core_db_value_text16be sqlite3_value_text16be
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1648,9 +1544,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(const void *switch_core_db_value_text16le(sqlite3_value*);)
+DoxyDefine(const void *switch_core_db_value_text16le(sqlite3_value *);)
 #define switch_core_db_value_text16le sqlite3_value_text16le
-
 /**
  * returns information about parameters to
  * a user-defined function.  Function implementations use this routines
@@ -1659,10 +1554,8 @@
  * sqlite3_value* pointer instead of an sqlite3_stmt* and an integer
  * column number.
  */
-DoxyDefine(int switch_core_db_value_type(sqlite3_value*);)
+DoxyDefine(int switch_core_db_value_type(sqlite3_value *);)
 #define switch_core_db_value_type sqlite3_value_type
-
-
 /**
  * This routine is a variant of the "sprintf()" from the
  * standard C library.  The resulting string is written into memory
@@ -1704,10 +1597,9 @@
  * should always use %q instead of %s when inserting text into a string 
  * literal.
  */
-DoxyDefine(char *switch_core_db_mprintf(const char*,...);)
+DoxyDefine(char *switch_core_db_mprintf(const char *, ...);)
 #define switch_core_db_mprintf sqlite3_mprintf
 #define switch_mprintf sqlite3_mprintf
-
 /**
  * This routine is a variant of the "sprintf()" from the
  * standard C library.  The resulting string is written into memory
@@ -1749,9 +1641,8 @@
  * should always use %q instead of %s when inserting text into a string 
  * literal.
  */
-DoxyDefine(char *switch_core_db_vmprintf(const char*, va_list);)
+DoxyDefine(char *switch_core_db_vmprintf(const char *, va_list);)
 #define switch_core_db_vmprintf sqlite3_vmprintf
-
 /**
  * This routine is a variant of the "sprintf()" from the
  * standard C library.  The resulting string is written into memory
@@ -1793,22 +1684,17 @@
  * should always use %q instead of %s when inserting text into a string 
  * literal.
  */
-DoxyDefine(char *switch_core_db_snprintf(int,char*,const char*, ...);)
+DoxyDefine(char *switch_core_db_snprintf(int, char *, const char *, ...);)
 #define switch_core_db_snprintf sqlite3_snprintf
-
 /**
  * call this routine to free memory malloced by a call to switch_core_db_mprintf, switch_core_db_vmprintf, or switch_core_db_snprintf
  */
 DoxyDefine(void switch_core_db_free(char *z);)
 #define switch_core_db_free sqlite3_free
-
 /** @} */
 /** @} */
-
-SWITCH_END_EXTERN_C
-
+	SWITCH_END_EXTERN_C
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_stun.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_stun.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_stun.h	Tue Apr 24 10:14:28 2007
@@ -38,59 +38,57 @@
 #define _SWITCH_STUN_PARSER_H
 
 SWITCH_BEGIN_EXTERN_C
-
 #define SWITCH_STUN_DEFAULT_PORT 3478
 #define SWITCH_STUN_PACKET_MIN_LEN 20
-
-typedef enum {
-	SWITCH_STUN_BINDING_REQUEST					= 0x0001,
-	SWITCH_STUN_BINDING_RESPONSE					= 0x0101,
-	SWITCH_STUN_BINDING_ERROR_RESPONSE				= 0x0111,
-	SWITCH_STUN_SHARED_SECRET_REQUEST				= 0x0002,
-	SWITCH_STUN_SHARED_SECRET_RESPONSE				= 0x0102,
-	SWITCH_STUN_SHARED_SECRET_ERROR_RESPONSE 		= 0x0112,
-	SWITCH_STUN_ALLOCATE_REQUEST					= 0x0003,
-	SWITCH_STUN_ALLOCATE_RESPONSE					= 0x0103,
-	SWITCH_STUN_ALLOCATE_ERROR_RESPONSE			= 0x0113,
-	SWITCH_STUN_SEND_REQUEST						= 0x0004,
-	SWITCH_STUN_SEND_RESPONSE						= 0x0104,
-	SWITCH_STUN_SEND_ERROR_RESPONSE				= 0x0114,
-	SWITCH_STUN_DATA_INDICATION					= 0x0115
+	typedef enum {
+	SWITCH_STUN_BINDING_REQUEST = 0x0001,
+	SWITCH_STUN_BINDING_RESPONSE = 0x0101,
+	SWITCH_STUN_BINDING_ERROR_RESPONSE = 0x0111,
+	SWITCH_STUN_SHARED_SECRET_REQUEST = 0x0002,
+	SWITCH_STUN_SHARED_SECRET_RESPONSE = 0x0102,
+	SWITCH_STUN_SHARED_SECRET_ERROR_RESPONSE = 0x0112,
+	SWITCH_STUN_ALLOCATE_REQUEST = 0x0003,
+	SWITCH_STUN_ALLOCATE_RESPONSE = 0x0103,
+	SWITCH_STUN_ALLOCATE_ERROR_RESPONSE = 0x0113,
+	SWITCH_STUN_SEND_REQUEST = 0x0004,
+	SWITCH_STUN_SEND_RESPONSE = 0x0104,
+	SWITCH_STUN_SEND_ERROR_RESPONSE = 0x0114,
+	SWITCH_STUN_DATA_INDICATION = 0x0115
 } switch_stun_message_t;
 
 typedef enum {
-	SWITCH_STUN_ATTR_MAPPED_ADDRESS				= 0x0001, /* Address */
-	SWITCH_STUN_ATTR_RESPONSE_ADDRESS				= 0x0002, /* Address */
-	SWITCH_STUN_ATTR_CHANGE_REQUEST				= 0x0003, /* UInt32 */
-	SWITCH_STUN_ATTR_SOURCE_ADDRESS				= 0x0004, /* Address */
-	SWITCH_STUN_ATTR_CHANGED_ADDRESS				= 0x0005, /* Address */
-	SWITCH_STUN_ATTR_USERNAME						= 0x0006, /* ByteString, multiple of 4 bytes */
-	SWITCH_STUN_ATTR_PASSWORD						= 0x0007, /* ByteString, multiple of 4 bytes */
-	SWITCH_STUN_ATTR_MESSAGE_INTEGRITY				= 0x0008, /* ByteString, 20 bytes */
-	SWITCH_STUN_ATTR_ERROR_CODE					= 0x0009, /* ErrorCode */
-	SWITCH_STUN_ATTR_UNKNOWN_ATTRIBUTES			= 0x000a, /* UInt16List */
-	SWITCH_STUN_ATTR_REFLECTED_FROM				= 0x000b, /* Address */
-	SWITCH_STUN_ATTR_TRANSPORT_PREFERENCES 		= 0x000c, /* TransportPrefs */
-	SWITCH_STUN_ATTR_LIFETIME						= 0x000d, /* UInt32 */
-	SWITCH_STUN_ATTR_ALTERNATE_SERVER				= 0x000e, /* Address */
-	SWITCH_STUN_ATTR_MAGIC_COOKIE					= 0x000f, /* ByteString, 4 bytes */
-	SWITCH_STUN_ATTR_BANDWIDTH						= 0x0010, /* UInt32 */
-	SWITCH_STUN_ATTR_DESTINATION_ADDRESS			= 0x0011, /* Address */
-	SWITCH_STUN_ATTR_SOURCE_ADDRESS2				= 0x0012, /* Address */
-	SWITCH_STUN_ATTR_DATA							= 0x0013, /* ByteString */
-	SWITCH_STUN_ATTR_OPTIONS						= 0x8001  /* UInt32 */
+	SWITCH_STUN_ATTR_MAPPED_ADDRESS = 0x0001,	/* Address */
+	SWITCH_STUN_ATTR_RESPONSE_ADDRESS = 0x0002,	/* Address */
+	SWITCH_STUN_ATTR_CHANGE_REQUEST = 0x0003,	/* UInt32 */
+	SWITCH_STUN_ATTR_SOURCE_ADDRESS = 0x0004,	/* Address */
+	SWITCH_STUN_ATTR_CHANGED_ADDRESS = 0x0005,	/* Address */
+	SWITCH_STUN_ATTR_USERNAME = 0x0006,	/* ByteString, multiple of 4 bytes */
+	SWITCH_STUN_ATTR_PASSWORD = 0x0007,	/* ByteString, multiple of 4 bytes */
+	SWITCH_STUN_ATTR_MESSAGE_INTEGRITY = 0x0008,	/* ByteString, 20 bytes */
+	SWITCH_STUN_ATTR_ERROR_CODE = 0x0009,	/* ErrorCode */
+	SWITCH_STUN_ATTR_UNKNOWN_ATTRIBUTES = 0x000a,	/* UInt16List */
+	SWITCH_STUN_ATTR_REFLECTED_FROM = 0x000b,	/* Address */
+	SWITCH_STUN_ATTR_TRANSPORT_PREFERENCES = 0x000c,	/* TransportPrefs */
+	SWITCH_STUN_ATTR_LIFETIME = 0x000d,	/* UInt32 */
+	SWITCH_STUN_ATTR_ALTERNATE_SERVER = 0x000e,	/* Address */
+	SWITCH_STUN_ATTR_MAGIC_COOKIE = 0x000f,	/* ByteString, 4 bytes */
+	SWITCH_STUN_ATTR_BANDWIDTH = 0x0010,	/* UInt32 */
+	SWITCH_STUN_ATTR_DESTINATION_ADDRESS = 0x0011,	/* Address */
+	SWITCH_STUN_ATTR_SOURCE_ADDRESS2 = 0x0012,	/* Address */
+	SWITCH_STUN_ATTR_DATA = 0x0013,	/* ByteString */
+	SWITCH_STUN_ATTR_OPTIONS = 0x8001	/* UInt32 */
 } switch_stun_attribute_t;
 
 typedef enum {
-	SWITCH_STUN_ERROR_BAD_REQUEST					= 400,
-	SWITCH_STUN_ERROR_UNAUTHORIZED					= 401,
-	SWITCH_STUN_ERROR_UNKNOWN_ATTRIBUTE			= 420,
-	SWITCH_STUN_ERROR_STALE_CREDENTIALS			= 430,
-	SWITCH_STUN_ERROR_INTEGRITY_CHECK_FAILURE		= 431,
-	SWITCH_STUN_ERROR_MISSING_USERNAME				= 432,
-	SWITCH_STUN_ERROR_USE_TLS						= 433,
-	SWITCH_STUN_ERROR_SERVER_ERROR					= 500,
-	SWITCH_STUN_ERROR_GLOBAL_FAILURE				= 600
+	SWITCH_STUN_ERROR_BAD_REQUEST = 400,
+	SWITCH_STUN_ERROR_UNAUTHORIZED = 401,
+	SWITCH_STUN_ERROR_UNKNOWN_ATTRIBUTE = 420,
+	SWITCH_STUN_ERROR_STALE_CREDENTIALS = 430,
+	SWITCH_STUN_ERROR_INTEGRITY_CHECK_FAILURE = 431,
+	SWITCH_STUN_ERROR_MISSING_USERNAME = 432,
+	SWITCH_STUN_ERROR_USE_TLS = 433,
+	SWITCH_STUN_ERROR_SERVER_ERROR = 500,
+	SWITCH_STUN_ERROR_GLOBAL_FAILURE = 600
 } switch_stun_error_t;
 
 typedef enum {
@@ -138,7 +136,7 @@
   \param len the length of the data
   \return a stun packet pointer to buf to use as an access point
 */
-SWITCH_DECLARE(switch_stun_packet_t *)switch_stun_packet_parse(uint8_t *buf, uint32_t len);
+SWITCH_DECLARE(switch_stun_packet_t *) switch_stun_packet_parse(uint8_t * buf, uint32_t len);
 
 /*!
   \brief Obtain a printable string form of a given value
@@ -146,7 +144,7 @@
   \param value the value to look up
   \return a sring version of value
 */
-SWITCH_DECLARE(const char *)switch_stun_value_to_name(int32_t type, uint32_t value);
+SWITCH_DECLARE(const char *) switch_stun_value_to_name(int32_t type, uint32_t value);
 
 
 /*!
@@ -156,7 +154,7 @@
   \param port the port
   \return true or false
 */
-SWITCH_DECLARE(uint8_t) switch_stun_packet_attribute_get_mapped_address(switch_stun_packet_attribute_t *attribute, char *ipstr, uint16_t *port);
+SWITCH_DECLARE(uint8_t) switch_stun_packet_attribute_get_mapped_address(switch_stun_packet_attribute_t *attribute, char *ipstr, uint16_t * port);
 
 /*!
   \brief Extract a username from a packet attribute
@@ -165,7 +163,7 @@
   \param len the maximum size of the username buffer
   \return a pointer to the username or NULL
 */
-SWITCH_DECLARE(char *)switch_stun_packet_attribute_get_username(switch_stun_packet_attribute_t *attribute, char *username, uint16_t len);
+SWITCH_DECLARE(char *) switch_stun_packet_attribute_get_username(switch_stun_packet_attribute_t *attribute, char *username, uint16_t len);
 
 
 /*!
@@ -175,10 +173,7 @@
   \param buf a pointer to data to use for the packet
   \return a pointer to a ready-to-use stun packet
 */
-SWITCH_DECLARE(switch_stun_packet_t *)switch_stun_packet_build_header(switch_stun_message_t type,
-																	  char *id,
-																	  uint8_t *buf
-																	  );
+SWITCH_DECLARE(switch_stun_packet_t *) switch_stun_packet_build_header(switch_stun_message_t type, char *id, uint8_t * buf);
 
 /*!
   \brief Add a username packet attribute
@@ -197,7 +192,7 @@
   \param port the port of the mapped address
   \return true or false
 */
-SWITCH_DECLARE(uint8_t) switch_stun_packet_attribute_add_binded_address(switch_stun_packet_t *packet, char *ipstr,  uint16_t port);
+SWITCH_DECLARE(uint8_t) switch_stun_packet_attribute_add_binded_address(switch_stun_packet_t *packet, char *ipstr, uint16_t port);
 
 /*!
   \brief Perform a stun lookup
@@ -209,12 +204,8 @@
   \param pool the memory pool to use
   \return SUCCESS or FAIL
 */
-SWITCH_DECLARE(switch_status_t) switch_stun_lookup (char **ip, 
-												  switch_port_t *port,
-												  char *stunip,
-												  switch_port_t stunport,
-												  char **err,
-												  switch_memory_pool_t *pool);
+SWITCH_DECLARE(switch_status_t) switch_stun_lookup(char **ip,
+												   switch_port_t *port, char *stunip, switch_port_t stunport, char **err, switch_memory_pool_t *pool);
 
 
 
@@ -241,9 +232,7 @@
 ///\}
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_types.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_types.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_types.h	Tue Apr 24 10:14:28 2007
@@ -35,11 +35,8 @@
 #define SWITCH_TYPES_H
 
 #include <switch.h>
-#include <ctype.h>
 SWITCH_BEGIN_EXTERN_C
-
 #define SWITCH_SEQ_ESC "\033["
-
 /* Ansi Control character suffixes */
 #define SWITCH_SEQ_HOME_CHAR 'H'
 #define SWITCH_SEQ_HOME_CHAR_STR "H"
@@ -49,11 +46,9 @@
 #define SWITCH_SEQ_CLEARSCR_CHAR0 '2'
 #define SWITCH_SEQ_CLEARSCR_CHAR1 'J'
 #define SWITCH_SEQ_CLEARSCR_CHAR "2J"
-
-#define SWITCH_SEQ_DEFAULT_COLOR SWITCH_SEQ_ESC SWITCH_SEQ_END_COLOR /* Reset to Default fg/bg color */
-#define SWITCH_SEQ_AND_COLOR ";" /* To add multiple color definitions */
-#define SWITCH_SEQ_END_COLOR "m" /* To end color definitions */
-
+#define SWITCH_SEQ_DEFAULT_COLOR SWITCH_SEQ_ESC SWITCH_SEQ_END_COLOR	/* Reset to Default fg/bg color */
+#define SWITCH_SEQ_AND_COLOR ";"	/* To add multiple color definitions */
+#define SWITCH_SEQ_END_COLOR "m"	/* To end color definitions */
 /* Foreground colors values */
 #define SWITCH_SEQ_F_BLACK "30"
 #define SWITCH_SEQ_F_RED "31"
@@ -63,7 +58,6 @@
 #define SWITCH_SEQ_F_MAGEN "35"
 #define SWITCH_SEQ_F_CYAN "36"
 #define SWITCH_SEQ_F_WHITE "37"
-
 /* Background colors values */
 #define SWITCH_SEQ_B_BLACK "40"
 #define SWITCH_SEQ_B_RED "41"
@@ -73,7 +67,6 @@
 #define SWITCH_SEQ_B_MAGEN "45"
 #define SWITCH_SEQ_B_CYAN "46"
 #define SWITCH_SEQ_B_WHITE "47"
-
 /* Preset escape sequences - Change foreground colors only */
 #define SWITCH_SEQ_FBLACK SWITCH_SEQ_ESC SWITCH_SEQ_F_BLACK SWITCH_SEQ_END_COLOR
 #define SWITCH_SEQ_FRED SWITCH_SEQ_ESC SWITCH_SEQ_F_RED SWITCH_SEQ_END_COLOR
@@ -83,7 +76,6 @@
 #define SWITCH_SEQ_FMAGEN SWITCH_SEQ_ESC SWITCH_SEQ_F_MAGEN SWITCH_SEQ_END_COLOR
 #define SWITCH_SEQ_FCYAN SWITCH_SEQ_ESC SWITCH_SEQ_F_CYAN SWITCH_SEQ_END_COLOR
 #define SWITCH_SEQ_FWHITE SWITCH_SEQ_ESC SWITCH_SEQ_F_WHITE SWITCH_SEQ_END_COLOR
-
 #define SWITCH_SEQ_BBLACK SWITCH_SEQ_ESC SWITCH_SEQ_B_BLACK SWITCH_SEQ_END_COLOR
 #define SWITCH_SEQ_BRED SWITCH_SEQ_ESC SWITCH_SEQ_B_RED SWITCH_SEQ_END_COLOR
 #define SWITCH_SEQ_BGREEN SWITCH_SEQ_ESC SWITCH_SEQ_B_GREEN SWITCH_SEQ_END_COLOR
@@ -92,78 +84,61 @@
 #define SWITCH_SEQ_BMAGEN SWITCH_SEQ_ESC SWITCH_SEQ_B_MAGEN SWITCH_SEQ_END_COLOR
 #define SWITCH_SEQ_BCYAN SWITCH_SEQ_ESC SWITCH_SEQ_B_CYAN SWITCH_SEQ_END_COLOR
 #define SWITCH_SEQ_BWHITE SWITCH_SEQ_ESC SWITCH_SEQ_B_WHITE SWITCH_SEQ_END_COLOR
-
 /* Preset escape sequences */
 #define SWITCH_SEQ_HOME SWITCH_SEQ_ESC SWITCH_SEQ_HOME_CHAR_STR
 #define SWITCH_SEQ_CLEARLINE SWITCH_SEQ_ESC SWITCH_SEQ_CLEARLINE_CHAR_STR
 #define SWITCH_SEQ_CLEARLINEEND SWITCH_SEQ_ESC SWITCH_SEQ_CLEARLINEEND_CHAR
 #define SWITCH_SEQ_CLEARSCR SWITCH_SEQ_ESC SWITCH_SEQ_CLEARSCR_CHAR SWITCH_SEQ_HOME
-
-
 #ifdef WIN32
 #define SWITCH_PATH_SEPARATOR "\\"
 #else
 #define SWITCH_PATH_SEPARATOR "/"
 #endif
-
-#ifndef SWITCH_PREFIX_DIR
-#define SWITCH_PREFIX_DIR "."
-#endif
-
-#ifndef SWITCH_MOD_DIR
-#define SWITCH_MOD_DIR SWITCH_PREFIX_DIR SWITCH_PATH_SEPARATOR "mod"
-#endif
-
-#ifndef SWITCH_CONF_DIR
-#define SWITCH_CONF_DIR SWITCH_PREFIX_DIR SWITCH_PATH_SEPARATOR "conf"
-#endif
-
-#ifndef SWITCH_LOG_DIR
-#define SWITCH_LOG_DIR SWITCH_PREFIX_DIR SWITCH_PATH_SEPARATOR "log"
-#endif
-
-#ifndef SWITCH_DB_DIR
-#define SWITCH_DB_DIR SWITCH_PREFIX_DIR SWITCH_PATH_SEPARATOR "db"
-#endif
-
-#ifndef SWITCH_SCRIPT_DIR
-#define SWITCH_SCRIPT_DIR SWITCH_PREFIX_DIR SWITCH_PATH_SEPARATOR "scripts"
-#endif
-
-#ifndef SWITCH_HTDOCS_DIR
-#define SWITCH_HTDOCS_DIR SWITCH_PREFIX_DIR SWITCH_PATH_SEPARATOR "htdocs"
-#endif
-
-#ifndef SWITCH_GRAMMAR_DIR
-#define SWITCH_GRAMMAR_DIR SWITCH_PREFIX_DIR SWITCH_PATH_SEPARATOR "grammar"
-#endif
-
+#define SWITCH_URL_SEPARATOR "://"
 #define SWITCH_ENDPOINT_DISPOSITION_VARIABLE "endpoint_disposition"
+#define SWITCH_HOLD_MUSIC_VARIABLE "hold_music"
 #define SWITCH_EXPORT_VARS_VARIABLE "export_vars"
 #define SWITCH_R_SDP_VARIABLE "switch_r_sdp"
 #define SWITCH_L_SDP_VARIABLE "switch_l_sdp"
 #define SWITCH_B_SDP_VARIABLE "switch_m_sdp"
 #define SWITCH_BRIDGE_VARIABLE "bridge_to"
 #define SWITCH_SIGNAL_BRIDGE_VARIABLE "signal_bridge_to"
+#define SWITCH_SIGNAL_BOND_VARIABLE "signal_bond"
 #define SWITCH_ORIGINATOR_VARIABLE "originator"
 #define SWITCH_ORIGINATOR_CODEC_VARIABLE "originator_codec"
 #define SWITCH_LOCAL_MEDIA_IP_VARIABLE "local_media_ip"
 #define SWITCH_LOCAL_MEDIA_PORT_VARIABLE "local_media_port"
 #define SWITCH_REMOTE_MEDIA_IP_VARIABLE "remote_media_ip"
 #define SWITCH_REMOTE_MEDIA_PORT_VARIABLE "remote_media_port"
+#define SWITCH_REMOTE_VIDEO_IP_VARIABLE "remote_video_ip"
+#define SWITCH_REMOTE_VIDEO_PORT_VARIABLE "remote_video_port"
+#define SWITCH_LOCAL_VIDEO_IP_VARIABLE "local_video_ip"
+#define SWITCH_LOCAL_VIDEO_PORT_VARIABLE "local_video_port"
 #define SWITCH_HANGUP_AFTER_BRIDGE_VARIABLE "hangup_after_bridge"
 #define SWITCH_MAX_FORWARDS_VARIABLE "max_forwards"
-
 #define SWITCH_SPEECH_KEY "speech"
 #define SWITCH_UUID_BRIDGE "uuid_bridge"
 #define SWITCH_BITS_PER_BYTE 8
-typedef uint8_t switch_byte_t;
+	typedef uint8_t switch_byte_t;
+
+
+typedef enum {
+	SUF_NONE = 0,
+	SUF_THREAD_RUNNING = (1 << 0),
+	SUF_READY = (1 << 1),
+	SUF_NATIVE = (1 << 2)
+} switch_unicast_flag_t;
+
+typedef enum {
+	SWITCH_FALSE = 0,
+	SWITCH_TRUE = 1
+} switch_bool_t;
 
 typedef enum {
 	SSM_NA,
 	SSM_PRONOUNCED,
 	SSM_ITERATED,
-    SSM_COUNTED
+	SSM_COUNTED
 } switch_say_method_t;
 
 typedef enum {
@@ -187,6 +162,18 @@
 	SST_NAME_PHONETIC,
 } switch_say_type_t;
 
+typedef enum {
+	SMA_NONE,
+	SMA_GET,
+	SMA_SET
+} switch_management_action_t;
+
+typedef enum {
+	SSHF_NONE = 0,
+	SSHF_OWN_THREAD = (1 << 0),
+	SSHF_FREE_ARG = (1 << 1),
+	SSHF_NO_DEL = (1 << 2)
+} switch_scheduler_flag_t;
 
 typedef enum {
 	SMF_NONE = 0,
@@ -194,6 +181,7 @@
 	SMF_ECHO_ALEG = (1 << 1),
 	SMF_ECHO_BLEG = (1 << 2),
 	SMF_FORCE = (1 << 3),
+	SMF_LOOP = (1 << 4)
 } switch_media_flag_t;
 
 typedef enum {
@@ -242,12 +230,11 @@
 SWITCH_DECLARE_DATA extern switch_directories SWITCH_GLOBAL_dirs;
 
 #define SWITCH_THREAD_STACKSIZE 240 * 1024
-#define SWITCH_RECCOMMENDED_BUFFER_SIZE 3968
+#define SWITCH_RECOMMENDED_BUFFER_SIZE 3968
 #define SWITCH_MAX_CODECS 30
 #define SWITCH_MAX_STATE_HANDLERS 30
-#define SWITCH_TRUE 1
-#define SWITCH_FALSE 0
 #define SWITCH_CORE_QUEUE_LEN 100000
+#define SWITCH_MAX_MANAGEMENT_BUFFER_LEN 1024 * 8
 
 typedef enum {
 	SWITCH_CPF_SCREEN = (1 << 0),
@@ -256,12 +243,12 @@
 } switch_caller_profile_flag_t;
 
 typedef enum {
-	SWITCH_AUDIO_COL_STR_TITLE                    = 0x01,
-	SWITCH_AUDIO_COL_STR_COPYRIGHT                = 0x02,
-	SWITCH_AUDIO_COL_STR_SOFTWARE                 = 0x03,
-	SWITCH_AUDIO_COL_STR_ARTIST                   = 0x04,
-	SWITCH_AUDIO_COL_STR_COMMENT                  = 0x05,
-	SWITCH_AUDIO_COL_STR_DATE                     = 0x06
+	SWITCH_AUDIO_COL_STR_TITLE = 0x01,
+	SWITCH_AUDIO_COL_STR_COPYRIGHT = 0x02,
+	SWITCH_AUDIO_COL_STR_SOFTWARE = 0x03,
+	SWITCH_AUDIO_COL_STR_ARTIST = 0x04,
+	SWITCH_AUDIO_COL_STR_COMMENT = 0x05,
+	SWITCH_AUDIO_COL_STR_DATE = 0x06
 } switch_audio_col_t;
 
 typedef enum {
@@ -283,12 +270,13 @@
 </pre>
  */
 typedef enum {
-	SWITCH_VAD_FLAG_TALKING = ( 1 << 0 ),
-	SWITCH_VAD_FLAG_EVENTS_TALK = ( 1 << 1 ),
-	SWITCH_VAD_FLAG_EVENTS_NOTALK = ( 1 << 2 ),
-	SWITCH_VAD_FLAG_CNG = ( 1 << 3)
+	SWITCH_VAD_FLAG_TALKING = (1 << 0),
+	SWITCH_VAD_FLAG_EVENTS_TALK = (1 << 1),
+	SWITCH_VAD_FLAG_EVENTS_NOTALK = (1 << 2),
+	SWITCH_VAD_FLAG_CNG = (1 << 3)
 } switch_vad_flag_t;
 
+#define SWITCH_RTP_CNG_PAYLOAD 13
 
 /*!
   \enum switch_rtp_flag_t
@@ -307,11 +295,12 @@
 	SWITCH_RTP_FLAG_MINI		  - Use mini RTP when possible
 	SWITCH_RTP_FLAG_DATAWAIT	  - Do not return from reads unless there is data even when non blocking
 	SWITCH_RTP_FLAG_BUGGY_2833    - Emulate the bug in cisco equipment to allow interop
-	SWITCH_RTP_FLAG_PASS_RFC2833     - Pass 2833 (ignore it)
+	SWITCH_RTP_FLAG_PASS_RFC2833  - Pass 2833 (ignore it)
+	SWITCH_RTP_FLAG_AUTO_CNG      - Generate outbound CNG frames when idle
 </pre>
  */
 typedef enum {
-	SWITCH_RTP_FLAG_NOBLOCK = ( 1 << 0),
+	SWITCH_RTP_FLAG_NOBLOCK = (1 << 0),
 	SWITCH_RTP_FLAG_IO = (1 << 1),
 	SWITCH_RTP_FLAG_USE_TIMER = (1 << 2),
 	SWITCH_RTP_FLAG_TIMER_RECLOCK = (1 << 3),
@@ -320,11 +309,12 @@
 	SWITCH_RTP_FLAG_RAW_WRITE = (1 << 6),
 	SWITCH_RTP_FLAG_GOOGLEHACK = (1 << 7),
 	SWITCH_RTP_FLAG_VAD = (1 << 8),
-	SWITCH_RTP_FLAG_BREAK = ( 1 << 9),
-	SWITCH_RTP_FLAG_MINI = ( 1 << 10),
+	SWITCH_RTP_FLAG_BREAK = (1 << 9),
+	SWITCH_RTP_FLAG_MINI = (1 << 10),
 	SWITCH_RTP_FLAG_DATAWAIT = (1 << 11),
 	SWITCH_RTP_FLAG_BUGGY_2833 = (1 << 12),
-	SWITCH_RTP_FLAG_PASS_RFC2833 = (1 << 13)
+	SWITCH_RTP_FLAG_PASS_RFC2833 = (1 << 13),
+	SWITCH_RTP_FLAG_AUTO_CNG = (1 << 14)
 } switch_rtp_flag_t;
 
 /*!
@@ -363,6 +353,7 @@
 <pre>
 	SWITCH_MESSAGE_REDIRECT_AUDIO     - Indication to redirect audio to another location if possible
 	SWITCH_MESSAGE_TRANSMIT_TEXT      - A text message
+	SWITCH_MESSAGE_INDICATE_ANSWER    - indicate answer
 	SWITCH_MESSAGE_INDICATE_PROGRESS  - indicate progress 
 	SWITCH_MESSAGE_INDICATE_BRIDGE    - indicate a bridge starting
 	SWITCH_MESSAGE_INDICATE_UNBRIDGE  - indicate a bridge ending
@@ -372,11 +363,13 @@
 	SWITCH_MESSAGE_INDICATE_HOLD      - indicate hold
 	SWITCH_MESSAGE_INDICATE_UNHOLD    - indicate unhold
 	SWITCH_MESSAGE_INDICATE_REDIRECT  - indicate redirect
+	SWITCH_MESSAGE_INDICATE_REJECT    - indicate reject
 </pre>
  */
 typedef enum {
 	SWITCH_MESSAGE_REDIRECT_AUDIO,
 	SWITCH_MESSAGE_TRANSMIT_TEXT,
+	SWITCH_MESSAGE_INDICATE_ANSWER,
 	SWITCH_MESSAGE_INDICATE_PROGRESS,
 	SWITCH_MESSAGE_INDICATE_BRIDGE,
 	SWITCH_MESSAGE_INDICATE_UNBRIDGE,
@@ -386,7 +379,8 @@
 	SWITCH_MESSAGE_INDICATE_NOMEDIA,
 	SWITCH_MESSAGE_INDICATE_HOLD,
 	SWITCH_MESSAGE_INDICATE_UNHOLD,
-	SWITCH_MESSAGE_INDICATE_REDIRECT
+	SWITCH_MESSAGE_INDICATE_REDIRECT,
+	SWITCH_MESSAGE_INDICATE_REJECT
 } switch_core_session_message_types_t;
 
 
@@ -464,7 +458,7 @@
 typedef enum {
 	SWITCH_LOG_CONSOLE = 8,
 	SWITCH_LOG_DEBUG = 7,
-	SWITCH_LOG_INFO  = 6,
+	SWITCH_LOG_INFO = 6,
 	SWITCH_LOG_NOTICE = 5,
 	SWITCH_LOG_WARNING = 4,
 	SWITCH_LOG_ERROR = 3,
@@ -493,7 +487,6 @@
 	SCSMF_DYNAMIC = (1 << 0)
 } switch_core_session_message_flag_t;
 
-#define SWITCH_UUID_FORMATTED_LENGTH APR_UUID_FORMATTED_LENGTH 	
 #define SWITCH_CHANNEL_LOG SWITCH_CHANNEL_ID_LOG, __FILE__, __SWITCH_FUNC__, __LINE__
 #define SWITCH_CHANNEL_LOG_CLEAN SWITCH_CHANNEL_ID_LOG_CLEAN, __FILE__, __SWITCH_FUNC__, __LINE__
 #define SWITCH_CHANNEL_EVENT SWITCH_CHANNEL_ID_EVENT, __FILE__, __SWITCH_FUNC__, __LINE__
@@ -524,7 +517,7 @@
 	CS_HOLD,
 	CS_HIBERNATE,
 	CS_HANGUP,
-	CS_DONE 
+	CS_DONE
 } switch_channel_state_t;
 
 
@@ -552,29 +545,37 @@
 CF_REPEAT_STATE = (1 << 16) - Tell the state machine to repeat a state
 CF_GEN_RINGBACK = (1 << 17) - Channel is generating it's own ringback
 CF_RING_READY   = (1 << 18) - Channel is ready to send ringback
+CF_BREAK        = (1 << 19) - Channel should stop what it's doing
+CF_BROADCAST    = (1 << 20) - Channel is broadcasting
+CF_UNICAST      = (1 << 21) - Channel has a unicast connection
+CF_VIDEO		= (1 << 22) - Channel has video
 </pre>
  */
 
 typedef enum {
-	CF_ANSWERED   	= (1 <<  0),
-	CF_OUTBOUND   	= (1 <<  1),
-	CF_EARLY_MEDIA	= (1 <<  2),
-	CF_ORIGINATOR	= (1 <<  3),
-	CF_TRANSFER		= (1 <<  4),
-	CF_ACCEPT_CNG	= (1 <<  5),
-	CF_LOCK_THREAD	= (1 <<  6),
-	CF_BRIDGED		= (1 <<  7),
-	CF_HOLD			= (1 <<  8),
-	CF_SERVICE		= (1 <<  9),
-	CF_TAGGED		= (1 << 10),
-	CF_WINNER		= (1 << 11),
-	CF_CONTROLLED	= (1 << 12),
-	CF_NOMEDIA		= (1 << 13),
-	CF_SUSPEND		= (1 << 14),
-	CF_EVENT_PARSE	= (1 << 15),
-    CF_REPEAT_STATE = (1 << 16),
-	CF_GEN_RINGBACK	= (1 << 17),
-	CF_RING_READY   = (1 << 18)
+	CF_ANSWERED = (1 << 0),
+	CF_OUTBOUND = (1 << 1),
+	CF_EARLY_MEDIA = (1 << 2),
+	CF_ORIGINATOR = (1 << 3),
+	CF_TRANSFER = (1 << 4),
+	CF_ACCEPT_CNG = (1 << 5),
+	CF_LOCK_THREAD = (1 << 6),
+	CF_BRIDGED = (1 << 7),
+	CF_HOLD = (1 << 8),
+	CF_SERVICE = (1 << 9),
+	CF_TAGGED = (1 << 10),
+	CF_WINNER = (1 << 11),
+	CF_CONTROLLED = (1 << 12),
+	CF_NOMEDIA = (1 << 13),
+	CF_SUSPEND = (1 << 14),
+	CF_EVENT_PARSE = (1 << 15),
+	CF_REPEAT_STATE = (1 << 16),
+	CF_GEN_RINGBACK = (1 << 17),
+	CF_RING_READY = (1 << 18),
+	CF_BREAK = (1 << 19),
+	CF_BROADCAST = (1 << 20),
+	CF_UNICAST = (1 << 21),
+	CF_VIDEO = (1 << 22)
 } switch_channel_flag_t;
 
 
@@ -585,12 +586,14 @@
 <pre>
 SFF_CNG       = (1 <<  0) - Frame represents comfort noise
 SFF_RAW_RTP   = (1 <<  1) - Frame has raw rtp accessible
+SFF_RTP_HEADER = (1 << 2) - Get the rtp header from the frame header
 </pre>
  */
 typedef enum {
 	SFF_NONE = 0,
 	SFF_CNG = (1 << 0),
-	SFF_RAW_RTP = (1 << 1)
+	SFF_RAW_RTP = (1 << 1),
+	SFF_RTP_HEADER = (1 << 2)
 } switch_frame_flag_t;
 
 
@@ -612,7 +615,7 @@
 	SWITCH_SIG_NONE,
 	SWITCH_SIG_KILL,
 	SWITCH_SIG_XFER,
-    SWITCH_SIG_BREAK
+	SWITCH_SIG_BREAK
 } switch_signal_t;
 
 /*!
@@ -630,14 +633,14 @@
 </pre>
 */
 typedef enum {
-	SWITCH_CODEC_FLAG_ENCODE =			(1 <<  0),
-	SWITCH_CODEC_FLAG_DECODE =			(1 <<  1),
-	SWITCH_CODEC_FLAG_SILENCE_START =	(1 <<  2),
-	SWITCH_CODEC_FLAG_SILENCE_STOP =	(1 <<  3),
-	SWITCH_CODEC_FLAG_SILENCE =			(1 <<  4),
-	SWITCH_CODEC_FLAG_FREE_POOL =		(1 <<  5),
-	SWITCH_CODEC_FLAG_AAL2 =			(1 <<  6),
-	SWITCH_CODEC_FLAG_PASSTHROUGH =		(1 <<  7)
+	SWITCH_CODEC_FLAG_ENCODE = (1 << 0),
+	SWITCH_CODEC_FLAG_DECODE = (1 << 1),
+	SWITCH_CODEC_FLAG_SILENCE_START = (1 << 2),
+	SWITCH_CODEC_FLAG_SILENCE_STOP = (1 << 3),
+	SWITCH_CODEC_FLAG_SILENCE = (1 << 4),
+	SWITCH_CODEC_FLAG_FREE_POOL = (1 << 5),
+	SWITCH_CODEC_FLAG_AAL2 = (1 << 6),
+	SWITCH_CODEC_FLAG_PASSTHROUGH = (1 << 7)
 } switch_codec_flag_t;
 
 
@@ -653,12 +656,12 @@
 </pre>
 */
 typedef enum {
-	SWITCH_SPEECH_FLAG_NONE =			0,
-	SWITCH_SPEECH_FLAG_HASTEXT =		(1 <<  0),
-	SWITCH_SPEECH_FLAG_PEEK =			(1 <<  1),
-	SWITCH_SPEECH_FLAG_FREE_POOL =		(1 <<  2),
-	SWITCH_SPEECH_FLAG_BLOCKING =		(1 <<  3),
-	SWITCH_SPEECH_FLAG_PAUSE =			(1 <<  4)
+	SWITCH_SPEECH_FLAG_NONE = 0,
+	SWITCH_SPEECH_FLAG_HASTEXT = (1 << 0),
+	SWITCH_SPEECH_FLAG_PEEK = (1 << 1),
+	SWITCH_SPEECH_FLAG_FREE_POOL = (1 << 2),
+	SWITCH_SPEECH_FLAG_BLOCKING = (1 << 3),
+	SWITCH_SPEECH_FLAG_PAUSE = (1 << 4)
 
 } switch_speech_flag_t;
 
@@ -674,12 +677,12 @@
 </pre>
 */
 typedef enum {
-	SWITCH_ASR_FLAG_NONE =			0,
-	SWITCH_ASR_FLAG_DATA =			(1 <<  0),
-	SWITCH_ASR_FLAG_FREE_POOL =		(1 <<  1),
-	SWITCH_ASR_FLAG_CLOSED =		(1 <<  2),
-	SWITCH_ASR_FLAG_FIRE_EVENTS =	(1 <<  3),
-	SWITCH_ASR_FLAG_AUTO_RESUME = 	(1 <<  4)
+	SWITCH_ASR_FLAG_NONE = 0,
+	SWITCH_ASR_FLAG_DATA = (1 << 0),
+	SWITCH_ASR_FLAG_FREE_POOL = (1 << 1),
+	SWITCH_ASR_FLAG_CLOSED = (1 << 2),
+	SWITCH_ASR_FLAG_FIRE_EVENTS = (1 << 3),
+	SWITCH_ASR_FLAG_AUTO_RESUME = (1 << 4)
 } switch_asr_flag_t;
 
 /*!
@@ -690,7 +693,7 @@
 </pre>
 */
 typedef enum {
-	SWITCH_DIRECTORY_FLAG_FREE_POOL =		(1 <<  0),
+	SWITCH_DIRECTORY_FLAG_FREE_POOL = (1 << 0),
 
 } switch_directory_flag_t;
 
@@ -720,7 +723,7 @@
 </pre>
 */
 typedef enum {
-		SWITCH_TIMER_FLAG_FREE_POOL =		(1 <<  0),
+	SWITCH_TIMER_FLAG_FREE_POOL = (1 << 0),
 } switch_timer_flag_t;
 
 
@@ -753,20 +756,24 @@
 SWITCH_FILE_DATA_DOUBLE =       (1 <<  6) - Read data in doubles
 SWITCH_FILE_DATA_RAW =          (1 <<  7) - Read data as is
 SWITCH_FILE_PAUSE =             (1 <<  8) - Pause
-SWITCH_FILE_NATIVE =            (1 <<  8) - File is in native format (no transcoding)
+SWITCH_FILE_NATIVE =            (1 <<  9) - File is in native format (no transcoding)
+SWITCH_FILE_SEEK = 				(1 << 10) - File has done a seek
+SWITCH_FILE_OPEN =              (1 << 11) - File is open
 </pre>
  */
 typedef enum {
-	SWITCH_FILE_FLAG_READ =			(1 <<  0),
-	SWITCH_FILE_FLAG_WRITE =		(1 <<  1),
-	SWITCH_FILE_FLAG_FREE_POOL =	(1 <<  2),
-	SWITCH_FILE_DATA_SHORT =		(1 <<  3),
-	SWITCH_FILE_DATA_INT =			(1 <<  4),
-	SWITCH_FILE_DATA_FLOAT =		(1 <<  5),
-	SWITCH_FILE_DATA_DOUBLE =		(1 <<  6),
-	SWITCH_FILE_DATA_RAW =			(1 <<  7),
-	SWITCH_FILE_PAUSE =				(1 <<  8),
-	SWITCH_FILE_NATIVE = 			(1 <<  9)
+	SWITCH_FILE_FLAG_READ = (1 << 0),
+	SWITCH_FILE_FLAG_WRITE = (1 << 1),
+	SWITCH_FILE_FLAG_FREE_POOL = (1 << 2),
+	SWITCH_FILE_DATA_SHORT = (1 << 3),
+	SWITCH_FILE_DATA_INT = (1 << 4),
+	SWITCH_FILE_DATA_FLOAT = (1 << 5),
+	SWITCH_FILE_DATA_DOUBLE = (1 << 6),
+	SWITCH_FILE_DATA_RAW = (1 << 7),
+	SWITCH_FILE_PAUSE = (1 << 8),
+	SWITCH_FILE_NATIVE = (1 << 9),
+	SWITCH_FILE_SEEK = (1 << 10),
+	SWITCH_FILE_OPEN = (1 << 11)
 } switch_file_flag_t;
 
 typedef enum {
@@ -811,11 +818,18 @@
 	SWITCH_EVENT_PRESENCE_IN		- Presence in
 	SWITCH_EVENT_PRESENCE_OUT		- Presence out
 	SWITCH_EVENT_PRESENCE_PROBE		- Presence probe
+	SWITCH_EVENT_MESSAGE_WAITING	- A message is waiting
+	SWITCH_EVENT_MESSAGE_QUERY		- A query for MESSAGE_WAITING events
 	SWITCH_EVENT_CODEC				- Codec Change
 	SWITCH_EVENT_BACKGROUND_JOB		- Background Job
 	SWITCH_EVENT_DETECTED_SPEECH	- Detected Speech
 	SWITCH_EVENT_PRIVATE_COMMAND	- A private command event 
 	SWITCH_EVENT_HEARTBEAT			- Machine is alive
+	SWITCH_EVENT_TRAP				- Error Trap
+	SWITCH_EVENT_ADD_SCHEDULE		- Something has been scheduled
+	SWITCH_EVENT_DEL_SCHEDULE		- Something has been unscheduled
+	SWITCH_EVENT_EXE_SCHEDULE		- Something scheduled has been executed
+	SWITCH_EVENT_RE_SCHEDULE		- Something scheduled has been rescheduled
     SWITCH_EVENT_ALL				- All events at once
 </pre>
 
@@ -851,12 +865,19 @@
 	SWITCH_EVENT_PRESENCE_IN,
 	SWITCH_EVENT_PRESENCE_OUT,
 	SWITCH_EVENT_PRESENCE_PROBE,
+	SWITCH_EVENT_MESSAGE_WAITING,
+	SWITCH_EVENT_MESSAGE_QUERY,
 	SWITCH_EVENT_ROSTER,
 	SWITCH_EVENT_CODEC,
 	SWITCH_EVENT_BACKGROUND_JOB,
 	SWITCH_EVENT_DETECTED_SPEECH,
 	SWITCH_EVENT_PRIVATE_COMMAND,
 	SWITCH_EVENT_HEARTBEAT,
+	SWITCH_EVENT_TRAP,
+	SWITCH_EVENT_ADD_SCHEDULE,
+	SWITCH_EVENT_DEL_SCHEDULE,
+	SWITCH_EVENT_EXE_SCHEDULE,
+	SWITCH_EVENT_RE_SCHEDULE,
 	SWITCH_EVENT_ALL
 } switch_event_types_t;
 
@@ -922,7 +943,8 @@
 	SWITCH_CAUSE_LOSE_RACE = 502,
 	SWITCH_CAUSE_MANAGER_REQUEST = 503,
 	SWITCH_CAUSE_BLIND_TRANSFER = 600,
-	SWITCH_CAUSE_ATTENDED_TRANSFER = 601
+	SWITCH_CAUSE_ATTENDED_TRANSFER = 601,
+	SWITCH_CAUSE_ALLOTTED_TIMEOUT = 602
 } switch_call_cause_t;
 
 typedef enum {
@@ -932,7 +954,9 @@
 	SCSC_CHECK_RUNNING
 } switch_session_ctl_t;
 
+typedef uint16_t switch_port_t;
 typedef uint8_t switch_payload_t;
+typedef struct switch_app_log switch_app_log_t;
 typedef struct switch_rtp switch_rtp_t;
 typedef struct switch_core_session_message switch_core_session_message_t;
 typedef struct switch_event_header switch_event_header_t;
@@ -954,20 +978,9 @@
 typedef struct switch_codec_implementation switch_codec_implementation_t;
 typedef struct switch_buffer switch_buffer_t;
 typedef struct switch_codec_settings switch_codec_settings_t;
-typedef struct switch_config switch_config_t;
 
-typedef struct switch_io_event_hook_outgoing_channel switch_io_event_hook_outgoing_channel_t;
-typedef struct switch_io_event_hook_answer_channel switch_io_event_hook_answer_channel_t;
-typedef struct switch_io_event_hook_receive_message switch_io_event_hook_receive_message_t;
-typedef struct switch_io_event_hook_receive_event switch_io_event_hook_receive_event_t;
-typedef struct switch_io_event_hook_read_frame switch_io_event_hook_read_frame_t;
-typedef struct switch_io_event_hook_write_frame switch_io_event_hook_write_frame_t;
-typedef struct switch_io_event_hook_kill_channel switch_io_event_hook_kill_channel_t;
-typedef struct switch_io_event_hook_waitfor_read switch_io_event_hook_waitfor_read_t;
-typedef struct switch_io_event_hook_waitfor_write switch_io_event_hook_waitfor_write_t;
-typedef struct switch_io_event_hook_send_dtmf switch_io_event_hook_send_dtmf_t;
+
 typedef struct switch_io_routines switch_io_routines_t;
-typedef struct switch_io_event_hooks switch_io_event_hooks_t;
 typedef struct switch_speech_handle switch_speech_handle_t;
 typedef struct switch_asr_handle switch_asr_handle_t;
 typedef struct switch_directory_handle switch_directory_handle_t;
@@ -983,43 +996,29 @@
 typedef struct switch_asr_interface switch_asr_interface_t;
 typedef struct switch_directory_interface switch_directory_interface_t;
 typedef struct switch_chat_interface switch_chat_interface_t;
+typedef struct switch_management_interface switch_management_interface_t;
 typedef struct switch_core_port_allocator switch_core_port_allocator_t;
 typedef struct switch_media_bug switch_media_bug_t;
-typedef void (*switch_media_bug_callback_t)(switch_media_bug_t *, void *, switch_abc_type_t);
-typedef void (*switch_application_function_t)(switch_core_session_t *, char *);
-typedef void (*switch_event_callback_t)(switch_event_t *);
-typedef switch_caller_extension_t *(*switch_dialplan_hunt_function_t)(switch_core_session_t *, void *);
-typedef switch_status_t (*switch_state_handler_t)(switch_core_session_t *);
-typedef switch_status_t (*switch_outgoing_channel_hook_t)(switch_core_session_t *, switch_caller_profile_t *, switch_core_session_t *);
-typedef switch_status_t (*switch_answer_channel_hook_t)(switch_core_session_t *);
-typedef switch_status_t (*switch_receive_message_hook_t)(switch_core_session_t *, switch_core_session_message_t *);
-typedef switch_status_t (*switch_receive_event_hook_t)(switch_core_session_t *, switch_event_t *);
-typedef switch_status_t (*switch_read_frame_hook_t)(switch_core_session_t *, switch_frame_t **, int, switch_io_flag_t, int);
-typedef switch_status_t (*switch_write_frame_hook_t)(switch_core_session_t *, switch_frame_t *, int, switch_io_flag_t, int);
-typedef switch_status_t (*switch_kill_channel_hook_t)(switch_core_session_t *, int);
-typedef switch_status_t (*switch_waitfor_read_hook_t)(switch_core_session_t *, int, int);
-typedef switch_status_t (*switch_waitfor_write_hook_t)(switch_core_session_t *, int, int);
-typedef switch_status_t (*switch_send_dtmf_hook_t)(switch_core_session_t *, char *);
+typedef switch_bool_t (*switch_media_bug_callback_t) (switch_media_bug_t *, void *, switch_abc_type_t);
+typedef void (*switch_application_function_t) (switch_core_session_t *, char *);
+typedef void (*switch_event_callback_t) (switch_event_t *);
+typedef switch_caller_extension_t *(*switch_dialplan_hunt_function_t) (switch_core_session_t *, void *, switch_caller_profile_t *);
+typedef struct switch_scheduler_task switch_scheduler_task_t;
+typedef void (*switch_scheduler_func_t) (switch_scheduler_task_t *task);
+typedef switch_status_t (*switch_state_handler_t) (switch_core_session_t *);
 typedef struct switch_stream_handle switch_stream_handle_t;
-typedef switch_status_t (*switch_stream_handle_write_function_t)(switch_stream_handle_t *handle, const char *fmt, ...);
-typedef switch_status_t (*switch_api_function_t)(char *in, switch_core_session_t *session, switch_stream_handle_t *stream);
-typedef switch_status_t (*switch_input_callback_function_t)(switch_core_session_t *session,
-															void *input,
-															switch_input_type_t input_type,
-															void *buf,
-															unsigned int buflen);
+typedef switch_status_t (*switch_stream_handle_write_function_t) (switch_stream_handle_t *handle, const char *fmt, ...);
+typedef switch_status_t (*switch_api_function_t) (char *in, switch_core_session_t *session, switch_stream_handle_t *stream);
+typedef switch_status_t (*switch_input_callback_function_t) (switch_core_session_t *session, void *input,
+															 switch_input_type_t input_type, void *buf, unsigned int buflen);
 typedef struct switch_say_interface switch_say_interface_t;
 typedef struct {
-    switch_input_callback_function_t input_callback;
-    void *buf;
-    uint32_t buflen;
+	switch_input_callback_function_t input_callback;
+	void *buf;
+	uint32_t buflen;
 } switch_input_args_t;
-typedef switch_status_t (*switch_say_callback_t)(switch_core_session_t *session,
-                                                 char *tosay,
-                                                 switch_say_type_t type,
-                                                 switch_say_method_t method,
-                                                 switch_input_args_t *args);
-typedef int (*switch_core_db_callback_func_t)(void *pArg, int argc, char **argv, char **columnNames);
+typedef switch_status_t (*switch_say_callback_t) (switch_core_session_t *session,
+												  char *tosay, switch_say_type_t type, switch_say_method_t method, switch_input_args_t *args);
 typedef switch_status_t (*switch_module_load_t) (switch_loadable_module_interface_t **, char *);
 typedef switch_status_t (*switch_module_reload_t) (void);
 typedef switch_status_t (*switch_module_pause_t) (void);
@@ -1029,12 +1028,9 @@
 typedef switch_status_t (*switch_module_shutdown_t) (void);
 typedef struct switch_xml *switch_xml_t;
 typedef struct switch_core_time_duration switch_core_time_duration_t;
-typedef switch_xml_t (*switch_xml_search_function_t)(char *section,
-													 char *tag_name,
-													 char *key_name,
-													 char *key_value,
-													 char *params,
-                                                     void *user_data);
+typedef switch_xml_t(*switch_xml_search_function_t) (const char *section,
+													 const char *tag_name, const char *key_name, const char *key_value, const char *params,
+													 void *user_data);
 
 /* things we don't deserve to know about */
 /*! \brief A channel */
@@ -1047,9 +1043,7 @@
 struct switch_ivr_digit_stream_parser;
 
 SWITCH_END_EXTERN_C
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_utils.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_utils.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_utils.h	Tue Apr 24 10:14:28 2007
@@ -39,41 +39,34 @@
 #define SWITCH_UTILS_H
 
 #include <switch.h>
-#include <pcre.h>
 
 SWITCH_BEGIN_EXTERN_C
-
-#ifndef snprintf
-#define snprintf apr_snprintf
-#endif
-#ifndef vsnprintf
-#define vsnprintf apr_vsnprintf
-#endif
-
 #define switch_bytes_per_frame(rate, interval) ((uint32_t)((float)rate / (1000.0f / (float)interval)))
-
 #define SWITCH_SMAX 32767
 #define SWITCH_SMIN -32768
 #define switch_normalize_to_16bit(n) if (n > SWITCH_SMAX) n = SWITCH_SMAX / 2; else if (n < SWITCH_SMIN) n = SWITCH_SMIN / 2;
-
-SWITCH_DECLARE(char *) switch_get_addr(char *buf, switch_size_t len, switch_sockaddr_t *in);
-
-SWITCH_DECLARE(apr_status_t) switch_socket_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock,
-									apr_int32_t flags, char *buf, 
-									apr_size_t *len);
-
-
 #define switch_codec2str(codec,buf,len) snprintf(buf, len, "%s@%uk@%ui", \
                                                  codec->implementation->iananame, \
                                                  codec->implementation->samples_per_second, \
                                                  codec->implementation->microseconds_per_frame / 1000)
-
 #ifdef WIN32
-#define switch_is_file_path(file) (*(file +1) == ':' || *file == '/')
+#define switch_is_file_path(file) (*(file +1) == ':' || *file == '/' || strstr(file, SWITCH_URL_SEPARATOR))
 #else
-#define switch_is_file_path(file) (*file == '/')
+#define switch_is_file_path(file) ((*file == '/') || strstr(file, SWITCH_URL_SEPARATOR))
 #endif
 
+static inline switch_bool_t switch_is_digit_string(char *s) {
+
+	while(s && *s) {
+		if (*s < 48 || *s > 57) {
+			return SWITCH_FALSE;
+		}
+		s++;
+	}
+
+	return SWITCH_TRUE;
+}
+
 /*!
   \brief Evaluate the truthfullness of a string expression
   \param expr a string expression
@@ -84,7 +77,6 @@
 !strcasecmp(expr, "on") ||\
 !strcasecmp(expr, "true") ||\
 atoi(expr))) ? SWITCH_TRUE : SWITCH_FALSE
-
 /*!
   \brief find local ip of the box
   \param buf the buffer to write the ip adress found into
@@ -98,7 +90,7 @@
   \brief find the char representation of an ip adress
   \param buf the buffer to write the ip adress found into
   \param len the length of the buf
-  \param the struct in_addr * to get the adress from
+  \param in the struct in_addr * to get the adress from
   \return the ip adress string
 */
 SWITCH_DECLARE(char *) get_addr(char *buf, switch_size_t len, struct in_addr *in);
@@ -133,10 +125,6 @@
  */
 #define is_dtmf(key)  ((key > 47 && key < 58) || (key > 64 && key < 69) || (key > 96 && key < 101) || key == 35 || key == 42 || key == 87 || key == 119)
 
-/*!
-  \brief Duplicate a string 
-*/
-#define switch_copy_string apr_cpystrn
 
 /*!
   \brief Test for the existance of a flag on an arbitary object
@@ -192,6 +180,60 @@
 */
 #define switch_safe_free(it) if (it) {free(it);it=NULL;}
 
+
+/*!
+  \brief Test if one string is inside another with extra case checking
+  \param s the inner string
+  \param q the big string
+  \return SWITCH_TRUE or SWITCH_FALSE
+*/
+static inline switch_bool_t switch_strstr(char *s, char *q)
+{
+	char *p, *S = NULL, *Q = NULL;
+	switch_bool_t tf = SWITCH_FALSE;
+
+	if (strstr(s, q)) {
+		return SWITCH_TRUE;
+	}
+
+	S = strdup(s);
+	
+	assert(S != NULL);
+
+	for (p = S; p && *p; p++) {
+		*p = (char)toupper(*p);
+	}
+
+	if (strstr(S, q)) {
+		tf = SWITCH_TRUE;
+		goto done;
+	}
+
+	Q = strdup(q);
+	assert(Q != NULL);
+
+	for (p = Q; p && *p; p++) {
+		*p = (char)toupper(*p);
+	}
+	
+	if (strstr(s, Q)) {
+		tf = SWITCH_TRUE;
+		goto done;
+	}
+
+	if (strstr(S, Q)) {
+		tf = SWITCH_TRUE;
+		goto done;
+	}
+	
+ done:
+	switch_safe_free(S);
+	switch_safe_free(Q);
+
+	return tf;
+}
+
+
 /*!
   \brief Test for NULL or zero length string
   \param s the string to test
@@ -209,13 +251,7 @@
 /*!
   \brief Wait a desired number of microseconds and yield the CPU
 */
-#if defined(HAVE_USLEEP)
-#define switch_yield(ms) usleep(ms);
-#elif defined(WIN32)
-#define switch_yield(ms) Sleep((DWORD)((ms) / 1000));
-#else
-#define switch_yield(ms) apr_sleep(ms); //apr_thread_yield();
-#endif
+#define switch_yield(ms) switch_sleep(ms);
 
 /*!
   \brief Converts a string representation of a date into a switch_time_t
@@ -253,22 +289,12 @@
 SWITCH_DECLARE(char *) switch_escape_char(switch_memory_pool_t *pool, char *in, char *delim, char esc);
 
 /*!
-  \brief Create a set of file descriptors to poll
-  \param poll the polfd to create
-  \param sock the socket to add
-  \param flags the flags to modify the behaviour
-  \param pool the memory pool to use
-  \return SWITCH_STATUS_SUCCESS when successful
-*/
-SWITCH_DECLARE(switch_status_t) switch_socket_create_pollfd(switch_pollfd_t *poll, switch_socket_t *sock, switch_int16_t flags, switch_memory_pool_t *pool);
-
-/*!
   \brief Wait for a socket
   \param poll the pollfd to wait on
   \param ms the number of milliseconds to wait
   \return the requested condition
 */
-SWITCH_DECLARE(int) switch_socket_waitfor(switch_pollfd_t *poll, int ms);
+SWITCH_DECLARE(int) switch_socket_waitfor(switch_pollfd_t * poll, int ms);
 
 /*!
   \brief Create a pointer to the file name in a given file path eliminating the directory name
@@ -276,23 +302,24 @@
 */
 SWITCH_DECLARE(const char *) switch_cut_path(const char *in);
 
-#define switch_clean_re(re)	if (re) {\
-				pcre_free(re);\
-				re = NULL;\
-			}
-
 SWITCH_DECLARE(char *) switch_string_replace(const char *string, const char *search, const char *replace);
 SWITCH_DECLARE(switch_status_t) switch_string_match(const char *string, size_t string_len, const char *search, size_t search_len);
-SWITCH_DECLARE(int) switch_perform_regex(char *field, char *expression, pcre **new_re, int *ovector, uint32_t olen);
-SWITCH_DECLARE(void) switch_perform_substitution(pcre *re, int match_count, char *data, char *field_data, char *substituted, uint32_t len, int *ovector);
 
 #define SWITCH_READ_ACCEPTABLE(status) (status == SWITCH_STATUS_SUCCESS || status == SWITCH_STATUS_BREAK)
 SWITCH_DECLARE(size_t) switch_url_encode(char *url, char *buf, size_t len);
 SWITCH_DECLARE(char *) switch_url_decode(char *s);
-SWITCH_END_EXTERN_C
 
+/* malloc or DIE macros */
+#ifdef NDEBUG
+#define switch_malloc(ptr, len) (void)( (!!(ptr = malloc(len))) || (fprintf(stderr,"ABORT! Malloc failure at: %s:%s", __FILE__, __LINE__),abort(), 0), ptr )
+#define switch_zmalloc(ptr, len) (void)( (!!(ptr = malloc(len))) || (fprintf(stderr,"ABORT! Malloc failure at: %s:%s", __FILE__, __LINE__),abort(), 0), memset(ptr, 0, len))
+#else
+#define switch_malloc(ptr, len) (void)(assert(((ptr) = malloc((len)))),ptr)
+#define switch_zmalloc(ptr, len) (void)(assert((ptr = malloc(len))),memset(ptr, 0, len))
 #endif
 
+SWITCH_END_EXTERN_C
+#endif
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/include/switch_xml.h
==============================================================================
--- freeswitch/branches/cparker/src/include/switch_xml.h	(original)
+++ freeswitch/branches/cparker/src/include/switch_xml.h	Tue Apr 24 10:14:28 2007
@@ -55,51 +55,45 @@
 
 #ifndef _SWITCH_XML_H
 #define _SWITCH_XML_H
-#include <switch_types.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <fcntl.h>
+#include <switch.h>
 
 
 ///\defgroup xml1 XML Library Functions
 ///\ingroup core1
 ///\{
 SWITCH_BEGIN_EXTERN_C
-
-#define SWITCH_XML_BUFSIZE 1024 // size of internal memory buffers
-
-typedef enum {
-	SWITCH_XML_ROOT =	   (1 << 0), // root
-	SWITCH_XML_NAMEM =  (1 << 1), // name is malloced
-	SWITCH_XML_TXTM =   (1 << 2), // txt is malloced
-	SWITCH_XML_DUP   =  (1 << 3) // attribute name and value are strduped
+#define SWITCH_XML_BUFSIZE 1024	// size of internal memory buffers
+	typedef enum {
+	SWITCH_XML_ROOT = (1 << 0),	// root
+	SWITCH_XML_NAMEM = (1 << 1),	// name is malloced
+	SWITCH_XML_TXTM = (1 << 2),	// txt is malloced
+	SWITCH_XML_DUP = (1 << 3)	// attribute name and value are strduped
 } switch_xml_flag_t;
 
 /*! \brief A representation of an XML tree */
 struct switch_xml {
 	/*! tag name */
-    char *name;      
+	char *name;
 	/*! tag attributes { name, value, name, value, ... NULL } */
-    char **attr;
+	char **attr;
 	/*! tag character content, empty string if none */
-    char *txt;
-    /*! path to free on destroy*/
-    char *free_path;
+	char *txt;
+	/*! path to free on destroy */
+	char *free_path;
 	/*! tag offset from start of parent tag character content */
-    switch_size_t off;
+	switch_size_t off;
 	/*! next tag with same name in this section at this depth */
-    switch_xml_t next;
-	/*! next tag with different name in same section and depth*/
-    switch_xml_t sibling;
+	switch_xml_t next;
+	/*! next tag with different name in same section and depth */
+	switch_xml_t sibling;
 	/*! next tag, same section and depth, in original order */
-    switch_xml_t ordered;
-	/*! head of sub tag list, NULL if none*/
-    switch_xml_t child;
-	/*! parent tag, NULL if current tag is root tag*/
-    switch_xml_t parent;
+	switch_xml_t ordered;
+	/*! head of sub tag list, NULL if none */
+	switch_xml_t child;
+	/*! parent tag, NULL if current tag is root tag */
+	switch_xml_t parent;
 	/*! flags */
-    uint32_t flags;
+	uint32_t flags;
 };
 
 ///\brief Given a string of xml data and its length, parses it and creates an switch_xml
@@ -122,13 +116,15 @@
 ///\param file a file to parse
 ///\return a formated xml node or NULL
 SWITCH_DECLARE(switch_xml_t) switch_xml_parse_file(const char *file);
-    
+
+SWITCH_DECLARE(switch_xml_t) switch_xml_parse_file_simple(const char *file);
+
 ///\brief Wrapper for switch_xml_parse_str() that accepts a file stream. Reads the entire
 ///\ stream into memory and then parses it. For xml files, use switch_xml_parse_file()
 ///\ or switch_xml_parse_fd()
 ///\param fp a FILE pointer to parse
 ///\return an xml node or NULL
-SWITCH_DECLARE(switch_xml_t) switch_xml_parse_fp(FILE *fp);
+SWITCH_DECLARE(switch_xml_t) switch_xml_parse_fp(FILE * fp);
 
 ///\brief returns the first child tag (one level deeper) with the given name or NULL
 ///\ if not found
@@ -156,7 +152,7 @@
 ///\param xml the xml node
 ///\param idx the index
 ///\return an xml node or NULL
-switch_xml_t switch_xml_idx(switch_xml_t xml, int idx);
+	 switch_xml_t switch_xml_idx(switch_xml_t xml, int idx);
 
 ///\brief returns the name of the given tag
 ///\param xml the xml node
@@ -188,7 +184,7 @@
 ///\ Returns NULL if not found.
 ///\param xml the xml node
 ///\return an xml node or NULL
-SWITCH_DECLARE(switch_xml_t) switch_xml_get(switch_xml_t xml, ...);
+SWITCH_DECLARE(switch_xml_t) switch_xml_get(switch_xml_t xml,...);
 
 ///\brief Converts an switch_xml structure back to xml. Returns a string of xml data that
 ///\ must be freed.
@@ -207,7 +203,7 @@
 ///\param xml the xml node
 ///\note in the case of the root node the readlock will be lifted
 SWITCH_DECLARE(void) switch_xml_free(switch_xml_t xml);
-    
+
 ///\brief returns parser error message or empty string if none
 ///\param xml the xml node
 ///\return the error string or nothing
@@ -228,7 +224,7 @@
 ///\param name the name of the tag
 ///\param off the offset
 ///\return an xml node or NULL
-switch_xml_t switch_xml_add_child(switch_xml_t xml, const char *name, switch_size_t off);
+	 SWITCH_DECLARE(switch_xml_t) switch_xml_add_child(switch_xml_t xml, const char *name, switch_size_t off);
 
 ///\brief wrapper for switch_xml_add_child() that strdup()s name
 ///\param xml the xml node
@@ -241,7 +237,7 @@
 ///\param xml the xml node
 ///\param txt the text
 ///\return an xml node or NULL
-switch_xml_t switch_xml_set_txt(switch_xml_t xml, const char *txt);
+	 SWITCH_DECLARE(switch_xml_t) switch_xml_set_txt(switch_xml_t xml, const char *txt);
 
 ///\brief wrapper for switch_xml_set_txt() that strdup()s txt
 ///\ sets the character content for the given tag and returns the tag
@@ -316,20 +312,24 @@
 ///\param node a pointer to the requested node
 ///\param params optional URL formatted params to pass to external gateways
 ///\return SWITCH_STATUS_SUCCESS if successful root and node will be assigned
-SWITCH_DECLARE(switch_status_t) switch_xml_locate(char *section,
-												  char *tag_name,
-												  char *key_name,
-												  char *key_value,
-												  switch_xml_t *root,
-												  switch_xml_t *node,
-												  char *params);
-												 
+SWITCH_DECLARE(switch_status_t) switch_xml_locate(const char *section,
+												  const char *tag_name,
+												  const char *key_name, const char *key_value, switch_xml_t * root, switch_xml_t * node,
+												  const char *params);
+
+SWITCH_DECLARE(switch_status_t) switch_xml_locate_domain(char *domain_name, char *params, switch_xml_t *root, switch_xml_t *domain);
+SWITCH_DECLARE(switch_status_t) switch_xml_locate_user(char *user_name, char *domain_name, 
+													   char *ip, 
+													   switch_xml_t *root,
+													   switch_xml_t *domain,
+													   switch_xml_t *user);
+
 ///\brief open a config in the core registry
 ///\param file_path the name of the config section e.g. modules.conf
 ///\param node a pointer to point to the node if it is found
 ///\param params optional URL formatted params to pass to external gateways
 ///\return the root xml node associated with the current request or NULL
-SWITCH_DECLARE(switch_xml_t) switch_xml_open_cfg(char *file_path, switch_xml_t *node, char *params);
+SWITCH_DECLARE(switch_xml_t) switch_xml_open_cfg(const char *file_path, switch_xml_t * node, const char *params);
 
 ///\brief bind a search function to an external gateway
 ///\param function the search function to bind
@@ -342,14 +342,11 @@
 ///\brief parse a string for a list of sections
 ///\param str a | delimited list of section names
 ///\return the section mask
-SWITCH_DECLARE(switch_xml_section_t) switch_xml_parse_section_string(char *str);
+SWITCH_DECLARE(switch_xml_section_t) switch_xml_parse_section_string(const char *str);
 
 SWITCH_END_EXTERN_C
-
 ///\}
-
 #endif // _SWITCH_XML_H
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/mod/applications/mod_bridgecall/mod_bridgecall.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_bridgecall/mod_bridgecall.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_bridgecall/mod_bridgecall.c	Tue Apr 24 10:14:28 2007
@@ -39,16 +39,16 @@
 static void audio_bridge_function(switch_core_session_t *session, char *data)
 {
 	switch_channel_t *caller_channel;
-	switch_core_session_t *peer_session;
+	switch_core_session_t *peer_session = NULL;
 	unsigned int timelimit = 60;
 	char *var;
 	uint8_t no_media_bridge = 0;
 	switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
-    uint8_t do_continue = 0;
+	uint8_t do_continue = 0;
 
-    if (switch_strlen_zero(data)) {
-        return;
-    }
+	if (switch_strlen_zero(data)) {
+		return;
+	}
 
 	caller_channel = switch_core_session_get_channel(session);
 	assert(caller_channel != NULL);
@@ -60,9 +60,11 @@
 	if ((var = switch_channel_get_variable(caller_channel, "continue_on_fail"))) {
 		do_continue = switch_true(var);
 	}
-	
-	if ((var = switch_channel_get_variable(caller_channel, "no_media")) && switch_true(var)) {
-		if (!switch_channel_test_flag(caller_channel, CF_ANSWERED) && !switch_channel_test_flag(caller_channel, CF_EARLY_MEDIA)) {
+
+	if (switch_channel_test_flag(caller_channel, CF_NOMEDIA)
+		|| ((var = switch_channel_get_variable(caller_channel, "no_media")) && switch_true(var))) {
+		if (!switch_channel_test_flag(caller_channel, CF_ANSWERED)
+			&& !switch_channel_test_flag(caller_channel, CF_EARLY_MEDIA)) {
 			switch_channel_set_flag(caller_channel, CF_NOMEDIA);
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Channel is already up, delaying point-to-point mode 'till both legs are up.\n");
@@ -72,31 +74,33 @@
 
 	if (switch_ivr_originate(session, &peer_session, &cause, data, timelimit, NULL, NULL, NULL, NULL) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Originate Failed.  Cause: %s\n", switch_channel_cause2str(cause));
-        if (!do_continue && cause != SWITCH_CAUSE_NO_ANSWER) {
-            /* All Causes besides NO_ANSWER terminate the originating session unless continue_on_fail is set.
-               We will pass the fail cause on when we hangup.*/
-            switch_channel_hangup(caller_channel, cause);
-        }
-        /* Otherwise.. nobody answered.  Go back to the dialplan instructions in case there was more to do. */
+		if (!do_continue && cause != SWITCH_CAUSE_NO_ANSWER) {
+			/* All Causes besides NO_ANSWER terminate the originating session unless continue_on_fail is set.
+			   We will pass the fail cause on when we hangup. */
+			switch_channel_hangup(caller_channel, cause);
+		}
+		/* Otherwise.. nobody answered.  Go back to the dialplan instructions in case there was more to do. */
 		return;
 	} else {
 		if (no_media_bridge) {
-            switch_channel_t *peer_channel = switch_core_session_get_channel(peer_session);
-            switch_frame_t *read_frame;
-            /* SIP won't let us redir media until the call has been answered #$^#%& so we will proxy any early media until they do */
-            while(switch_channel_ready(caller_channel) && switch_channel_ready(peer_channel) && !switch_channel_test_flag(peer_channel, CF_ANSWERED)) {
-                switch_status_t status = switch_core_session_read_frame(peer_session, &read_frame, -1, 0);
-                uint8_t bad = 1;
-
-                if (SWITCH_READ_ACCEPTABLE(status) && switch_core_session_write_frame(session, read_frame, -1, 0) == SWITCH_STATUS_SUCCESS) {
-                    bad = 0;
-                }
-                if (bad) {
-                    switch_channel_hangup(caller_channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-                    switch_channel_hangup(peer_channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-                    return;
-                }
-            }
+			switch_channel_t *peer_channel = switch_core_session_get_channel(peer_session);
+			switch_frame_t *read_frame;
+			/* SIP won't let us redir media until the call has been answered #$^#%& so we will proxy any early media until they do */
+			while (switch_channel_ready(caller_channel) && switch_channel_ready(peer_channel)
+				   && !switch_channel_test_flag(peer_channel, CF_ANSWERED)) {
+				switch_status_t status = switch_core_session_read_frame(peer_session, &read_frame, -1, 0);
+				uint8_t bad = 1;
+
+				if (SWITCH_READ_ACCEPTABLE(status)
+					&& switch_core_session_write_frame(session, read_frame, -1, 0) == SWITCH_STATUS_SUCCESS) {
+					bad = 0;
+				}
+				if (bad) {
+					switch_channel_hangup(caller_channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					switch_channel_hangup(peer_channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					goto end;
+				}
+			}
 
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Redirecting media to point-to-point mode.\n");
 			switch_ivr_nomedia(switch_core_session_get_uuid(session), SMF_FORCE);
@@ -109,6 +113,10 @@
 				switch_ivr_multi_threaded_bridge(session, peer_session, NULL, NULL, NULL);
 			}
 		}
+	end:
+		if (peer_session) {
+			switch_core_session_rwunlock(peer_session);
+		}
 	}
 }
 

Modified: freeswitch/branches/cparker/src/mod/applications/mod_commands/mod_commands.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_commands/mod_commands.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_commands/mod_commands.c	Tue Apr 24 10:14:28 2007
@@ -27,6 +27,7 @@
  * Michael Jerris <mike at jerris.com>
  * Johny Kadarisman <jkr888 at gmail.com>
  * Paul Tinsley <jackhammer at gmail.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * 
  * mod_commands.c -- Misc. Command Module
@@ -35,7 +36,7 @@
 #include <switch.h>
 #include <switch_version.h>
 
-static const switch_state_handler_table_t noop_state_handler = {0};
+
 static const char modname[] = "mod_commands";
 static switch_api_interface_t ctl_api_interface;
 static switch_api_interface_t uuid_bridge_api_interface;
@@ -51,6 +52,9 @@
 static switch_api_interface_t media_api_interface;
 static switch_api_interface_t hold_api_interface;
 static switch_api_interface_t broadcast_api_interface;
+static switch_api_interface_t sched_broadcast_api_interface;
+static switch_api_interface_t sched_transfer_api_interface;
+static switch_api_interface_t sched_hangup_api_interface;
 
 static switch_status_t status_function(char *cmd, switch_core_session_t *session, switch_stream_handle_t *stream)
 {
@@ -73,18 +77,16 @@
 		stream->write_function(stream, "<h1>FreeSWITCH Status</h1>\n<b>");
 	}
 
-	stream->write_function(stream, "UP %u year%s, %u day%s, %u hour%s, %u minute%s, %u second%s, %u millisecond%s, %u microsecond%s\n",
-						   duration.yr, duration.yr == 1 ? "" : "s",
-						   duration.day, duration.day == 1 ? "" : "s",
-						   duration.hr, duration.hr == 1 ? "" : "s",
-						   duration.min, duration.min == 1 ? "" : "s",
-						   duration.sec, duration.sec == 1 ? "" : "s",
-						   duration.ms, duration.ms == 1 ? "" : "s",
-						   duration.mms, duration.mms == 1 ? "" : "s"
-						   );
+	stream->write_function(stream,
+						   "UP %u year%s, %u day%s, %u hour%s, %u minute%s, %u second%s, %u millisecond%s, %u microsecond%s\n",
+						   duration.yr, duration.yr == 1 ? "" : "s", duration.day, duration.day == 1 ? "" : "s",
+						   duration.hr, duration.hr == 1 ? "" : "s", duration.min, duration.min == 1 ? "" : "s",
+						   duration.sec, duration.sec == 1 ? "" : "s", duration.ms, duration.ms == 1 ? "" : "s", duration.mms,
+						   duration.mms == 1 ? "" : "s");
 
+	stream->write_function(stream, "%"SWITCH_SIZE_T_FMT" sessions since startup\n", switch_core_session_id() - 1 );
 	stream->write_function(stream, "%d sessions\n", switch_core_session_count());
-	
+
 	if (html) {
 		stream->write_function(stream, "</b>\n");
 	}
@@ -95,7 +97,7 @@
 			int r;
 			refresh++;
 			r = atoi(refresh);
-			if (r > 0) { 
+			if (r > 0) {
 				stream->write_function(stream, "<META HTTP-EQUIV=REFRESH CONTENT=\"%d; URL=/api/status?refresh=%d%s\">\n", r, r, html ? "html=1" : "");
 			}
 		}
@@ -117,7 +119,7 @@
 
 	if ((mydata = strdup(data))) {
 		argc = switch_separate_string(mydata, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
-	
+
 		if (!strcmp(argv[0], "hupall")) {
 			arg = 1;
 			switch_core_session_ctl(SCSC_HUPALL, &arg);
@@ -133,17 +135,17 @@
 		} else {
 			stream->write_function(stream, "INVALID COMMAND [%s]\nUSAGE: fsctl [hupall|pause|resume|shutdown]\n", argv[0]);
 			goto end;
-		} 
+		}
 
 		stream->write_function(stream, "OK\n");
-	end:
+	  end:
 		free(mydata);
 	} else {
 		stream->write_function(stream, "MEM ERR\n");
 	}
 
-    return SWITCH_STATUS_SUCCESS;
-	
+	return SWITCH_STATUS_SUCCESS;
+
 }
 
 static switch_status_t load_function(char *mod, switch_core_session_t *session, switch_stream_handle_t *stream)
@@ -158,8 +160,11 @@
 		return SWITCH_STATUS_SUCCESS;
 	}
 
-	switch_loadable_module_load_module((char *) SWITCH_GLOBAL_dirs.mod_dir, (char *) mod);
-	stream->write_function(stream, "OK\n");
+	if (switch_loadable_module_load_module((char *) SWITCH_GLOBAL_dirs.mod_dir, (char *) mod, SWITCH_TRUE) == SWITCH_STATUS_SUCCESS) {
+		stream->write_function(stream, "OK\n");
+	} else {
+		stream->write_function(stream, "ERROR\n");
+	}
 
 	return SWITCH_STATUS_SUCCESS;
 }
@@ -172,11 +177,11 @@
 	if (session) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	if ((xml_root = switch_xml_open_root(1, &err))) {
 		switch_xml_free(xml_root);
 	}
-	
+
 	stream->write_function(stream, "OK [%s]\n", err);
 
 	return SWITCH_STATUS_SUCCESS;
@@ -207,13 +212,13 @@
 static switch_status_t transfer_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
 	switch_core_session_t *session = NULL;
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	int argc = 0;
 
 	if (isession) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
 
 	if (switch_strlen_zero(cmd) || argc < 2 || argc > 4) {
@@ -223,11 +228,11 @@
 		char *dest = argv[1];
 		char *dp = argv[2];
 		char *context = argv[3];
-		
+
 		if ((session = switch_core_session_locate(uuid))) {
 
 			if (switch_ivr_session_transfer(session, dest, dp, context) == SWITCH_STATUS_SUCCESS) {
-				 stream->write_function(stream, "OK\n");
+				stream->write_function(stream, "OK\n");
 			} else {
 				stream->write_function(stream, "ERROR\n");
 			}
@@ -242,16 +247,99 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
+
+static switch_status_t sched_transfer_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
+{
+	switch_core_session_t *session = NULL;
+	char *argv[6] = { 0 };
+	int argc = 0;
+
+	if (isession) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
+
+	if (switch_strlen_zero(cmd) || argc < 2 || argc > 5) {
+		stream->write_function(stream, "USAGE: %s\n", sched_transfer_api_interface.syntax);
+	} else {
+		char *uuid = argv[1];
+		char *dest = argv[2];
+		char *dp = argv[3];
+		char *context = argv[4];
+		time_t when;
+
+		if (*argv[0] == '+') {
+			when = time(NULL) + atol(argv[0] + 1);
+		} else {
+			when = atol(argv[0]);
+		}
+
+		if ((session = switch_core_session_locate(uuid))) {
+			switch_ivr_schedule_transfer(when, uuid, dest, dp, context);
+			stream->write_function(stream, "OK\n");
+			switch_core_session_rwunlock(session);
+		} else {
+			stream->write_function(stream, "No Such Channel!\n");
+		}
+	}
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+static switch_status_t sched_hangup_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
+{
+	switch_core_session_t *session = NULL;
+	char *argv[4] = { 0 };
+	int argc = 0;
+
+	if (isession) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
+
+	if (switch_strlen_zero(cmd) || argc < 1) {
+		stream->write_function(stream, "USAGE: %s\n", sched_hangup_api_interface.syntax);
+	} else {
+		char *uuid = argv[1];
+		char *cause_str = argv[2];
+		time_t when;
+		switch_call_cause_t cause = SWITCH_CAUSE_ALLOTTED_TIMEOUT;
+
+		if (*argv[0] == '+') {
+			when = time(NULL) + atol(argv[0] + 1);
+		} else {
+			when = atol(argv[0]);
+		}
+
+		if (cause_str) {
+			cause = switch_channel_str2cause(cause_str);
+		}
+
+		if ((session = switch_core_session_locate(uuid))) {
+			switch_ivr_schedule_hangup(when, uuid, cause, SWITCH_FALSE);
+			stream->write_function(stream, "OK\n");
+			switch_core_session_rwunlock(session);
+		} else {
+			stream->write_function(stream, "No Such Channel!\n");
+		}
+	}
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+
 static switch_status_t uuid_media_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	int argc = 0;
 	switch_status_t status = SWITCH_STATUS_FALSE;
-	
+
 	if (isession) {
 		return status;
 	}
-	
+
 	argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
 
 	if (switch_strlen_zero(cmd) || argc < 1) {
@@ -276,14 +364,14 @@
 
 static switch_status_t uuid_broadcast_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	int argc = 0;
 	switch_status_t status = SWITCH_STATUS_FALSE;
 
 	if (isession) {
 		return status;
 	}
-	
+
 	argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
 
 	if (switch_strlen_zero(cmd) || argc < 2) {
@@ -302,7 +390,7 @@
 		} else {
 			flags |= SMF_ECHO_ALEG;
 		}
-		
+
 		status = switch_ivr_broadcast(argv[0], argv[1], flags);
 		stream->write_function(stream, "+OK Message Sent\n");
 	}
@@ -310,16 +398,60 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
+
+static switch_status_t sched_broadcast_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
+{
+	char *argv[4] = { 0 };
+	int argc = 0;
+	switch_status_t status = SWITCH_STATUS_FALSE;
+
+	if (isession) {
+		return status;
+	}
+
+	argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
+
+	if (switch_strlen_zero(cmd) || argc < 3) {
+		stream->write_function(stream, "USAGE: %s\n", sched_broadcast_api_interface.syntax);
+	} else {
+		switch_media_flag_t flags = SMF_NONE;
+		time_t when;
+
+		if (*argv[0] == '+') {
+			when = time(NULL) + atol(argv[0] + 1);
+		} else {
+			when = atol(argv[0]);
+		}
+
+		if (argv[3]) {
+			if (!strcmp(argv[3], "both")) {
+				flags |= (SMF_ECHO_ALEG | SMF_ECHO_BLEG);
+			} else if (!strcmp(argv[3], "aleg")) {
+				flags |= SMF_ECHO_ALEG;
+			} else if (!strcmp(argv[3], "bleg")) {
+				flags |= SMF_ECHO_BLEG;
+			}
+		} else {
+			flags |= SMF_ECHO_ALEG;
+		}
+
+		status = switch_ivr_schedule_broadcast(when, argv[1], argv[2], flags);
+		stream->write_function(stream, "+OK Message Scheduled\n");
+	}
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
 static switch_status_t uuid_hold_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	int argc = 0;
 	switch_status_t status = SWITCH_STATUS_FALSE;
-	
+
 	if (isession) {
 		return status;
 	}
-	
+
 	argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
 
 	if (switch_strlen_zero(cmd) || argc < 1) {
@@ -343,13 +475,13 @@
 
 static switch_status_t uuid_bridge_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	int argc = 0;
 
 	if (isession) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
 
 	if (switch_strlen_zero(cmd) || argc != 2) {
@@ -365,70 +497,70 @@
 
 static switch_status_t session_record_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
-    switch_core_session_t *session = NULL;
-	char *argv[4] = {0};
-    char *uuid = NULL, *action = NULL, *path = NULL;
+	switch_core_session_t *session = NULL;
+	char *argv[4] = { 0 };
+	char *uuid = NULL, *action = NULL, *path = NULL;
 	int argc = 0;
 
 	if (isession) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	if (switch_strlen_zero(cmd)) {
-        goto usage;
-    }
+		goto usage;
+	}
 
 	if ((argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])))) != 3) {
-        goto usage;
-    }
+		goto usage;
+	}
+
+	uuid = argv[0];
+	action = argv[1];
+	path = argv[2];
 
-    uuid = argv[0];
-    action = argv[1];
-    path = argv[2];
-    
-    if (!(session = switch_core_session_locate(uuid))) {
+	if (!(session = switch_core_session_locate(uuid))) {
 		stream->write_function(stream, "-Error Cannot locate session!\n");
-        return SWITCH_STATUS_SUCCESS;
-    }
-    
-    if (switch_strlen_zero(action) || switch_strlen_zero(path)) {
-        goto usage;
-    }
-
-    if (!strcasecmp(action, "start")) {
-        switch_ivr_record_session(session, path, NULL);
-    } else if (!strcasecmp(action, "stop")) {
-        switch_ivr_stop_record_session(session, path);
-    } else {
-        goto usage;
-    }
-
-    goto done;
-
- usage:
-
-    stream->write_function(stream, "USAGE: %s\n", session_record_api_interface.syntax);
-    return SWITCH_STATUS_SUCCESS;
-
- done:
-
-    if (session) {
-        switch_core_session_rwunlock(session);
-    }
+		return SWITCH_STATUS_SUCCESS;
+	}
+
+	if (switch_strlen_zero(action) || switch_strlen_zero(path)) {
+		goto usage;
+	}
+
+	if (!strcasecmp(action, "start")) {
+		switch_ivr_record_session(session, path, NULL);
+	} else if (!strcasecmp(action, "stop")) {
+		switch_ivr_stop_record_session(session, path);
+	} else {
+		goto usage;
+	}
+
+	goto done;
+
+  usage:
+
+	stream->write_function(stream, "USAGE: %s\n", session_record_api_interface.syntax);
+	return SWITCH_STATUS_SUCCESS;
 
-    return SWITCH_STATUS_SUCCESS;
+  done:
+
+	if (session) {
+		switch_core_session_rwunlock(session);
+	}
+
+	return SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t pause_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
 	switch_core_session_t *session = NULL;
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	int argc = 0;
 
 	if (isession) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	argc = switch_separate_string(cmd, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
 
 	if (switch_strlen_zero(cmd) || argc < 2) {
@@ -436,7 +568,7 @@
 	} else {
 		char *uuid = argv[0];
 		char *dest = argv[1];
-		
+
 		if ((session = switch_core_session_locate(uuid))) {
 			switch_channel_t *channel = switch_core_session_get_channel(session);
 
@@ -459,8 +591,8 @@
 static switch_status_t originate_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
 	switch_channel_t *caller_channel;
-	switch_core_session_t *caller_session;
-	char *argv[7] = {0};
+	switch_core_session_t *caller_session = NULL;
+	char *argv[7] = { 0 };
 	int i = 0, x, argc = 0;
 	char *aleg, *exten, *dp, *context, *cid_name, *cid_num;
 	uint32_t timeout = 60;
@@ -479,12 +611,12 @@
 		return SWITCH_STATUS_SUCCESS;
 	}
 
-	for(x = 0; x < argc; x++) {
+	for (x = 0; x < argc; x++) {
 		if (!strcasecmp(argv[x], "undef")) {
 			argv[x] = NULL;
 		}
 	}
-	
+
 	if (!strcasecmp(argv[0], "machine")) {
 		machine = 1;
 		i++;
@@ -496,7 +628,7 @@
 	context = argv[i++];
 	cid_name = argv[i++];
 	cid_num = argv[i++];
-	
+
 	if (!dp) {
 		dp = "XML";
 	}
@@ -509,20 +641,20 @@
 		timeout = atoi(argv[6]);
 	}
 
-	if (switch_ivr_originate(NULL, &caller_session, &cause, aleg, timeout, &noop_state_handler, cid_name, cid_num, NULL) != SWITCH_STATUS_SUCCESS) {
+	if (switch_ivr_originate(NULL, &caller_session, &cause, aleg, timeout, NULL, cid_name, cid_num, NULL) != SWITCH_STATUS_SUCCESS) {
 		if (machine) {
 			stream->write_function(stream, "fail: %s\n", switch_channel_cause2str(cause));
 		} else {
 			stream->write_function(stream, "Cannot Create Outgoing Channel! [%s] cause: %s\n", aleg, switch_channel_cause2str(cause));
 		}
 		return SWITCH_STATUS_SUCCESS;
-	} 
+	}
 
 	caller_channel = switch_core_session_get_channel(caller_session);
 	assert(caller_channel != NULL);
 	switch_channel_clear_state_handler(caller_channel, NULL);
 
-	if (*exten == '&'  && *(exten + 1)) {
+	if (*exten == '&' && *(exten + 1)) {
 		switch_caller_extension_t *extension = NULL;
 		char *app_name = switch_core_session_strdup(caller_session, (exten + 1));
 		char *arg = NULL, *e;
@@ -553,17 +685,184 @@
 		stream->write_function(stream, "Created Session: %s\n", switch_core_session_get_uuid(caller_session));
 	}
 
+	if (caller_session) {
+		switch_core_session_rwunlock(caller_session);
+	}
+
 	return SWITCH_STATUS_SUCCESS;;
 }
 
+static void sch_api_callback(switch_scheduler_task_t *task)
+{
+	char *cmd, *arg = NULL;
+	switch_stream_handle_t stream = { 0 };
+
+	assert(task);
+
+	cmd = (char *) task->cmd_arg;
+
+	if ((arg = strchr(cmd, ' '))) {
+		*arg++ = '\0';
+	}
+
+	SWITCH_STANDARD_STREAM(stream);
+	switch_api_execute(cmd, arg, NULL, &stream);
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Command %s(%s):\n%s\n", cmd, arg, switch_str_nil((char *) stream.data));
+	switch_safe_free(stream.data);
+}
+
+static switch_status_t sched_del_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
+{
+	uint32_t cnt = 0;
+	
+	if (switch_is_digit_string(cmd)) {
+		int64_t tmp;
+		tmp = (uint32_t) atoi(cmd);
+		if (tmp > 0) {
+			cnt = switch_scheduler_del_task_id((uint32_t)tmp);
+		}
+	} else {
+		cnt = switch_scheduler_del_task_group(cmd);
+	}
+
+	stream->write_function(stream, "DELETED: %u\n", cnt);
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+static switch_status_t xml_wrap_api_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
+{
+	char *dcommand, *edata = NULL, *send = NULL, *command, *arg = NULL;
+	switch_stream_handle_t mystream = { 0 };
+	int encoded = 0, elen = 0;
+	
+	if ((dcommand = strdup(cmd))) {
+		if (!strncasecmp(dcommand, "encoded ", 8)) {
+			encoded++;
+			command = dcommand + 8;
+		} else {
+			command = dcommand;
+		}
+
+		if ((arg = strchr(command, ' '))) {
+			*arg++ = '\0';
+		}
+		SWITCH_STANDARD_STREAM(mystream);
+		switch_api_execute(command, arg, NULL, &mystream);
+
+		if (mystream.data) {
+			if (encoded) {
+				elen = (int) strlen(mystream.data) * 3;
+				edata = malloc(elen);
+				assert(edata != NULL);
+				memset(edata, 0, elen);
+				switch_url_encode(mystream.data, edata, elen);
+				send = edata;
+			} else {
+				send = mystream.data;
+			}
+		}
+
+		stream->write_function(stream, 
+							   "<result>\n"
+							   "  <row id=\"1\">\n"
+							   "    <data>%s</data>\n"
+							   "  </row>\n"
+							   "</result>\n",
+							   send ? send : "ERROR"
+							   );
+		switch_safe_free(mystream.data);
+		switch_safe_free(edata);
+		free(dcommand);
+	}
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+static switch_status_t sched_api_function(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
+{
+	char *tm = NULL, *dcmd, *group;
+	time_t when;
+
+	assert(cmd != NULL);
+	tm = strdup(cmd);
+	assert(tm != NULL);
+
+	if ((group = strchr(tm, ' '))) {
+		uint32_t id;
+
+		*group++ = '\0';
+
+		if ((dcmd = strchr(group, ' '))) {
+			*dcmd++ = '\0';
+
+			if (*tm == '+') {
+				when = time(NULL) + atol(tm + 1);
+			} else {
+				when = atol(tm);
+			}
+		
+			id = switch_scheduler_add_task(when, sch_api_callback, (char *) __SWITCH_FUNC__, group, 0, strdup(dcmd), SSHF_FREE_ARG);
+			stream->write_function(stream, "ADDED: %u\n", id);
+			goto good;
+		} 
+	}
+
+	stream->write_function(stream, "Invalid syntax\n");
+
+ good:
+
+	switch_safe_free(tm);
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+
 struct holder {
 	switch_stream_handle_t *stream;
 	char *http;
+	char *delim;
 	uint32_t count;
 	int print_title;
+	switch_xml_t xml;
+	int rows;
 };
 
-static int show_callback(void *pArg, int argc, char **argv, char **columnNames){
+static int show_as_xml_callback(void *pArg, int argc, char **argv, char **columnNames)
+{
+	struct holder *holder = (struct holder *) pArg;
+	switch_xml_t row, field;
+	int x, f_off = 0;
+	char id[50];
+
+	if (holder->count == 0) {
+		if (!(holder->xml = switch_xml_new("result"))) {
+			return -1;
+		}
+	}
+
+	if (!(row = switch_xml_add_child_d(holder->xml, "row", holder->rows++))) {
+		return -1;
+	}
+
+	snprintf(id, sizeof(id), "%d", holder->rows);
+	switch_xml_set_attr_d(row, "row_id", id);
+
+	for(x = 0; x < argc; x++) {
+		if ((field = switch_xml_add_child_d(row, columnNames[x], f_off++))) {
+			switch_xml_set_txt_d(field, argv[x]);
+		} else {
+			return -1;
+		}
+	}
+
+	holder->count++;
+
+	return 0;
+}
+
+static int show_callback(void *pArg, int argc, char **argv, char **columnNames)
+{
 	struct holder *holder = (struct holder *) pArg;
 	int x;
 
@@ -573,26 +872,26 @@
 			holder->stream->write_function(holder->stream, "\n<tr>");
 		}
 
-		for(x = 0; x < argc; x++) {
+		for (x = 0; x < argc; x++) {
 			if (holder->http) {
 				holder->stream->write_function(holder->stream, "<td>");
 				holder->stream->write_function(holder->stream, "<b>%s</b>%s", columnNames[x], x == (argc - 1) ? "</td></tr>\n" : "</td><td>");
 			} else {
-				holder->stream->write_function(holder->stream, "%s%s", columnNames[x], x == (argc - 1) ? "\n" : ",");
+				holder->stream->write_function(holder->stream, "%s%s", columnNames[x], x == (argc - 1) ? "\n" : holder->delim);
 			}
 		}
-	} 
+	}
 
 	if (holder->http) {
 		holder->stream->write_function(holder->stream, "<tr bgcolor=%s>", holder->count % 2 == 0 ? "eeeeee" : "ffffff");
 	}
 
-	for(x = 0; x < argc; x++) {
+	for (x = 0; x < argc; x++) {
 		if (holder->http) {
 			holder->stream->write_function(holder->stream, "<td>");
 			holder->stream->write_function(holder->stream, "%s%s", argv[x] ? argv[x] : "", x == (argc - 1) ? "</td></tr>\n" : "</td><td>");
 		} else {
-			holder->stream->write_function(holder->stream, "%s%s", argv[x] ? argv[x] : "", x == (argc - 1) ? "\n" : ",");
+			holder->stream->write_function(holder->stream, "%s%s", argv[x] ? argv[x] : "", x == (argc - 1) ? "\n" : holder->delim);
 		}
 	}
 
@@ -600,21 +899,35 @@
 	return 0;
 }
 
-static switch_status_t show_function(char *cmd, switch_core_session_t *session, switch_stream_handle_t *stream)
+static switch_status_t show_function(char *data, switch_core_session_t *session, switch_stream_handle_t *stream)
 {
 	char sql[1024];
 	char *errmsg;
 	switch_core_db_t *db = switch_core_db_handle();
-	struct holder holder = {0};
+	struct holder holder = { 0 };
 	int help = 0;
+	char *mydata = NULL, *argv[6] = {0};
+	int argc;
+	char *cmd = NULL, *as = NULL;
 
 	if (session) {
 		return SWITCH_STATUS_FALSE;
 	}
 
-	if (stream->event) {
+	if (data) {
+		if ((mydata = strdup(data))) {
+			argc = switch_separate_string(mydata, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
+		}	
+
+		cmd = argv[0];
+		if (argv[2] && !strcasecmp(argv[1], "as")) {
+			as = argv[2];
+		}
+	}
+	
+	if (!as && stream->event) {
 		holder.http = switch_event_get_header(stream->event, "http-host");
-	} 
+	}
 
 	holder.print_title = 1;
 
@@ -623,14 +936,16 @@
 	if (!cmd) {
 		stream->write_function(stream, "USAGE: %s\n", show_api_interface.syntax);
 		return SWITCH_STATUS_SUCCESS;
-	} else if ( !strcmp(cmd,"codec") || !strcmp(cmd,"dialplan") || !strcmp(cmd,"file") || !strcmp(cmd,"timer")) {
-		sprintf (sql, "select type, name from interfaces where type = '%s'", cmd);
-	} else if (!strcmp(cmd,"application") || !strcmp(cmd,"api")) {
-		sprintf (sql, "select name, description, syntax from interfaces where type = '%s' and description != ''" , cmd);
-	} else if ( !strcmp(cmd,"calls")) {
-		sprintf (sql, "select * from calls");
-	} else if ( !strcmp(cmd,"channels")) {
-		sprintf (sql, "select * from channels");
+	} else if (!strcmp(cmd, "codec") || !strcmp(cmd, "dialplan") || !strcmp(cmd, "file") || !strcmp(cmd, "timer")) {
+		sprintf(sql, "select type, name from interfaces where type = '%s'", cmd);
+	} else if (!strcmp(cmd, "tasks")) {
+		sprintf(sql, "select * from %s", cmd);
+	} else if (!strcmp(cmd, "application") || !strcmp(cmd, "api")) {
+		sprintf(sql, "select name, description, syntax from interfaces where type = '%s' and description != ''", cmd);
+	} else if (!strcmp(cmd, "calls")) {
+		sprintf(sql, "select * from calls");
+	} else if (!strcmp(cmd, "channels")) {
+		sprintf(sql, "select * from channels");
 	} else if (!strncasecmp(cmd, "help", 4)) {
 		char *cmdname = NULL;
 
@@ -638,15 +953,15 @@
 		holder.print_title = 0;
 		if ((cmdname = strchr(cmd, ' ')) != 0) {
 			*cmdname++ = '\0';
-			snprintf (sql, sizeof(sql) - 1, "select name, syntax, description from interfaces where type = 'api' and name = '%s'", cmdname);
+			snprintf(sql, sizeof(sql) - 1, "select name, syntax, description from interfaces where type = 'api' and name = '%s'", cmdname);
 		} else {
-			snprintf (sql, sizeof(sql) - 1, "select name, syntax, description from interfaces where type = 'api'");
+			snprintf(sql, sizeof(sql) - 1, "select name, syntax, description from interfaces where type = 'api'");
 		}
 	} else {
 		stream->write_function(stream, "USAGE: %s\n", show_api_interface.syntax);
 		return SWITCH_STATUS_SUCCESS;
 	}
-    
+
 	holder.stream = stream;
 	holder.count = 0;
 
@@ -654,23 +969,55 @@
 		holder.stream->write_function(holder.stream, "<table cellpadding=1 cellspacing=4 border=1>\n");
 	}
 
-	switch_core_db_exec(db, sql, show_callback, &holder, &errmsg);
-
-	if (holder.http) {
-		holder.stream->write_function(holder.stream, "</table>");
+	if (!as) {
+		as = "delim";
+		holder.delim = ",";
 	}
 
-	if (errmsg) {
-		stream->write_function(stream, "SQL ERR [%s]\n",errmsg);
-		switch_core_db_free(errmsg);
-		errmsg = NULL;
-	} else if (help) {
-		if (holder.count == 0)
-			stream->write_function(stream, "No such command.\n");
+	if (!strcasecmp(as, "delim") || !strcasecmp(as, "csv")) {
+		if (switch_strlen_zero(holder.delim)) {
+			if (!(holder.delim = argv[3])) {
+				holder.delim = ",";
+			}
+		}
+		switch_core_db_exec(db, sql, show_callback, &holder, &errmsg);
+		if (holder.http) {
+			holder.stream->write_function(holder.stream, "</table>");
+		}
+
+		if (errmsg) {
+			stream->write_function(stream, "SQL ERR [%s]\n", errmsg);
+			switch_core_db_free(errmsg);
+			errmsg = NULL;
+		} else if (help) {
+			if (holder.count == 0)
+				stream->write_function(stream, "No such command.\n");
+		} else {
+			stream->write_function(stream, "\n%u total.\n", holder.count);
+		}
+	} else if (!strcasecmp(as, "xml")) {
+		switch_core_db_exec(db, sql, show_as_xml_callback, &holder, &errmsg);
+		if (holder.xml) {
+			char count[50];
+			char *xmlstr;
+			snprintf(count, sizeof(count), "%d", holder.count);
+			switch_xml_set_attr_d(holder.xml, "row_count", count);
+			xmlstr = switch_xml_toxml(holder.xml);
+
+			if (xmlstr) {
+				holder.stream->write_function(holder.stream, "%s", xmlstr);
+				free(xmlstr);
+			} else {
+				holder.stream->write_function(holder.stream, "<result row_count=\"0\"/>\n");
+			}
+		} else {
+			holder.stream->write_function(holder.stream, "<result row_count=\"0\"/>\n");
+		}
 	} else {
-		stream->write_function(stream, "\n%u total.\n", holder.count);
+		holder.stream->write_function(holder.stream, "Cannot find format %s\n", as);
 	}
 
+	switch_safe_free(mydata);
 	switch_core_db_close(db);
 	return SWITCH_STATUS_SUCCESS;
 }
@@ -678,7 +1025,7 @@
 static switch_status_t version_function(char *cmd, switch_core_session_t *session, switch_stream_handle_t *stream)
 {
 	char version_string[1024];
-	snprintf(version_string, sizeof(version_string) - 1,  "FreeSwitch Version %s\n", SWITCH_VERSION_FULL);
+	snprintf(version_string, sizeof(version_string) - 1, "FreeSwitch Version %s\n", SWITCH_VERSION_FULL);
 
 	stream->write_function(stream, version_string);
 	return SWITCH_STATUS_SUCCESS;
@@ -689,10 +1036,10 @@
 	char showcmd[1024];
 	int all = 0;
 	if (switch_strlen_zero(cmd)) {
-		sprintf (showcmd, "help");
+		sprintf(showcmd, "help");
 		all = 1;
 	} else {
-		snprintf(showcmd, sizeof(showcmd) -1, "help %s", cmd);
+		snprintf(showcmd, sizeof(showcmd) - 1, "help %s", cmd);
 	}
 
 	if (all) {
@@ -704,12 +1051,61 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
+
+static switch_api_interface_t xml_wrap_api_interface = {
+	/*.interface_name */ "xml_wrap",
+	/*.desc */ "Wrap another api command in xml",
+	/*.function */ xml_wrap_api_function,
+	/*.syntax */ "<command> <args>",
+	/*.next */ NULL
+};
+
+static switch_api_interface_t sched_del_api_interface = {
+	/*.interface_name */ "sched_del",
+	/*.desc */ "Delete a Scheduled task",
+	/*.function */ sched_del_function,
+	/*.syntax */ "<task_id>|<group_id>",
+	/*.next */ &xml_wrap_api_interface
+};
+
+static switch_api_interface_t sched_api_api_interface = {
+	/*.interface_name */ "sched_api",
+	/*.desc */ "Schedule an api command",
+	/*.function */ sched_api_function,
+	/*.syntax */ "[+]<time> <group_name> <command_string>",
+	/*.next */ &sched_del_api_interface
+};
+
+static switch_api_interface_t sched_transfer_api_interface = {
+	/*.interface_name */ "sched_transfer",
+	/*.desc */ "Schedule a broadcast event to a running call",
+	/*.function */ sched_transfer_function,
+	/*.syntax */ "[+]<time> <uuid> <extension> [<dialplan>] [<context>]",
+	/*.next */ &sched_api_api_interface
+};
+
+static switch_api_interface_t sched_broadcast_api_interface = {
+	/*.interface_name */ "sched_broadcast",
+	/*.desc */ "Schedule a broadcast event to a running call",
+	/*.function */ sched_broadcast_function,
+	/*.syntax */ "[+]<time> <uuid> <path> [aleg|bleg|both]",
+	/*.next */ &sched_transfer_api_interface
+};
+
+static switch_api_interface_t sched_hangup_api_interface = {
+	/*.interface_name */ "sched_hangup",
+	/*.desc */ "Schedule a running call to hangup",
+	/*.function */ sched_hangup_function,
+	/*.syntax */ "[+]<time> <uuid> [<cause>]",
+	/*.next */ &sched_broadcast_api_interface
+};
+
 static switch_api_interface_t version_api_interface = {
 	/*.interface_name */ "version",
 	/*.desc */ "Show version of the switch",
 	/*.function */ version_function,
 	/*.syntax */ "",
-	/*.next */ NULL
+	/*.next */ &sched_hangup_api_interface
 };
 
 static switch_api_interface_t help_api_interface = {
@@ -829,7 +1225,8 @@
 	/*.interface_name */ "originate",
 	/*.desc */ "Originate a Call",
 	/*.function */ originate_function,
-	/*.syntax */ "<call url> <exten>|&<application_name>(<app_args>) [<dialplan>] [<context>] [<cid_name>] [<cid_num>] [<timeout_sec>]",
+	/*.syntax */
+	"<call url> <exten>|&<application_name>(<app_args>) [<dialplan>] [<context>] [<cid_name>] [<cid_num>] [<timeout_sec>]",
 	/*.next */ &kill_api_interface
 };
 

Modified: freeswitch/branches/cparker/src/mod/applications/mod_conference/mod_conference.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_conference/mod_conference.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_conference/mod_conference.c	Tue Apr 24 10:14:28 2007
@@ -39,7 +39,7 @@
 static switch_api_interface_t conf_api_interface;
 
 /* Size to allocate for audio buffers */
-#define CONF_BUFFER_SIZE 1024 * 128 
+#define CONF_BUFFER_SIZE 1024 * 128
 #define CONF_EVENT_MAINT "conference::maintenence"
 #define CONF_DEFAULT_LEADIN 20
 
@@ -52,11 +52,8 @@
 #define MIN(a, b) ((a)<(b)?(a):(b))
 #endif
 
-/* this doesn't work correctly yet, don't bother trying! */
-//#define OPTION_IVR_MENU_SUPPORT */
-
 typedef enum {
-	FILE_STOP_CURRENT, 
+	FILE_STOP_CURRENT,
 	FILE_STOP_ALL
 } file_stop_t;
 
@@ -73,35 +70,46 @@
 } globals;
 
 typedef enum {
-	CALLER_CONTROL_MUTE, 
-	CALLER_CONTROL_DEAF_MUTE, 
-	CALLER_CONTROL_ENERGY_UP, 
-	CALLER_CONTROL_ENERGY_EQU_CONF, 
-	CALLER_CONTROL_ENERGEY_DN, 
-	CALLER_CONTROL_VOL_TALK_UP, 
-	CALLER_CONTROL_VOL_TALK_ZERO, 
-	CALLER_CONTROL_VOL_TALK_DN, 
-	CALLER_CONTROL_VOL_LISTEN_UP, 
-	CALLER_CONTROL_VOL_LISTEN_ZERO, 
-	CALLER_CONTROL_VOL_LISTEN_DN, 
-	CALLER_CONTROL_HANGUP, 
-	CALLER_CONTROL_MENU, 
-	CALLER_CONTROL_DIAL, 
+	CALLER_CONTROL_MUTE,
+	CALLER_CONTROL_DEAF_MUTE,
+	CALLER_CONTROL_ENERGY_UP,
+	CALLER_CONTROL_ENERGY_EQU_CONF,
+	CALLER_CONTROL_ENERGEY_DN,
+	CALLER_CONTROL_VOL_TALK_UP,
+	CALLER_CONTROL_VOL_TALK_ZERO,
+	CALLER_CONTROL_VOL_TALK_DN,
+	CALLER_CONTROL_VOL_LISTEN_UP,
+	CALLER_CONTROL_VOL_LISTEN_ZERO,
+	CALLER_CONTROL_VOL_LISTEN_DN,
+	CALLER_CONTROL_HANGUP,
+	CALLER_CONTROL_MENU,
+	CALLER_CONTROL_DIAL,
+	CALLER_CONTROL_EVENT
 } caller_control_t;
 
 /* forward declaration for conference_obj and caller_control */
 struct conference_member;
 typedef struct conference_member conference_member_t;
 
+struct call_list {
+	char *string;
+	int itteration;
+	struct call_list *next;
+};
+typedef struct call_list call_list_t;
+
+struct caller_control_actions;
+
 typedef struct caller_control_fn_table {
 	char *key;
 	char *digits;
 	caller_control_t action;
-	void (*handler)(conference_member_t *, void *);
+	void (*handler) (conference_member_t *, struct caller_control_actions *);
 } caller_control_fn_table_t;
 
 typedef struct caller_control_actions {
 	caller_control_fn_table_t *fndesc;
+	char *binded_dtmf;
 	void *data;
 } caller_control_action_t;
 
@@ -111,32 +119,33 @@
 } caller_control_menu_info_t;
 
 typedef enum {
-	MFLAG_RUNNING = (1 << 0), 
-	MFLAG_CAN_SPEAK = (1 << 1), 
-	MFLAG_CAN_HEAR = (1 << 2), 
-	MFLAG_KICKED = (1 << 3), 
-	MFLAG_ITHREAD = (1 << 4), 
+	MFLAG_RUNNING = (1 << 0),
+	MFLAG_CAN_SPEAK = (1 << 1),
+	MFLAG_CAN_HEAR = (1 << 2),
+	MFLAG_KICKED = (1 << 3),
+	MFLAG_ITHREAD = (1 << 4),
 	MFLAG_NOCHANNEL = (1 << 5),
-    MFLAG_INTREE = (1 << 6),
-	MFLAG_WASTE_BANDWIDTH = (1 << 7)
+	MFLAG_INTREE = (1 << 6),
+	MFLAG_WASTE_BANDWIDTH = (1 << 7),
+	MFLAG_FLUSH_BUFFER = (1 << 8)
 } member_flag_t;
 
 typedef enum {
-	CFLAG_RUNNING = (1 << 0), 
-	CFLAG_DYNAMIC = (1 << 1), 
-	CFLAG_ENFORCE_MIN = (1 << 2), 
-	CFLAG_DESTRUCT = (1 << 3), 
-	CFLAG_LOCKED = (1 << 4), 
+	CFLAG_RUNNING = (1 << 0),
+	CFLAG_DYNAMIC = (1 << 1),
+	CFLAG_ENFORCE_MIN = (1 << 2),
+	CFLAG_DESTRUCT = (1 << 3),
+	CFLAG_LOCKED = (1 << 4),
 	CFLAG_ANSWERED = (1 << 5)
 } conf_flag_t;
 
 typedef enum {
-	RFLAG_CAN_SPEAK = (1 << 0), 
+	RFLAG_CAN_SPEAK = (1 << 0),
 	RFLAG_CAN_HEAR = (1 << 1)
 } relation_flag_t;
 
 typedef enum {
-	NODE_TYPE_FILE, 
+	NODE_TYPE_FILE,
 	NODE_TYPE_SPEECH
 } node_type_t;
 
@@ -145,6 +154,7 @@
 	switch_speech_handle_t sh;
 	node_type_t type;
 	uint8_t done;
+	uint8_t async;
 	switch_memory_pool_t *pool;
 	uint32_t leadin;
 	struct conference_file_node *next;
@@ -154,9 +164,6 @@
 typedef struct conf_xml_cfg {
 	switch_xml_t profile;
 	switch_xml_t controls;
-#ifdef OPTION_IVR_MENU_SUPPORT
-	switch_xml_t menus;
-#endif
 } conf_xml_cfg_t;
 
 /* Conference Object */
@@ -178,10 +185,11 @@
 	char *kicked_sound;
 	char *caller_id_name;
 	char *caller_id_number;
-    char *sound_prefix;
-    uint32_t max_members;
-    char *maxmember_sound;
-    uint32_t anounce_count;
+	char *sound_prefix;
+	char *special_announce;
+	uint32_t max_members;
+	char *maxmember_sound;
+	uint32_t anounce_count;
 	switch_ivr_digit_stream_parser_t *dtmf_parser;
 	char *pin;
 	char *pin_sound;
@@ -196,8 +204,9 @@
 	uint32_t interval;
 	switch_mutex_t *mutex;
 	conference_member_t *members;
-    switch_mutex_t *member_mutex;
+	switch_mutex_t *member_mutex;
 	conference_file_node_t *fnode;
+	conference_file_node_t *async_fnode;
 	switch_memory_pool_t *pool;
 	switch_thread_rwlock_t *rwlock;
 	uint32_t count;
@@ -253,12 +262,12 @@
 } conference_record_t;
 
 typedef enum {
-	CONF_API_SUB_ARGS_SPLIT, 
-	CONF_API_SUB_MEMBER_TARGET, 
+	CONF_API_SUB_ARGS_SPLIT,
+	CONF_API_SUB_MEMBER_TARGET,
 	CONF_API_SUB_ARGS_AS_ONE
 } conference_fntype_t;
 
-typedef void (*void_fn_t)(void);
+typedef void (*void_fn_t) (void);
 
 /* API command parser */
 typedef struct api_command {
@@ -271,67 +280,48 @@
 
 /* Function Prototypes */
 static uint32_t next_member_id(void);
-static conference_relationship_t *member_get_relationship(conference_member_t *member, conference_member_t *other_member);
-static conference_member_t *conference_member_get(conference_obj_t *conference, uint32_t id);
-static conference_relationship_t *member_add_relationship(conference_member_t *member, uint32_t id);
-static switch_status_t member_del_relationship(conference_member_t *member, uint32_t id);
-static switch_status_t conference_add_member(conference_obj_t *conference, conference_member_t *member);
-static switch_status_t conference_del_member(conference_obj_t *conference, conference_member_t *member);
-static void *SWITCH_THREAD_FUNC conference_thread_run(switch_thread_t *thread, void *obj);
-static void conference_loop_output(conference_member_t *member);
-static uint32_t conference_stop_file(conference_obj_t *conference, file_stop_t stop);
-static switch_status_t conference_play_file(conference_obj_t *conference, char *file, uint32_t leadin, switch_channel_t *channel);
-static switch_status_t conference_say(conference_obj_t *conference, const char *text, uint32_t leadin);
-static void conference_list(conference_obj_t *conference, switch_stream_handle_t *stream, char *delim);
+static conference_relationship_t *member_get_relationship(conference_member_t * member, conference_member_t * other_member);
+static conference_member_t *conference_member_get(conference_obj_t * conference, uint32_t id);
+static conference_relationship_t *member_add_relationship(conference_member_t * member, uint32_t id);
+static switch_status_t member_del_relationship(conference_member_t * member, uint32_t id);
+static switch_status_t conference_add_member(conference_obj_t * conference, conference_member_t * member);
+static switch_status_t conference_del_member(conference_obj_t * conference, conference_member_t * member);
+static void *SWITCH_THREAD_FUNC conference_thread_run(switch_thread_t * thread, void *obj);
+static void conference_loop_output(conference_member_t * member);
+static uint32_t conference_stop_file(conference_obj_t * conference, file_stop_t stop);
+static switch_status_t conference_play_file(conference_obj_t * conference, char *file, uint32_t leadin, switch_channel_t *channel, uint8_t async);
+static switch_status_t conference_say(conference_obj_t * conference, const char *text, uint32_t leadin);
+static void conference_list(conference_obj_t * conference, switch_stream_handle_t *stream, char *delim);
 static switch_status_t conf_api_main(char *buf, switch_core_session_t *session, switch_stream_handle_t *stream);
 static switch_status_t audio_bridge_on_ring(switch_core_session_t *session);
-static switch_status_t conference_outcall(conference_obj_t *conference, 
-										  switch_core_session_t *session, 
-										  char *bridgeto, 
-										  uint32_t timeout, 
-										  char *flags, 
-										  char *cid_name, 
-										  char *cid_num,
-                                          switch_call_cause_t *cause);
-static switch_status_t conference_outcall_bg(conference_obj_t *conference, 
-                                             switch_core_session_t *session, 
-                                             char *bridgeto, 
-                                             uint32_t timeout, 
-                                             char *flags, 
-                                             char *cid_name, 
-                                             char *cid_num);
+static switch_status_t conference_outcall(conference_obj_t * conference,
+										  char *conference_name,
+										  switch_core_session_t *session,
+										  char *bridgeto, uint32_t timeout, char *flags, char *cid_name, char *cid_num, switch_call_cause_t *cause);
+static switch_status_t conference_outcall_bg(conference_obj_t * conference,
+											 char *conference_name,
+											 switch_core_session_t *session, char *bridgeto, uint32_t timeout, char *flags, char *cid_name, char *cid_num);
 static void conference_function(switch_core_session_t *session, char *data);
-static void launch_conference_thread(conference_obj_t *conference);
-static void *SWITCH_THREAD_FUNC conference_loop_input(switch_thread_t *thread, void *obj);
-static switch_status_t conference_local_play_file(conference_obj_t *conference,
-                                                  switch_core_session_t *session, char *path, uint32_t leadin, char *buf, switch_size_t len);
-static switch_status_t conference_member_play_file(conference_member_t *member, char *file, uint32_t leadin);
-static switch_status_t conference_member_say(conference_member_t *member, char *text, uint32_t leadin);
-static uint32_t conference_member_stop_file(conference_member_t *member, file_stop_t stop);
+static void launch_conference_thread(conference_obj_t * conference);
+static void *SWITCH_THREAD_FUNC conference_loop_input(switch_thread_t * thread, void *obj);
+static switch_status_t conference_local_play_file(conference_obj_t * conference,
+												  switch_core_session_t *session, char *path, uint32_t leadin);
+static switch_status_t conference_member_play_file(conference_member_t * member, char *file, uint32_t leadin);
+static switch_status_t conference_member_say(conference_member_t * member, char *text, uint32_t leadin);
+static uint32_t conference_member_stop_file(conference_member_t * member, file_stop_t stop);
 static conference_obj_t *conference_new(char *name, conf_xml_cfg_t cfg, switch_memory_pool_t *pool);
 static switch_status_t chat_send(char *proto, char *from, char *to, char *subject, char *body, char *hint);
-static void launch_conference_record_thread(conference_obj_t *conference, char *path);
+static void launch_conference_record_thread(conference_obj_t * conference, char *path);
 
-typedef switch_status_t (*conf_api_args_cmd_t)(conference_obj_t*, switch_stream_handle_t*, int, char**);
-typedef switch_status_t (*conf_api_member_cmd_t)(conference_member_t*, switch_stream_handle_t*, void*);
-typedef switch_status_t (*conf_api_text_cmd_t)(conference_obj_t*, switch_stream_handle_t*, const char*);
-
-static void conference_member_itterator(conference_obj_t *conference, 
-										switch_stream_handle_t *stream, 
-										conf_api_member_cmd_t pfncallback, 
-										void *data);
-static switch_status_t conf_api_sub_mute(conference_member_t *member, 
-                                         switch_stream_handle_t *stream, 
-                                         void *data);
-static switch_status_t conf_api_sub_unmute(conference_member_t *member, 
-                                           switch_stream_handle_t *stream, 
-                                           void *data);
-static switch_status_t conf_api_sub_deaf(conference_member_t *member, 
-                                         switch_stream_handle_t *stream, 
-                                         void *data);
-static switch_status_t conf_api_sub_undeaf(conference_member_t *member, 
-                                           switch_stream_handle_t *stream, 
-                                           void *data);
+typedef switch_status_t (*conf_api_args_cmd_t) (conference_obj_t *, switch_stream_handle_t *, int, char **);
+typedef switch_status_t (*conf_api_member_cmd_t) (conference_member_t *, switch_stream_handle_t *, void *);
+typedef switch_status_t (*conf_api_text_cmd_t) (conference_obj_t *, switch_stream_handle_t *, const char *);
+
+static void conference_member_itterator(conference_obj_t * conference, switch_stream_handle_t *stream, conf_api_member_cmd_t pfncallback, void *data);
+static switch_status_t conf_api_sub_mute(conference_member_t * member, switch_stream_handle_t *stream, void *data);
+static switch_status_t conf_api_sub_unmute(conference_member_t * member, switch_stream_handle_t *stream, void *data);
+static switch_status_t conf_api_sub_deaf(conference_member_t * member, switch_stream_handle_t *stream, void *data);
+static switch_status_t conf_api_sub_undeaf(conference_member_t * member, switch_stream_handle_t *stream, void *data);
 
 /* Return a Distinct ID # */
 static uint32_t next_member_id(void)
@@ -346,7 +336,7 @@
 }
 
 /* if other_member has a relationship with member, produce it */
-static conference_relationship_t *member_get_relationship(conference_member_t *member, conference_member_t *other_member)
+static conference_relationship_t *member_get_relationship(conference_member_t * member, conference_member_t * other_member)
 {
 	conference_relationship_t *rel = NULL;
 
@@ -365,7 +355,7 @@
 				/* 0 matches everyone.
 				   (We will still test the others brcause a real match carries more clout) */
 
-				if (rel->id == 0) { 
+				if (rel->id == 0) {
 					global = rel;
 				}
 			}
@@ -383,54 +373,54 @@
 }
 
 /* traverse the conference member list for the specified member id and return it's pointer */
-static conference_member_t *conference_member_get(conference_obj_t *conference, uint32_t id)
+static conference_member_t *conference_member_get(conference_obj_t * conference, uint32_t id)
 {
 	conference_member_t *member = NULL;
 
-    assert(conference != NULL);
-    assert(id != 0);
+	assert(conference != NULL);
+	assert(id != 0);
+
+	switch_mutex_lock(conference->member_mutex);
+	for (member = conference->members; member; member = member->next) {
+
+		if (switch_test_flag(member, MFLAG_NOCHANNEL)) {
+			continue;
+		}
+
+		if (member->id == id) {
+			break;
+		}
+	}
 
-    switch_mutex_lock(conference->member_mutex);
-    for(member = conference->members; member; member = member->next) {
-        
-        if (switch_test_flag(member, MFLAG_NOCHANNEL)) {
-            continue;
-        }
-        
-        if (member->id == id) {
-            break;
-        }
-    }
-
-    if (member && !switch_test_flag(member, MFLAG_INTREE)) {
-        member = NULL;
-    }
+	if (member && !switch_test_flag(member, MFLAG_INTREE)) {
+		member = NULL;
+	}
 
-    switch_mutex_unlock(conference->member_mutex);
+	switch_mutex_unlock(conference->member_mutex);
 
 	return member;
 }
 
 /* stop the specified recording */
-static switch_status_t conference_record_stop(conference_obj_t *conference, char *path)
+static switch_status_t conference_record_stop(conference_obj_t * conference, char *path)
 {
 	conference_member_t *member = NULL;
 	int count = 0;
 
-	assert (conference != NULL);
-    switch_mutex_lock(conference->member_mutex);
-    for(member = conference->members; member; member = member->next) {
-        if (switch_test_flag(member, MFLAG_NOCHANNEL) && (!path || !strcmp(path, member->rec_path))) {
-            switch_clear_flag_locked(member, MFLAG_RUNNING);
-            count++;
-        }
-    }
-    switch_mutex_unlock(conference->member_mutex);
+	assert(conference != NULL);
+	switch_mutex_lock(conference->member_mutex);
+	for (member = conference->members; member; member = member->next) {
+		if (switch_test_flag(member, MFLAG_NOCHANNEL) && (!path || !strcmp(path, member->rec_path))) {
+			switch_clear_flag_locked(member, MFLAG_RUNNING);
+			count++;
+		}
+	}
+	switch_mutex_unlock(conference->member_mutex);
 	return count;
 }
 
 /* Add a custom relationship to a member */
-static conference_relationship_t *member_add_relationship(conference_member_t *member, uint32_t id)
+static conference_relationship_t *member_add_relationship(conference_member_t * member, uint32_t id)
 {
 	conference_relationship_t *rel = NULL;
 
@@ -447,7 +437,7 @@
 }
 
 /* Remove a custom relationship from a member */
-static switch_status_t member_del_relationship(conference_member_t *member, uint32_t id)
+static switch_status_t member_del_relationship(conference_member_t * member, uint32_t id)
 {
 	switch_status_t status = SWITCH_STATUS_FALSE;
 	conference_relationship_t *rel, *last = NULL;
@@ -474,193 +464,214 @@
 }
 
 /* Gain exclusive access and add the member to the list */
-static switch_status_t conference_add_member(conference_obj_t *conference, conference_member_t *member)
+static switch_status_t conference_add_member(conference_obj_t * conference, conference_member_t * member)
 {
 	switch_status_t status = SWITCH_STATUS_FALSE;
-    switch_event_t *event;
-    char msg[512]; // for conference count anouncement
+	switch_event_t *event;
+	char msg[512];				// for conference count anouncement
+	call_list_t *call_list = NULL;
+	switch_channel_t *channel;
 
-    assert(conference != NULL);
-    assert(member != NULL);
+	assert(conference != NULL);
+	assert(member != NULL);
 
-    switch_mutex_lock(conference->mutex);
-    switch_mutex_lock(member->audio_in_mutex);
-    switch_mutex_lock(member->audio_out_mutex);
-    switch_mutex_lock(member->flag_mutex);
-    
-    switch_mutex_lock(conference->member_mutex);
-    member->conference = conference;
-    member->next = conference->members;
-    member->energy_level = conference->energy_level;
-    conference->members = member;
-    switch_set_flag(member, MFLAG_INTREE);
-    switch_mutex_unlock(conference->member_mutex);
-
-    if (!switch_test_flag(member, MFLAG_NOCHANNEL)) {
-        conference->count++;
-        if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", conference->name, conference->domain);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Active (%d caller%s)", conference->count, conference->count == 1 ? "" : "s");
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
-            switch_event_fire(&event);
-        }
-
-        if (conference->count > 1 && conference->enter_sound) {
-            conference_play_file(conference, conference->enter_sound, CONF_DEFAULT_LEADIN, switch_core_session_get_channel(member->session));
-        }
-
-        // anounce the total number of members in the conference
-        if (conference->count >= conference->anounce_count && conference->anounce_count > 1) {
-            snprintf(msg, sizeof(msg), "There are %d callers", conference->count);
-            conference_member_say(member, msg, CONF_DEFAULT_LEADIN);
-        } else if (conference->count == 1) {
-            if (conference->alone_sound) {
-                conference_play_file(conference, conference->alone_sound, CONF_DEFAULT_LEADIN, switch_core_session_get_channel(member->session));
-            } else {
-                snprintf(msg, sizeof(msg), "You are currently the only person in this conference.", conference->count);
-                conference_member_say(member, msg, CONF_DEFAULT_LEADIN);
-            }
-        }
-
-        if (conference->min && conference->count >= conference->min) {
-            switch_set_flag(conference, CFLAG_ENFORCE_MIN);	
-        }
-        
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_channel_t *channel = switch_core_session_get_channel(member->session);
-            switch_channel_event_set_data(channel, event);
-
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "add-member");
-            switch_event_fire(&event);
-        }
-    }
-    switch_mutex_unlock(member->flag_mutex);
-    switch_mutex_unlock(member->audio_out_mutex);
-    switch_mutex_unlock(member->audio_in_mutex);
+	switch_mutex_lock(conference->mutex);
+	switch_mutex_lock(member->audio_in_mutex);
+	switch_mutex_lock(member->audio_out_mutex);
+	switch_mutex_lock(member->flag_mutex);
+
+	switch_mutex_lock(conference->member_mutex);
+	member->conference = conference;
+	member->next = conference->members;
+	member->energy_level = conference->energy_level;
+	conference->members = member;
+	switch_set_flag(member, MFLAG_INTREE);
+	switch_mutex_unlock(conference->member_mutex);
+
+	if (!switch_test_flag(member, MFLAG_NOCHANNEL)) {
+		conference->count++;
+		if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", conference->name, conference->domain);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Active (%d caller%s)", conference->count, conference->count == 1 ? "" : "s");
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
+			switch_event_fire(&event);
+		}
+
+		if (conference->count > 1 && conference->enter_sound) {
+			conference_play_file(conference, conference->enter_sound, CONF_DEFAULT_LEADIN, switch_core_session_get_channel(member->session), 0);
+		}
+
+		channel = switch_core_session_get_channel(member->session);
+		call_list = (call_list_t *) switch_channel_get_private(channel, "_conference_autocall_list_");
+			
+		if (call_list) {
+			char msg[1024];
+			snprintf(msg, sizeof(msg), "Auto Calling %d parties", call_list->itteration);
+			conference_member_say(member, msg, 0);
+		} else {
+			if (switch_strlen_zero(conference->special_announce)) {
+				// anounce the total number of members in the conference
+				if (conference->count >= conference->anounce_count && conference->anounce_count > 1) {
+					snprintf(msg, sizeof(msg), "There are %d callers", conference->count);
+					conference_member_say(member, msg, CONF_DEFAULT_LEADIN);
+				} else if (conference->count == 1) {
+					if (conference->alone_sound) {
+						conference_play_file(conference, conference->alone_sound, CONF_DEFAULT_LEADIN, switch_core_session_get_channel(member->session), 0);
+					} else {
+						snprintf(msg, sizeof(msg), "You are currently the only person in this conference.");
+						conference_member_say(member, msg, CONF_DEFAULT_LEADIN);
+					}
+				}
+			} 
+		}
+
+		
+
+		if (conference->min && conference->count >= conference->min) {
+			switch_set_flag(conference, CFLAG_ENFORCE_MIN);
+		}
+
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_channel_t *channel = switch_core_session_get_channel(member->session);
+			switch_channel_event_set_data(channel, event);
+
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "add-member");
+			switch_event_fire(&event);
+		}
+	}
+	switch_mutex_unlock(member->flag_mutex);
+	switch_mutex_unlock(member->audio_out_mutex);
+	switch_mutex_unlock(member->audio_in_mutex);
+
+	switch_mutex_unlock(conference->mutex);
+	status = SWITCH_STATUS_SUCCESS;
 
-    switch_mutex_unlock(conference->mutex);
-    status = SWITCH_STATUS_SUCCESS;
-	
 
 	return status;
 }
 
 /* Gain exclusive access and remove the member from the list */
-static switch_status_t conference_del_member(conference_obj_t *conference, conference_member_t *member)
+static switch_status_t conference_del_member(conference_obj_t * conference, conference_member_t * member)
 {
 	switch_status_t status = SWITCH_STATUS_FALSE;
-    conference_member_t *imember, *last = NULL;
-    switch_event_t *event;
+	conference_member_t *imember, *last = NULL;
+	switch_event_t *event;
+
+	assert(conference != NULL);
+	assert(member != NULL);
+
+	switch_mutex_lock(conference->mutex);
+	switch_mutex_lock(conference->member_mutex);
+	switch_mutex_lock(member->audio_in_mutex);
+	switch_mutex_lock(member->audio_out_mutex);
+	switch_mutex_lock(member->flag_mutex);
+	switch_clear_flag(member, MFLAG_INTREE);
+
+	for (imember = conference->members; imember; imember = imember->next) {
+		if (imember == member) {
+			if (last) {
+				last->next = imember->next;
+			} else {
+				conference->members = imember->next;
+			}
+			break;
+		}
+		last = imember;
+	}
+
+	/* Close Unused Handles */
+	if (member->fnode) {
+		conference_file_node_t *fnode, *cur;
+		switch_memory_pool_t *pool;
+
+		fnode = member->fnode;
+		while (fnode) {
+			cur = fnode;
+			fnode = fnode->next;
+
+			if (cur->type == NODE_TYPE_SPEECH) {
+				switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
+				switch_core_speech_close(&cur->sh, &flags);
+			} else {
+				switch_core_file_close(&cur->fh);
+			}
+
+			pool = cur->pool;
+			switch_core_destroy_memory_pool(&pool);
+		}
+	}
+
+	member->conference = NULL;
+
+	if (!switch_test_flag(member, MFLAG_NOCHANNEL)) {
+		conference->count--;
+		if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", conference->name, conference->domain);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Active (%d caller%s)", conference->count, conference->count == 1 ? "" : "s");
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
+			switch_event_fire(&event);
+		}
+
+		if ((conference->min && switch_test_flag(conference, CFLAG_ENFORCE_MIN) && conference->count < conference->min)
+			|| (switch_test_flag(conference, CFLAG_DYNAMIC) && conference->count == 0)) {
+			switch_set_flag(conference, CFLAG_DESTRUCT);
+		} else {
+			if (conference->exit_sound) {
+				conference_play_file(conference, conference->exit_sound, 0, switch_core_session_get_channel(member->session), 0);
+			}
+			if (conference->count == 1 && conference->alone_sound) {
+				conference_play_file(conference, conference->alone_sound, 0, switch_core_session_get_channel(member->session), 0);
+			}
+		}
+
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_channel_t *channel = switch_core_session_get_channel(member->session);
+			switch_channel_event_set_data(channel, event);
+
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "del-member");
+			switch_event_fire(&event);
+		}
+	}
+	switch_mutex_unlock(conference->member_mutex);
+	switch_mutex_unlock(member->flag_mutex);
+	switch_mutex_unlock(member->audio_out_mutex);
+	switch_mutex_unlock(member->audio_in_mutex);
+	switch_mutex_unlock(conference->mutex);
+	status = SWITCH_STATUS_SUCCESS;
 
-    assert(conference != NULL);
-    assert(member != NULL);
-    
-    switch_mutex_lock(conference->mutex);
-    switch_mutex_lock(conference->member_mutex);
-    switch_mutex_lock(member->audio_in_mutex);
-    switch_mutex_lock(member->audio_out_mutex);
-    switch_mutex_lock(member->flag_mutex);
-    switch_clear_flag(member, MFLAG_INTREE);
-    
-    for (imember = conference->members; imember; imember = imember->next) {
-        if (imember == member ) {
-            if (last) {
-                last->next = imember->next;
-            } else {
-                conference->members = imember->next;
-            }
-            break;
-        }
-        last = imember;
-    }
-
-    /* Close Unused Handles */
-    if (member->fnode) {
-        conference_file_node_t *fnode, *cur;
-        switch_memory_pool_t *pool;
-
-        fnode = member->fnode;
-        while(fnode) {
-            cur = fnode;
-            fnode = fnode->next;
-
-            if (cur->type == NODE_TYPE_SPEECH) {
-                switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
-                switch_core_speech_close(&cur->sh, &flags);
-            } else {
-                switch_core_file_close(&cur->fh);
-            }
-
-            pool = cur->pool;
-            switch_core_destroy_memory_pool(&pool);
-        }
-    }
-
-    member->conference = NULL;
-
-    if (!switch_test_flag(member, MFLAG_NOCHANNEL)) {
-        conference->count--;
-        if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", conference->name, conference->domain);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Active (%d caller%s)", conference->count, conference->count == 1 ? "" : "s");
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
-            switch_event_fire(&event);
-        }
-
-        if ((conference->min && switch_test_flag(conference, CFLAG_ENFORCE_MIN) && conference->count < conference->min) 
-            || (switch_test_flag(conference, CFLAG_DYNAMIC) && conference->count == 0) ) {
-            switch_set_flag(conference, CFLAG_DESTRUCT);
-        } else { 
-            if (conference->exit_sound) {
-                conference_play_file(conference, conference->exit_sound, 0, switch_core_session_get_channel(member->session));
-            }
-            if (conference->count == 1 && conference->alone_sound) {
-                conference_play_file(conference, conference->alone_sound, 0, switch_core_session_get_channel(member->session));
-            } 
-        }
-
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_channel_t *channel = switch_core_session_get_channel(member->session);
-            switch_channel_event_set_data(channel, event);
-
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "del-member");
-            switch_event_fire(&event);
-        }
-    }
-    switch_mutex_unlock(conference->member_mutex);
-    switch_mutex_unlock(member->flag_mutex);
-    switch_mutex_unlock(member->audio_out_mutex);
-    switch_mutex_unlock(member->audio_in_mutex);
-    switch_mutex_unlock(conference->mutex);
-    status = SWITCH_STATUS_SUCCESS;
-	
 
 	return status;
 }
 
 /* Main monitor thread (1 per distinct conference room) */
-static void *SWITCH_THREAD_FUNC conference_thread_run(switch_thread_t *thread, void *obj)
+static void *SWITCH_THREAD_FUNC conference_thread_run(switch_thread_t * thread, void *obj)
 {
 	conference_obj_t *conference = (conference_obj_t *) obj;
 	conference_member_t *imember, *omember;
 	uint32_t samples = switch_bytes_per_frame(conference->rate, conference->interval);
 	uint32_t bytes = samples * 2;
 	uint8_t ready = 0;
-	switch_timer_t timer = {0};
+	switch_timer_t timer = { 0 };
 	switch_event_t *event;
+	uint8_t *file_frame;
+	uint8_t *async_file_frame;
+
+	file_frame = switch_core_alloc(conference->pool, CONF_BUFFER_SIZE);
+	async_file_frame = switch_core_alloc(conference->pool, CONF_BUFFER_SIZE);
+
 
 	if (switch_core_timer_init(&timer, conference->timer_name, conference->interval, samples, conference->pool) == SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "setup timer success interval: %u  samples: %u\n", conference->interval, samples);	
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "setup timer success interval: %u  samples: %u\n", conference->interval, samples);
 	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Timer Setup Failed.  Conference Cannot Start\n");	
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Timer Setup Failed.  Conference Cannot Start\n");
 		return NULL;
 	}
 
@@ -668,13 +679,16 @@
 	globals.threads++;
 	switch_mutex_unlock(globals.hash_mutex);
 
-	while(globals.running && !switch_test_flag(conference, CFLAG_DESTRUCT)) {
-		uint8_t file_frame[CONF_BUFFER_SIZE] = {0};
+	while (globals.running && !switch_test_flag(conference, CFLAG_DESTRUCT)) {
 		switch_size_t file_sample_len = samples;
 		switch_size_t file_data_len = samples * 2;
+		int has_file_data = 0;
 
 		/* Sync the conference to a single timing source */
-		switch_core_timer_next(&timer);
+		if (switch_core_timer_next(&timer) != SWITCH_STATUS_SUCCESS) {
+			switch_set_flag(conference, CFLAG_DESTRUCT);
+			break;
+		}
 		switch_mutex_lock(conference->mutex);
 		ready = 0;
 
@@ -691,9 +705,9 @@
 			switch_mutex_lock(imember->audio_in_mutex);
 			/* if there is audio in the resample buffer it takes precedence over the other data */
 			if (imember->mux_resampler && switch_buffer_inuse(imember->resample_buffer) >= bytes) {
-				imember->read = (uint32_t)switch_buffer_read(imember->resample_buffer, imember->frame, bytes);
+				imember->read = (uint32_t) switch_buffer_read(imember->resample_buffer, imember->frame, bytes);
 				ready++;
-			} else if ((imember->read = (uint32_t)switch_buffer_read(imember->audio_buffer, imember->frame, imember->buflen))) {
+			} else if ((imember->read = (uint32_t) switch_buffer_read(imember->audio_buffer, imember->frame, imember->buflen))) {
 				/* If the caller is not at the right sample rate resample him to suit and buffer accordingly */
 				if (imember->mux_resampler) {
 					int16_t *bptr = (int16_t *) imember->frame;
@@ -701,18 +715,18 @@
 					int len = (int) imember->read;
 
 					imember->mux_resampler->from_len = switch_short_to_float(bptr, imember->mux_resampler->from, (int) len / 2);
-					imember->mux_resampler->to_len = switch_resample_process(imember->mux_resampler, imember->mux_resampler->from, 
-                                                                             imember->mux_resampler->from_len, imember->mux_resampler->to, 
-                                                                             imember->mux_resampler->to_size, 0);
+					imember->mux_resampler->to_len =
+						switch_resample_process(imember->mux_resampler, imember->mux_resampler->from,
+												imember->mux_resampler->from_len, imember->mux_resampler->to, imember->mux_resampler->to_size, 0);
 					switch_float_to_short(imember->mux_resampler->to, out, len);
 					len = imember->mux_resampler->to_len * 2;
 					switch_buffer_write(imember->resample_buffer, out, len);
 					if (switch_buffer_inuse(imember->resample_buffer) >= bytes) {
-						imember->read = (uint32_t)switch_buffer_read(imember->resample_buffer, imember->frame, bytes);
+						imember->read = (uint32_t) switch_buffer_read(imember->resample_buffer, imember->frame, bytes);
 						ready++;
 					}
 				} else {
-					ready++; /* Tally of how many channels had data */
+					ready++;	/* Tally of how many channels had data */
 				}
 			}
 			switch_mutex_unlock(imember->audio_in_mutex);
@@ -723,19 +737,15 @@
 			if (conference->fnode->leadin) {
 				conference->fnode->leadin--;
 			} else {
-				ready++;
+				file_sample_len = samples;
 				if (conference->fnode->type == NODE_TYPE_SPEECH) {
 					switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_BLOCKING;
 					uint32_t rate = conference->rate;
 
-					if (switch_core_speech_read_tts(&conference->fnode->sh, 
-													file_frame, 
-													&file_data_len, 
-													&rate, 
-													&flags) == SWITCH_STATUS_SUCCESS) {
+					if (switch_core_speech_read_tts(&conference->fnode->sh, file_frame, &file_data_len, &rate, &flags) == SWITCH_STATUS_SUCCESS) {
 						file_sample_len = file_data_len / 2;
 					} else {
-						file_sample_len = file_data_len  = 0;
+						file_sample_len = file_data_len = 0;
 					}
 				} else if (conference->fnode->type == NODE_TYPE_FILE) {
 					switch_core_file_read(&conference->fnode->fh, file_frame, &file_sample_len);
@@ -745,13 +755,48 @@
 					conference->fnode->done++;
 				}
 			}
+			has_file_data = 1;
+			ready++;
+		} else {
+			has_file_data = 0;
+		}
+
+		if (conference->async_fnode) {
+			/* Lead in time */
+			if (conference->async_fnode->leadin) {
+				conference->async_fnode->leadin--;
+			} else {
+				file_sample_len = samples;
+				switch_core_file_read(&conference->async_fnode->fh, async_file_frame, &file_sample_len);
+				if (file_sample_len <= 0) {
+					conference->async_fnode->done++;
+				} else {
+					if (has_file_data) {
+						switch_size_t x;
+						for (x = 0; x < file_sample_len; x++) {
+							int32_t z;
+							int16_t *bptr, *muxed;
+
+							muxed = (int16_t *) file_frame;
+							bptr = (int16_t *) async_file_frame;
+							z = muxed[x] + bptr[x];
+							switch_normalize_to_16bit(z);
+							muxed[x] = (int16_t) z;
+						}
+					} else {
+						memcpy(file_frame, async_file_frame, file_sample_len * 2);
+						has_file_data = 1;
+						ready++;
+					}
+				}
+			}
 		}
 
 		if (ready) {
 			/* Build a muxed frame for every member that contains the mixed audio of everyone else */
 			for (omember = conference->members; omember; omember = omember->next) {
 				omember->len = bytes;
-				if (conference->fnode) {
+				if (has_file_data) {
 					memcpy(omember->mux_frame, file_frame, file_sample_len * 2);
 				} else {
 					memset(omember->mux_frame, 255, bytes);
@@ -763,7 +808,7 @@
 						continue;
 					}
 
-					if (imember->read) { /* mux the frame with the collective */
+					if (imember->read) {	/* mux the frame with the collective */
 						uint32_t x;
 						int16_t *bptr, *muxed;
 
@@ -772,7 +817,7 @@
 							conference_relationship_t *rel;
 
 							if ((rel = member_get_relationship(omember, imember))) {
-								if (! switch_test_flag(rel, RFLAG_CAN_HEAR)) {
+								if (!switch_test_flag(rel, RFLAG_CAN_HEAR)) {
 									continue;
 								}
 							}
@@ -783,7 +828,7 @@
 							conference_relationship_t *rel;
 
 							if ((rel = member_get_relationship(imember, omember))) {
-								if (! switch_test_flag(rel, RFLAG_CAN_SPEAK)) {
+								if (!switch_test_flag(rel, RFLAG_CAN_SPEAK)) {
 									continue;
 								}
 							}
@@ -800,7 +845,7 @@
 						for (x = 0; x < imember->read / 2; x++) {
 							int32_t z = muxed[x] + bptr[x];
 							switch_normalize_to_16bit(z);
-							muxed[x] = (int16_t)z;
+							muxed[x] = (int16_t) z;
 						}
 
 						ready++;
@@ -810,12 +855,22 @@
 
 			/* Go back and write each member his dedicated copy of the audio frame that does not contain his own audio. */
 			for (imember = conference->members; imember; imember = imember->next) {
-				switch_mutex_lock(imember->audio_out_mutex);
-				switch_buffer_write(imember->mux_buffer, imember->mux_frame, imember->len);
-				switch_mutex_unlock(imember->audio_out_mutex);
+				if (switch_test_flag(imember, MFLAG_RUNNING)) {
+					switch_mutex_lock(imember->audio_out_mutex);
+					switch_buffer_write(imember->mux_buffer, imember->mux_frame, imember->len);
+					switch_mutex_unlock(imember->audio_out_mutex);
+				}
 			}
 		}
 
+		if (conference->async_fnode && conference->async_fnode->done) {
+			switch_memory_pool_t *pool;
+			switch_core_file_close(&conference->async_fnode->fh);
+			pool = conference->async_fnode->pool;
+			conference->async_fnode = NULL;
+			switch_core_destroy_memory_pool(&pool);
+		}
+
 		if (conference->fnode && conference->fnode->done) {
 			conference_file_node_t *fnode;
 			switch_memory_pool_t *pool;
@@ -837,7 +892,7 @@
 		}
 
 		switch_mutex_unlock(conference->mutex);
-	} /* Rinse ... Repeat */
+	}							/* Rinse ... Repeat */
 
 	if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
 		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO);
@@ -851,36 +906,36 @@
 	}
 
 	switch_core_timer_destroy(&timer);
-    
+
 	if (switch_test_flag(conference, CFLAG_DESTRUCT)) {
 
 		switch_mutex_lock(conference->mutex);
 
-		/* Close Unused Handles */ 
+		/* Close Unused Handles */
 		if (conference->fnode) {
-			conference_file_node_t *fnode, *cur; 
-			switch_memory_pool_t *pool; 
+			conference_file_node_t *fnode, *cur;
+			switch_memory_pool_t *pool;
 
-			fnode = conference->fnode; 
-			while (fnode) { 
-				cur = fnode; 
-				fnode = fnode->next; 
-
-				if (cur->type == NODE_TYPE_SPEECH) { 
-					switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE; 
-					switch_core_speech_close(&cur->sh, &flags); 
-				} else { 
-					switch_core_file_close(&cur->fh); 
-				} 
+			fnode = conference->fnode;
+			while (fnode) {
+				cur = fnode;
+				fnode = fnode->next;
 
-				pool = cur->pool; 
-				switch_core_destroy_memory_pool(&pool); 
-			} 
-			conference->fnode = NULL; 
-		} 
+				if (cur->type == NODE_TYPE_SPEECH) {
+					switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
+					switch_core_speech_close(&cur->sh, &flags);
+				} else {
+					switch_core_file_close(&cur->fh);
+				}
+
+				pool = cur->pool;
+				switch_core_destroy_memory_pool(&pool);
+			}
+			conference->fnode = NULL;
+		}
 
-        switch_mutex_lock(conference->member_mutex);
-		for(imember = conference->members; imember; imember = imember->next) {
+		switch_mutex_lock(conference->member_mutex);
+		for (imember = conference->members; imember; imember = imember->next) {
 			switch_channel_t *channel;
 
 			if (!switch_test_flag(imember, MFLAG_NOCHANNEL)) {
@@ -889,8 +944,8 @@
 				/* add this little bit to preserve the bridge cause code in case of an early media call that */
 				/* never answers */
 				if (switch_test_flag(conference, CFLAG_ANSWERED)) {
-					switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);	
-				} else 	{
+					switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
+				} else {
 					/* put actual cause code from outbound channel hangup here */
 					switch_channel_hangup(channel, conference->bridge_hangup_cause);
 				}
@@ -898,11 +953,11 @@
 
 			switch_clear_flag_locked(imember, MFLAG_RUNNING);
 		}
-        switch_mutex_unlock(conference->member_mutex);
+		switch_mutex_unlock(conference->member_mutex);
 
 		switch_mutex_unlock(conference->mutex);
 
-		switch_mutex_lock(globals.hash_mutex);		
+		switch_mutex_lock(globals.hash_mutex);
 		switch_core_hash_delete(globals.conference_hash, conference->name);
 		switch_mutex_unlock(globals.hash_mutex);
 
@@ -922,44 +977,44 @@
 	}
 
 	switch_mutex_lock(globals.hash_mutex);
-	globals.threads--;	
+	globals.threads--;
 	switch_mutex_unlock(globals.hash_mutex);
 
 	return NULL;
 }
 
-static void conference_loop_fn_mute_toggle(conference_member_t *member, void *data)
+static void conference_loop_fn_mute_toggle(conference_member_t * member, caller_control_action_t * action)
 {
 	if (member != NULL) {
 		if (switch_test_flag(member, MFLAG_CAN_SPEAK)) {
 			conf_api_sub_mute(member, NULL, NULL);
 		} else {
 			conf_api_sub_unmute(member, NULL, NULL);
-            if (!switch_test_flag(member, MFLAG_CAN_HEAR)) {
-                conf_api_sub_undeaf(member, NULL, NULL);
-            }
+			if (!switch_test_flag(member, MFLAG_CAN_HEAR)) {
+				conf_api_sub_undeaf(member, NULL, NULL);
+			}
 		}
 	}
 }
 
-static void conference_loop_fn_deafmute_toggle(conference_member_t *member, void *data)
+static void conference_loop_fn_deafmute_toggle(conference_member_t * member, caller_control_action_t * action)
 {
 	if (member != NULL) {
 		if (switch_test_flag(member, MFLAG_CAN_SPEAK)) {
 			conf_api_sub_mute(member, NULL, NULL);
-            if (switch_test_flag(member, MFLAG_CAN_HEAR)) {
-                conf_api_sub_deaf(member, NULL, NULL);
-            }
+			if (switch_test_flag(member, MFLAG_CAN_HEAR)) {
+				conf_api_sub_deaf(member, NULL, NULL);
+			}
 		} else {
 			conf_api_sub_unmute(member, NULL, NULL);
-            if (!switch_test_flag(member, MFLAG_CAN_HEAR)) {
-                conf_api_sub_undeaf(member, NULL, NULL);
-            }
+			if (!switch_test_flag(member, MFLAG_CAN_HEAR)) {
+				conf_api_sub_undeaf(member, NULL, NULL);
+			}
 		}
 	}
 }
 
-static void conference_loop_fn_energy_up(conference_member_t *member, void *data)
+static void conference_loop_fn_energy_up(conference_member_t * member, caller_control_action_t * action)
 {
 	if (member != NULL) {
 		char msg[512];
@@ -988,9 +1043,9 @@
 	}
 }
 
-static void conference_loop_fn_energy_equ_conf(conference_member_t *member, void *data)
+static void conference_loop_fn_energy_equ_conf(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member!= NULL) {
+	if (member != NULL) {
 		char msg[512];
 		switch_event_t *event;
 
@@ -1013,10 +1068,10 @@
 		}
 	}
 }
-					
-static void conference_loop_fn_energy_dn(conference_member_t *member, void *data)
+
+static void conference_loop_fn_energy_dn(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member!= NULL) {
+	if (member != NULL) {
 		char msg[512];
 		switch_event_t *event;
 
@@ -1043,9 +1098,9 @@
 	}
 }
 
-static void conference_loop_fn_volume_talk_up(conference_member_t *member, void *data)
+static void conference_loop_fn_volume_talk_up(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member!= NULL) {
+	if (member != NULL) {
 		char msg[512];
 		switch_event_t *event;
 
@@ -1070,9 +1125,9 @@
 	}
 }
 
-static void conference_loop_fn_volume_talk_zero(conference_member_t *member, void *data)
+static void conference_loop_fn_volume_talk_zero(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member!= NULL) {
+	if (member != NULL) {
 		char msg[512];
 		switch_event_t *event;
 
@@ -1096,9 +1151,9 @@
 	}
 }
 
-static void conference_loop_fn_volume_talk_dn(conference_member_t *member, void *data)
+static void conference_loop_fn_volume_talk_dn(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member!= NULL) {
+	if (member != NULL) {
 		char msg[512];
 		switch_event_t *event;
 
@@ -1123,9 +1178,9 @@
 	}
 }
 
-static void conference_loop_fn_volume_listen_up(conference_member_t *member, void *data)
+static void conference_loop_fn_volume_listen_up(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member!= NULL) {
+	if (member != NULL) {
 		char msg[512];
 		switch_event_t *event;
 
@@ -1150,9 +1205,9 @@
 	}
 }
 
-static void conference_loop_fn_volume_listen_zero(conference_member_t *member, void *data)
+static void conference_loop_fn_volume_listen_zero(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member!= NULL) {
+	if (member != NULL) {
 		char msg[512];
 		switch_event_t *event;
 
@@ -1176,9 +1231,9 @@
 	}
 }
 
-static void conference_loop_fn_volume_listen_dn(conference_member_t *member, void *data)
+static void conference_loop_fn_volume_listen_dn(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member!= NULL) {
+	if (member != NULL) {
 		char msg[512];
 		switch_event_t *event;
 
@@ -1203,76 +1258,35 @@
 	}
 }
 
-static void conference_loop_fn_hangup(conference_member_t *member, void *data)
-{
-	switch_clear_flag_locked(member, MFLAG_RUNNING);
-}
-
-#ifdef OPTION_IVR_MENU_SUPPORT
-typedef struct caller_control_menu_ctx {
-	switch_ivr_menu_xml_ctx_t *xml_ctx;
-	switch_ivr_menu_t *menu_stack;
-	char *name;
-} caller_control_menu_ctx_t;
-
-static void conference_loop_fn_menu(conference_member_t *member, void *data)
+static void conference_loop_fn_event(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member != NULL && data != NULL) {
-		caller_control_menu_ctx_t *menu_ctx = (caller_control_menu_ctx_t *)data;
+	switch_event_t *event;
+	if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+		switch_channel_t *channel = switch_core_session_get_channel(member->session);
 
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "conference_loop_fn_menu handler '%s'\n", menu_ctx->name);
-		if (menu_ctx->menu_stack != NULL && menu_ctx->xml_ctx != NULL) {
-			switch_ivr_menu_execute(member->session, menu_ctx->menu_stack, menu_ctx->name, member);
-		} else {
-			if (menu_ctx->menu_stack == NULL)
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "conference_loop_fn_menu handler NULL menu_stack\n");
-			if (menu_ctx->xml_ctx == NULL)
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "conference_loop_fn_menu handler NULL xml_ctx\n");
-		}
+		switch_channel_event_set_data(channel, event);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "dtmf");
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "DTMF-Key", "%s", action->binded_dtmf);
+		switch_event_fire(&event);
 	}
 }
-#endif
 
-static void conference_loop_fn_dial(conference_member_t *member, void *data)
+static void conference_loop_fn_hangup(conference_member_t * member, caller_control_action_t * action)
 {
-	if (member != NULL && data != NULL) {
-		char *lbuf = strdup(data);
-		char *argv[4];
-		int argc = 0;
-
-		if (lbuf != NULL) {
-			memset(argv, 0, sizeof(argv));
-			argc = switch_separate_string(lbuf, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "dial argc %u 1 '%s' 2 '%s' 3 '%s' 4 '%s'\n", 
-                              argc, argv[0], argv[1], argv[2], argv[3]);
-			if (argc >= 4) {
-                switch_call_cause_t cause;
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "executing conference outcall\n");
-				conference_outcall(member->conference, NULL, argv[0], atoi(argv[1]), NULL, argv[3], argv[2], &cause);
-			} else {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "conference outcall not executed\n");
-			}
-
-			free(lbuf);
-		}
-	}
+	switch_clear_flag_locked(member, MFLAG_RUNNING);
 }
 
-
 /* marshall frames from the call leg to the conference thread for muxing to other call legs */
-static void *SWITCH_THREAD_FUNC conference_loop_input(switch_thread_t *thread, void *obj)
+static void *SWITCH_THREAD_FUNC conference_loop_input(switch_thread_t * thread, void *obj)
 {
 	conference_member_t *member = obj;
 	switch_channel_t *channel;
 	switch_status_t status;
 	switch_frame_t *read_frame = NULL;
 	switch_codec_t *read_codec;
-	uint32_t hangover = 40, 
-		hangunder = 15, 
-		hangover_hits = 0, 
-		hangunder_hits = 0, 
-		energy_level = 0, 
-		diff_level = 400;
+	uint32_t hangover = 40, hangunder = 15, hangover_hits = 0, hangunder_hits = 0, energy_level = 0, diff_level = 400;
 	uint8_t talking = 0;
 
 	assert(member != NULL);
@@ -1286,7 +1300,7 @@
 	/* As long as we have a valid read, feed that data into an input buffer where the conference thread will take it 
 	   and mux it with any audio from other channels. */
 
-	while(switch_test_flag(member, MFLAG_RUNNING) && switch_channel_ready(channel)) {
+	while (switch_test_flag(member, MFLAG_RUNNING) && switch_channel_ready(channel)) {
 		/* Read a frame. */
 		status = switch_core_session_read_frame(member->session, &read_frame, -1, 0);
 
@@ -1328,7 +1342,8 @@
 
 					if (!talking) {
 						switch_event_t *event;
-						talking = 1;		
+						talking = 1;
+						switch_set_flag_locked(member, MFLAG_FLUSH_BUFFER);
 						if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
 							switch_channel_event_set_data(channel, event);
 							switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
@@ -1337,7 +1352,7 @@
 							switch_event_fire(&event);
 						}
 					}
-				} 
+				}
 			} else {
 				if (hangunder_hits) {
 					hangunder_hits--;
@@ -1354,27 +1369,22 @@
 							switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
 							switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "stop-talking");
 							switch_event_fire(&event);
-						}					
+						}
 					}
 				}
 			}
 		}
 
-
-		if (switch_test_flag(member, MFLAG_WASTE_BANDWIDTH) && !talking) {
-			memset(read_frame->data, 255, read_frame->datalen);
-		}
-
 		/* skip frames that are not actual media or when we are muted or silent */
-		if ((talking || energy_level == 0) && switch_test_flag(member, MFLAG_CAN_SPEAK) || switch_test_flag(member, MFLAG_WASTE_BANDWIDTH)) {
+		if ((talking || energy_level == 0) && switch_test_flag(member, MFLAG_CAN_SPEAK)) {
 			if (member->read_resampler) {
 				int16_t *bptr = (int16_t *) read_frame->data;
 				int len = (int) read_frame->datalen;;
 
 				member->read_resampler->from_len = switch_short_to_float(bptr, member->read_resampler->from, (int) len / 2);
-				member->read_resampler->to_len = switch_resample_process(member->read_resampler, member->read_resampler->from, 
-																		 member->read_resampler->from_len, member->read_resampler->to, 
-																		 member->read_resampler->to_size, 0);
+				member->read_resampler->to_len =
+					switch_resample_process(member->read_resampler, member->read_resampler->from,
+											member->read_resampler->from_len, member->read_resampler->to, member->read_resampler->to_size, 0);
 				switch_float_to_short(member->read_resampler->to, read_frame->data, len);
 				len = member->read_resampler->to_len * 2;
 				read_frame->datalen = len;
@@ -1398,7 +1408,7 @@
 }
 
 /* launch an input thread for the call leg */
-static void launch_conference_loop_input(conference_member_t *member, switch_memory_pool_t *pool)
+static void launch_conference_loop_input(conference_member_t * member, switch_memory_pool_t *pool)
 {
 	if (member != NULL) {
 		switch_thread_t *thread;
@@ -1413,50 +1423,50 @@
 }
 
 static caller_control_fn_table_t ccfntbl[] = {
-	{"mute", 		"0", 	CALLER_CONTROL_MUTE, 		conference_loop_fn_mute_toggle}, 
-	{"deaf mute", 		"*", 	CALLER_CONTROL_DEAF_MUTE, 	conference_loop_fn_deafmute_toggle}, 
-	{"energy up", 		"9", 	CALLER_CONTROL_ENERGY_UP, 	conference_loop_fn_energy_up}, 
-	{"energy equ", 		"8", 	CALLER_CONTROL_ENERGY_EQU_CONF, 	conference_loop_fn_energy_equ_conf}, 
-	{"energy dn", 		"7", 	CALLER_CONTROL_ENERGEY_DN, 	conference_loop_fn_energy_dn}, 
-	{"vol talk up", 		"3", 	CALLER_CONTROL_VOL_TALK_UP, 	conference_loop_fn_volume_talk_up}, 
-	{"vol talk zero", 	"2", 	CALLER_CONTROL_VOL_TALK_ZERO, 	conference_loop_fn_volume_talk_zero}, 
-	{"vol talk dn", 		"1", 	CALLER_CONTROL_VOL_TALK_DN, 	conference_loop_fn_volume_talk_dn}, 
-	{"vol listen up", 	"6", 	CALLER_CONTROL_VOL_LISTEN_UP, 	conference_loop_fn_volume_listen_up}, 
-	{"vol listen zero", 	"5", 	CALLER_CONTROL_VOL_LISTEN_ZERO, 	conference_loop_fn_volume_listen_zero}, 
-	{"vol listen dn", 	"4", 	CALLER_CONTROL_VOL_LISTEN_DN, 	conference_loop_fn_volume_listen_dn}, 
-	{"hangup", 		"#", 	CALLER_CONTROL_HANGUP, 		conference_loop_fn_hangup}, 
-#ifdef OPTION_IVR_MENU_SUPPORT
-	{"menu", 		NULL, 	CALLER_CONTROL_MENU, 		conference_loop_fn_menu}, 
-#endif
-	{"dial", 		NULL, 	CALLER_CONTROL_DIAL, 		conference_loop_fn_dial}, 
+	{"mute", "0", CALLER_CONTROL_MUTE, conference_loop_fn_mute_toggle},
+	{"deaf mute", "*", CALLER_CONTROL_DEAF_MUTE, conference_loop_fn_deafmute_toggle},
+	{"energy up", "9", CALLER_CONTROL_ENERGY_UP, conference_loop_fn_energy_up},
+	{"energy equ", "8", CALLER_CONTROL_ENERGY_EQU_CONF, conference_loop_fn_energy_equ_conf},
+	{"energy dn", "7", CALLER_CONTROL_ENERGEY_DN, conference_loop_fn_energy_dn},
+	{"vol talk up", "3", CALLER_CONTROL_VOL_TALK_UP, conference_loop_fn_volume_talk_up},
+	{"vol talk zero", "2", CALLER_CONTROL_VOL_TALK_ZERO, conference_loop_fn_volume_talk_zero},
+	{"vol talk dn", "1", CALLER_CONTROL_VOL_TALK_DN, conference_loop_fn_volume_talk_dn},
+	{"vol listen up", "6", CALLER_CONTROL_VOL_LISTEN_UP, conference_loop_fn_volume_listen_up},
+	{"vol listen zero", "5", CALLER_CONTROL_VOL_LISTEN_ZERO, conference_loop_fn_volume_listen_zero},
+	{"vol listen dn", "4", CALLER_CONTROL_VOL_LISTEN_DN, conference_loop_fn_volume_listen_dn},
+	{"hangup", "#", CALLER_CONTROL_HANGUP, conference_loop_fn_hangup},
+	{"event", NULL, CALLER_CONTROL_EVENT, conference_loop_fn_event}
 };
+
 #define CCFNTBL_QTY (sizeof(ccfntbl)/sizeof(ccfntbl[0]))
 
 /* marshall frames from the conference (or file or tts output) to the call leg */
 /* NB. this starts the input thread after some initial setup for the call leg */
-static void conference_loop_output(conference_member_t *member)
+static void conference_loop_output(conference_member_t * member)
 {
 	switch_channel_t *channel;
-	switch_frame_t write_frame = {0};
-	uint8_t data[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-	switch_timer_t timer = {0};
-	uint32_t samples = switch_bytes_per_frame(member->conference->rate, member->conference->interval);
-	uint32_t bytes = samples * 2;
+	switch_frame_t write_frame = { 0 };
+	uint8_t data[SWITCH_RECOMMENDED_BUFFER_SIZE];
+	switch_timer_t timer = { 0 };
+	switch_codec_t *read_codec = switch_core_session_get_read_codec(member->session);
+	uint32_t interval = read_codec->implementation->microseconds_per_frame / 1000;
+	//uint32_t samples = switch_bytes_per_frame(member->conference->rate, member->conference->interval);
+	uint32_t samples = switch_bytes_per_frame(read_codec->implementation->samples_per_second, interval);
+	uint32_t low_count = 0, bytes = samples * 2;
+	call_list_t *call_list = NULL, *cp = NULL;
 
 	channel = switch_core_session_get_channel(member->session);
 
 	assert(channel != NULL);
 	assert(member->conference != NULL);
 
-	if (switch_core_timer_init(&timer, 
-							   member->conference->timer_name, 
-							   member->conference->interval, 
-							   samples, 
-							   NULL) == SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "setup timer %s success interval: %u  samples: %u\n", 
-						  member->conference->timer_name, member->conference->interval, samples);	
+	if (switch_core_timer_init(&timer, member->conference->timer_name, interval,
+							   //member->conference->interval, 
+							   samples, NULL) == SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "setup timer %s success interval: %u  samples: %u\n",
+						  member->conference->timer_name, interval, samples);
 	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Timer Setup Failed.  Conference Cannot Start\n");	
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Timer Setup Failed.  Conference Cannot Start\n");
 		return;
 	}
 
@@ -1472,16 +1482,46 @@
 	launch_conference_loop_input(member, switch_core_session_get_pool(member->session));
 
 	/* build a digit stream object */
-	if (member->conference->dtmf_parser != NULL && 
-        switch_ivr_digit_stream_new(member->conference->dtmf_parser, &member->digit_stream) != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Warning Will Robinson, there is no digit parser stream object\n");
+	if (member->conference->dtmf_parser != NULL
+		&& switch_ivr_digit_stream_new(member->conference->dtmf_parser, &member->digit_stream) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Danger Will Robinson, there is no digit parser stream object\n");
 	}
+	
+
+	if ((call_list = switch_channel_get_private(channel, "_conference_autocall_list_"))) {
+		char *cid_name = switch_channel_get_variable(channel, "conference_auto_outcall_caller_id_name");
+		char *cid_num = switch_channel_get_variable(channel, "conference_auto_outcall_caller_id_number");
+		char *toval = switch_channel_get_variable(channel, "conference_auto_outcall_timeout");
+		char *flags = switch_channel_get_variable(channel, "conference_auto_outcall_flags");
+		char *ann = switch_channel_get_variable(channel, "conference_auto_outcall_announce");
+		int to = 60;
+		
+		if (ann) {
+			member->conference->special_announce = switch_core_strdup(member->conference->pool, ann);
+		}
+
+		switch_channel_set_private(channel, "_conference_autocall_list_", NULL);
+		
+		if (toval) {
+			to = atoi(toval);
+		}
+		
+		if (to < 10 || to > 500) {
+			to = 60;
+		}
+		
+		for (cp = call_list; cp; cp = cp->next) {
+			conference_outcall_bg(member->conference, NULL, member->session, cp->string, to, switch_str_nil(flags), cid_name, cid_num);
+
+		}
 
-	/* Fair WARNING, If you expect the caller to hear anything or for digit handling to be proccessed, 		*/
-	/* you better not block this thread loop for more than the duration of member->conference->timer_name!	*/
-	while(switch_test_flag(member, MFLAG_RUNNING) && switch_test_flag(member, MFLAG_ITHREAD) && switch_channel_ready(channel)) {
+	}
+	/* Fair WARNING, If you expect the caller to hear anything or for digit handling to be proccessed,      */
+	/* you better not block this thread loop for more than the duration of member->conference->timer_name!  */
+	while (switch_test_flag(member, MFLAG_RUNNING) && switch_test_flag(member, MFLAG_ITHREAD)
+		   && switch_channel_ready(channel)) {
 		char dtmf[128] = "";
-		uint8_t file_frame[CONF_BUFFER_SIZE] = {0};
+		uint8_t file_frame[CONF_BUFFER_SIZE] = { 0 };
 		switch_size_t file_data_len = samples * 2;
 		switch_size_t file_sample_len = samples;
 		char *digit;
@@ -1497,8 +1537,7 @@
 			char *body = switch_event_get_body(event);
 			char *p, *freeme = NULL;
 
-			if ((p = strchr(to, '+')) && 
-				strncmp(to, CONF_CHAT_PROTO, strlen(CONF_CHAT_PROTO))) {
+			if ((p = strchr(to, '+')) && strncmp(to, CONF_CHAT_PROTO, strlen(CONF_CHAT_PROTO))) {
 				freeme = switch_mprintf("%s+%s@%s", CONF_CHAT_PROTO, member->conference->name, member->conference->domain);
 				to = freeme;
 			}
@@ -1528,35 +1567,33 @@
 			if (member->conference->dtmf_parser != NULL) {
 
 				for (digit = dtmf; *digit && caller_action == NULL; digit++) {
-					caller_action = (caller_control_action_t *)switch_ivr_digit_stream_parser_feed(member->conference->dtmf_parser, member->digit_stream, *digit);
+					caller_action = (caller_control_action_t *)
+						switch_ivr_digit_stream_parser_feed(member->conference->dtmf_parser, member->digit_stream, *digit);
 				}
 			}
-            /* otherwise, clock the parser so that it can handle digit timeout detection */
+			/* otherwise, clock the parser so that it can handle digit timeout detection */
 		} else if (member->conference->dtmf_parser != NULL) {
-			caller_action = (caller_control_action_t *)switch_ivr_digit_stream_parser_feed(member->conference->dtmf_parser, member->digit_stream, '\0');
+			caller_action = (caller_control_action_t *) switch_ivr_digit_stream_parser_feed(member->conference->dtmf_parser, member->digit_stream, '\0');
 		}
 
 		/* if a caller action has been detected, handle it */
 		if (caller_action != NULL && caller_action->fndesc != NULL && caller_action->fndesc->handler != NULL) {
-			switch_channel_t *channel		 = switch_core_session_get_channel(member->session);
-			switch_caller_profile_t *profile	 = switch_channel_get_caller_profile(channel);
-            char *param = NULL;
-
-            if (caller_action->fndesc->action != CALLER_CONTROL_MENU) {
-                param = caller_action->data;
-            }
-
-			switch_log_printf(SWITCH_CHANNEL_LOG, 
-                              SWITCH_LOG_INFO, 
-                              "executing caller control '%s' param '%s' on call '%u, %s, %s, %s'\n", 
-                              caller_action->fndesc->key, 
-                              param ? param : "none", 
-                              member->id, 
-                              switch_channel_get_name(channel), 
-                              profile->caller_id_name, 
-                              profile->caller_id_number
-                              );
-			caller_action->fndesc->handler(member, caller_action->data);
+			//switch_channel_t *channel      = switch_core_session_get_channel(member->session);
+			//switch_caller_profile_t *profile   = switch_channel_get_caller_profile(channel);
+			char *param = NULL;
+
+			if (caller_action->fndesc->action != CALLER_CONTROL_MENU) {
+				param = caller_action->data;
+			}
+#ifdef INTENSE_DEBUG
+			switch_log_printf(SWITCH_CHANNEL_LOG,
+							  SWITCH_LOG_INFO,
+							  "executing caller control '%s' param '%s' on call '%u, %s, %s, %s'\n",
+							  caller_action->fndesc->key,
+							  param ? param : "none", member->id, switch_channel_get_name(channel), profile->caller_id_name, profile->caller_id_number);
+#endif
+
+			caller_action->fndesc->handler(member, caller_action);
 
 			/* set up for next pass */
 			caller_action = NULL;
@@ -1564,7 +1601,7 @@
 
 		/* handle file and TTS frames */
 		if (member->fnode) {
-            switch_mutex_lock(member->flag_mutex);
+			switch_mutex_lock(member->flag_mutex);
 			/* if we are done, clean it up */
 			if (member->fnode->done) {
 				conference_file_node_t *fnode;
@@ -1588,19 +1625,15 @@
 				/* skip this frame until leadin time has expired */
 				if (member->fnode->leadin) {
 					member->fnode->leadin--;
-				} else {	/* send the node frame instead of the conference frame to the call leg */
+				} else {		/* send the node frame instead of the conference frame to the call leg */
 					if (member->fnode->type == NODE_TYPE_SPEECH) {
 						switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_BLOCKING;
 						uint32_t rate = member->conference->rate;
 
-						if (switch_core_speech_read_tts(&member->fnode->sh, 
-														file_frame, 
-														&file_data_len, 
-														&rate, 
-														&flags) == SWITCH_STATUS_SUCCESS) {
+						if (switch_core_speech_read_tts(&member->fnode->sh, file_frame, &file_data_len, &rate, &flags) == SWITCH_STATUS_SUCCESS) {
 							file_sample_len = file_data_len / 2;
 						} else {
-							file_sample_len = file_data_len  = 0;
+							file_sample_len = file_data_len = 0;
 						}
 					} else if (member->fnode->type == NODE_TYPE_FILE) {
 						switch_core_file_read(&member->fnode->fh, file_frame, &file_sample_len);
@@ -1609,35 +1642,59 @@
 
 					if (file_sample_len <= 0) {
 						member->fnode->done++;
-					} else { /* there is file node data to deliver */
+					} else {	/* there is file node data to deliver */
 						write_frame.data = file_frame;
-						write_frame.datalen = (uint32_t)file_data_len;
-						write_frame.samples = (uint32_t)file_sample_len;
+						write_frame.datalen = (uint32_t) file_data_len;
+						write_frame.samples = (uint32_t) file_sample_len;
 						/* Check for output volume adjustments */
 						if (member->volume_out_level) {
 							switch_change_sln_volume(write_frame.data, write_frame.samples, member->volume_out_level);
 						}
+						write_frame.timestamp = timer.samplecount;
 						switch_core_session_write_frame(member->session, &write_frame, -1, 0);
+						switch_core_timer_next(&timer);
 
 						/* forget the conference data we played file node data instead */
-						switch_mutex_lock(member->audio_out_mutex);
-						switch_buffer_zero(member->mux_buffer);
-						switch_mutex_unlock(member->audio_out_mutex);
+						switch_set_flag_locked(member, MFLAG_FLUSH_BUFFER);
 					}
 				}
 			}
-            switch_mutex_unlock(member->flag_mutex);
-		} else {	/* send the conferecne frame to the call leg */
+			switch_mutex_unlock(member->flag_mutex);
+		} else {				/* send the conferecne frame to the call leg */
 			switch_buffer_t *use_buffer = NULL;
-			uint32_t mux_used = (uint32_t)switch_buffer_inuse(member->mux_buffer);
+			uint32_t mux_used = (uint32_t) switch_buffer_inuse(member->mux_buffer);
+
+			if (mux_used) {
+				if (mux_used < bytes) {
+					if (++low_count >= 5) {
+						/* partial frame sitting around this long is useless and builds delay */
+						switch_set_flag_locked(member, MFLAG_FLUSH_BUFFER);
+					}
+					mux_used = 0;
+				} else if (mux_used > bytes * 2) {
+					/* getting behind, clear the buffer */
+					switch_set_flag_locked(member, MFLAG_FLUSH_BUFFER);
+				}
+			}
+
+			if (switch_test_flag(member, MFLAG_FLUSH_BUFFER)) {
+				if (mux_used) {
+					switch_mutex_lock(member->audio_out_mutex);
+					switch_buffer_zero(member->mux_buffer);
+					switch_mutex_unlock(member->audio_out_mutex);
+					mux_used = 0;
+				}
+				switch_clear_flag_locked(member, MFLAG_FLUSH_BUFFER);
+			}
 
 			if (mux_used) {
 				/* Flush the output buffer and write all the data (presumably muxed) back to the channel */
 				switch_mutex_lock(member->audio_out_mutex);
 				write_frame.data = data;
 				use_buffer = member->mux_buffer;
+				low_count = 0;
 
-				while ((write_frame.datalen = (uint32_t)switch_buffer_read(use_buffer, write_frame.data, bytes))) {
+				if ((write_frame.datalen = (uint32_t) switch_buffer_read(use_buffer, write_frame.data, bytes))) {
 					if (write_frame.datalen && switch_test_flag(member, MFLAG_CAN_HEAR)) {
 						write_frame.samples = write_frame.datalen / 2;
 
@@ -1645,19 +1702,27 @@
 						if (member->volume_out_level) {
 							switch_change_sln_volume(write_frame.data, write_frame.samples, member->volume_out_level);
 						}
-
+						//printf("WRITE %d %d\n", write_frame.datalen, ++x);
+						write_frame.timestamp = timer.samplecount;
 						switch_core_session_write_frame(member->session, &write_frame, -1, 0);
 					}
 				}
 
 				switch_mutex_unlock(member->audio_out_mutex);
-				continue;
-			} 
-		}
-
-		switch_core_timer_next(&timer);
+				switch_core_timer_next(&timer);
 
-	} /* Rinse ... Repeat */
+			} else {
+				if (switch_test_flag(member, MFLAG_WASTE_BANDWIDTH)) {
+					switch_generate_sln_silence(write_frame.data, samples, 1400);
+					write_frame.datalen = bytes;
+					write_frame.samples = samples;
+					write_frame.timestamp = timer.samplecount;
+					switch_core_session_write_frame(member->session, &write_frame, -1, 0);
+				}
+				switch_core_timer_next(&timer);
+			}
+		}
+	}							/* Rinse ... Repeat */
 
 	if (member->digit_stream != NULL) {
 		switch_ivr_digit_stream_destroy(member->digit_stream);
@@ -1666,8 +1731,8 @@
 	switch_clear_flag_locked(member, MFLAG_RUNNING);
 	switch_core_timer_destroy(&timer);
 
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Channel leaving conference, cause: %s\n", 
-                      switch_channel_cause2str(switch_channel_get_cause(channel)));
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Channel leaving conference, cause: %s\n",
+					  switch_channel_cause2str(switch_channel_get_cause(channel)));
 
 	/* if it's an outbound channel, store the release cause in the conference struct, we might need it */
 	if (switch_channel_test_flag(channel, CF_OUTBOUND)) {
@@ -1675,24 +1740,25 @@
 	}
 
 	/* Wait for the input thead to end */
-	while(switch_test_flag(member, MFLAG_ITHREAD)) {
+	while (switch_test_flag(member, MFLAG_ITHREAD)) {
 		switch_yield(1000);
 	}
 }
 
 /* Sub-Routine called by a record entity inside a conference */
-static void *SWITCH_THREAD_FUNC conference_record_thread_run(switch_thread_t *thread, void *obj)
+static void *SWITCH_THREAD_FUNC conference_record_thread_run(switch_thread_t * thread, void *obj)
 {
-	switch_frame_t write_frame = {0};
-	uint8_t data[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-	switch_file_handle_t fh = {0};
-	conference_member_t smember = {0}, *member;
+	uint8_t data[SWITCH_RECOMMENDED_BUFFER_SIZE];
+	switch_file_handle_t fh = { 0 };
+	conference_member_t smember = { 0 }, *member;
 	conference_record_t *rec = (conference_record_t *) obj;
 	conference_obj_t *conference = rec->conference;
 	uint32_t samples = switch_bytes_per_frame(conference->rate, conference->interval);
-	uint32_t bytes = samples * 2;
-	uint32_t mux_used;
+	//uint32_t bytes = samples * 2;
+	uint32_t low_count = 0, mux_used;
 	char *vval;
+	switch_timer_t timer = { 0 };
+	uint32_t rlen;
 
 	if (switch_thread_rwlock_tryrdlock(conference->rwlock) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Read Lock Fail\n");
@@ -1701,15 +1767,12 @@
 
 	switch_mutex_lock(globals.hash_mutex);
 	globals.threads++;
-	switch_mutex_unlock(globals.hash_mutex);		
+	switch_mutex_unlock(globals.hash_mutex);
 
 	member = &smember;
 
 	member->flags = MFLAG_CAN_HEAR | MFLAG_NOCHANNEL | MFLAG_RUNNING;
 
-	write_frame.data = data;
-	write_frame.buflen = sizeof(data);
-
 	member->conference = conference;
 	member->native_rate = conference->rate;
 	member->rec_path = rec->path;
@@ -1739,43 +1802,69 @@
 		goto end;
 	}
 
-	if (switch_core_file_open(&fh, 
-							  rec->path, 
-							  SWITCH_FILE_FLAG_WRITE | SWITCH_FILE_DATA_SHORT, 
+	if (switch_core_file_open(&fh,
+							  rec->path, (uint8_t) 1, conference->rate, SWITCH_FILE_FLAG_WRITE | SWITCH_FILE_DATA_SHORT,
 							  rec->pool) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening File [%s]\n", rec->path);
 		goto end;
 	}
 
+
+	if (switch_core_timer_init(&timer, conference->timer_name, conference->interval, samples, rec->pool) == SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "setup timer success interval: %u  samples: %u\n", conference->interval, samples);
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Timer Setup Failed.  Conference Cannot Start\n");
+		goto end;
+	}
+
 	if ((vval = switch_mprintf("Conference %s", conference->name))) {
 		switch_core_file_set_string(&fh, SWITCH_AUDIO_COL_STR_TITLE, vval);
 		switch_safe_free(vval);
 	}
 
-	while(switch_test_flag(member, MFLAG_RUNNING) && switch_test_flag(conference, CFLAG_RUNNING) && conference->count) {
-		if ((mux_used = (uint32_t) switch_buffer_inuse(member->mux_buffer)) >= bytes) {
+	switch_core_file_set_string(&fh, SWITCH_AUDIO_COL_STR_ARTIST, "FreeSWITCH mod_conference Software Conference Module");
+
+	while (switch_test_flag(member, MFLAG_RUNNING) && switch_test_flag(conference, CFLAG_RUNNING) && conference->count) {
+		mux_used = (uint32_t) switch_buffer_inuse(member->mux_buffer);
+
+		if (switch_test_flag(member, MFLAG_FLUSH_BUFFER)) {
+			if (mux_used) {
+				switch_mutex_lock(member->audio_out_mutex);
+				switch_buffer_zero(member->mux_buffer);
+				switch_mutex_unlock(member->audio_out_mutex);
+				mux_used = 0;
+			}
+			switch_clear_flag_locked(member, MFLAG_FLUSH_BUFFER);
+		}
+
+		if (mux_used) {
 			/* Flush the output buffer and write all the data (presumably muxed) to the file */
 			switch_mutex_lock(member->audio_out_mutex);
-			write_frame.data = data;
-			while ((write_frame.datalen = (uint32_t)switch_buffer_read(member->mux_buffer, write_frame.data, mux_used))) {
+			low_count = 0;
+
+			if ((rlen = (uint32_t) switch_buffer_read(member->mux_buffer, data, sizeof(data)))) {
 				if (!switch_test_flag((&fh), SWITCH_FILE_PAUSE)) {
-					switch_size_t len = (switch_size_t) mux_used / 2;
-					switch_core_file_write(&fh, write_frame.data, &len);
+					switch_size_t len = (switch_size_t) rlen / sizeof(int16_t);
+					if (switch_core_file_write(&fh, data, &len) != SWITCH_STATUS_SUCCESS) {
+						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Write Failed\n");
+						switch_clear_flag_locked(member, MFLAG_RUNNING);
+					}
 				}
 			}
 			switch_mutex_unlock(member->audio_out_mutex);
 		} else {
-			switch_yield(20000);
+			switch_core_timer_next(&timer);
 		}
-	} /* Rinse ... Repeat */
+	}							/* Rinse ... Repeat */
 
- end:
+  end:
 
+	switch_core_timer_destroy(&timer);
 	conference_del_member(conference, member);
 	switch_buffer_destroy(&member->audio_buffer);
 	switch_buffer_destroy(&member->mux_buffer);
 	switch_clear_flag_locked(member, MFLAG_RUNNING);
-	if (fh.fd) {
+	if (switch_test_flag((&fh), SWITCH_FILE_OPEN)) {
 		switch_core_file_close(&fh);
 	}
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Recording Stopped\n");
@@ -1795,34 +1884,38 @@
 }
 
 /* Make files stop playing in a conference either the current one or all of them */
-static uint32_t conference_stop_file(conference_obj_t *conference, file_stop_t stop)
+static uint32_t conference_stop_file(conference_obj_t * conference, file_stop_t stop)
 {
 	uint32_t count = 0;
-    conference_file_node_t *nptr;
+	conference_file_node_t *nptr;
+
+	assert(conference != NULL);
 
-    assert(conference != NULL);
+	switch_mutex_lock(conference->mutex);
 
-    switch_mutex_lock(conference->mutex);
+	if (stop == FILE_STOP_ALL) {
+		for (nptr = conference->fnode; nptr; nptr = nptr->next) {
+			nptr->done++;
+			count++;
+		}
+		if (conference->async_fnode) {
+			conference->async_fnode->done++;
+			count++;
+		}
+	} else {
+		if (conference->fnode) {
+			conference->fnode->done++;
+			count++;
+		}
+	}
 
-    if (stop == FILE_STOP_ALL) {
-        for (nptr = conference->fnode; nptr; nptr = nptr->next) {
-            nptr->done++;
-            count++;
-        }
-    } else {
-        if (conference->fnode) {
-            conference->fnode->done++;
-            count++;
-        }
-    }
-    
-    switch_mutex_unlock(conference->mutex);	
+	switch_mutex_unlock(conference->mutex);
 
 	return count;
 }
 
 /* stop playing a file for the member of the conference */
-static uint32_t conference_member_stop_file(conference_member_t *member, file_stop_t stop)
+static uint32_t conference_member_stop_file(conference_member_t * member, file_stop_t stop)
 {
 	uint32_t count = 0;
 
@@ -1850,3073 +1943,3011 @@
 }
 
 /* Play a file in the conference room */
-static switch_status_t conference_play_file(conference_obj_t *conference, char *file, uint32_t leadin, switch_channel_t *channel)
+static switch_status_t conference_play_file(conference_obj_t * conference, char *file, uint32_t leadin, switch_channel_t *channel, uint8_t async)
 {
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
-    conference_file_node_t *fnode, *nptr;
-    switch_memory_pool_t *pool;
-    uint32_t count;
-    char *dfile = NULL, *expanded = NULL;
-
-    assert(conference != NULL);
-
-    switch_mutex_lock(conference->mutex);
-    switch_mutex_lock(conference->member_mutex);
-    count = conference->count;
-    switch_mutex_unlock(conference->member_mutex);
-    switch_mutex_unlock(conference->mutex);	
-
-    if (!count) {
-        status = SWITCH_STATUS_FALSE;
-        goto done;
-    }
-
-    if (channel) {
-        if ((expanded = switch_channel_expand_variables(channel, file)) != file) {
-            file = expanded;
-        } else {
-            expanded = NULL;
-        }
-    }
-
-    if (!strncasecmp(file, "say:", 4)) {
-        status = conference_say(conference, file + 4, leadin);
-        goto done;
-    } 
-
-    if (!switch_is_file_path(file)) {
-        if (conference->sound_prefix) {
-            if (!(dfile = switch_mprintf("%s/%s", conference->sound_prefix, file))) {
-                goto done;
-            }
-            file = dfile;
-        } else {
-            status = conference_say(conference, file, leadin);
-            goto done;  
-        }
-    }
-
-    /* Setup a memory pool to use. */
-    if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
-        status = SWITCH_STATUS_MEMERR;
-        goto done;
-    }
-
-    /* Create a node object*/
-    if (!(fnode = switch_core_alloc(pool, sizeof(*fnode)))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
-        switch_core_destroy_memory_pool(&pool);
-        status = SWITCH_STATUS_MEMERR;
-        goto done;
-    }
-
-    fnode->type = NODE_TYPE_FILE;
-    fnode->leadin = leadin;
-
-    /* Open the file */
-    if (switch_core_file_open(&fnode->fh, 
-                              file, 
-                              SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT, 
-                              pool) != SWITCH_STATUS_SUCCESS) {
-        switch_core_destroy_memory_pool(&pool);
-        status = SWITCH_STATUS_NOTFOUND;
-        goto done;
-    }
-
-    fnode->pool = pool;
-
-    /* Queue the node */
-    switch_mutex_lock(conference->mutex);
-    for (nptr = conference->fnode; nptr && nptr->next; nptr = nptr->next);
-
-    if (nptr) {
-        nptr->next = fnode;
-    } else {
-        conference->fnode = fnode;
-    }
-    switch_mutex_unlock(conference->mutex);
+	conference_file_node_t *fnode, *nptr = NULL;
+	switch_memory_pool_t *pool;
+	uint32_t count;
+	char *dfile = NULL, *expanded = NULL;
 
- done:
+	assert(conference != NULL);
 
+	switch_mutex_lock(conference->mutex);
+	switch_mutex_lock(conference->member_mutex);
+	count = conference->count;
+	switch_mutex_unlock(conference->member_mutex);
+	switch_mutex_unlock(conference->mutex);
+
+	if (!count) {
+		status = SWITCH_STATUS_FALSE;
+		goto done;
+	}
 
-    switch_safe_free(expanded);
-    switch_safe_free(dfile);
+	if (channel) {
+		if ((expanded = switch_channel_expand_variables(channel, file)) != file) {
+			file = expanded;
+		} else {
+			expanded = NULL;
+		}
+	}
 
-	
+	if (!async && !strncasecmp(file, "say:", 4)) {
+		status = conference_say(conference, file + 4, leadin);
+		goto done;
+	}
 
-    return status;
-}
+	if (!switch_is_file_path(file)) {
+		if (conference->sound_prefix) {
+			if (!(dfile = switch_mprintf("%s/%s", conference->sound_prefix, file))) {
+				goto done;
+			}
+			file = dfile;
+		} else if (!async) {
+			status = conference_say(conference, file, leadin);
+			goto done;
+		} else {
+			goto done;
+		}
+	}
 
-/* Play a file in the conference room to a member */
-static switch_status_t conference_member_play_file(conference_member_t *member, char *file, uint32_t leadin)
-{
-    switch_status_t status = SWITCH_STATUS_FALSE;
-    char *dfile = NULL, *expanded = NULL;
+	/* Setup a memory pool to use. */
+	if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
+		status = SWITCH_STATUS_MEMERR;
+		goto done;
+	}
 
-    if (member != NULL && file != NULL) {
-        conference_file_node_t *fnode, *nptr;
-        switch_memory_pool_t *pool;
-
-        if ((expanded = switch_channel_expand_variables(switch_core_session_get_channel(member->session), file)) != file) {
-            file = expanded;
-        } else {
-            expanded = NULL;
-        }
-
-        if (!strncasecmp(file, "say:", 4)) {
-            status = conference_say(member->conference, file + 4, leadin);
-            goto done;
-        } 
-
-        if (!switch_is_file_path(file)) {
-            if (member->conference->sound_prefix) {
-                if (!(dfile = switch_mprintf("%s/%s", member->conference->sound_prefix, file))) {
-                    goto done;
-                }
-                file = dfile;
-            } else {
-                status = conference_say(member->conference, file, leadin);
-                goto done;  
-            }
-        }
-
-        /* Setup a memory pool to use. */
-        if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
-            status = SWITCH_STATUS_MEMERR;
-            goto done;
-        }
-
-        /* Create a node object*/
-        if (!(fnode = switch_core_alloc(pool, sizeof(*fnode)))) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
-            switch_core_destroy_memory_pool(&pool);
-            status = SWITCH_STATUS_MEMERR;
-            goto done;
-        }
-
-        fnode->type = NODE_TYPE_FILE;
-        fnode->leadin = leadin;
-
-        /* Open the file */
-        if (switch_core_file_open(&fnode->fh, 
-                                  file, 
-                                  SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT, 
-                                  pool) != SWITCH_STATUS_SUCCESS) {
-            switch_core_destroy_memory_pool(&pool);
-            status = SWITCH_STATUS_NOTFOUND;
-            goto done;
-        }
-
-        fnode->pool = pool;
-
-        /* Queue the node */
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "queueing file '%s' for play\n", file);
-        switch_mutex_lock(member->flag_mutex);
-        for (nptr = member->fnode; nptr && nptr->next; nptr = nptr->next);
-
-        if (nptr) {
-            nptr->next = fnode;
-        } else {
-            member->fnode = fnode;
-        }
-        switch_mutex_unlock(member->flag_mutex);
+	/* Create a node object */
+	if (!(fnode = switch_core_alloc(pool, sizeof(*fnode)))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
+		switch_core_destroy_memory_pool(&pool);
+		status = SWITCH_STATUS_MEMERR;
+		goto done;
+	}
 
-        status = SWITCH_STATUS_SUCCESS;
-    }
+	fnode->type = NODE_TYPE_FILE;
+	fnode->leadin = leadin;
 
- done:
+	/* Open the file */
+	if (switch_core_file_open(&fnode->fh, file, (uint8_t) 1, conference->rate, SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT, pool) !=
+		SWITCH_STATUS_SUCCESS) {
+		switch_core_destroy_memory_pool(&pool);
+		status = SWITCH_STATUS_NOTFOUND;
+		goto done;
+	}
 
-    switch_safe_free(expanded);
-    switch_safe_free(dfile);
+	fnode->pool = pool;
+	fnode->async = async;
+	/* Queue the node */
+	switch_mutex_lock(conference->mutex);
+
+	if (async) {
+		if (conference->async_fnode) {
+			nptr = conference->async_fnode;
+		}
+		conference->async_fnode = fnode;
 
-    return status;
-}
+		if (nptr) {
+			switch_memory_pool_t *pool;
+			switch_core_file_close(&nptr->fh);
+			pool = nptr->pool;
+			switch_core_destroy_memory_pool(&pool);
+		}
 
-/* Say some thing with TTS in the conference room */
-static switch_status_t conference_member_say(conference_member_t *member, char *text, uint32_t leadin)
-{
-    switch_status_t status = SWITCH_STATUS_FALSE;
+	} else {
+		for (nptr = conference->fnode; nptr && nptr->next; nptr = nptr->next);
 
-    if (member != NULL && !switch_strlen_zero(text)) {
-        conference_obj_t *conference = (member != NULL ? member->conference : NULL);
-        conference_file_node_t *fnode, *nptr;
-        switch_memory_pool_t *pool;
-        switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
-
-        assert(conference != NULL);
-        
-        if (!(conference->tts_engine && conference->tts_voice)) {
-            return SWITCH_STATUS_SUCCESS;
-        }
-
-        /* Setup a memory pool to use. */
-        if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
-            return SWITCH_STATUS_MEMERR;
-        }
-
-        /* Create a node object*/
-        if (!(fnode = switch_core_alloc(pool, sizeof(*fnode)))) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
-            switch_core_destroy_memory_pool(&pool);
-            return SWITCH_STATUS_MEMERR;
-        }
-
-        fnode->type = NODE_TYPE_SPEECH;
-        fnode->leadin = leadin;
-        fnode->pool = pool;
-
-        memset(&fnode->sh, 0, sizeof(fnode->sh));
-        if (switch_core_speech_open(&fnode->sh, 
-                                    conference->tts_engine, 
-                                    conference->tts_voice, 
-                                    conference->rate, 
-                                    &flags, 
-                                    fnode->pool) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid TTS module [%s]!\n", conference->tts_engine);
-            return SWITCH_STATUS_FALSE;
-        }
-
-        /* Queue the node */
-        switch_mutex_lock(member->flag_mutex);
-        for (nptr = member->fnode; nptr && nptr->next; nptr = nptr->next);
-
-        if (nptr) {
-            nptr->next = fnode;
-        } else {
-            member->fnode = fnode;
-        }
-
-        /* Begin Generation */
-        switch_sleep(200000);
-        switch_core_speech_feed_tts(&fnode->sh, text, &flags);
-        switch_mutex_unlock(member->flag_mutex);
+		if (nptr) {
+			nptr->next = fnode;
+		} else {
+			conference->fnode = fnode;
+		}
+	}
 
-        status = SWITCH_STATUS_SUCCESS;
-    }
+	switch_mutex_unlock(conference->mutex);
 
-    return status;
-}
+  done:
 
-/* Say some thing with TTS in the conference room */
-static switch_status_t conference_say(conference_obj_t *conference, const char *text, uint32_t leadin)
-{
-    switch_status_t status = SWITCH_STATUS_FALSE;
-    conference_file_node_t *fnode, *nptr;
-    switch_memory_pool_t *pool;
-    switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
-    uint32_t count;
-
-    assert(conference != NULL);
-
-    if (switch_strlen_zero(text)) {
-        return SWITCH_STATUS_GENERR;
-    }
-
-    switch_mutex_lock(conference->mutex);
-    switch_mutex_lock(conference->member_mutex);
-    count = conference->count;
-    if (!(conference->tts_engine && conference->tts_voice)) {
-        count = 0;
-    }
-    switch_mutex_unlock(conference->member_mutex);
-    switch_mutex_unlock(conference->mutex);	
-
-    if (!count) {
-        return SWITCH_STATUS_FALSE;
-    }
-
-    /* Setup a memory pool to use. */
-    if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
-        return SWITCH_STATUS_MEMERR;
-    }
-
-    /* Create a node object*/
-    if (!(fnode = switch_core_alloc(pool, sizeof(*fnode)))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
-        switch_core_destroy_memory_pool(&pool);
-        return SWITCH_STATUS_MEMERR;
-    }
-
-    fnode->type = NODE_TYPE_SPEECH;
-    fnode->leadin = leadin;
-
-    memset(&fnode->sh, 0, sizeof(fnode->sh));
-    if (switch_core_speech_open(&fnode->sh, 
-                                conference->tts_engine, 
-                                conference->tts_voice, 
-                                conference->rate, 
-                                &flags, 
-                                conference->pool) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid TTS module [%s]!\n", conference->tts_engine);
-        return SWITCH_STATUS_FALSE;
-    }
-
-    fnode->pool = pool;
-
-    /* Queue the node */
-    switch_mutex_lock(conference->mutex);
-    for (nptr = conference->fnode; nptr && nptr->next; nptr = nptr->next);
-
-    if (nptr) {
-        nptr->next = fnode;
-    } else {
-        conference->fnode = fnode;
-    }
-
-    /* Begin Generation */
-    switch_sleep(200000);
-    switch_core_speech_feed_tts(&fnode->sh, (char *)text, &flags);
-    switch_mutex_unlock(conference->mutex);
 
-    status = SWITCH_STATUS_SUCCESS;
+	switch_safe_free(expanded);
+	switch_safe_free(dfile);
 
-    return status;
-}
 
-/* execute a callback for every member of the conference */
-static void conference_member_itterator(conference_obj_t *conference, switch_stream_handle_t *stream, conf_api_member_cmd_t pfncallback, void *data)
-{
-    conference_member_t *member = NULL;
 
-    assert(conference != NULL);
-    assert(stream != NULL);
-    assert(pfncallback != NULL);
-
-    switch_mutex_lock(conference->member_mutex);
-    for (member = conference->members; member; member = member->next) {
-        pfncallback(member, stream, data);
-    }
-    switch_mutex_unlock(conference->member_mutex);
-	
+	return status;
 }
 
-static void conference_list_pretty(conference_obj_t *conference, switch_stream_handle_t *stream)
+/* Play a file in the conference room to a member */
+static switch_status_t conference_member_play_file(conference_member_t * member, char *file, uint32_t leadin)
 {
-    conference_member_t *member = NULL;
+	switch_status_t status = SWITCH_STATUS_FALSE;
+	char *dfile = NULL, *expanded = NULL;
 
-    assert(conference != NULL);
-    assert(stream != NULL);
+	if (member != NULL && file != NULL) {
+		conference_file_node_t *fnode, *nptr;
+		switch_memory_pool_t *pool;
 
-    switch_mutex_lock(conference->member_mutex);
-    //		stream->write_function(stream, "<pre>Current Callers:\n");
+		if ((expanded = switch_channel_expand_variables(switch_core_session_get_channel(member->session), file)) != file) {
+			file = expanded;
+		} else {
+			expanded = NULL;
+		}
 
-    for (member = conference->members; member; member = member->next) {
-        switch_channel_t *channel;
-        switch_caller_profile_t *profile;
+		if (!strncasecmp(file, "say:", 4)) {
+			status = conference_say(member->conference, file + 4, leadin);
+			goto done;
+		}
 
-        if (switch_test_flag(member, MFLAG_NOCHANNEL)) {
-            continue;
-        }
-        channel = switch_core_session_get_channel(member->session);
-        profile = switch_channel_get_caller_profile(channel);
+		if (!switch_is_file_path(file)) {
+			if (member->conference->sound_prefix) {
+				if (!(dfile = switch_mprintf("%s/%s", member->conference->sound_prefix, file))) {
+					goto done;
+				}
+				file = dfile;
+			} else {
+				status = conference_say(member->conference, file, leadin);
+				goto done;
+			}
+		}
 
+		/* Setup a memory pool to use. */
+		if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
+			status = SWITCH_STATUS_MEMERR;
+			goto done;
+		}
 
-        stream->write_function(stream, "%u) %s (%s)\n", 
-                               member->id, 
-                               profile->caller_id_name, 
-                               profile->caller_id_number
-                               );
+		/* Create a node object */
+		if (!(fnode = switch_core_alloc(pool, sizeof(*fnode)))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
+			switch_core_destroy_memory_pool(&pool);
+			status = SWITCH_STATUS_MEMERR;
+			goto done;
+		}
 
-    }
+		fnode->type = NODE_TYPE_FILE;
+		fnode->leadin = leadin;
 
-    switch_mutex_unlock(conference->member_mutex);
-	
-}
+		/* Open the file */
+		if (switch_core_file_open(&fnode->fh,
+								  file, (uint8_t) 1, member->conference->rate, SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT,
+								  pool) != SWITCH_STATUS_SUCCESS) {
+			switch_core_destroy_memory_pool(&pool);
+			status = SWITCH_STATUS_NOTFOUND;
+			goto done;
+		}
 
-static void conference_list(conference_obj_t *conference, switch_stream_handle_t *stream, char *delim)
-{
-    conference_member_t *member = NULL;
+		fnode->pool = pool;
 
-    assert(conference != NULL);
-    assert(stream != NULL);
-    assert(delim != NULL);
-
-
-    switch_mutex_lock(conference->member_mutex);
-
-    for (member = conference->members; member; member = member->next) {
-        switch_channel_t *channel;
-        switch_caller_profile_t *profile;
-        char *uuid;
-        char *name;
-        uint32_t count = 0;
-
-        if (switch_test_flag(member, MFLAG_NOCHANNEL)) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "continue\n");
-            continue;
-        }
-
-        uuid = switch_core_session_get_uuid(member->session);
-        channel = switch_core_session_get_channel(member->session);
-        profile = switch_channel_get_caller_profile(channel);
-        name = switch_channel_get_name(channel);
-
-
-        stream->write_function(stream, "%u%s%s%s%s%s%s%s%s%s", 
-                               member->id, delim, 
-                               name, delim, 
-                               uuid, delim, 
-                               profile->caller_id_name, delim, 
-                               profile->caller_id_number, delim);
-
-        if (switch_test_flag(member, MFLAG_CAN_HEAR)) {
-            stream->write_function(stream, "hear");
-            count++;
-        }
-
-        if (switch_test_flag(member, MFLAG_CAN_SPEAK)) {
-            stream->write_function(stream, "%s%s", count ? "|" : "", "speak");
-            count++;
-        }
-
-        stream->write_function(stream, "%s%d%s%d%s%d\n", 
-                               delim, 
-                               member->volume_in_level, delim, 
-                               member->volume_out_level, delim, 
-                               member->energy_level);
-    }
+		/* Queue the node */
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "queueing file '%s' for play\n", file);
+		switch_mutex_lock(member->flag_mutex);
+		for (nptr = member->fnode; nptr && nptr->next; nptr = nptr->next);
 
-    switch_mutex_unlock(conference->member_mutex);
-	
-}
+		if (nptr) {
+			nptr->next = fnode;
+		} else {
+			member->fnode = fnode;
+		}
+		switch_mutex_unlock(member->flag_mutex);
 
-static switch_status_t conf_api_sub_mute(conference_member_t *member, switch_stream_handle_t *stream, void *data)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+		status = SWITCH_STATUS_SUCCESS;
+	}
 
-    if (member != NULL) {
-        switch_event_t *event;
+  done:
 
-        switch_clear_flag_locked(member, MFLAG_CAN_SPEAK);
-        if (member->conference->muted_sound) {
-            conference_member_play_file(member, member->conference->muted_sound, 0);
-        } else {
-            char msg[512];
-
-            snprintf(msg, sizeof(msg), "Muted");
-            conference_member_say(member, msg, 0);
-        }
-        if (stream != NULL) {
-            stream->write_function(stream, "OK mute %u\n", member->id);
-        }
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_channel_t *channel = switch_core_session_get_channel(member->session);
-            switch_channel_event_set_data(channel, event);
-
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "mute-member");
-            switch_event_fire(&event);
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_unmute(conference_member_t *member, switch_stream_handle_t *stream, void *data)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-
-    if (member != NULL) {
-        switch_event_t *event;
-
-        switch_set_flag_locked(member, MFLAG_CAN_SPEAK);
-        if (stream != NULL) {
-            stream->write_function(stream, "OK unmute %u\n", member->id);
-        }
-        if (member->conference->unmuted_sound) {
-            conference_member_play_file(member, member->conference->unmuted_sound, 0);
-        } else {
-            char msg[512];
-
-            snprintf(msg, sizeof(msg), "Un-Muted");
-            conference_member_say(member, msg, 0);
-        }
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_channel_t *channel = switch_core_session_get_channel(member->session);
-            switch_channel_event_set_data(channel, event);
-
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "unmute-member");
-            switch_event_fire(&event);
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_deaf(conference_member_t *member, switch_stream_handle_t *stream, void *data)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-
-    if (member != NULL) {
-        switch_event_t *event;
-
-        switch_clear_flag_locked(member, MFLAG_CAN_HEAR);
-        if (stream != NULL) {
-            stream->write_function(stream, "OK deaf %u\n", member->id);
-        }
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_channel_t *channel = switch_core_session_get_channel(member->session);
-            switch_channel_event_set_data(channel, event);
-
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "deaf-member");
-            switch_event_fire(&event);
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_undeaf(conference_member_t *member, switch_stream_handle_t *stream, void *data)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-
-    if (member != NULL) {
-        switch_event_t *event;
-
-        switch_set_flag_locked(member, MFLAG_CAN_HEAR);
-        if (stream != NULL) {
-            stream->write_function(stream, "OK undeaf %u\n", member->id);
-        }
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_channel_t *channel = switch_core_session_get_channel(member->session);
-            switch_channel_event_set_data(channel, event);
-
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "undeaf-member");
-            switch_event_fire(&event);
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_kick(conference_member_t *member, switch_stream_handle_t *stream, void *data)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-
-    if (member != NULL) {
-        switch_event_t *event;
-
-        switch_mutex_lock(member->flag_mutex);
-        switch_clear_flag(member, MFLAG_RUNNING);
-        switch_set_flag(member, MFLAG_KICKED);
-        switch_core_session_kill_channel(member->session, SWITCH_SIG_BREAK);
-        switch_mutex_unlock(member->flag_mutex);
-
-        if (stream != NULL) {
-            stream->write_function(stream, "OK kicked %u\n", member->id);
-        }
-
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_channel_t *channel = switch_core_session_get_channel(member->session);
-            switch_channel_event_set_data(channel, event);
-
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "kick-member");
-            switch_event_fire(&event);
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-
-    return ret_status;
-}
-
-
-static switch_status_t conf_api_sub_dtmf(conference_member_t *member, switch_stream_handle_t *stream, void *data)
-{
-    switch_event_t *event;
-    char *dtmf = (char *) data;
-
-    if (member == NULL) {
-        stream->write_function(stream, "Invalid member!\n");
-        return SWITCH_STATUS_GENERR;
-    }
-
-    if (switch_strlen_zero(dtmf)) {
-        stream->write_function(stream, "Invalid input!\n");
-        return SWITCH_STATUS_GENERR;
-    }
-
-    
-    switch_mutex_lock(member->flag_mutex);
-    switch_core_session_kill_channel(member->session, SWITCH_SIG_BREAK);
-    switch_core_session_send_dtmf(member->session, dtmf);
-    switch_mutex_unlock(member->flag_mutex);
-
-
-    if (stream != NULL) {
-        stream->write_function(stream, "OK sent %s to %u\n", (char *) data, member->id);
-    }
-
-    if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-        switch_channel_t *channel = switch_core_session_get_channel(member->session);
-        switch_channel_event_set_data(channel, event);
-
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "dtmf-member");
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Digits", "%s", dtmf);
-        switch_event_fire(&event);
-    }
-
-    return SWITCH_STATUS_SUCCESS;
-}
-
-static switch_status_t conf_api_sub_energy(conference_member_t *member, switch_stream_handle_t *stream, void *data)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-
-    if (member != NULL) {
-        switch_event_t *event;
-
-        if (data) {
-            switch_mutex_lock(member->flag_mutex);
-            member->energy_level = atoi((char *)data);
-            switch_mutex_unlock(member->flag_mutex);
-        }
-
-        if (stream != NULL) {
-            stream->write_function(stream, "Energy %u = %d\n", member->id, member->energy_level);
-        }
-
-        if (data) {
-            if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-                switch_channel_t *channel = switch_core_session_get_channel(member->session);
-                switch_channel_event_set_data(channel, event);
-
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "energy-level-member");
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Energy-Level", "%d", member->energy_level);
-
-                switch_event_fire(&event);
-            }
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_volume_in(conference_member_t *member, switch_stream_handle_t *stream, void *data)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-
-    if (member != NULL) {
-        switch_event_t *event;
-
-        if (data) {
-            switch_mutex_lock(member->flag_mutex);
-            member->volume_in_level = atoi((char *)data);
-            switch_normalize_volume(member->volume_in_level);
-            switch_mutex_unlock(member->flag_mutex);
-        }
-
-        if (stream != NULL) {
-            stream->write_function(stream, "Volume IN %u = %d\n", member->id, member->volume_in_level);
-        }
-        if (data) {
-            if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-                switch_channel_t *channel = switch_core_session_get_channel(member->session);
-                switch_channel_event_set_data(channel, event);
-
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "volume-in-member");
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Volume-Level", "%u", member->volume_in_level);
-
-                switch_event_fire(&event);
-            }
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_volume_out(conference_member_t *member, switch_stream_handle_t *stream, void *data)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-
-    if (member != NULL) {
-        switch_event_t *event;
-
-        if (data) {
-            switch_mutex_lock(member->flag_mutex);
-            member->volume_out_level = atoi((char *)data);
-            switch_normalize_volume(member->volume_out_level);
-            switch_mutex_unlock(member->flag_mutex);
-        }
-
-        if (stream != NULL) {
-            stream->write_function(stream, "Volume OUT %u = %d\n", member->id, member->volume_out_level);
-        }
-
-        if (data) {
-            if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-                switch_channel_t *channel = switch_core_session_get_channel(member->session);
-                switch_channel_event_set_data(channel, event);
-
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "volume-out-member");
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Volume-Level", "%u", member->volume_out_level);
-
-                switch_event_fire(&event);
-            }
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_list(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
-{
-    int ret_status = SWITCH_STATUS_GENERR;
-
-    switch_hash_index_t *hi;
-    void *val;
-    char *d = ";";
-    int pretty = 0;
-    int argofs = (argc >= 2 && strcasecmp(argv[1], "list") == 0);	// detect being called from chat vs. api
-
-    if (argv[1+argofs]) {
-        if (argv[2+argofs] && !strcasecmp(argv[1+argofs], "delim")) {
-            d = argv[2+argofs];
-
-            if (*d == '"') {
-                if (++d) {
-                    char *p;
-                    if ((p = strchr(d, '"'))) {
-                        *p = '\0';
-                    }
-                } else {
-                    d = ";";
-                }
-            }
-        } else if (strcasecmp(argv[1+argofs], "pretty") == 0) {
-            pretty = 1;
-        }
-    }
-
-    if (conference == NULL) {
-        for (hi = switch_hash_first(globals.conference_pool, globals.conference_hash); hi; hi = switch_hash_next(hi)) {
-            switch_hash_this(hi, NULL, NULL, &val);
-            conference = (conference_obj_t *) val;
-
-            stream->write_function(stream, "Conference %s (%u member%s%s)\n", 
-                                   conference->name, 
-                                   conference->count, 
-                                   conference->count == 1 ? "" : "s",
-                                   switch_test_flag(conference, CFLAG_LOCKED) ? " locked" : ""
-                                   );
-            if (pretty) {
-                conference_list_pretty(conference, stream);
-            } else {
-                conference_list(conference, stream, d);
-            }
-        }
-    } else {
-        if (pretty) {
-            conference_list_pretty(conference, stream);
-        } else {
-            conference_list(conference, stream, d);
-        }
-    }
-
-    ret_status = SWITCH_STATUS_SUCCESS;
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_play(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
-{
-    int ret_status = SWITCH_STATUS_GENERR;
-    switch_event_t *event;
-
-    assert(conference != NULL);
-    assert(stream != NULL);
-
-    
-    if (argc == 3) {
-        if (conference_play_file(conference, argv[2], 0, NULL) == SWITCH_STATUS_SUCCESS) {
-            stream->write_function(stream, "(play) Playing file %s\n", argv[2]);
-            if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "play-file");
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "File", "%s", argv[2]);
-                switch_event_fire(&event);
-            }
-        } else {
-            stream->write_function(stream, "(play) File: %s not found.\n", argv[2] ? argv[2] : "(unspecified)");
-        }
-        ret_status = SWITCH_STATUS_SUCCESS;
-    } else if (argc == 4) {
-        uint32_t id = atoi(argv[3]);
-        conference_member_t *member;
-
-        if ((member = conference_member_get(conference, id))) {
-            if (conference_member_play_file(member, argv[2], 0) == SWITCH_STATUS_SUCCESS) {
-                stream->write_function(stream, "(play) Playing file %s to member %u\n", argv[2], id);
-                if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-                    switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
-                    switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", id);
-                    switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "play-file-member");
-                    switch_event_add_header(event, SWITCH_STACK_BOTTOM, "File", "%s", argv[2]);
-                    switch_event_fire(&event);
-                }
-            } else {
-                stream->write_function(stream, "(play) File: %s not found.\n", argv[2] ? argv[2] : "(unspecified)");
-            }
-            ret_status = SWITCH_STATUS_SUCCESS;
-        } else {
-            stream->write_function(stream, "Member: %u not found.\n", id);
-        }
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_say(conference_obj_t *conference, switch_stream_handle_t *stream, const char *text)
-{
-    int ret_status = SWITCH_STATUS_GENERR;
-
-    if (switch_strlen_zero(text)) {
-        stream->write_function(stream, "(say) Error! No text.");
-        return ret_status;
-    }
-
-    if (conference_say(conference, text, 0) == SWITCH_STATUS_SUCCESS) {
-        switch_event_t *event;
-
-        stream->write_function(stream, "(say) OK\n");
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "speak-text");
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Text", "%s", text);
-            switch_event_fire(&event);
-        }
-        ret_status = SWITCH_STATUS_SUCCESS;
-    } else {
-        stream->write_function(stream, "(say) Error!");
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_saymember(conference_obj_t *conference, switch_stream_handle_t *stream, const char *text)
-{
-    int ret_status = SWITCH_STATUS_GENERR;
-    char *expanded = NULL;
-    char *start_text = NULL;
-    char *workspace = NULL;
-    uint32_t id = 0;
-    conference_member_t *member;
-
-    if (switch_strlen_zero(text)) {
-        stream->write_function(stream, "(saymember) No Text!\n");
-        goto done;
-    }
-
-    if (!(workspace = strdup(text))) {
-        stream->write_function(stream, "(saymember) Memory Error!\n");
-        goto done;
-    }
-
-    if ((start_text = strchr(workspace, ' '))) {
-        *start_text++ = '\0';
-        text = start_text;
-    }
-
-    id = atoi(workspace);
-
-    if (!id || switch_strlen_zero(text)) {
-        stream->write_function(stream, "(saymember) No Text!\n");
-        goto done;
-    }
-
-    if (!(member = conference_member_get(conference, id))) {
-        stream->write_function(stream, "(saymember) Unknown Member %u!", id);
-        goto done;
-    }
-
-    if ((expanded = switch_channel_expand_variables(switch_core_session_get_channel(member->session), (char *)text)) != text) {
-        text = expanded;
-    } else {
-        expanded = NULL;
-    }
-
-    if (text && conference_member_say(member, (char *)text, 0) == SWITCH_STATUS_SUCCESS) {
-        switch_event_t *event;
-
-        stream->write_function(stream, "(saymember) OK\n");
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "speak-text-member");
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", id);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Text", "%s", text);
-            switch_event_fire(&event);
-        }
-        ret_status = SWITCH_STATUS_SUCCESS;
-    } else {
-        stream->write_function(stream, "(saymember) Error!");
-    }
-
- done:    
-    switch_safe_free(workspace);
-    switch_safe_free(expanded);
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_stop(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
-{
-    int ret_status = SWITCH_STATUS_GENERR;
-    uint8_t current = 0, all = 0;
-
-    assert(conference != NULL);
-    assert(stream != NULL);
-
-    if (argc > 2) {
-        current = strcasecmp(argv[2], "current") ? 0 : 1;
-        all = strcasecmp(argv[2], "all") ? 0 : 1;
-    } else {
-        all = 1;
-    }
-
-    if (current || all) {
-        if (argc == 4) {
-            uint32_t id = atoi(argv[3]);
-            conference_member_t *member;
-
-            if ((member = conference_member_get(conference, id))) {
-                uint32_t stopped = conference_member_stop_file(member, current ? FILE_STOP_CURRENT : FILE_STOP_ALL);
-                stream->write_function(stream, "Stopped %u files.\n", stopped);
-            } else {
-                stream->write_function(stream, "Member: %u not found.\n", id);
-            }
-            ret_status = SWITCH_STATUS_SUCCESS;
-        } else {
-            uint32_t stopped = conference_stop_file(conference, current ? FILE_STOP_CURRENT : FILE_STOP_ALL);
-            stream->write_function(stream, "Stopped %u files.\n", stopped);
-            ret_status = SWITCH_STATUS_SUCCESS;
-        }
-    }
-
-    return ret_status;
-}
-
-static switch_status_t conf_api_sub_relate(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
-{
-    int ret_status = SWITCH_STATUS_GENERR;
-
-    assert(conference != NULL);
-    assert(stream != NULL);
-
-    if (argc > 4) {
-        uint8_t nospeak = 0, nohear = 0, clear = 0;
-        nospeak = strstr(argv[4], "nospeak") ? 1 : 0;
-        nohear = strstr(argv[4], "nohear") ? 1 : 0;
-
-        if (!strcasecmp(argv[4], "clear")) {
-            clear = 1;
-        }
-
-        if (!(clear || nospeak || nohear)) { 
-            ret_status = SWITCH_STATUS_GENERR;
-            goto done;
-        }
-        ret_status = SWITCH_STATUS_SUCCESS;
-
-        if (clear) {
-            conference_member_t *member = NULL;
-            uint32_t id = atoi(argv[2]);
-            uint32_t oid = atoi(argv[3]);
-
-            if ((member = conference_member_get(conference, id))) {
-                member_del_relationship(member, oid);
-                stream->write_function(stream, "relationship %u->%u cleared.", id, oid);
-            } else {
-                stream->write_function(stream, "relationship %u->%u not found", id, oid);
-            }
-        } else if (nospeak || nohear) {
-            conference_member_t *member = NULL, *other_member = NULL;
-            uint32_t id = atoi(argv[2]);
-            uint32_t oid = atoi(argv[3]);
-
-            if ((member = conference_member_get(conference, id)) && (other_member = conference_member_get(conference, oid))) {
-                conference_relationship_t *rel = NULL;
-                if ((rel = member_get_relationship(member, other_member))) {
-                    rel->flags = 0;
-                } else {
-                    rel = member_add_relationship(member, oid);
-                }
-
-                if (rel) {
-                    switch_set_flag(rel, RFLAG_CAN_SPEAK | RFLAG_CAN_HEAR);
-                    if (nospeak) {
-                        switch_clear_flag(rel, RFLAG_CAN_SPEAK);
-                    }
-                    if (nohear) {
-                        switch_clear_flag(rel, RFLAG_CAN_HEAR);
-                    }
-                    stream->write_function(stream, "ok %u->%u set\n", id, oid);
-                } else {
-                    stream->write_function(stream, "error!\n");
-                }
-            } else {
-                stream->write_function(stream, "relationship %u->%u not found", id, oid);
-            }
-        }
-    }
+	switch_safe_free(expanded);
+	switch_safe_free(dfile);
 
- done:
-    return ret_status;
+	return status;
 }
 
-static switch_status_t conf_api_sub_lock(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
+/* Say some thing with TTS in the conference room */
+static switch_status_t conference_member_say(conference_member_t * member, char *text, uint32_t leadin)
 {
-    switch_event_t *event;
-
-    assert(conference != NULL);
-    assert(stream != NULL);
-
-    if (conference->is_locked_sound) {
-        conference_play_file(conference, conference->is_locked_sound, CONF_DEFAULT_LEADIN, NULL);
-    }
+	switch_status_t status = SWITCH_STATUS_FALSE;
 
-    switch_set_flag_locked(conference, CFLAG_LOCKED);
-    stream->write_function(stream, "OK %s locked\n", argv[0]);
-    if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "lock");
-        switch_event_fire(&event);
-    }
+	if (member != NULL && !switch_strlen_zero(text)) {
+		conference_obj_t *conference = (member != NULL ? member->conference : NULL);
+		conference_file_node_t *fnode, *nptr;
+		switch_memory_pool_t *pool;
+		switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
 
-    return 0;
-}
+		assert(conference != NULL);
 
-static switch_status_t conf_api_sub_unlock(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
-{
-    switch_event_t *event;
+		if (!(conference->tts_engine && conference->tts_voice)) {
+			return SWITCH_STATUS_SUCCESS;
+		}
 
-    assert(conference != NULL);
-    assert(stream != NULL);
+		/* Setup a memory pool to use. */
+		if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
+			return SWITCH_STATUS_MEMERR;
+		}
 
-    if (conference->is_unlocked_sound) {
-        conference_play_file(conference, conference->is_unlocked_sound, CONF_DEFAULT_LEADIN, NULL);
-    }
+		/* Create a node object */
+		if (!(fnode = switch_core_alloc(pool, sizeof(*fnode)))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
+			switch_core_destroy_memory_pool(&pool);
+			return SWITCH_STATUS_MEMERR;
+		}
 
-    switch_clear_flag_locked(conference, CFLAG_LOCKED);
-    stream->write_function(stream, "OK %s unlocked\n", argv[0]);
-    if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "unlock");
-        switch_event_fire(&event);
-    }
-	
+		fnode->type = NODE_TYPE_SPEECH;
+		fnode->leadin = leadin;
+		fnode->pool = pool;
+
+		memset(&fnode->sh, 0, sizeof(fnode->sh));
+		if (switch_core_speech_open(&fnode->sh, conference->tts_engine, conference->tts_voice, conference->rate, &flags, fnode->pool) !=
+			SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid TTS module [%s]!\n", conference->tts_engine);
+			return SWITCH_STATUS_FALSE;
+		}
 
-    return 0;
-}
+		/* Queue the node */
+		switch_mutex_lock(member->flag_mutex);
+		for (nptr = member->fnode; nptr && nptr->next; nptr = nptr->next);
 
-static switch_status_t conf_api_sub_dial(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+		if (nptr) {
+			nptr->next = fnode;
+		} else {
+			member->fnode = fnode;
+		}
 
-    assert(stream != NULL);
+		/* Begin Generation */
+		switch_sleep(200000);
+		switch_core_speech_feed_tts(&fnode->sh, text, &flags);
+		switch_mutex_unlock(member->flag_mutex);
 
-	if(!conference) {
-		stream->write_function(stream, "Conference %s not found\n", argv[0]);
-	} else if (argc > 2) {
-        switch_call_cause_t cause;
-        conference_outcall(conference, NULL, argv[2], 60, NULL, argv[4], argv[3], &cause);
-        stream->write_function(stream, "Call Requested: result: [%s]\n", switch_channel_cause2str(cause));
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
+		status = SWITCH_STATUS_SUCCESS;
+	}
 
-    return ret_status;
+	return status;
 }
 
-
-static switch_status_t conf_api_sub_bgdial(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
+/* Say some thing with TTS in the conference room */
+static switch_status_t conference_say(conference_obj_t * conference, const char *text, uint32_t leadin)
 {
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-
-    assert(stream != NULL);
-
-	if(!conference) {
-		stream->write_function(stream, "Conference %s not found\n", argv[0]);
-	} else if (argc > 2) {
-        conference_outcall_bg(conference, NULL, argv[2], 60, NULL, argv[4], argv[3]);
-        stream->write_function(stream, "OK\n");
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-
-    return ret_status;
-}
+	switch_status_t status = SWITCH_STATUS_FALSE;
+	conference_file_node_t *fnode, *nptr;
+	switch_memory_pool_t *pool;
+	switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
+	uint32_t count;
 
-static switch_status_t conf_api_sub_transfer(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
-{
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-    char *params = NULL;
-    assert(conference != NULL);
-    assert(stream != NULL);
+	assert(conference != NULL);
 
-    if (argc > 3 && !switch_strlen_zero(argv[2])) {
-        int x;
+	if (switch_strlen_zero(text)) {
+		return SWITCH_STATUS_GENERR;
+	}
 
-        for (x = 3; x<argc; x++) {
-            conference_member_t *member = NULL;
-            uint32_t id = atoi(argv[x]);
-            conference_obj_t *new_conference = NULL;
-            switch_channel_t *channel;
-            switch_event_t *event;
-            char *profile_name;
-            switch_xml_t cxml = NULL, cfg = NULL, profiles = NULL;
+	switch_mutex_lock(conference->mutex);
+	switch_mutex_lock(conference->member_mutex);
+	count = conference->count;
+	if (!(conference->tts_engine && conference->tts_voice)) {
+		count = 0;
+	}
+	switch_mutex_unlock(conference->member_mutex);
+	switch_mutex_unlock(conference->mutex);
 
-            if (!id || !(member = conference_member_get(conference, id))) {								
-                stream->write_function(stream, "No Member %u in conference %s.\n", id, conference->name);
-                continue;
-            }
+	if (!count) {
+		return SWITCH_STATUS_FALSE;
+	}
 
-            channel = switch_core_session_get_channel(member->session);
+	/* Setup a memory pool to use. */
+	if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
+		return SWITCH_STATUS_MEMERR;
+	}
 
-            /* build a new conference if it doesn't exist */
-            if (!(new_conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, argv[2]))) {
-                switch_memory_pool_t *pool = NULL;
-                char *conf_name;
-                conf_xml_cfg_t xml_cfg = {0};
+	/* Create a node object */
+	if (!(fnode = switch_core_alloc(pool, sizeof(*fnode)))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
+		switch_core_destroy_memory_pool(&pool);
+		return SWITCH_STATUS_MEMERR;
+	}
 
-                /* Setup a memory pool to use. */
-                if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
-                    goto done;
-                }
+	fnode->type = NODE_TYPE_SPEECH;
+	fnode->leadin = leadin;
 
-                conf_name = switch_core_strdup(pool, argv[2]);
+	memset(&fnode->sh, 0, sizeof(fnode->sh));
+	if (switch_core_speech_open(&fnode->sh, conference->tts_engine, conference->tts_voice, conference->rate, &flags, conference->pool) !=
+		SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid TTS module [%s]!\n", conference->tts_engine);
+		return SWITCH_STATUS_FALSE;
+	}
 
-                if ((profile_name = strchr(conf_name, '@'))) {
-                    *profile_name++ = '\0';
-                } else {
-                    profile_name = "default";
-                }
-                params = switch_mprintf("conf_name=%s&profile_name=%s", conf_name, profile_name);
-                /* Open the config from the xml registry  */
-                if (!(cxml = switch_xml_open_cfg(global_cf_name, &cfg, params))) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", global_cf_name);
-                    goto done;
-                }
+	fnode->pool = pool;
 
-                if ((profiles = switch_xml_child(cfg, "profiles"))) {
-                    xml_cfg.profile = switch_xml_find_child(profiles, "profile", "name", profile_name);
-                }
+	/* Queue the node */
+	switch_mutex_lock(conference->mutex);
+	for (nptr = conference->fnode; nptr && nptr->next; nptr = nptr->next);
 
-                if (!xml_cfg.profile) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find profile: %s\n", profile_name);
-                    switch_xml_free(cxml);
-                    cxml = NULL;
-                    goto done;
-                }
+	if (nptr) {
+		nptr->next = fnode;
+	} else {
+		conference->fnode = fnode;
+	}
 
-                xml_cfg.controls = switch_xml_child(cfg, "caller-controls");
-#ifdef OPTION_IVR_MENU_SUPPORT
-                xml_cfg.menus = switch_xml_child(cfg, "menus");
-#endif
+	/* Begin Generation */
+	switch_sleep(200000);
+	switch_core_speech_feed_tts(&fnode->sh, (char *) text, &flags);
+	switch_mutex_unlock(conference->mutex);
 
-                /* Release the config registry handle */
-                if (cxml) {
-                    switch_xml_free(cxml);
-                    cxml = NULL;
-                }
-
-                /* Create the conference object. */
-                new_conference = conference_new(conf_name, xml_cfg, pool);
-
-                if (!new_conference) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-                    if (pool != NULL) {
-                        switch_core_destroy_memory_pool(&pool);
-                    }
-                    goto done;
-                }
-
-                /* Set the minimum number of members (once you go above it you cannot go below it) */
-                new_conference->min = 1;
-
-                /* Indicate the conference is dynamic */
-                switch_set_flag_locked(new_conference, CFLAG_DYNAMIC);
-
-                switch_mutex_lock(new_conference->mutex);
-
-                /* Start the conference thread for this conference */
-                launch_conference_thread(new_conference);
-            } else {
-                switch_mutex_lock(new_conference->mutex);
-            }
-
-            /* move the member from the old conference to the new one */
-            conference_del_member(conference, member);
-            conference_add_member(new_conference, member);
-            switch_mutex_unlock(new_conference->mutex);
-
-            stream->write_function(stream, "OK Members sent to conference %s.\n", argv[2]);
-
-            /* tell them what happened */
-            if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-                switch_channel_event_set_data(channel, event);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Old-Conference-Name", "%s", conference->name);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "New-Conference-Name", "%s", argv[3]);
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "transfer");
-                switch_event_fire(&event);
-            }
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
+	status = SWITCH_STATUS_SUCCESS;
 
- done:
-    switch_safe_free(params);
-    return ret_status;
+	return status;
 }
 
-static switch_status_t conf_api_sub_record(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
+/* execute a callback for every member of the conference */
+static void conference_member_itterator(conference_obj_t * conference, switch_stream_handle_t *stream, conf_api_member_cmd_t pfncallback, void *data)
 {
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-    assert(conference != NULL);
-    assert(stream != NULL);
+	conference_member_t *member = NULL;
 
-    if (argc > 2) {
-        launch_conference_record_thread(conference, argv[2]);
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
+	assert(conference != NULL);
+	assert(stream != NULL);
+	assert(pfncallback != NULL);
+
+	switch_mutex_lock(conference->member_mutex);
+	for (member = conference->members; member; member = member->next) {
+		pfncallback(member, stream, data);
+	}
+	switch_mutex_unlock(conference->member_mutex);
 
-    return ret_status;
 }
 
-static switch_status_t conf_api_sub_norecord(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char**argv)
+static void conference_list_pretty(conference_obj_t * conference, switch_stream_handle_t *stream)
 {
-    switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
-
-    assert(conference != NULL);
-    assert(stream != NULL);
-
-    if (argc > 2) {
-        int all = (strcasecmp(argv[2], "all") == 0 );
-
-        if (!conference_record_stop(conference, all ? NULL : argv[2]) && !all) {
-            stream->write_function(stream, "non-existant recording '%s'\n", argv[2]);
-        }
-    } else {
-        ret_status = SWITCH_STATUS_GENERR;
-    }
-	
-    return ret_status;
-}
+	conference_member_t *member = NULL;
 
-typedef enum {
-	CONF_API_COMMAND_LIST = 0,
-	CONF_API_COMMAND_ENERGY,
-	CONF_API_COMMAND_VOLUME_IN,
-	CONF_API_COMMAND_VOLUME_OUT,
-	CONF_API_COMMAND_PLAY,
-	CONF_API_COMMAND_SAY,
-	CONF_API_COMMAND_SAYMEMBER,
-	CONF_API_COMMAND_STOP,
-	CONF_API_COMMAND_DTMF,
-	CONF_API_COMMAND_KICK,
-	CONF_API_COMMAND_MUTE,
-	CONF_API_COMMAND_UNMUTE,
-	CONF_API_COMMAND_DEAF,
-	CONF_API_COMMAND_UNDEAF,
-	CONF_API_COMMAND_RELATE,
-	CONF_API_COMMAND_LOCK,
-	CONF_API_COMMAND_UNLOCK,
-	CONF_API_COMMAND_DIAL,
-	CONF_API_COMMAND_BGDIAL,
-	CONF_API_COMMAND_TRANSFER,
-	CONF_API_COMMAND_RECORD,
-	CONF_API_COMMAND_NORECORD
-} api_command_type_t;
+	assert(conference != NULL);
+	assert(stream != NULL);
 
-/* API Interface Function sub-commands */
-/* Entries in this list should be kept in sync with the enum above */
-static api_command_t conf_api_sub_commands[] = {
-	{"list", (void_fn_t)&conf_api_sub_list, CONF_API_SUB_ARGS_SPLIT, "<confname> list [delim <string>]"}, 
-	{"energy", (void_fn_t)&conf_api_sub_energy, CONF_API_SUB_MEMBER_TARGET, "<confname> energy <member_id|all|last> [<newval>]"}, 
-	{"volume_in", (void_fn_t)&conf_api_sub_volume_in, CONF_API_SUB_MEMBER_TARGET, "<confname> volume_in <member_id|all|last> [<newval>]"}, 
-	{"volume_out", (void_fn_t)&conf_api_sub_volume_out, CONF_API_SUB_MEMBER_TARGET, "<confname> volume_out <member_id|all|last> [<newval>]"}, 
-	{"play", (void_fn_t)&conf_api_sub_play, CONF_API_SUB_ARGS_SPLIT, "<confname> play <file_path> [<member_id>]"}, 
-	{"say", (void_fn_t)&conf_api_sub_say, CONF_API_SUB_ARGS_AS_ONE, "<confname> say <text>"}, 
-	{"saymember", (void_fn_t)&conf_api_sub_saymember, CONF_API_SUB_ARGS_AS_ONE, "<confname> saymember <member_id> <text>"}, 
-	{"stop", (void_fn_t)&conf_api_sub_stop, CONF_API_SUB_ARGS_SPLIT, "<confname> stop <[current|all|last]> [<member_id>]"}, 
-	{"dtmf", (void_fn_t)&conf_api_sub_dtmf, CONF_API_SUB_MEMBER_TARGET, "<confname> dtmf <[member_id|all|last]> <digits>"}, 
-	{"kick", (void_fn_t)&conf_api_sub_kick, CONF_API_SUB_MEMBER_TARGET, "<confname> kick <[member_id|all|last]>"}, 
-	{"mute", (void_fn_t)&conf_api_sub_mute, CONF_API_SUB_MEMBER_TARGET, "<confname> mute <[member_id|all]|last>"}, 
-	{"unmute", (void_fn_t)&conf_api_sub_unmute, CONF_API_SUB_MEMBER_TARGET, "<confname> unmute <[member_id|all]|last>"}, 
-	{"deaf", (void_fn_t)&conf_api_sub_deaf, CONF_API_SUB_MEMBER_TARGET, "<confname> deaf <[member_id|all]|last>"}, 
-	{"undeaf", (void_fn_t)&conf_api_sub_undeaf, CONF_API_SUB_MEMBER_TARGET, "<confname> undeaf <[member_id|all]|last>"}, 
-	{"relate", (void_fn_t)&conf_api_sub_relate, CONF_API_SUB_ARGS_SPLIT, "<confname> relate <member_id> <other_member_id> [nospeak|nohear|clear]"}, 
-	{"lock", (void_fn_t)&conf_api_sub_lock, CONF_API_SUB_ARGS_SPLIT, "<confname> lock"}, 
-	{"unlock", (void_fn_t)&conf_api_sub_unlock, CONF_API_SUB_ARGS_SPLIT, "<confname> unlock"}, 
-	{"dial", (void_fn_t)&conf_api_sub_dial, CONF_API_SUB_ARGS_SPLIT, "<confname> dial <endpoint_module_name>/<destination> <callerid number> <callerid name>"}, 
-	{"bgdial", (void_fn_t)&conf_api_sub_bgdial, CONF_API_SUB_ARGS_SPLIT, "<confname> bgdial <endpoint_module_name>/<destination> <callerid number> <callerid name>"}, 
-	{"transfer", (void_fn_t)&conf_api_sub_transfer, CONF_API_SUB_ARGS_SPLIT, "<confname> transfer <conference_name> <member id> [...<member id>]"}, 
-	{"record", (void_fn_t)&conf_api_sub_record, CONF_API_SUB_ARGS_SPLIT, "<confname> record <filename>"}, 
-	{"norecord", (void_fn_t)&conf_api_sub_norecord, CONF_API_SUB_ARGS_SPLIT, "<confname> norecord <[filename|all]>"}, 
-};
+	switch_mutex_lock(conference->member_mutex);
+	//      stream->write_function(stream, "<pre>Current Callers:\n");
 
-#define CONFFUNCAPISIZE (sizeof(conf_api_sub_commands)/sizeof(conf_api_sub_commands[0]))
+	for (member = conference->members; member; member = member->next) {
+		switch_channel_t *channel;
+		switch_caller_profile_t *profile;
 
-switch_status_t conf_api_dispatch(conference_obj_t *conference, switch_stream_handle_t *stream, int argc, char **argv, const char *cmdline, int argn)
-{	
-    switch_status_t status = SWITCH_STATUS_FALSE;
-    uint32_t i, found = 0;
-    assert(conference != NULL);
-    assert(stream != NULL);
-
-    /* loop through the command table to find a match */
-    for (i = 0; i<CONFFUNCAPISIZE && !found; i++) {
-        if (strcasecmp(argv[argn], conf_api_sub_commands[i].pname) == 0) {
-            found = 1;
-            switch(conf_api_sub_commands[i].fntype) {
-
-                /* commands that we've broken the command line into arguments for */
-            case CONF_API_SUB_ARGS_SPLIT:
-                {	conf_api_args_cmd_t pfn = (conf_api_args_cmd_t)conf_api_sub_commands[i].pfnapicmd;
-
-                    if (pfn(conference, stream, argc, argv) != SWITCH_STATUS_SUCCESS) {
-                        /* command returned error, so show syntax usage */
-                        stream->write_function(stream, conf_api_sub_commands[i].psyntax);
-                    }
-                }
-                break;
-
-                /* member specific command that can be itteratted */
-            case CONF_API_SUB_MEMBER_TARGET:
-                {
-                    uint32_t id = 0;
-                    uint8_t all = 0;
-                    uint8_t last = 0;
-
-                    if (argv[argn+1]) {
-                        if (!(id = atoi(argv[argn+1]))) {
-                            all = strcasecmp(argv[argn+1], "all") ? 0 : 1;
-                            last = strcasecmp(argv[argn+1], "last") ? 0 : 1;
-                        }                        
-                    }
-
-                    if (all) {
-                        conference_member_itterator(conference, stream, (conf_api_member_cmd_t)conf_api_sub_commands[i].pfnapicmd, argv[argn+2]);
-                    } else if (last) {
-                        conference_member_t *member = NULL;
-                        conference_member_t *last_member = NULL;
-
-                        switch_mutex_lock(conference->member_mutex);
-
-                        /* find last (oldest) member */
-                        member = conference->members;
-                        while (member != NULL) {
-                            if (last_member == NULL || member->id > last_member->id) {
-                                last_member = member;
-                            }
-                            member = member->next;
-                        }
-
-                        /* exec functio on last (oldest) member */
-                        if (last_member != NULL) {
-                            conf_api_member_cmd_t pfn = (conf_api_member_cmd_t)conf_api_sub_commands[i].pfnapicmd;
-                            pfn(last_member, stream, argv[argn+2]);
-                        }
-
-                        switch_mutex_unlock(conference->member_mutex);
-                    } else if (id) {
-                        conf_api_member_cmd_t pfn = (conf_api_member_cmd_t)conf_api_sub_commands[i].pfnapicmd;
-                        conference_member_t *member = conference_member_get(conference, id);
-                        
-                        if (member != NULL) {
-                            pfn(conference_member_get(conference, id), stream, argv[argn+2]);
-                        } else {
-                            stream->write_function(stream, "Non-Existant ID %u\n", id);
-                        }
-                    } else {
-                        stream->write_function(stream, conf_api_sub_commands[i].psyntax);
-                    }
-                }
-                break;
-
-                /* commands that deals with all text after command */
-            case CONF_API_SUB_ARGS_AS_ONE:
-                {	
-                    conf_api_text_cmd_t pfn = (conf_api_text_cmd_t) conf_api_sub_commands[i].pfnapicmd;
-                    char *start_text;
-                    const char *modified_cmdline = cmdline;
-                    const char *cmd = conf_api_sub_commands[i].pname;
-
-                    if ((start_text = strstr(modified_cmdline, cmd))) {
-                        modified_cmdline = start_text + strlen(cmd);
-                        while(modified_cmdline && *modified_cmdline && (*modified_cmdline  == ' ' || *modified_cmdline == '\t')) {
-                            modified_cmdline++;
-                        }
-                    }
-                            
-                    /* call the command handler */
-                    if (pfn(conference, stream, modified_cmdline) != SWITCH_STATUS_SUCCESS) {
-                        /* command returned error, so show syntax usage */
-                        stream->write_function(stream, conf_api_sub_commands[i].psyntax);
-                    }
-                }
-                break;
-            }
-        }
-    }
-
-    if (!found) {
-        stream->write_function(stream, "Confernece command '%s' not found.\n", argv[argn]);
-    } else {
-        status = SWITCH_STATUS_SUCCESS;
-    }
+		if (switch_test_flag(member, MFLAG_NOCHANNEL)) {
+			continue;
+		}
+		channel = switch_core_session_get_channel(member->session);
+		profile = switch_channel_get_caller_profile(channel);
 
-    return status;
-}
 
-/* API Interface Function */
-static switch_status_t conf_api_main(char *buf, switch_core_session_t *session, switch_stream_handle_t *stream)
-{
-    char *lbuf = NULL;
-    switch_status_t status = SWITCH_STATUS_SUCCESS;
-    char *http = NULL;
-    int argc;
-    char *argv[25] = {0};
-
-    if (!buf) {
-        buf = "help";
-    }
-
-    if (session) {
-        return SWITCH_STATUS_FALSE;
-    }
-
-    if (stream->event) {
-        http = switch_event_get_header(stream->event, "http-host");
-    }
-
-    if (http) {
-        /* Output must be to a web browser */
-        stream->write_function(stream, "<pre>\n");
-    }
-
-    if (!(lbuf = strdup(buf))) {
-        return status;
-    }
-
-    argc = switch_separate_string(lbuf, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
-
-    /* try to find a command to execute */
-    if (argc) {
-        conference_obj_t *conference = NULL;
-
-        if ((conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, argv[0]))) {
-            if (switch_thread_rwlock_tryrdlock(conference->rwlock) != SWITCH_STATUS_SUCCESS) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Read Lock Fail\n");
-                goto done;
-            }
-            if (argc >= 2) {
-                conf_api_dispatch(conference, stream, argc, argv, (const char *)buf, 1);
-            } else {
-                stream->write_function(stream, "Conference command, not specified.\nTry 'help'\n");
-            }
-            switch_thread_rwlock_unlock(conference->rwlock);
-
-        } else {
-            /* special case the list command, because it doesn't require a conference argument */
-            if (strcasecmp(argv[0], "list") == 0) {
-                conf_api_sub_list(NULL, stream, argc, argv);
-            } else if (strcasecmp(argv[0], "help") == 0 || strcasecmp(argv[0], "commands") == 0) {
-                stream->write_function(stream, "%s\n", conf_api_interface.syntax);
-			} else if (strcasecmp(argv[0], "dial") == 0) {
-				if (conf_api_sub_dial(NULL, stream, argc, argv) != SWITCH_STATUS_SUCCESS) {
-					/* command returned error, so show syntax usage */
-					stream->write_function(stream, conf_api_sub_commands[CONF_API_COMMAND_DIAL].psyntax);
-				}
-			} else if (strcasecmp(argv[0], "bgdial") == 0) {
-				if (conf_api_sub_bgdial(NULL, stream, argc, argv) != SWITCH_STATUS_SUCCESS) {
-					/* command returned error, so show syntax usage */
-					stream->write_function(stream, conf_api_sub_commands[CONF_API_COMMAND_BGDIAL].psyntax);
-				}
-            } else {
-                stream->write_function(stream, "Conference %s not found\n", argv[0]);
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Conference %s not found\n", argv[0]);
-            }
-        }
-
-    } else {
-        stream->write_function(stream, "No parameters specified.\nTry 'help conference'\n");
-    }
+		stream->write_function(stream, "%u) %s (%s)\n", member->id, profile->caller_id_name, profile->caller_id_number);
 
- done:
-    switch_safe_free(lbuf);
+	}
 
-    return status;
+	switch_mutex_unlock(conference->member_mutex);
 
 }
 
-/* outbound call bridge progress call state callback handler */
-static switch_status_t audio_bridge_on_ring(switch_core_session_t *session)
+static void conference_list(conference_obj_t * conference, switch_stream_handle_t *stream, char *delim)
 {
-    switch_channel_t *channel = NULL;
-
-    channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	conference_member_t *member = NULL;
 
-    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "CUSTOM RING\n");
+	assert(conference != NULL);
+	assert(stream != NULL);
+	assert(delim != NULL);
 
-    /* put the channel in a passive state so we can loop audio to it */
-    switch_channel_set_state(channel, CS_TRANSMIT);
-    return SWITCH_STATUS_FALSE;
-}
 
-static const switch_state_handler_table_t audio_bridge_peer_state_handlers = {
-    /*.on_init */ NULL, 
-    /*.on_ring */ audio_bridge_on_ring, 
-    /*.on_execute */ NULL, 
-    /*.on_hangup */ NULL, 
-    /*.on_loopback */ NULL, 
-    /*.on_transmit */ NULL, 
-    /*.on_hold */ NULL, 
-};
+	switch_mutex_lock(conference->member_mutex);
 
+	for (member = conference->members; member; member = member->next) {
+		switch_channel_t *channel;
+		switch_caller_profile_t *profile;
+		char *uuid;
+		char *name;
+		uint32_t count = 0;
 
-/* generate an outbound call from the conference */
-static switch_status_t conference_outcall(conference_obj_t *conference, 
-                                          switch_core_session_t *session, 
-                                          char *bridgeto, 
-                                          uint32_t timeout, 
-                                          char *flags, 
-                                          char *cid_name, 
-                                          char *cid_num,
-                                          switch_call_cause_t *cause)
-{
-    switch_core_session_t *peer_session;
-    switch_channel_t *peer_channel;
-    switch_status_t status = SWITCH_STATUS_SUCCESS;
-    switch_channel_t *caller_channel = NULL;
-    char appdata[512];
-
-    *cause = SWITCH_CAUSE_NORMAL_CLEARING;
-
-
-    if (switch_thread_rwlock_tryrdlock(conference->rwlock) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Read Lock Fail\n");
-        return SWITCH_STATUS_FALSE;
-    }
+		if (switch_test_flag(member, MFLAG_NOCHANNEL)) {
+			continue;
+		}
 
-    if (session != NULL) {
-        caller_channel = switch_core_session_get_channel(session);
-	
-    }
+		uuid = switch_core_session_get_uuid(member->session);
+		channel = switch_core_session_get_channel(member->session);
+		profile = switch_channel_get_caller_profile(channel);
+		name = switch_channel_get_name(channel);
 
-    if (switch_strlen_zero(cid_name)) {
-        cid_name = conference->caller_id_name;
-    }
-
-    if (switch_strlen_zero(cid_num)) {
-        cid_num = conference->caller_id_number;
-    }
-
-    /* establish an outbound call leg */
-    if (switch_ivr_originate(session, 
-                             &peer_session, 
-                             cause, 
-                             bridgeto, 
-                             timeout, 
-                             &audio_bridge_peer_state_handlers, 
-                             cid_name, 
-                             cid_num, 
-                             NULL) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot create outgoing channel, cause: %s\n", 
-                          switch_channel_cause2str(*cause));
-        if (caller_channel) {
-            switch_channel_hangup(caller_channel, *cause);
-        }
-        goto done;
-    } 
-
-
-    peer_channel = switch_core_session_get_channel(peer_session);
-    assert(peer_channel != NULL);
-
-    /* make sure the conference still exists */
-    if (!switch_test_flag(conference, CFLAG_RUNNING)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Conference is gone now, nevermind..\n");
-        if (caller_channel) {
-            switch_channel_hangup(caller_channel, SWITCH_CAUSE_NO_ROUTE_DESTINATION);
-        }
-        switch_channel_hangup(peer_channel, SWITCH_CAUSE_NO_ROUTE_DESTINATION);
-        goto done;
-    }
-
-    if (caller_channel && switch_channel_test_flag(peer_channel, CF_ANSWERED)) {
-        switch_channel_answer(caller_channel);
-    }
-
-    /* if the outbound call leg is ready */
-    if (switch_channel_test_flag(peer_channel, CF_ANSWERED) || switch_channel_test_flag(peer_channel, CF_EARLY_MEDIA)) {
-        switch_caller_extension_t *extension = NULL;
-
-        /* build an extension name object */
-        if ((extension = switch_caller_extension_new(peer_session, conference->name, conference->name)) == 0) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "memory error!\n");
-            status = SWITCH_STATUS_MEMERR;
-            goto done;
-        }
-        /* add them to the conference */
-        if (flags && strcasecmp(flags, "none")) {
-            snprintf(appdata, sizeof(appdata), "%s +flags{%s}", conference->name, flags);
-            switch_caller_extension_add_application(peer_session, extension, (char *) global_app_name, appdata);
-        } else {
-            switch_caller_extension_add_application(peer_session, extension, (char *) global_app_name, conference->name);
-        }
-
-        switch_channel_set_caller_extension(peer_channel, extension);
-        switch_channel_set_state(peer_channel, CS_EXECUTE);
-
-    } else {
-        switch_channel_hangup(peer_channel, SWITCH_CAUSE_NO_ANSWER);
-        status = SWITCH_STATUS_FALSE;
-        goto done;
-    }
 
- done:
-    switch_thread_rwlock_unlock(conference->rwlock);
-    return status;
-}
+		stream->write_function(stream, "%u%s%s%s%s%s%s%s%s%s",
+							   member->id, delim, name, delim, uuid, delim, profile->caller_id_name, delim, profile->caller_id_number, delim);
+
+		if (switch_test_flag(member, MFLAG_CAN_HEAR)) {
+			stream->write_function(stream, "hear");
+			count++;
+		}
 
-struct bg_call {
-    conference_obj_t *conference;
-    switch_core_session_t *session;
-    char *bridgeto;
-    uint32_t timeout;
-    char *flags;
-    char *cid_name;
-    char *cid_num;
-};
+		if (switch_test_flag(member, MFLAG_CAN_SPEAK)) {
+			stream->write_function(stream, "%s%s", count ? "|" : "", "speak");
+			count++;
+		}
 
-static void *SWITCH_THREAD_FUNC conference_outcall_run(switch_thread_t *thread, void *obj)
-{
-    struct bg_call *call = (struct bg_call *) obj;
-    
-    if (call) {
-        switch_call_cause_t cause;
-        switch_event_t *event;
-
-        conference_outcall(call->conference, call->session, call->bridgeto, call->timeout, call->flags, call->cid_name, call->cid_num, &cause);
-
-        if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", call->conference->name);
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "bgdial-result");
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Result", "%s", switch_channel_cause2str(cause));
-            switch_event_fire(&event);
-        }
-        switch_safe_free(call->bridgeto);
-        switch_safe_free(call->flags);
-        switch_safe_free(call->cid_name);
-        switch_safe_free(call->cid_num);
-        switch_safe_free(call);
-    }
-
-    return NULL;
-}
-
-static switch_status_t conference_outcall_bg(conference_obj_t *conference, 
-                                             switch_core_session_t *session, 
-                                             char *bridgeto, 
-                                             uint32_t timeout, 
-                                             char *flags, 
-                                             char *cid_name, 
-                                             char *cid_num)
-{
-    struct bg_call *call = NULL;
-    
-    if ((call = malloc(sizeof(*call)))) {
-        switch_thread_t *thread;
-        switch_threadattr_t *thd_attr = NULL;
-
-        memset(call, 0, sizeof(*call));
-        call->conference = conference;
-        call->session = session;
-        call->timeout = timeout;
-
-        if (bridgeto) {
-            call->bridgeto = strdup(bridgeto);
-        }
-        if (flags) {
-            call->flags = strdup(flags);
-        }
-        if (cid_name) {
-            call->cid_name = strdup(cid_name);
-        }
-        if (cid_num) {
-            call->cid_num = strdup(cid_num);
-        }
-        
-        switch_threadattr_create(&thd_attr, conference->pool);
-        switch_threadattr_detach_set(thd_attr, 1);
-        switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-        switch_thread_create(&thread, thd_attr, conference_outcall_run, call, conference->pool);
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Lanuching BG Thread for outcall\n");
+		stream->write_function(stream, "%s%d%s%d%s%d\n", delim, member->volume_in_level, delim, member->volume_out_level, delim, member->energy_level);
+	}
 
-		return SWITCH_STATUS_SUCCESS;
-    }
+	switch_mutex_unlock(conference->member_mutex);
 
-	return SWITCH_STATUS_MEMERR;
 }
 
-/* Play a file */
-static switch_status_t conference_local_play_file(conference_obj_t *conference, 
-                                                  switch_core_session_t *session, char *path, uint32_t leadin, char *buf, switch_size_t len)
+static switch_status_t conf_api_sub_mute(conference_member_t * member, switch_stream_handle_t *stream, void *data)
 {
-    uint32_t x = 0;
-    switch_status_t status = SWITCH_STATUS_SUCCESS;
-
-    /* generate some space infront of the file to be played */
-    for (x = 0; x < leadin; x++) {
-        switch_frame_t *read_frame;
-        switch_status_t status = switch_core_session_read_frame(session, &read_frame, 1000, 0);
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
 
-        if (!SWITCH_READ_ACCEPTABLE(status)) {
-            break;
-        }
-    }
-
-    /* if all is well, really play the file */
-    if (status == SWITCH_STATUS_SUCCESS) {
-        char *dpath = NULL;
-
-        if (conference->sound_prefix) {
-            if (!(dpath = switch_mprintf("%s/%s", conference->sound_prefix, path))) {
-                return SWITCH_STATUS_MEMERR;
-            }
-            path = dpath;
-        }
+	if (member != NULL) {
+		switch_event_t *event;
 
-        status = switch_ivr_play_file(session, NULL, path, NULL);
-        switch_safe_free(dpath);
-    }
+		switch_clear_flag_locked(member, MFLAG_CAN_SPEAK);
+		if (member->conference->muted_sound) {
+			conference_member_play_file(member, member->conference->muted_sound, 0);
+		} else {
+			char msg[512];
 
-    return status;
-}
+			snprintf(msg, sizeof(msg), "Muted");
+			conference_member_say(member, msg, 0);
+		}
+		if (stream != NULL) {
+			stream->write_function(stream, "OK mute %u\n", member->id);
+		}
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_channel_t *channel = switch_core_session_get_channel(member->session);
+			switch_channel_event_set_data(channel, event);
 
-static void set_mflags(char *flags, member_flag_t *f)
-{
-	if (flags) {
-		if (strstr(flags, "mute")) {
-			*f &= ~MFLAG_CAN_SPEAK;
-		} else if (strstr(flags, "deaf")) {
-			*f &= ~MFLAG_CAN_HEAR;
-		} else if (strstr(flags, "waste")) {
-			*f |= MFLAG_WASTE_BANDWIDTH;
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "mute-member");
+			switch_event_fire(&event);
 		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
 	}
 
+	return ret_status;
 }
 
-
-/* Application interface function that is called from the dialplan to join the channel to a conference */
-static void conference_function(switch_core_session_t *session, char *data)
+static switch_status_t conf_api_sub_unmute(conference_member_t * member, switch_stream_handle_t *stream, void *data)
 {
-    switch_codec_t *read_codec = NULL;
-    uint32_t flags = 0;
-    conference_member_t member = {0};
-    conference_obj_t *conference = NULL;
-    switch_channel_t *channel = NULL;
-    char *mydata = switch_core_session_strdup(session, data);
-    char *conf_name = NULL;
-    char *bridge_prefix = "bridge:";
-    char *flags_prefix = "+flags{";
-    char *bridgeto = NULL;
-    char *profile_name = NULL;
-    switch_xml_t cxml = NULL, cfg = NULL, profiles = NULL;
-    char *flags_str;
-    member_flag_t mflags = 0;
-    switch_core_session_message_t msg = {0};
-    uint8_t rl = 0, isbr = 0;
-    char *dpin = NULL;
-    conf_xml_cfg_t xml_cfg = {0};
-    char *params = NULL;
-
-    channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
 
-    if (!mydata) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
-        return;
-    }
-
-
-    /* is this a bridging conference ? */
-    if (!strncasecmp(mydata, bridge_prefix, strlen(bridge_prefix))) {
-        isbr = 1;
-        mydata += strlen(bridge_prefix);
-        if ((bridgeto = strchr(mydata, ':'))) {
-            *bridgeto++ = '\0';
-        } else {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Config Error!\n");
-            goto done;
-        }
-    }
-
-    conf_name = mydata;
-
-    /* is there a conference pin ? */
-    if ((dpin = strchr(conf_name, '+'))) {
-        *dpin++ = '\0';
-    }
-
-    /* is there profile specification ? */
-    if ((profile_name = strchr(conf_name, '@'))) {
-        *profile_name++ = '\0';
-    } else {
-        profile_name = "default";
-    }
-
-    params = switch_mprintf("conf_name=%s&profile_name=%s", conf_name, profile_name);
-
-    /* Open the config from the xml registry */
-    if (!(cxml = switch_xml_open_cfg(global_cf_name, &cfg, params))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", global_cf_name);
-        goto done;
-    }
-
-    if ((profiles = switch_xml_child(cfg, "profiles"))) {
-        xml_cfg.profile = switch_xml_find_child(profiles, "profile", "name", profile_name);
-    }
-
-    if (!xml_cfg.profile) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find profile: %s\n", profile_name);
-        switch_xml_free(cxml);
-        cxml = NULL;
-        goto done;
-    }
-
-    xml_cfg.controls = switch_xml_child(cfg, "caller-controls");
-#ifdef OPTION_IVR_MENU_SUPPORT
-    xml_cfg.menus = switch_xml_child(cfg, "menus");
-#endif 
-
-
-    /* if this is a bridging call, and it's not a duplicate, build a */
-    /* conference object, and skip pin handling, and locked checking */
-    if (isbr) {
-        char *uuid = switch_core_session_get_uuid(session);
-
-        if (!strcmp(conf_name, "_uuid_")) {
-            conf_name = uuid;
-        }
-
-        if ((conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, conf_name))) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Conference %s already exists!\n", conf_name);
-            goto done;
-        }
-
-        /* Create the conference object. */
-        conference = conference_new(conf_name, xml_cfg, NULL);
-
-        if (!conference) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-            goto done;
-        }
-
-        /* Set the minimum number of members (once you go above it you cannot go below it) */
-        conference->min = 2;
-
-        /* if the dialplan specified a pin, override the profile's value */
-        if (dpin) {
-            conference->pin = switch_core_strdup(conference->pool, dpin);
-        }
-
-        /* Indicate the conference is dynamic */
-        switch_set_flag_locked(conference, CFLAG_DYNAMIC);	
-
-        /* Start the conference thread for this conference */
-        launch_conference_thread(conference);
-
-    } else {
-        /* if the conference exists, get the pointer to it */
-        if (!(conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, conf_name))) {
-            /* couldn't find the conference, create one */
-            conference = conference_new(conf_name, xml_cfg, NULL);
-
-            if (!conference) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-                goto done;
-            }
-
-            /* if the dialplan specified a pin, override the profile's value */
-            if (dpin) {
-                conference->pin = switch_core_strdup(conference->pool, dpin);
-            }
-
-            /* Set the minimum number of members (once you go above it you cannot go below it) */
-            conference->min = 1;
-
-            /* Indicate the conference is dynamic */
-            switch_set_flag_locked(conference, CFLAG_DYNAMIC);
-
-            /* Start the conference thread for this conference */
-            launch_conference_thread(conference);
-        }
-
-        /* acquire a read lock on the thread so it can't leave without us */
-        if (switch_thread_rwlock_tryrdlock(conference->rwlock) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Read Lock Fail\n");
-            goto done;
-        }
-        rl++;
-        
-        /* if this is not an outbound call, deal with conference pins */
-        if (!switch_channel_test_flag(channel, CF_OUTBOUND) && conference->pin) {
-            char pin_buf[80] = "";
-            int  pin_retries = 3;	/* XXX - this should be configurable - i'm too lazy to do it right now... */
-            int  pin_valid = 0;
-            switch_status_t status = SWITCH_STATUS_SUCCESS;
-
-            /* Answer the channel */
-            switch_channel_answer(channel);
-
-            while(!pin_valid && pin_retries && status == SWITCH_STATUS_SUCCESS) {
-
-                /* be friendly */
-                if (conference->pin_sound) {
-                    conference_local_play_file(conference, session, conference->pin_sound, 20, pin_buf, sizeof(pin_buf));
-                } 
-                /* wait for them if neccessary */
-                if (strlen(pin_buf) < strlen(conference->pin)) {
-                    char *buf = pin_buf + strlen(pin_buf);
-                    char term = '\0';
-
-                    status = switch_ivr_collect_digits_count(session, 
-                                                             buf, 
-                                                             sizeof(pin_buf) - (unsigned int)strlen(pin_buf), 
-                                                             (unsigned int)strlen(conference->pin) - (unsigned int)strlen(pin_buf), 
-                                                             "#", &term, 10000);
-                }
-
-                pin_valid = (status == SWITCH_STATUS_SUCCESS && strcmp(pin_buf, conference->pin) == 0);
-                if (!pin_valid) {
-                    /* zero the collected pin */
-                    memset(pin_buf, 0, sizeof(pin_buf));
-
-                    /* more friendliness */
-                    if (conference->bad_pin_sound) {
-                        conference_local_play_file(conference, session, conference->bad_pin_sound, 20, pin_buf, sizeof(pin_buf));
-                    }
-                }
-                pin_retries --;
-            }
-
-            if (!pin_valid) {
-                goto done;
-            }
-        }
-
-        /* don't allow more callers if the conference is locked, unless we invited them */
-        if (switch_test_flag(conference, CFLAG_LOCKED) && !switch_channel_test_flag(channel, CF_OUTBOUND)) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Conference %s is locked.\n", conf_name);
-            if (conference->locked_sound) {
-                /* Answer the channel */
-                switch_channel_answer(channel);
-                conference_local_play_file(conference, session, conference->locked_sound, 20, NULL, 0);
-            }
-            goto done;
-        }
-
-        /* dont allow more callers than the max_members allows for -- I explicitly didnt allow outbound calls
-         * someone else can add that (see above) if they feel that outbound calls should be able to violate the
-         * max_members limit -- TRX
-         */
-        if((conference->max_members > 0) && (conference->count >= conference->max_members)) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Conference %s is full.\n",conf_name);
-            if(conference->maxmember_sound) {
-                /* Answer the channel */
-                switch_channel_answer(channel);
-                conference_local_play_file(conference, session, conference->maxmember_sound, 20, NULL, 0);
-            }
-            goto done;
-        }
-
-    }
-
-    /* Release the config registry handle */
-    if (cxml) {
-        switch_xml_free(cxml);
-        cxml = NULL;
-    }
-
-    /* if we're using "bridge:" make an outbound call and bridge it in */
-    if (!switch_strlen_zero(bridgeto) && strcasecmp(bridgeto, "none")) {
-        switch_call_cause_t cause;
-        if (conference_outcall(conference, session, bridgeto, 60, NULL, NULL, NULL, &cause) != SWITCH_STATUS_SUCCESS) {
-            goto done;
-        }
-    } else {	
-        /* if we're not using "bridge:" set the conference answered flag */
-        /* and this isn't an outbound channel, answer the call */
-        if (!switch_channel_test_flag(channel, CF_OUTBOUND)) 
-            switch_set_flag(conference, CFLAG_ANSWERED);
-    }
-
-    /* Save the original read codec. */
-    read_codec = switch_core_session_get_read_codec(session);
-    member.native_rate = read_codec->implementation->samples_per_second;
-    member.pool = switch_core_session_get_pool(session);
-
-    /* Setup a Signed Linear codec for reading audio. */
-    if (switch_core_codec_init(&member.read_codec, 
-                               "L16", 
-                               NULL, 
-                               read_codec->implementation->samples_per_second, 
-                               read_codec->implementation->microseconds_per_frame / 1000, 
-                               1, 
-                               SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, 
-                               NULL, 
-                               member.pool) == SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Success L16@%uhz 1 channel %dms\n", 
-                          conference->rate, conference->interval);
-    } else {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Failed L16@%uhz 1 channel %dms\n", 
-                          conference->rate, conference->interval);
-        flags = 0;
-        goto done;
-    }
-
-    if (read_codec->implementation->samples_per_second != conference->rate) {
-        switch_audio_resampler_t **resampler = read_codec->implementation->samples_per_second > conference->rate ? 
-            &member.read_resampler : &member.mux_resampler;
-
-        switch_resample_create(resampler, 
-                               read_codec->implementation->samples_per_second, 
-                               read_codec->implementation->samples_per_second * 20, 
-                               conference->rate, 
-                               conference->rate * 20, 
-                               member.pool);
-
-        /* Setup an audio buffer for the resampled audio */
-        if (switch_buffer_create_dynamic(&member.resample_buffer, CONF_DBLOCK_SIZE, CONF_DBUFFER_SIZE, CONF_DBUFFER_MAX) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error Creating Audio Buffer!\n");
-            goto done;
-        }
-    }
-    /* Setup a Signed Linear codec for writing audio. */
-    if (switch_core_codec_init(&member.write_codec, 
-                               "L16", 
-                               NULL, 
-                               conference->rate, 
-                               conference->interval, 
-                               1, 
-                               SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, 
-                               NULL, 
-                               member.pool) == SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Success L16@%uhz 1 channel %dms\n", 
-                          conference->rate, conference->interval);
-    } else {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Failed L16@%uhz 1 channel %dms\n", 
-                          conference->rate, conference->interval);
-        flags = 0;
-        goto codec_done2;
-    }
-
-    /* Setup an audio buffer for the incoming audio */
-    if (switch_buffer_create_dynamic(&member.audio_buffer, CONF_DBLOCK_SIZE, CONF_DBUFFER_SIZE, CONF_DBUFFER_MAX) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error Creating Audio Buffer!\n");
-        goto codec_done1;
-    }
-
-    /* Setup an audio buffer for the outgoing audio */
-    if (switch_buffer_create_dynamic(&member.mux_buffer, CONF_DBLOCK_SIZE, CONF_DBUFFER_SIZE, CONF_DBUFFER_MAX) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error Creating Audio Buffer!\n");
-        goto codec_done1;
-    }
-
-    /* Prepare MUTEXS */
-    member.id = next_member_id();
-    member.session = session;
-    switch_mutex_init(&member.flag_mutex, SWITCH_MUTEX_NESTED, member.pool);
-    switch_mutex_init(&member.audio_in_mutex, SWITCH_MUTEX_NESTED, member.pool);
-    switch_mutex_init(&member.audio_out_mutex, SWITCH_MUTEX_NESTED, member.pool);
-
-    /* Install our Signed Linear codec so we get the audio in that format */
-    switch_core_session_set_read_codec(member.session, &member.read_codec);
-
-    if ((flags_str = strstr(mydata, flags_prefix))) {
-        char *p;
-
-        *flags_str = '\0';
-        flags_str += strlen(flags_prefix);
-        if ((p = strchr(flags_str, '}'))) {
-            *p = '\0';
-        }
-    }
-	
-	mflags = conference->mflags;
-	set_mflags(flags_str, &mflags);
-    switch_set_flag_locked((&member), MFLAG_RUNNING | mflags);
-	
-    /* Add the caller to the conference */
-    if (conference_add_member(conference, &member) != SWITCH_STATUS_SUCCESS) {
-        goto codec_done1;
-    }
-
-    msg.from = __FILE__;
-
-    /* Tell the channel we are going to be in a bridge */
-    msg.message_id = SWITCH_MESSAGE_INDICATE_BRIDGE;
-    switch_core_session_receive_message(session, &msg);
-
-    /* Run the confernece loop */
-    conference_loop_output(&member);
-
-    /* Tell the channel we are no longer going to be in a bridge */
-    msg.message_id = SWITCH_MESSAGE_INDICATE_UNBRIDGE;
-    switch_core_session_receive_message(session, &msg);
-
-    /* Remove the caller from the conference */
-    conference_del_member(member.conference, &member);
-
-    /* Put the original codec back */
-    switch_core_session_set_read_codec(member.session, read_codec);
-
-    /* Clean Up.  codec_done(X): is for error situations after the codecs were setup and done: is for situations before */
- codec_done1:
-    switch_core_codec_destroy(&member.read_codec);
- codec_done2:
-    switch_core_codec_destroy(&member.write_codec);
- done:
-    switch_safe_free(params);
-    switch_buffer_destroy(&member.resample_buffer);
-    switch_buffer_destroy(&member.audio_buffer);
-    switch_buffer_destroy(&member.mux_buffer);
-
-    /* Release the config registry handle */
-    if (cxml) {
-        switch_xml_free(cxml);
-    }
-
-    if (switch_test_flag(&member, MFLAG_KICKED) && conference->kicked_sound) {
-        switch_ivr_play_file(session, NULL, conference->kicked_sound, NULL);
-    }
-
-    switch_core_session_reset(session);
-
-    /* release the readlock */
-    if (rl) {
-        switch_thread_rwlock_unlock(conference->rwlock);
-    }
-}
+	if (member != NULL) {
+		switch_event_t *event;
 
-/* Create a thread for the conference and launch it */
-static void launch_conference_thread(conference_obj_t *conference)
-{
-    switch_thread_t *thread;
-    switch_threadattr_t *thd_attr = NULL;
+		switch_set_flag_locked(member, MFLAG_CAN_SPEAK);
+		if (stream != NULL) {
+			stream->write_function(stream, "OK unmute %u\n", member->id);
+		}
+		if (member->conference->unmuted_sound) {
+			conference_member_play_file(member, member->conference->unmuted_sound, 0);
+		} else {
+			char msg[512];
 
-    switch_set_flag_locked(conference, CFLAG_RUNNING);
-    switch_threadattr_create(&thd_attr, conference->pool);
-    switch_threadattr_detach_set(thd_attr, 1);
-    switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-    switch_mutex_lock(globals.hash_mutex);
-    switch_core_hash_insert(globals.conference_hash, conference->name, conference);
-    switch_mutex_unlock(globals.hash_mutex);
-    switch_thread_create(&thread, thd_attr, conference_thread_run, conference, conference->pool);
-}
-
-static void launch_conference_record_thread(conference_obj_t *conference, char *path)
-{
-    switch_thread_t *thread;
-    switch_threadattr_t *thd_attr = NULL;
-    switch_memory_pool_t *pool;
-    conference_record_t *rec;
-
-    /* Setup a memory pool to use. */
-    if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
-    }
-
-    /* Create a node object*/
-    if (!(rec = switch_core_alloc(pool, sizeof(*rec)))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
-        switch_core_destroy_memory_pool(&pool);
-    }
-
-    rec->conference = conference;
-    rec->path = switch_core_strdup(pool, path);
-    rec->pool = pool;
-
-    switch_threadattr_create(&thd_attr, rec->pool);
-    switch_threadattr_detach_set(thd_attr, 1);
-    switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-    switch_thread_create(&thread, thd_attr, conference_record_thread_run, rec, rec->pool);
-}
+			snprintf(msg, sizeof(msg), "Un-Muted");
+			conference_member_say(member, msg, 0);
+		}
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_channel_t *channel = switch_core_session_get_channel(member->session);
+			switch_channel_event_set_data(channel, event);
 
-static const switch_application_interface_t conference_application_interface = {
-    /*.interface_name */ global_app_name, 
-    /*.application_function */ conference_function, 
-    NULL, NULL, NULL, 
-	/* flags */ SAF_NONE,
-    /*.next*/ NULL
-};
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "unmute-member");
+			switch_event_fire(&event);
+		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
 
-static switch_api_interface_t conf_api_interface = {
-    /*.interface_name */	"conference", 
-    /*.desc */				"Conference module commands", 
-    /*.function */			conf_api_main, 
-    /*.syntax */		/* see switch_module_load, this is built on the fly */
-    /*.next */ 
-};
+	return ret_status;
+}
 
-static switch_status_t chat_send(char *proto, char *from, char *to, char *subject, char *body, char *hint)
+static switch_status_t conf_api_sub_deaf(conference_member_t * member, switch_stream_handle_t *stream, void *data)
 {
-    char name[512] = "", *p, *lbuf = NULL;
-    switch_chat_interface_t *ci;
-    conference_obj_t *conference = NULL;
-    switch_stream_handle_t stream = {0};
-
-    if ((p = strchr(to, '+'))) {
-        to = ++p;
-    }
-
-    if (!body) {
-        return SWITCH_STATUS_SUCCESS;
-    }
-
-    if (!(ci = switch_loadable_module_get_chat_interface(proto))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Chat Interface [%s]!\n", proto);
-    }
-
-
-    if ((p = strchr(to, '@'))) {
-        switch_copy_string(name, to, ++p-to);
-    } else {
-        switch_copy_string(name, to, sizeof(name));
-    }
-
-    if (!(conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, name))) {
-        ci->chat_send(CONF_CHAT_PROTO, to, hint && strchr(hint, '/') ? hint : from, "", "Conference not active.", NULL);
-        return SWITCH_STATUS_FALSE;
-    }
-
-    SWITCH_STANDARD_STREAM(stream);
-
-    if (body != NULL && (lbuf = strdup(body))) {
-        int argc;
-        char *argv[25];
-
-        memset(argv, 0, sizeof(argv));
-        argc = switch_separate_string(lbuf, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
-
-        /* try to find a command to execute */
-        if (argc) {
-            /* special case list */
-            if (strcasecmp(argv[0], "list") == 0) {
-                conference_list_pretty(conference, &stream);
-                /* provide help */
-            } 
-#if 0
-            else {
-                if (strcasecmp(argv[0], "help") == 0 || strcasecmp(argv[0], "commands") == 0) {
-                    stream.write_function(&stream, "%s\n", conf_api_interface.syntax);
-                    /* find a normal command */
-                } else {
-                    conf_api_dispatch(conference, &stream, argc, argv, (const char *)body, 0);
-                }
-            }
-#endif
-        } else {
-            stream.write_function(&stream, "No parameters specified.\nTry 'help'\n");
-        }
-    }
-    switch_safe_free(lbuf);
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
 
-    ci->chat_send(CONF_CHAT_PROTO, to, from, "", stream.data, NULL);
-    switch_safe_free(stream.data);
-
-    return SWITCH_STATUS_SUCCESS;
-}
+	if (member != NULL) {
+		switch_event_t *event;
 
-static const switch_chat_interface_t conference_chat_interface = {
-    /*.name */ CONF_CHAT_PROTO, 
-    /*.chat_send */ chat_send, 
+		switch_clear_flag_locked(member, MFLAG_CAN_HEAR);
+		if (stream != NULL) {
+			stream->write_function(stream, "OK deaf %u\n", member->id);
+		}
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_channel_t *channel = switch_core_session_get_channel(member->session);
+			switch_channel_event_set_data(channel, event);
 
-};
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "deaf-member");
+			switch_event_fire(&event);
+		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
 
-static switch_loadable_module_interface_t conference_module_interface = {
-    /*.module_name */ modname, 
-    /*.endpoint_interface */ NULL, 
-    /*.timer_interface */ NULL, 
-    /*.dialplan_interface */ NULL, 
-    /*.codec_interface */ NULL, 
-    /*.application_interface */ &conference_application_interface, 
-    /*.api_interface */ &conf_api_interface, 
-    /*.file_interface */ NULL, 
-    /*.speech_interface */ NULL, 
-    /*.directory_interface */ NULL, 
-    /*.chat_interface */ &conference_chat_interface
-};
+	return ret_status;
+}
 
-#ifdef OPTION_IVR_MENU_SUPPORT
-static switch_ivr_action_t conference_caller_control_menu_handler(switch_ivr_menu_t *menu, char *param, char *buf, size_t buflen, void *obj)
+static switch_status_t conf_api_sub_undeaf(conference_member_t * member, switch_stream_handle_t *stream, void *data)
 {
-    switch_ivr_action_t action = SWITCH_IVR_ACTION_NOOP;
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
 
-    if (!switch_strlen_zero(param)) {
-        if (obj != NULL) {
-            int i, found;
-            char *action_name = strdup(param);
-
-            if (action_name != NULL) {
-                char *sep = (action_name != NULL ? strchr(action_name, ' ') : NULL);
-
-                /* split the action from any parameters */
-                if (sep != NULL) {
-                    *sep  = '\0';
-                }
-
-                /* find and execute the caller control handler */
-                for(i = 0, found = 0; !found && i<CCFNTBL_QTY; i++) {
-                    found = (ccfntbl[i].action != CALLER_CONTROL_MENU && strcasecmp(ccfntbl[i].key, action_name) == 0);
-                    if (found) {
-                        if (obj != NULL) {
-                            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "invoking caller control menu action '%s'\n", ccfntbl[i].key);
-                            ccfntbl[i].handler((conference_member_t *)obj, (sep != NULL ? sep+1 : NULL));
-                            if (ccfntbl[i].action == CALLER_CONTROL_HANGUP) {
-                                action = SWITCH_IVR_ACTION_DIE;
-                            }
-                        }
-                    }
-                }
-
-                free(action_name);
-            }
-
-            if (!found) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unknown caller control menu action '%s'\n", param);
-            }
-        } else {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "unable to invoke caller control menu action '%s', NULL member!\n", param);
-        }
-    } else {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "NULL or empty param!\n");
-    }
-
-    return action;
-}
-
-/*
-  static switch_status_t ivr_menu_callback_play_file(char *file, uint32_t leadin, void *member)
-  {
-  switch_status_t status;
-
-  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "ivr_menu_callback_play_file\n");
-  status = conference_member_play_file((conference_member_t *)member, file, leadin);
-  if (status != SWITCH_STATUS_SUCCESS) {
-  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "ivr_menu_callback_play_file ERROR\n");
-  }
-
-  return status;
-  }
-
-  static switch_status_t ivr_menu_callback_say(char *file, uint32_t leadin, void *member)
-  {
-  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "ivr_menu_callback_say\n");
-  return conference_member_say((conference_member_t *)member, file, leadin);
-  }
-*/
-
-static switch_status_t conference_caller_control_menu_build(caller_control_menu_ctx_t **ctx, 
-                                                            conference_obj_t *conference, 
-                                                            switch_xml_t menu_group, 
-                                                            char *menu_name)
-{
-    switch_status_t status = SWITCH_STATUS_FALSE;
-    switch_xml_t xml_menus;
-    switch_xml_t xml_menu;
-
-    assert(conference != NULL);
-    assert(ctx != NULL);
-    assert(menu_group != NULL);
-    assert(menu_name != NULL);
-    assert(xml_menus != NULL);
-
-    xml_menus = switch_xml_child(menu_group, "menus");
-    xml_menu = (xml_menus != NULL ? switch_xml_find_child(xml_menus, "menu", "name", menu_name) : NULL);
-
-
-
-    /* if we found the requested menu in our menu_group */
-    if (xml_menu != NULL && xml_menu != NULL) {
-        *ctx = (caller_control_menu_ctx_t *)switch_core_alloc(conference->pool, sizeof(caller_control_menu_ctx_t));
-
-        if (*ctx != NULL) {
-            memset(*ctx, 0, sizeof(caller_control_menu_ctx_t));
-
-            /* setup an xml parser context, and a menu stack context for the specified menu in our memory pool */
-            status = switch_ivr_menu_stack_xml_init(&(*ctx)->xml_ctx, conference->pool);
-            if (status == SWITCH_STATUS_SUCCESS) {
-                (*ctx)->name = switch_core_strdup(conference->pool, menu_name);
-
-                /* add our xml menu handler to the xml stack parser */
-                status = switch_ivr_menu_stack_xml_add_custom((*ctx)->xml_ctx, "control", &conference_caller_control_menu_handler);
-                if (status != SWITCH_STATUS_SUCCESS)
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to add custom xml handler\n");
-
-                /* parse the xml stack to build the menu stack */
-                status = switch_ivr_menu_stack_xml_build((*ctx)->xml_ctx, &(*ctx)->menu_stack, xml_menus, xml_menu, conference->timer_name);
-                if (status != SWITCH_STATUS_SUCCESS)
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to build xml menu stack\n");
-
-                /*
-                // instruct ivr menu to use our file play and tts routines
-                status = switch_ivr_menu_set_fileplay_callback((*ctx)->menu_stack, &ivr_menu_callback_play_file);
-                if (status != SWITCH_STATUS_SUCCESS)
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to set file play calback\n");
-                status = switch_ivr_menu_set_tts_callback((*ctx)->menu_stack, &ivr_menu_callback_say);
-                if (status != SWITCH_STATUS_SUCCESS)
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to set tts calback\n");
-                */
-            } else {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to init xml menu context\n");
-            }
-            if (status != SWITCH_STATUS_SUCCESS)
-                *ctx = NULL;
-        }
-    } else {
-        if (xml_menus == NULL)
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "caller control menu unable to find xml menus\n");
-        if (xml_menu == NULL)
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "caller control menu unable to find xml menu '%s'\n", menu_name);
-    }
+	if (member != NULL) {
+		switch_event_t *event;
 
-    return status;
-}
-#endif
+		switch_set_flag_locked(member, MFLAG_CAN_HEAR);
+		if (stream != NULL) {
+			stream->write_function(stream, "OK undeaf %u\n", member->id);
+		}
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_channel_t *channel = switch_core_session_get_channel(member->session);
+			switch_channel_event_set_data(channel, event);
 
-static switch_status_t conf_default_controls(conference_obj_t *conference)
-{
-    switch_status_t status = SWITCH_STATUS_FALSE;
-    uint32_t i;
-    caller_control_action_t *action;
-
-    assert(conference != NULL);
-
-    for(i = 0, status = SWITCH_STATUS_SUCCESS; status == SWITCH_STATUS_SUCCESS && i<CCFNTBL_QTY; i++) {
-        if (!switch_strlen_zero(ccfntbl[i].digits)) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Installing default caller control action '%s' bound to '%s'.\n", 
-                              ccfntbl[i].key, 
-                              ccfntbl[i].digits);
-            action = (caller_control_action_t *)switch_core_alloc(conference->pool, sizeof(caller_control_action_t));
-            if (action != NULL) {
-                action->fndesc = &ccfntbl[i];
-                action->data = NULL;
-                status = switch_ivr_digit_stream_parser_set_event(conference->dtmf_parser, ccfntbl[i].digits, action);
-            } else {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to alloc memory for caller control binding '%s' to '%s'\n", 
-                                  ccfntbl[i].key, ccfntbl[i].digits);
-                status = SWITCH_STATUS_MEMERR;
-            }
-        }
-    }
-	
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "undeaf-member");
+			switch_event_fire(&event);
+		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
 
-    return status;
+	return ret_status;
 }
 
-static switch_status_t conference_new_install_caller_controls_custom(conference_obj_t *conference, switch_xml_t xml_controls, switch_xml_t xml_menus)
+static switch_status_t conf_api_sub_kick(conference_member_t * member, switch_stream_handle_t *stream, void *data)
 {
-    switch_status_t status = SWITCH_STATUS_FALSE;
-    switch_xml_t xml_kvp;
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
 
-    assert(conference != NULL);
-    assert(xml_controls != NULL);
-
-    /* parse the controls tree for caller control digit strings */
-    for (xml_kvp = switch_xml_child(xml_controls, "control"); xml_kvp; xml_kvp = xml_kvp->next) {
-        char *key = (char *) switch_xml_attr(xml_kvp, "action");
-        char *val = (char *) switch_xml_attr(xml_kvp, "digits");
-        char *data = (char *)switch_xml_attr_soft(xml_kvp, "data");
-
-        if (!switch_strlen_zero(key) && !switch_strlen_zero(val)) {
-            uint32_t i;
-
-            /* scan through all of the valid actions, and if found, */
-            /* set the new caller control action digit string, then */
-            /* stop scanning the table, and go to the next xml kvp. */
-            for(i = 0, status = SWITCH_STATUS_NOOP; i<CCFNTBL_QTY && status == SWITCH_STATUS_NOOP; i++) {
-
-                if (strcasecmp(ccfntbl[i].key, key) == 0) {
-                    status = SWITCH_STATUS_SUCCESS;
-#ifdef OPTION_IVR_MENU_SUPPORT
-                    if (xml_menus != NULL && ccfntbl[i].action == CALLER_CONTROL_MENU) {
-                        char *menu_group_name = strdup(data);
-                        char *menu_name = (menu_group_name != NULL ? strchr(menu_group_name, '/') : NULL);
-
-                        /* format: "menu_group_name/menu_name" */
-                        /* separate the menu name from the menu group */
-                        if (menu_name != NULL) {
-                            *(menu_name++) = '\0';
-                        }
-                        /* if there is a menu name, build the menu */
-                        if (menu_name != NULL) {
-                            caller_control_menu_ctx_t *menu_ctx = NULL;
-                            switch_xml_t menu_group = switch_xml_find_child(xml_menus, "group", "name", menu_group_name);
-
-                            status = conference_caller_control_menu_build(&menu_ctx, conference, menu_group, menu_name);
-                            data = (char *)menu_ctx;
-                        } else {
-                            status = SWITCH_STATUS_FALSE;
-                        }
-
-                        if (status != SWITCH_STATUS_SUCCESS) {
-                            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to build menu '%s' bound to '%s'\n", data, val);
-                        }
-
-                        /* clean up */
-                        if (menu_group_name != NULL) {
-                            free(menu_group_name);
-                        }
-                    }
-#endif
+	if (member != NULL) {
+		switch_event_t *event;
 
-                    if (status == SWITCH_STATUS_SUCCESS) {
-                        caller_control_action_t *action;
+		switch_mutex_lock(member->flag_mutex);
+		switch_clear_flag(member, MFLAG_RUNNING);
+		switch_set_flag(member, MFLAG_KICKED);
+		switch_core_session_kill_channel(member->session, SWITCH_SIG_BREAK);
+		switch_mutex_unlock(member->flag_mutex);
 
-                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Installing caller control action '%s' bound to '%s'.\n", key, val);
-                        action = (caller_control_action_t *)switch_core_alloc(conference->pool, sizeof(caller_control_action_t));
-                        if (action != NULL) {
-                            action->fndesc = &ccfntbl[i];
-                            action->data = (void *)switch_core_strdup(conference->pool, data);
-                            status = switch_ivr_digit_stream_parser_set_event(conference->dtmf_parser, val, action);
-                        } else {
-                            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to alloc memory for caller control binding '%s' to '%s'\n", ccfntbl[i].key, ccfntbl[i].digits);
-                            status = SWITCH_STATUS_MEMERR;
-                        }
-                    }
-                }
-            }
-            if (status == SWITCH_STATUS_NOOP) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid caller control action name '%s'.\n", key);
-            }
-        } else {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid caller control config entry pair action = '%s' digits = '%s'\n", key, val);
-        }
-    }
+		if (stream != NULL) {
+			stream->write_function(stream, "OK kicked %u\n", member->id);
+		}
+
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_channel_t *channel = switch_core_session_get_channel(member->session);
+			switch_channel_event_set_data(channel, event);
+
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "kick-member");
+			switch_event_fire(&event);
+		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
+
+	return ret_status;
+}
+
+
+static switch_status_t conf_api_sub_dtmf(conference_member_t * member, switch_stream_handle_t *stream, void *data)
+{
+	switch_event_t *event;
+	char *dtmf = (char *) data;
+
+	if (member == NULL) {
+		stream->write_function(stream, "Invalid member!\n");
+		return SWITCH_STATUS_GENERR;
+	}
+
+	if (switch_strlen_zero(dtmf)) {
+		stream->write_function(stream, "Invalid input!\n");
+		return SWITCH_STATUS_GENERR;
+	}
+
+
+	switch_mutex_lock(member->flag_mutex);
+	switch_core_session_kill_channel(member->session, SWITCH_SIG_BREAK);
+	switch_core_session_send_dtmf(member->session, dtmf);
+	switch_mutex_unlock(member->flag_mutex);
+
+
+	if (stream != NULL) {
+		stream->write_function(stream, "OK sent %s to %u\n", (char *) data, member->id);
+	}
+
+	if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+		switch_channel_t *channel = switch_core_session_get_channel(member->session);
+		switch_channel_event_set_data(channel, event);
+
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "dtmf-member");
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Digits", "%s", dtmf);
+		switch_event_fire(&event);
+	}
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+static switch_status_t conf_api_sub_energy(conference_member_t * member, switch_stream_handle_t *stream, void *data)
+{
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+
+	if (member != NULL) {
+		switch_event_t *event;
+
+		if (data) {
+			switch_mutex_lock(member->flag_mutex);
+			member->energy_level = atoi((char *) data);
+			switch_mutex_unlock(member->flag_mutex);
+		}
+
+		if (stream != NULL) {
+			stream->write_function(stream, "Energy %u = %d\n", member->id, member->energy_level);
+		}
+
+		if (data) {
+			if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+				switch_channel_t *channel = switch_core_session_get_channel(member->session);
+				switch_channel_event_set_data(channel, event);
+
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "energy-level-member");
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Energy-Level", "%d", member->energy_level);
+
+				switch_event_fire(&event);
+			}
+		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
+
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_volume_in(conference_member_t * member, switch_stream_handle_t *stream, void *data)
+{
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+
+	if (member != NULL) {
+		switch_event_t *event;
+
+		if (data) {
+			switch_mutex_lock(member->flag_mutex);
+			member->volume_in_level = atoi((char *) data);
+			switch_normalize_volume(member->volume_in_level);
+			switch_mutex_unlock(member->flag_mutex);
+		}
+
+		if (stream != NULL) {
+			stream->write_function(stream, "Volume IN %u = %d\n", member->id, member->volume_in_level);
+		}
+		if (data) {
+			if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+				switch_channel_t *channel = switch_core_session_get_channel(member->session);
+				switch_channel_event_set_data(channel, event);
+
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "volume-in-member");
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Volume-Level", "%u", member->volume_in_level);
+
+				switch_event_fire(&event);
+			}
+		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
+
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_volume_out(conference_member_t * member, switch_stream_handle_t *stream, void *data)
+{
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+
+	if (member != NULL) {
+		switch_event_t *event;
+
+		if (data) {
+			switch_mutex_lock(member->flag_mutex);
+			member->volume_out_level = atoi((char *) data);
+			switch_normalize_volume(member->volume_out_level);
+			switch_mutex_unlock(member->flag_mutex);
+		}
+
+		if (stream != NULL) {
+			stream->write_function(stream, "Volume OUT %u = %d\n", member->id, member->volume_out_level);
+		}
+
+		if (data) {
+			if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+				switch_channel_t *channel = switch_core_session_get_channel(member->session);
+				switch_channel_event_set_data(channel, event);
+
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", member->conference->name);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "volume-out-member");
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Volume-Level", "%u", member->volume_out_level);
+
+				switch_event_fire(&event);
+			}
+		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
+
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_list(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	int ret_status = SWITCH_STATUS_GENERR;
+
+	switch_hash_index_t *hi;
+	void *val;
+	char *d = ";";
+	int pretty = 0;
+	int argofs = (argc >= 2 && strcasecmp(argv[1], "list") == 0);	// detect being called from chat vs. api
+
+	if (argv[1 + argofs]) {
+		if (argv[2 + argofs] && !strcasecmp(argv[1 + argofs], "delim")) {
+			d = argv[2 + argofs];
+
+			if (*d == '"') {
+				if (++d) {
+					char *p;
+					if ((p = strchr(d, '"'))) {
+						*p = '\0';
+					}
+				} else {
+					d = ";";
+				}
+			}
+		} else if (strcasecmp(argv[1 + argofs], "pretty") == 0) {
+			pretty = 1;
+		}
+	}
+
+	if (conference == NULL) {
+		for (hi = switch_hash_first(globals.conference_pool, globals.conference_hash); hi; hi = switch_hash_next(hi)) {
+			switch_hash_this(hi, NULL, NULL, &val);
+			conference = (conference_obj_t *) val;
+
+			stream->write_function(stream, "Conference %s (%u member%s%s)\n",
+								   conference->name,
+								   conference->count, conference->count == 1 ? "" : "s", switch_test_flag(conference, CFLAG_LOCKED) ? " locked" : "");
+			if (pretty) {
+				conference_list_pretty(conference, stream);
+			} else {
+				conference_list(conference, stream, d);
+			}
+		}
+	} else {
+		if (pretty) {
+			conference_list_pretty(conference, stream);
+		} else {
+			conference_list(conference, stream, d);
+		}
+	}
+
+	ret_status = SWITCH_STATUS_SUCCESS;
+
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_play(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	int ret_status = SWITCH_STATUS_GENERR;
+	switch_event_t *event;
+	uint8_t async = 0;
+
+	assert(conference != NULL);
+	assert(stream != NULL);
+
+	if ((argc == 4 && !strcasecmp(argv[3], "async")) || (argc == 5 && !strcasecmp(argv[4], "async"))) {
+		argc--;
+		async++;
+	}
+
+	if (argc == 3) {
+		if (conference_play_file(conference, argv[2], 0, NULL, async) == SWITCH_STATUS_SUCCESS) {
+			stream->write_function(stream, "(play) Playing file %s\n", argv[2]);
+			if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "play-file");
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "File", "%s", argv[2]);
+				switch_event_fire(&event);
+			}
+		} else {
+			stream->write_function(stream, "(play) File: %s not found.\n", argv[2] ? argv[2] : "(unspecified)");
+		}
+		ret_status = SWITCH_STATUS_SUCCESS;
+	} else if (argc == 4) {
+		uint32_t id = atoi(argv[3]);
+		conference_member_t *member;
+
+		if ((member = conference_member_get(conference, id))) {
+			if (conference_member_play_file(member, argv[2], 0) == SWITCH_STATUS_SUCCESS) {
+				stream->write_function(stream, "(play) Playing file %s to member %u\n", argv[2], id);
+				if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
+					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", id);
+					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "play-file-member");
+					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "File", "%s", argv[2]);
+					switch_event_fire(&event);
+				}
+			} else {
+				stream->write_function(stream, "(play) File: %s not found.\n", argv[2] ? argv[2] : "(unspecified)");
+			}
+			ret_status = SWITCH_STATUS_SUCCESS;
+		} else {
+			stream->write_function(stream, "Member: %u not found.\n", id);
+		}
+	}
+
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_say(conference_obj_t * conference, switch_stream_handle_t *stream, const char *text)
+{
+	int ret_status = SWITCH_STATUS_GENERR;
+
+	if (switch_strlen_zero(text)) {
+		stream->write_function(stream, "(say) Error! No text.");
+		return ret_status;
+	}
+
+	if (conference_say(conference, text, 0) == SWITCH_STATUS_SUCCESS) {
+		switch_event_t *event;
+
+		stream->write_function(stream, "(say) OK\n");
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "speak-text");
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Text", "%s", text);
+			switch_event_fire(&event);
+		}
+		ret_status = SWITCH_STATUS_SUCCESS;
+	} else {
+		stream->write_function(stream, "(say) Error!");
+	}
+
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_saymember(conference_obj_t * conference, switch_stream_handle_t *stream, const char *text)
+{
+	int ret_status = SWITCH_STATUS_GENERR;
+	char *expanded = NULL;
+	char *start_text = NULL;
+	char *workspace = NULL;
+	uint32_t id = 0;
+	conference_member_t *member;
+
+	if (switch_strlen_zero(text)) {
+		stream->write_function(stream, "(saymember) No Text!\n");
+		goto done;
+	}
+
+	if (!(workspace = strdup(text))) {
+		stream->write_function(stream, "(saymember) Memory Error!\n");
+		goto done;
+	}
+
+	if ((start_text = strchr(workspace, ' '))) {
+		*start_text++ = '\0';
+		text = start_text;
+	}
+
+	id = atoi(workspace);
+
+	if (!id || switch_strlen_zero(text)) {
+		stream->write_function(stream, "(saymember) No Text!\n");
+		goto done;
+	}
+
+	if (!(member = conference_member_get(conference, id))) {
+		stream->write_function(stream, "(saymember) Unknown Member %u!", id);
+		goto done;
+	}
+
+	if ((expanded = switch_channel_expand_variables(switch_core_session_get_channel(member->session), (char *) text)) != text) {
+		text = expanded;
+	} else {
+		expanded = NULL;
+	}
+
+	if (text && conference_member_say(member, (char *) text, 0) == SWITCH_STATUS_SUCCESS) {
+		switch_event_t *event;
+
+		stream->write_function(stream, "(saymember) OK\n");
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "speak-text-member");
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", id);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Text", "%s", text);
+			switch_event_fire(&event);
+		}
+		ret_status = SWITCH_STATUS_SUCCESS;
+	} else {
+		stream->write_function(stream, "(saymember) Error!");
+	}
+
+  done:
+	switch_safe_free(workspace);
+	switch_safe_free(expanded);
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_stop(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	int ret_status = SWITCH_STATUS_GENERR;
+	uint8_t current = 0, all = 0;
+
+	assert(conference != NULL);
+	assert(stream != NULL);
+
+	if (argc > 2) {
+		current = strcasecmp(argv[2], "current") ? 0 : 1;
+		all = strcasecmp(argv[2], "all") ? 0 : 1;
+	} else {
+		all = 1;
+	}
+
+	if (current || all) {
+		if (argc == 4) {
+			uint32_t id = atoi(argv[3]);
+			conference_member_t *member;
+
+			if ((member = conference_member_get(conference, id))) {
+				uint32_t stopped = conference_member_stop_file(member, current ? FILE_STOP_CURRENT : FILE_STOP_ALL);
+				stream->write_function(stream, "Stopped %u files.\n", stopped);
+			} else {
+				stream->write_function(stream, "Member: %u not found.\n", id);
+			}
+			ret_status = SWITCH_STATUS_SUCCESS;
+		} else {
+			uint32_t stopped = conference_stop_file(conference, current ? FILE_STOP_CURRENT : FILE_STOP_ALL);
+			stream->write_function(stream, "Stopped %u files.\n", stopped);
+			ret_status = SWITCH_STATUS_SUCCESS;
+		}
+	}
+
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_relate(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	int ret_status = SWITCH_STATUS_GENERR;
+
+	assert(conference != NULL);
+	assert(stream != NULL);
+
+	if (argc > 4) {
+		uint8_t nospeak = 0, nohear = 0, clear = 0;
+		nospeak = strstr(argv[4], "nospeak") ? 1 : 0;
+		nohear = strstr(argv[4], "nohear") ? 1 : 0;
+
+		if (!strcasecmp(argv[4], "clear")) {
+			clear = 1;
+		}
+
+		if (!(clear || nospeak || nohear)) {
+			ret_status = SWITCH_STATUS_GENERR;
+			goto done;
+		}
+		ret_status = SWITCH_STATUS_SUCCESS;
+
+		if (clear) {
+			conference_member_t *member = NULL;
+			uint32_t id = atoi(argv[2]);
+			uint32_t oid = atoi(argv[3]);
+
+			if ((member = conference_member_get(conference, id))) {
+				member_del_relationship(member, oid);
+				stream->write_function(stream, "relationship %u->%u cleared.", id, oid);
+			} else {
+				stream->write_function(stream, "relationship %u->%u not found", id, oid);
+			}
+		} else if (nospeak || nohear) {
+			conference_member_t *member = NULL, *other_member = NULL;
+			uint32_t id = atoi(argv[2]);
+			uint32_t oid = atoi(argv[3]);
+
+			if ((member = conference_member_get(conference, id))
+				&& (other_member = conference_member_get(conference, oid))) {
+				conference_relationship_t *rel = NULL;
+				if ((rel = member_get_relationship(member, other_member))) {
+					rel->flags = 0;
+				} else {
+					rel = member_add_relationship(member, oid);
+				}
+
+				if (rel) {
+					switch_set_flag(rel, RFLAG_CAN_SPEAK | RFLAG_CAN_HEAR);
+					if (nospeak) {
+						switch_clear_flag(rel, RFLAG_CAN_SPEAK);
+					}
+					if (nohear) {
+						switch_clear_flag(rel, RFLAG_CAN_HEAR);
+					}
+					stream->write_function(stream, "ok %u->%u set\n", id, oid);
+				} else {
+					stream->write_function(stream, "error!\n");
+				}
+			} else {
+				stream->write_function(stream, "relationship %u->%u not found", id, oid);
+			}
+		}
+	}
+
+  done:
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_lock(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	switch_event_t *event;
+
+	assert(conference != NULL);
+	assert(stream != NULL);
+
+	if (conference->is_locked_sound) {
+		conference_play_file(conference, conference->is_locked_sound, CONF_DEFAULT_LEADIN, NULL, 0);
+	}
+
+	switch_set_flag_locked(conference, CFLAG_LOCKED);
+	stream->write_function(stream, "OK %s locked\n", argv[0]);
+	if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "lock");
+		switch_event_fire(&event);
+	}
+
+	return 0;
+}
+
+static switch_status_t conf_api_sub_unlock(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	switch_event_t *event;
+
+	assert(conference != NULL);
+	assert(stream != NULL);
+
+	if (conference->is_unlocked_sound) {
+		conference_play_file(conference, conference->is_unlocked_sound, CONF_DEFAULT_LEADIN, NULL, 0);
+	}
+
+	switch_clear_flag_locked(conference, CFLAG_LOCKED);
+	stream->write_function(stream, "OK %s unlocked\n", argv[0]);
+	if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", conference->name);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "unlock");
+		switch_event_fire(&event);
+	}
+
+
+	return 0;
+}
+
+static switch_status_t conf_api_sub_dial(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+
+	assert(stream != NULL);
+
+	if (argc > 2) {
+		switch_call_cause_t cause;
+
+		if (conference) {
+			conference_outcall(conference, NULL, NULL, argv[2], 60, NULL, argv[4], argv[3], &cause);
+		} else {
+			conference_outcall(NULL, argv[0], NULL, argv[2], 60, NULL, argv[4], argv[3], &cause);
+		}
+
+		stream->write_function(stream, "Call Requested: result: [%s]\n", switch_channel_cause2str(cause));
+	} else {
+		stream->write_function(stream, "Bad Args\n");
+		ret_status = SWITCH_STATUS_GENERR;
+	}
+
+	return ret_status;
+}
+
+
+static switch_status_t conf_api_sub_bgdial(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+
+	assert(stream != NULL);
+
+	if (argc > 2) {
+		if (conference) {
+			conference_outcall_bg(conference, NULL, NULL, argv[2], 60, NULL, argv[4], argv[3]);
+		} else {
+			conference_outcall_bg(NULL, argv[1], NULL, argv[2], 60, NULL, argv[4], argv[3]);
+		}
+		stream->write_function(stream, "OK\n");
+	} else {
+		stream->write_function(stream, "Bad Args\n");
+		ret_status = SWITCH_STATUS_GENERR;
+	}
+
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_transfer(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+	char *params = NULL;
+	assert(conference != NULL);
+	assert(stream != NULL);
+
+	if (argc > 3 && !switch_strlen_zero(argv[2])) {
+		int x;
+
+		for (x = 3; x < argc; x++) {
+			conference_member_t *member = NULL;
+			uint32_t id = atoi(argv[x]);
+			conference_obj_t *new_conference = NULL;
+			switch_channel_t *channel;
+			switch_event_t *event;
+			char *profile_name;
+			switch_xml_t cxml = NULL, cfg = NULL, profiles = NULL;
+
+			if (!id || !(member = conference_member_get(conference, id))) {
+				stream->write_function(stream, "No Member %u in conference %s.\n", id, conference->name);
+				continue;
+			}
+
+			channel = switch_core_session_get_channel(member->session);
+
+			/* build a new conference if it doesn't exist */
+			if (!(new_conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, argv[2]))) {
+				switch_memory_pool_t *pool = NULL;
+				char *conf_name;
+				conf_xml_cfg_t xml_cfg = { 0 };
+
+				/* Setup a memory pool to use. */
+				if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
+					goto done;
+				}
+
+				conf_name = switch_core_strdup(pool, argv[2]);
+
+				if ((profile_name = strchr(conf_name, '@'))) {
+					*profile_name++ = '\0';
+				} else {
+					profile_name = "default";
+				}
+				params = switch_mprintf("conf_name=%s&profile_name=%s", conf_name, profile_name);
+				/* Open the config from the xml registry  */
+				if (!(cxml = switch_xml_open_cfg(global_cf_name, &cfg, params))) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", global_cf_name);
+					goto done;
+				}
+
+				if ((profiles = switch_xml_child(cfg, "profiles"))) {
+					xml_cfg.profile = switch_xml_find_child(profiles, "profile", "name", profile_name);
+				}
+
+				if (!xml_cfg.profile) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find profile: %s\n", profile_name);
+					switch_xml_free(cxml);
+					cxml = NULL;
+					goto done;
+				}
+
+				xml_cfg.controls = switch_xml_child(cfg, "caller-controls");
+
+				/* Release the config registry handle */
+				if (cxml) {
+					switch_xml_free(cxml);
+					cxml = NULL;
+				}
+
+				/* Create the conference object. */
+				new_conference = conference_new(conf_name, xml_cfg, pool);
+
+				if (!new_conference) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
+					if (pool != NULL) {
+						switch_core_destroy_memory_pool(&pool);
+					}
+					goto done;
+				}
+
+				/* Set the minimum number of members (once you go above it you cannot go below it) */
+				new_conference->min = 1;
+
+				/* Indicate the conference is dynamic */
+				switch_set_flag_locked(new_conference, CFLAG_DYNAMIC);
+
+				switch_mutex_lock(new_conference->mutex);
+
+				/* Start the conference thread for this conference */
+				launch_conference_thread(new_conference);
+			} else {
+				switch_mutex_lock(new_conference->mutex);
+			}
+
+			/* move the member from the old conference to the new one */
+			conference_del_member(conference, member);
+			conference_add_member(new_conference, member);
+			switch_mutex_unlock(new_conference->mutex);
+
+			stream->write_function(stream, "OK Members sent to conference %s.\n", argv[2]);
+
+			/* tell them what happened */
+			if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+				switch_channel_event_set_data(channel, event);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Member-ID", "%u", member->id);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Old-Conference-Name", "%s", conference->name);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "New-Conference-Name", "%s", argv[3]);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "transfer");
+				switch_event_fire(&event);
+			}
+		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
+
+  done:
+	switch_safe_free(params);
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_record(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+	assert(conference != NULL);
+	assert(stream != NULL);
+
+	if (argc > 2) {
+		stream->write_function(stream, "Record file %s\n", argv[2]);
+		launch_conference_record_thread(conference, argv[2]);
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
+
+	return ret_status;
+}
+
+static switch_status_t conf_api_sub_norecord(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv)
+{
+	switch_status_t ret_status = SWITCH_STATUS_SUCCESS;
+
+	assert(conference != NULL);
+	assert(stream != NULL);
+
+	if (argc > 2) {
+		int all = (strcasecmp(argv[2], "all") == 0);
+		stream->write_function(stream, "Stop recording file %s\n", argv[2]);
+
+		if (!conference_record_stop(conference, all ? NULL : argv[2]) && !all) {
+			stream->write_function(stream, "non-existant recording '%s'\n", argv[2]);
+		}
+	} else {
+		ret_status = SWITCH_STATUS_GENERR;
+	}
+
+	return ret_status;
+}
+
+typedef enum {
+	CONF_API_COMMAND_LIST = 0,
+	CONF_API_COMMAND_ENERGY,
+	CONF_API_COMMAND_VOLUME_IN,
+	CONF_API_COMMAND_VOLUME_OUT,
+	CONF_API_COMMAND_PLAY,
+	CONF_API_COMMAND_SAY,
+	CONF_API_COMMAND_SAYMEMBER,
+	CONF_API_COMMAND_STOP,
+	CONF_API_COMMAND_DTMF,
+	CONF_API_COMMAND_KICK,
+	CONF_API_COMMAND_MUTE,
+	CONF_API_COMMAND_UNMUTE,
+	CONF_API_COMMAND_DEAF,
+	CONF_API_COMMAND_UNDEAF,
+	CONF_API_COMMAND_RELATE,
+	CONF_API_COMMAND_LOCK,
+	CONF_API_COMMAND_UNLOCK,
+	CONF_API_COMMAND_DIAL,
+	CONF_API_COMMAND_BGDIAL,
+	CONF_API_COMMAND_TRANSFER,
+	CONF_API_COMMAND_RECORD,
+	CONF_API_COMMAND_NORECORD
+} api_command_type_t;
+
+/* API Interface Function sub-commands */
+/* Entries in this list should be kept in sync with the enum above */
+static api_command_t conf_api_sub_commands[] = {
+	{"list", (void_fn_t) & conf_api_sub_list, CONF_API_SUB_ARGS_SPLIT, "<confname> list [delim <string>]"},
+	{"energy", (void_fn_t) & conf_api_sub_energy, CONF_API_SUB_MEMBER_TARGET,
+	 "<confname> energy <member_id|all|last> [<newval>]"},
+	{"volume_in", (void_fn_t) & conf_api_sub_volume_in, CONF_API_SUB_MEMBER_TARGET,
+	 "<confname> volume_in <member_id|all|last> [<newval>]"},
+	{"volume_out", (void_fn_t) & conf_api_sub_volume_out, CONF_API_SUB_MEMBER_TARGET,
+	 "<confname> volume_out <member_id|all|last> [<newval>]"},
+	{"play", (void_fn_t) & conf_api_sub_play, CONF_API_SUB_ARGS_SPLIT, "<confname> play <file_path> [<member_id>]"},
+	{"say", (void_fn_t) & conf_api_sub_say, CONF_API_SUB_ARGS_AS_ONE, "<confname> say <text>"},
+	{"saymember", (void_fn_t) & conf_api_sub_saymember, CONF_API_SUB_ARGS_AS_ONE,
+	 "<confname> saymember <member_id> <text>"},
+	{"stop", (void_fn_t) & conf_api_sub_stop, CONF_API_SUB_ARGS_SPLIT,
+	 "<confname> stop <[current|all|last]> [<member_id>]"},
+	{"dtmf", (void_fn_t) & conf_api_sub_dtmf, CONF_API_SUB_MEMBER_TARGET,
+	 "<confname> dtmf <[member_id|all|last]> <digits>"},
+	{"kick", (void_fn_t) & conf_api_sub_kick, CONF_API_SUB_MEMBER_TARGET, "<confname> kick <[member_id|all|last]>"},
+	{"mute", (void_fn_t) & conf_api_sub_mute, CONF_API_SUB_MEMBER_TARGET, "<confname> mute <[member_id|all]|last>"},
+	{"unmute", (void_fn_t) & conf_api_sub_unmute, CONF_API_SUB_MEMBER_TARGET,
+	 "<confname> unmute <[member_id|all]|last>"},
+	{"deaf", (void_fn_t) & conf_api_sub_deaf, CONF_API_SUB_MEMBER_TARGET, "<confname> deaf <[member_id|all]|last>"},
+	{"undeaf", (void_fn_t) & conf_api_sub_undeaf, CONF_API_SUB_MEMBER_TARGET,
+	 "<confname> undeaf <[member_id|all]|last>"},
+	{"relate", (void_fn_t) & conf_api_sub_relate, CONF_API_SUB_ARGS_SPLIT,
+	 "<confname> relate <member_id> <other_member_id> [nospeak|nohear|clear]"},
+	{"lock", (void_fn_t) & conf_api_sub_lock, CONF_API_SUB_ARGS_SPLIT, "<confname> lock"},
+	{"unlock", (void_fn_t) & conf_api_sub_unlock, CONF_API_SUB_ARGS_SPLIT, "<confname> unlock"},
+	{"dial", (void_fn_t) & conf_api_sub_dial, CONF_API_SUB_ARGS_SPLIT,
+	 "<confname> dial <endpoint_module_name>/<destination> <callerid number> <callerid name>"},
+	{"bgdial", (void_fn_t) & conf_api_sub_bgdial, CONF_API_SUB_ARGS_SPLIT,
+	 "<confname> bgdial <endpoint_module_name>/<destination> <callerid number> <callerid name>"},
+	{"transfer", (void_fn_t) & conf_api_sub_transfer, CONF_API_SUB_ARGS_SPLIT,
+	 "<confname> transfer <conference_name> <member id> [...<member id>]"},
+	{"record", (void_fn_t) & conf_api_sub_record, CONF_API_SUB_ARGS_SPLIT, "<confname> record <filename>"},
+	{"norecord", (void_fn_t) & conf_api_sub_norecord, CONF_API_SUB_ARGS_SPLIT, "<confname> norecord <[filename|all]>"},
+};
+
+#define CONFFUNCAPISIZE (sizeof(conf_api_sub_commands)/sizeof(conf_api_sub_commands[0]))
+
+switch_status_t conf_api_dispatch(conference_obj_t * conference, switch_stream_handle_t *stream, int argc, char **argv, const char *cmdline, int argn)
+{
+	switch_status_t status = SWITCH_STATUS_FALSE;
+	uint32_t i, found = 0;
+	assert(conference != NULL);
+	assert(stream != NULL);
+
+	/* loop through the command table to find a match */
+	for (i = 0; i < CONFFUNCAPISIZE && !found; i++) {
+		if (strcasecmp(argv[argn], conf_api_sub_commands[i].pname) == 0) {
+			found = 1;
+			switch (conf_api_sub_commands[i].fntype) {
+
+				/* commands that we've broken the command line into arguments for */
+			case CONF_API_SUB_ARGS_SPLIT:
+				{
+					conf_api_args_cmd_t pfn = (conf_api_args_cmd_t) conf_api_sub_commands[i].pfnapicmd;
+
+					if (pfn(conference, stream, argc, argv) != SWITCH_STATUS_SUCCESS) {
+						/* command returned error, so show syntax usage */
+						stream->write_function(stream, conf_api_sub_commands[i].psyntax);
+					}
+				}
+				break;
+
+				/* member specific command that can be itteratted */
+			case CONF_API_SUB_MEMBER_TARGET:
+				{
+					uint32_t id = 0;
+					uint8_t all = 0;
+					uint8_t last = 0;
+
+					if (argv[argn + 1]) {
+						if (!(id = atoi(argv[argn + 1]))) {
+							all = strcasecmp(argv[argn + 1], "all") ? 0 : 1;
+							last = strcasecmp(argv[argn + 1], "last") ? 0 : 1;
+						}
+					}
+
+					if (all) {
+						conference_member_itterator(conference, stream, (conf_api_member_cmd_t) conf_api_sub_commands[i].pfnapicmd, argv[argn + 2]);
+					} else if (last) {
+						conference_member_t *member = NULL;
+						conference_member_t *last_member = NULL;
+
+						switch_mutex_lock(conference->member_mutex);
+
+						/* find last (oldest) member */
+						member = conference->members;
+						while (member != NULL) {
+							if (last_member == NULL || member->id > last_member->id) {
+								last_member = member;
+							}
+							member = member->next;
+						}
+
+						/* exec functio on last (oldest) member */
+						if (last_member != NULL) {
+							conf_api_member_cmd_t pfn = (conf_api_member_cmd_t) conf_api_sub_commands[i].pfnapicmd;
+							pfn(last_member, stream, argv[argn + 2]);
+						}
+
+						switch_mutex_unlock(conference->member_mutex);
+					} else if (id) {
+						conf_api_member_cmd_t pfn = (conf_api_member_cmd_t) conf_api_sub_commands[i].pfnapicmd;
+						conference_member_t *member = conference_member_get(conference, id);
+
+						if (member != NULL) {
+							pfn(conference_member_get(conference, id), stream, argv[argn + 2]);
+						} else {
+							stream->write_function(stream, "Non-Existant ID %u\n", id);
+						}
+					} else {
+						stream->write_function(stream, conf_api_sub_commands[i].psyntax);
+					}
+				}
+				break;
+
+				/* commands that deals with all text after command */
+			case CONF_API_SUB_ARGS_AS_ONE:
+				{
+					conf_api_text_cmd_t pfn = (conf_api_text_cmd_t) conf_api_sub_commands[i].pfnapicmd;
+					char *start_text;
+					const char *modified_cmdline = cmdline;
+					const char *cmd = conf_api_sub_commands[i].pname;
+
+					if ((start_text = strstr(modified_cmdline, cmd))) {
+						modified_cmdline = start_text + strlen(cmd);
+						while (modified_cmdline && *modified_cmdline && (*modified_cmdline == ' ' || *modified_cmdline == '\t')) {
+							modified_cmdline++;
+						}
+					}
+
+					/* call the command handler */
+					if (pfn(conference, stream, modified_cmdline) != SWITCH_STATUS_SUCCESS) {
+						/* command returned error, so show syntax usage */
+						stream->write_function(stream, conf_api_sub_commands[i].psyntax);
+					}
+				}
+				break;
+			}
+		}
+	}
+
+	if (!found) {
+		stream->write_function(stream, "Confernece command '%s' not found.\n", argv[argn]);
+	} else {
+		status = SWITCH_STATUS_SUCCESS;
+	}
+
+	return status;
+}
+
+/* API Interface Function */
+static switch_status_t conf_api_main(char *buf, switch_core_session_t *session, switch_stream_handle_t *stream)
+{
+	char *lbuf = NULL;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
+	char *http = NULL;
+	int argc;
+	char *argv[25] = { 0 };
+
+	if (!buf) {
+		buf = "help";
+	}
+
+	if (session) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	if (stream->event) {
+		http = switch_event_get_header(stream->event, "http-host");
+	}
+
+	if (http) {
+		/* Output must be to a web browser */
+		stream->write_function(stream, "<pre>\n");
+	}
+
+	if (!(lbuf = strdup(buf))) {
+		return status;
+	}
+
+	argc = switch_separate_string(lbuf, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
+
+	/* try to find a command to execute */
+	if (argc) {
+		conference_obj_t *conference = NULL;
+
+		if ((conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, argv[0]))) {
+			if (switch_thread_rwlock_tryrdlock(conference->rwlock) != SWITCH_STATUS_SUCCESS) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Read Lock Fail\n");
+				goto done;
+			}
+			if (argc >= 2) {
+				conf_api_dispatch(conference, stream, argc, argv, (const char *) buf, 1);
+			} else {
+				stream->write_function(stream, "Conference command, not specified.\nTry 'help'\n");
+			}
+			switch_thread_rwlock_unlock(conference->rwlock);
+
+		} else {
+			/* special case the list command, because it doesn't require a conference argument */
+			if (strcasecmp(argv[0], "list") == 0) {
+				conf_api_sub_list(NULL, stream, argc, argv);
+			} else if (strcasecmp(argv[0], "help") == 0 || strcasecmp(argv[0], "commands") == 0) {
+				stream->write_function(stream, "%s\n", conf_api_interface.syntax);
+			} else if (argv[1] && strcasecmp(argv[1], "dial") == 0) {
+				if (conf_api_sub_dial(NULL, stream, argc, argv) != SWITCH_STATUS_SUCCESS) {
+					/* command returned error, so show syntax usage */
+					stream->write_function(stream, conf_api_sub_commands[CONF_API_COMMAND_DIAL].psyntax);
+				}
+			} else if (strcasecmp(argv[0], "bgdial") == 0) {
+				if (conf_api_sub_bgdial(NULL, stream, argc, argv) != SWITCH_STATUS_SUCCESS) {
+					/* command returned error, so show syntax usage */
+					stream->write_function(stream, conf_api_sub_commands[CONF_API_COMMAND_BGDIAL].psyntax);
+				}
+			} else {
+				stream->write_function(stream, "Conference %s not found\n", argv[0]);
+				//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Conference %s not found\n", argv[0]);
+			}
+		}
+
+	} else {
+		stream->write_function(stream, "No parameters specified.\nTry 'help conference'\n");
+	}
+
+  done:
+	switch_safe_free(lbuf);
+
+	return status;
+
+}
+
+/* outbound call bridge progress call state callback handler */
+static switch_status_t audio_bridge_on_ring(switch_core_session_t *session)
+{
+	switch_channel_t *channel = NULL;
+
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "CUSTOM RING\n");
+
+	/* put the channel in a passive state so we can loop audio to it */
+	switch_channel_set_state(channel, CS_TRANSMIT);
+	return SWITCH_STATUS_FALSE;
+}
+
+static const switch_state_handler_table_t audio_bridge_peer_state_handlers = {
+	/*.on_init */ NULL,
+	/*.on_ring */ audio_bridge_on_ring,
+	/*.on_execute */ NULL,
+	/*.on_hangup */ NULL,
+	/*.on_loopback */ NULL,
+	/*.on_transmit */ NULL,
+	/*.on_hold */ NULL,
+};
+
+
+/* generate an outbound call from the conference */
+static switch_status_t conference_outcall(conference_obj_t * conference,
+										  char *conference_name,
+										  switch_core_session_t *session,
+										  char *bridgeto, uint32_t timeout, char *flags, char *cid_name, char *cid_num, switch_call_cause_t *cause)
+{
+	switch_core_session_t *peer_session = NULL;
+	switch_channel_t *peer_channel;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
+	switch_channel_t *caller_channel = NULL;
+	char appdata[512];
+	int rdlock = 0;
+
+	*cause = SWITCH_CAUSE_NORMAL_CLEARING;
+
+
+	if (conference == NULL) {
+		char *dialstr = switch_mprintf("{ignore_early_media=true}%s", bridgeto);
+
+		status = switch_ivr_originate(NULL, &peer_session, cause, dialstr, 60, NULL, cid_name, cid_num, NULL);
+		switch_safe_free(dialstr);
+
+		if (status != SWITCH_STATUS_SUCCESS) {
+			return status;
+		}
+
+		peer_channel = switch_core_session_get_channel(peer_session);
+		assert(peer_channel != NULL);
+		rdlock = 1;
+		goto callup;
+	}
+
+
+	conference_name = conference->name;
+
+	if (switch_thread_rwlock_tryrdlock(conference->rwlock) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Read Lock Fail\n");
+		return SWITCH_STATUS_FALSE;
+	}
+
+	if (session != NULL) {
+		caller_channel = switch_core_session_get_channel(session);
+
+	}
+
+	if (switch_strlen_zero(cid_name)) {
+		cid_name = conference->caller_id_name;
+	}
+
+	if (switch_strlen_zero(cid_num)) {
+		cid_num = conference->caller_id_number;
+	}
+
+	/* establish an outbound call leg */
+	if (switch_ivr_originate(session,
+							 &peer_session, cause, bridgeto, timeout, &audio_bridge_peer_state_handlers, cid_name, cid_num,
+							 NULL) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot create outgoing channel, cause: %s\n", switch_channel_cause2str(*cause));
+		if (caller_channel) {
+			switch_channel_hangup(caller_channel, *cause);
+		}
+		goto done;
+	}
+
+	rdlock = 1;
+	peer_channel = switch_core_session_get_channel(peer_session);
+	assert(peer_channel != NULL);
+
+	/* make sure the conference still exists */
+	if (!switch_test_flag(conference, CFLAG_RUNNING)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Conference is gone now, nevermind..\n");
+		if (caller_channel) {
+			switch_channel_hangup(caller_channel, SWITCH_CAUSE_NO_ROUTE_DESTINATION);
+		}
+		switch_channel_hangup(peer_channel, SWITCH_CAUSE_NO_ROUTE_DESTINATION);
+		goto done;
+	}
+
+	if (caller_channel && switch_channel_test_flag(peer_channel, CF_ANSWERED)) {
+		switch_channel_answer(caller_channel);
+	}
+
+  callup:
+
+	/* if the outbound call leg is ready */
+	if (switch_channel_test_flag(peer_channel, CF_ANSWERED) || switch_channel_test_flag(peer_channel, CF_EARLY_MEDIA)) {
+		switch_caller_extension_t *extension = NULL;
+
+		/* build an extension name object */
+		if ((extension = switch_caller_extension_new(peer_session, conference_name, conference_name)) == 0) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "memory error!\n");
+			status = SWITCH_STATUS_MEMERR;
+			goto done;
+		}
+		/* add them to the conference */
+		if (flags && !strcasecmp(flags, "none")) {
+			snprintf(appdata, sizeof(appdata), "%s+flags{%s}", conference_name, flags);
+			switch_caller_extension_add_application(peer_session, extension, (char *) global_app_name, appdata);
+		} else {
+			switch_caller_extension_add_application(peer_session, extension, (char *) global_app_name, conference_name);
+		}
+
+		switch_channel_set_caller_extension(peer_channel, extension);
+		switch_channel_set_state(peer_channel, CS_EXECUTE);
+
+	} else {
+		switch_channel_hangup(peer_channel, SWITCH_CAUSE_NO_ANSWER);
+		status = SWITCH_STATUS_FALSE;
+		goto done;
+	}
+
+  done:
+	if (conference) {
+		switch_thread_rwlock_unlock(conference->rwlock);
+	}
+	if (rdlock && peer_session) {
+		switch_core_session_rwunlock(peer_session);
+	}
+
+	return status;
+}
+
+struct bg_call {
+	conference_obj_t *conference;
+	switch_core_session_t *session;
+	char *bridgeto;
+	uint32_t timeout;
+	char *flags;
+	char *cid_name;
+	char *cid_num;
+	char *conference_name;
+};
+
+static void *SWITCH_THREAD_FUNC conference_outcall_run(switch_thread_t * thread, void *obj)
+{
+	struct bg_call *call = (struct bg_call *) obj;
+
+	if (call) {
+		switch_call_cause_t cause;
+		switch_event_t *event;
+
+		conference_outcall(call->conference, call->conference_name, 
+						   call->session, call->bridgeto, call->timeout, call->flags, call->cid_name, call->cid_num, &cause);
+
+		if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, CONF_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) {
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Conference-Name", "%s", call->conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Action", "bgdial-result");
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Result", "%s", switch_channel_cause2str(cause));
+			switch_event_fire(&event);
+		}
+		switch_safe_free(call->bridgeto);
+		switch_safe_free(call->flags);
+		switch_safe_free(call->cid_name);
+		switch_safe_free(call->cid_num);
+		switch_safe_free(call->conference_name);
+		switch_safe_free(call);
+	}
+
+	return NULL;
+}
+
+static switch_status_t conference_outcall_bg(conference_obj_t * conference,
+											 char *conference_name,
+											 switch_core_session_t *session, char *bridgeto, uint32_t timeout, char *flags, char *cid_name, char *cid_num)
+{
+	struct bg_call *call = NULL;
+
+	if ((call = malloc(sizeof(*call)))) {
+		switch_thread_t *thread;
+		switch_threadattr_t *thd_attr = NULL;
+
+		memset(call, 0, sizeof(*call));
+		call->conference = conference;
+		call->session = session;
+		call->timeout = timeout;
+
+		if (bridgeto) {
+			call->bridgeto = strdup(bridgeto);
+		}
+		if (flags) {
+			call->flags = strdup(flags);
+		}
+		if (cid_name) {
+			call->cid_name = strdup(cid_name);
+		}
+		if (cid_num) {
+			call->cid_num = strdup(cid_num);
+		}
+
+		if (conference_name) {
+			call->conference_name = strdup(conference_name);
+		}
+
+
+		switch_threadattr_create(&thd_attr, conference->pool);
+		switch_threadattr_detach_set(thd_attr, 1);
+		switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
+		switch_thread_create(&thread, thd_attr, conference_outcall_run, call, conference->pool);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Lanuching BG Thread for outcall\n");
+
+		return SWITCH_STATUS_SUCCESS;
+	}
+
+	return SWITCH_STATUS_MEMERR;
+}
+
+/* Play a file */
+static switch_status_t conference_local_play_file(conference_obj_t * conference,
+												  switch_core_session_t *session, char *path, uint32_t leadin)
+{
+	uint32_t x = 0;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
+	switch_channel_t *channel;
+	char *expanded = NULL;
+
+	/* generate some space infront of the file to be played */
+	for (x = 0; x < leadin; x++) {
+		switch_frame_t *read_frame;
+		switch_status_t status = switch_core_session_read_frame(session, &read_frame, 1000, 0);
+
+		if (!SWITCH_READ_ACCEPTABLE(status)) {
+			break;
+		}
+	}
+
+	/* if all is well, really play the file */
+	if (status == SWITCH_STATUS_SUCCESS) {
+		char *dpath = NULL;
+	
+		channel = switch_core_session_get_channel(session);
+		if ((expanded = switch_channel_expand_variables(channel, path)) != path) {
+			path = expanded;
+		} else {
+			expanded = NULL;
+		}
+
+		if (!strncasecmp(path, "say:", 4)) {
+			if (!(conference->tts_engine && conference->tts_voice)) {
+				status = SWITCH_STATUS_FALSE;
+			} else {
+				status = switch_ivr_speak_text(session, conference->tts_engine, conference->tts_voice, 0, path + 4, NULL);
+			}
+			goto done;
+		}
+			
+
+		if (conference->sound_prefix) {
+			if (!(dpath = switch_mprintf("%s/%s", conference->sound_prefix, path))) {
+				status = SWITCH_STATUS_MEMERR;
+				goto done;
+			}
+			path = dpath;
+		}
+
+		status = switch_ivr_play_file(session, NULL, path, NULL);
+		switch_safe_free(dpath);
+	}
+
+ done:
+	switch_safe_free(expanded);
+	
+	return status;
+}
+
+static void set_mflags(char *flags, member_flag_t * f)
+{
+	if (flags) {
+		if (strstr(flags, "mute")) {
+			*f &= ~MFLAG_CAN_SPEAK;
+		} else if (strstr(flags, "deaf")) {
+			*f &= ~MFLAG_CAN_HEAR;
+		} else if (strstr(flags, "waste")) {
+			*f |= MFLAG_WASTE_BANDWIDTH;
+		}
+	}
+
+}
+
+static void conference_auto_function(switch_core_session_t *session, char *data)
+{
+	switch_channel_t *channel = NULL;
+	call_list_t *call_list, *np;
+	char *addition = (char *) data;
+
+	channel = switch_core_session_get_channel(session);
+    assert(channel != NULL);
+
+	call_list = switch_channel_get_private(channel, "_conference_autocall_list_");
+
+	if (switch_strlen_zero(addition)) {
+		call_list = NULL;
+	} else {
+		np = switch_core_session_alloc(session, sizeof(*np));
+		assert(np != NULL);
+
+		np->string = switch_core_session_strdup(session, addition);
+		if (call_list) {
+			np->next = call_list;
+			np->itteration = call_list->itteration + 1;
+		} else {
+			np->itteration = 1;
+		}
+
+		call_list = np;
+		
+	}
+	
+	switch_channel_set_private(channel, "_conference_autocall_list_", call_list);
+	
+
+}
+
+/* Application interface function that is called from the dialplan to join the channel to a conference */
+static void conference_function(switch_core_session_t *session, char *data)
+{
+	switch_codec_t *read_codec = NULL;
+	uint32_t flags = 0;
+	conference_member_t member = { 0 };
+	conference_obj_t *conference = NULL;
+	switch_channel_t *channel = NULL;
+	char *mydata = switch_core_session_strdup(session, data);
+	char *conf_name = NULL;
+	char *bridge_prefix = "bridge:";
+	char *flags_prefix = "+flags{";
+	char *bridgeto = NULL;
+	char *profile_name = NULL;
+	switch_xml_t cxml = NULL, cfg = NULL, profiles = NULL;
+	char *flags_str;
+	member_flag_t mflags = 0;
+	switch_core_session_message_t msg = { 0 };
+	uint8_t rl = 0, isbr = 0;
+	char *dpin = NULL;
+	conf_xml_cfg_t xml_cfg = { 0 };
+	char *params = NULL;
+
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
+
+	if (!mydata) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
+		return;
+	}
+
+
+	/* is this a bridging conference ? */
+	if (!strncasecmp(mydata, bridge_prefix, strlen(bridge_prefix))) {
+		isbr = 1;
+		mydata += strlen(bridge_prefix);
+		if ((bridgeto = strchr(mydata, ':'))) {
+			*bridgeto++ = '\0';
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Config Error!\n");
+			goto done;
+		}
+	}
+
+	conf_name = mydata;
+
+	/* is there a conference pin ? */
+	if ((dpin = strchr(conf_name, '+'))) {
+		*dpin++ = '\0';
+	}
+
+	/* is there profile specification ? */
+	if ((profile_name = strchr(conf_name, '@'))) {
+		*profile_name++ = '\0';
+	} else {
+		profile_name = "default";
+	}
+
+	params = switch_mprintf("conf_name=%s&profile_name=%s", conf_name, profile_name);
+
+	/* Open the config from the xml registry */
+	if (!(cxml = switch_xml_open_cfg(global_cf_name, &cfg, params))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", global_cf_name);
+		goto done;
+	}
+
+	if ((profiles = switch_xml_child(cfg, "profiles"))) {
+		xml_cfg.profile = switch_xml_find_child(profiles, "profile", "name", profile_name);
+	}
+
+	if (!xml_cfg.profile) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find profile: %s\n", profile_name);
+		switch_xml_free(cxml);
+		cxml = NULL;
+		goto done;
+	}
+
+	xml_cfg.controls = switch_xml_child(cfg, "caller-controls");
+
+	/* if this is a bridging call, and it's not a duplicate, build a */
+	/* conference object, and skip pin handling, and locked checking */
+	if (isbr) {
+		char *uuid = switch_core_session_get_uuid(session);
+
+		if (!strcmp(conf_name, "_uuid_")) {
+			conf_name = uuid;
+		}
+
+		if ((conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, conf_name))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Conference %s already exists!\n", conf_name);
+			goto done;
+		}
+
+		/* Create the conference object. */
+		conference = conference_new(conf_name, xml_cfg, NULL);
+
+		if (!conference) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
+			goto done;
+		}
+
+		/* Set the minimum number of members (once you go above it you cannot go below it) */
+		conference->min = 2;
+
+		/* if the dialplan specified a pin, override the profile's value */
+		if (dpin) {
+			conference->pin = switch_core_strdup(conference->pool, dpin);
+		}
+
+		/* Indicate the conference is dynamic */
+		switch_set_flag_locked(conference, CFLAG_DYNAMIC);
+
+		/* Start the conference thread for this conference */
+		launch_conference_thread(conference);
+
+	} else {
+		/* if the conference exists, get the pointer to it */
+		if (!(conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, conf_name))) {
+			/* couldn't find the conference, create one */
+			conference = conference_new(conf_name, xml_cfg, NULL);
+			
+			if (!conference) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
+				goto done;
+			}
+
+			/* if the dialplan specified a pin, override the profile's value */
+			if (dpin) {
+				conference->pin = switch_core_strdup(conference->pool, dpin);
+			}
+
+			/* Set the minimum number of members (once you go above it you cannot go below it) */
+			conference->min = 1;
+
+			/* Indicate the conference is dynamic */
+			switch_set_flag_locked(conference, CFLAG_DYNAMIC);
+
+			/* Start the conference thread for this conference */
+			launch_conference_thread(conference);
+		}
+
+		/* acquire a read lock on the thread so it can't leave without us */
+		if (switch_thread_rwlock_tryrdlock(conference->rwlock) != SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Read Lock Fail\n");
+			goto done;
+		}
+		rl++;
+
+		/* if this is not an outbound call, deal with conference pins */
+		if (!switch_channel_test_flag(channel, CF_OUTBOUND) && conference->pin) {
+			char pin_buf[80] = "";
+			int pin_retries = 3;	/* XXX - this should be configurable - i'm too lazy to do it right now... */
+			int pin_valid = 0;
+			switch_status_t status = SWITCH_STATUS_SUCCESS;
+
+			/* Answer the channel */
+			switch_channel_answer(channel);
+
+			while (!pin_valid && pin_retries && status == SWITCH_STATUS_SUCCESS) {
+
+				/* be friendly */
+				if (conference->pin_sound) {
+					conference_local_play_file(conference, session, conference->pin_sound, 20);
+				}
+				/* wait for them if neccessary */
+				if (strlen(pin_buf) < strlen(conference->pin)) {
+					char *buf = pin_buf + strlen(pin_buf);
+					char term = '\0';
+
+					status = switch_ivr_collect_digits_count(session,
+															 buf,
+															 sizeof(pin_buf) - (unsigned int) strlen(pin_buf),
+															 (unsigned int) strlen(conference->pin) - (unsigned int) strlen(pin_buf), "#", &term, 10000);
+				}
+
+				pin_valid = (status == SWITCH_STATUS_SUCCESS && strcmp(pin_buf, conference->pin) == 0);
+				if (!pin_valid) {
+					/* zero the collected pin */
+					memset(pin_buf, 0, sizeof(pin_buf));
+
+					/* more friendliness */
+					if (conference->bad_pin_sound) {
+						conference_local_play_file(conference, session, conference->bad_pin_sound, 20);
+					}
+				}
+				pin_retries--;
+			}
+
+			if (!pin_valid) {
+				goto done;
+			}
+		}
+
+		if (conference->special_announce) {
+			conference_local_play_file(conference, session, conference->special_announce, CONF_DEFAULT_LEADIN);
+		}
+
+		/* don't allow more callers if the conference is locked, unless we invited them */
+		if (switch_test_flag(conference, CFLAG_LOCKED) && !switch_channel_test_flag(channel, CF_OUTBOUND)) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Conference %s is locked.\n", conf_name);
+			if (conference->locked_sound) {
+				/* Answer the channel */
+				switch_channel_answer(channel);
+				conference_local_play_file(conference, session, conference->locked_sound, 20);
+			}
+			goto done;
+		}
+
+		/* dont allow more callers than the max_members allows for -- I explicitly didnt allow outbound calls
+		 * someone else can add that (see above) if they feel that outbound calls should be able to violate the
+		 * max_members limit -- TRX
+		 */
+		if ((conference->max_members > 0) && (conference->count >= conference->max_members)) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Conference %s is full.\n", conf_name);
+			if (conference->maxmember_sound) {
+				/* Answer the channel */
+				switch_channel_answer(channel);
+				conference_local_play_file(conference, session, conference->maxmember_sound, 20);
+			}
+			goto done;
+		}
+
+	}
+
+	/* Release the config registry handle */
+	if (cxml) {
+		switch_xml_free(cxml);
+		cxml = NULL;
+	}
+
+	/* if we're using "bridge:" make an outbound call and bridge it in */
+	if (!switch_strlen_zero(bridgeto) && strcasecmp(bridgeto, "none")) {
+		switch_call_cause_t cause;
+		if (conference_outcall(conference, NULL, session, bridgeto, 60, NULL, NULL, NULL, &cause) != SWITCH_STATUS_SUCCESS) {
+			goto done;
+		}
+	} else {
+		/* if we're not using "bridge:" set the conference answered flag */
+		/* and this isn't an outbound channel, answer the call */
+		if (!switch_channel_test_flag(channel, CF_OUTBOUND))
+			switch_set_flag(conference, CFLAG_ANSWERED);
+	}
+
+	/* Save the original read codec. */
+	read_codec = switch_core_session_get_read_codec(session);
+	member.native_rate = read_codec->implementation->samples_per_second;
+	member.pool = switch_core_session_get_pool(session);
+
+	/* Setup a Signed Linear codec for reading audio. */
+	if (switch_core_codec_init(&member.read_codec,
+							   "L16",
+							   NULL,
+							   read_codec->implementation->samples_per_second,
+							   read_codec->implementation->microseconds_per_frame / 1000,
+							   1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL, member.pool) == SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
+						  "Raw Codec Activation Success L16@%uhz 1 channel %dms\n",
+						  read_codec->implementation->samples_per_second, read_codec->implementation->microseconds_per_frame / 1000);
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Failed L16@%uhz 1 channel %dms\n",
+						  read_codec->implementation->samples_per_second, read_codec->implementation->microseconds_per_frame / 1000);
+		flags = 0;
+		goto done;
+	}
+
+	if (read_codec->implementation->samples_per_second != conference->rate) {
+		switch_audio_resampler_t **resampler = read_codec->implementation->samples_per_second > conference->rate ?
+			&member.read_resampler : &member.mux_resampler;
+
+		if (switch_resample_create(resampler,
+								   read_codec->implementation->samples_per_second,
+								   read_codec->implementation->samples_per_second * 20,
+								   conference->rate, conference->rate * 20, member.pool) != SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Unable to crete resampler!\n");
+			goto done;
+		}
+
+		/* Setup an audio buffer for the resampled audio */
+		if (switch_buffer_create_dynamic(&member.resample_buffer, CONF_DBLOCK_SIZE, CONF_DBUFFER_SIZE, CONF_DBUFFER_MAX)
+			!= SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error Creating Audio Buffer!\n");
+			goto done;
+		}
+	}
+	/* Setup a Signed Linear codec for writing audio. */
+	if (switch_core_codec_init(&member.write_codec,
+							   "L16",
+							   NULL,
+							   read_codec->implementation->samples_per_second,
+							   read_codec->implementation->microseconds_per_frame / 1000,
+							   1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL, member.pool) == SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
+						  "Raw Codec Activation Success L16@%uhz 1 channel %dms\n",
+						  read_codec->implementation->samples_per_second, read_codec->implementation->microseconds_per_frame / 1000);
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Failed L16@%uhz 1 channel %dms\n",
+						  read_codec->implementation->samples_per_second, read_codec->implementation->microseconds_per_frame / 1000);
+		flags = 0;
+		goto codec_done2;
+	}
+
+	/* Setup an audio buffer for the incoming audio */
+	if (switch_buffer_create_dynamic(&member.audio_buffer, CONF_DBLOCK_SIZE, CONF_DBUFFER_SIZE, CONF_DBUFFER_MAX) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error Creating Audio Buffer!\n");
+		goto codec_done1;
+	}
+
+	/* Setup an audio buffer for the outgoing audio */
+	if (switch_buffer_create_dynamic(&member.mux_buffer, CONF_DBLOCK_SIZE, CONF_DBUFFER_SIZE, CONF_DBUFFER_MAX) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error Creating Audio Buffer!\n");
+		goto codec_done1;
+	}
+
+	/* Prepare MUTEXS */
+	member.id = next_member_id();
+	member.session = session;
+	switch_mutex_init(&member.flag_mutex, SWITCH_MUTEX_NESTED, member.pool);
+	switch_mutex_init(&member.audio_in_mutex, SWITCH_MUTEX_NESTED, member.pool);
+	switch_mutex_init(&member.audio_out_mutex, SWITCH_MUTEX_NESTED, member.pool);
+
+	/* Install our Signed Linear codec so we get the audio in that format */
+	switch_core_session_set_read_codec(member.session, &member.read_codec);
+
+	if ((flags_str = strstr(mydata, flags_prefix))) {
+		char *p;
+
+		*flags_str = '\0';
+		flags_str += strlen(flags_prefix);
+		if ((p = strchr(flags_str, '}'))) {
+			*p = '\0';
+		}
+	}
+
+	mflags = conference->mflags;
+	set_mflags(flags_str, &mflags);
+	switch_set_flag_locked((&member), MFLAG_RUNNING | mflags);
+
+	/* Add the caller to the conference */
+	if (conference_add_member(conference, &member) != SWITCH_STATUS_SUCCESS) {
+		goto codec_done1;
+	}
+
+	msg.from = __FILE__;
+
+	/* Tell the channel we are going to be in a bridge */
+	msg.message_id = SWITCH_MESSAGE_INDICATE_BRIDGE;
+	switch_core_session_receive_message(session, &msg);
+
+	/* Run the confernece loop */
+	conference_loop_output(&member);
+	switch_channel_set_private(channel, "_conference_autocall_list_", NULL);
+	
+	/* Tell the channel we are no longer going to be in a bridge */
+	msg.message_id = SWITCH_MESSAGE_INDICATE_UNBRIDGE;
+	switch_core_session_receive_message(session, &msg);
+
+	/* Remove the caller from the conference */
+	conference_del_member(member.conference, &member);
+
+	/* Put the original codec back */
+	switch_core_session_set_read_codec(member.session, read_codec);
+
+	/* Clean Up.  codec_done(X): is for error situations after the codecs were setup and done: is for situations before */
+  codec_done1:
+	switch_core_codec_destroy(&member.read_codec);
+  codec_done2:
+	switch_core_codec_destroy(&member.write_codec);
+  done:
+	switch_safe_free(params);
+	switch_buffer_destroy(&member.resample_buffer);
+	switch_buffer_destroy(&member.audio_buffer);
+	switch_buffer_destroy(&member.mux_buffer);
+
+	/* Release the config registry handle */
+	if (cxml) {
+		switch_xml_free(cxml);
+	}
+
+	if (switch_test_flag(&member, MFLAG_KICKED) && conference->kicked_sound) {
+		char *toplay = NULL;
+		char *dfile = NULL;
+
+		if (conference->sound_prefix) {
+			assert((dfile = switch_mprintf("%s/%s", conference->sound_prefix, conference->kicked_sound)));
+			toplay = dfile;
+		} else {
+			toplay = conference->kicked_sound;
+		}
+
+		switch_ivr_play_file(session, NULL, toplay, NULL);
+		switch_safe_free(dfile);
+	}
+
+	switch_core_session_reset(session);
+
+	/* release the readlock */
+	if (rl) {
+		switch_thread_rwlock_unlock(conference->rwlock);
+	}
+}
+
+/* Create a thread for the conference and launch it */
+static void launch_conference_thread(conference_obj_t * conference)
+{
+	switch_thread_t *thread;
+	switch_threadattr_t *thd_attr = NULL;
+
+	switch_set_flag_locked(conference, CFLAG_RUNNING);
+	switch_threadattr_create(&thd_attr, conference->pool);
+	switch_threadattr_detach_set(thd_attr, 1);
+	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
+	switch_mutex_lock(globals.hash_mutex);
+	switch_core_hash_insert(globals.conference_hash, conference->name, conference);
+	switch_mutex_unlock(globals.hash_mutex);
+	switch_thread_create(&thread, thd_attr, conference_thread_run, conference, conference->pool);
+}
+
+static void launch_conference_record_thread(conference_obj_t * conference, char *path)
+{
+	switch_thread_t *thread;
+	switch_threadattr_t *thd_attr = NULL;
+	switch_memory_pool_t *pool;
+	conference_record_t *rec;
+
+	/* Setup a memory pool to use. */
+	if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
+	}
+
+	/* Create a node object */
+	if (!(rec = switch_core_alloc(pool, sizeof(*rec)))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Alloc Failure\n");
+		switch_core_destroy_memory_pool(&pool);
+	}
+
+	rec->conference = conference;
+	rec->path = switch_core_strdup(pool, path);
+	rec->pool = pool;
+
+	switch_threadattr_create(&thd_attr, rec->pool);
+	switch_threadattr_detach_set(thd_attr, 1);
+	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
+	switch_thread_create(&thread, thd_attr, conference_record_thread_run, rec, rec->pool);
+}
+
+static const switch_application_interface_t conference_autocall_application_interface = {
+	/*.interface_name */ "conference_set_auto_outcall",
+	/*.application_function */ conference_auto_function,
+	NULL, NULL, NULL,
+	/* flags */ SAF_NONE,
+	/*.next */
+};
+
+static const switch_application_interface_t conference_application_interface = {
+	/*.interface_name */ global_app_name,
+	/*.application_function */ conference_function,
+	NULL, NULL, NULL,
+	/* flags */ SAF_NONE,
+	/*.next */ &conference_autocall_application_interface
+};
+
+static switch_api_interface_t conf_api_interface = {
+	/*.interface_name */ "conference",
+	/*.desc */ "Conference module commands",
+	/*.function */ conf_api_main,
+	/*.syntax *//* see switch_module_load, this is built on the fly */
+	/*.next */
+};
+
+static switch_status_t chat_send(char *proto, char *from, char *to, char *subject, char *body, char *hint)
+{
+	char name[512] = "", *p, *lbuf = NULL;
+	switch_chat_interface_t *ci;
+	conference_obj_t *conference = NULL;
+	switch_stream_handle_t stream = { 0 };
+
+	if ((p = strchr(to, '+'))) {
+		to = ++p;
+	}
+
+	if (!body) {
+		return SWITCH_STATUS_SUCCESS;
+	}
 
-    return status;
+	if (!(ci = switch_loadable_module_get_chat_interface(proto))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Chat Interface [%s]!\n", proto);
+	}
+
+
+	if ((p = strchr(to, '@'))) {
+		switch_copy_string(name, to, ++p - to);
+	} else {
+		switch_copy_string(name, to, sizeof(name));
+	}
+
+	if (!(conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, name))) {
+		ci->chat_send(CONF_CHAT_PROTO, to, hint && strchr(hint, '/') ? hint : from, "", "Conference not active.", NULL);
+		return SWITCH_STATUS_FALSE;
+	}
+
+	SWITCH_STANDARD_STREAM(stream);
+
+	if (body != NULL && (lbuf = strdup(body))) {
+		int argc;
+		char *argv[25];
+
+		memset(argv, 0, sizeof(argv));
+		argc = switch_separate_string(lbuf, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
+
+		/* try to find a command to execute */
+		if (argc) {
+			/* special case list */
+			if (strcasecmp(argv[0], "list") == 0) {
+				conference_list_pretty(conference, &stream);
+				/* provide help */
+			}
+#if 0
+			else {
+				if (strcasecmp(argv[0], "help") == 0 || strcasecmp(argv[0], "commands") == 0) {
+					stream.write_function(&stream, "%s\n", conf_api_interface.syntax);
+					/* find a normal command */
+				} else {
+					conf_api_dispatch(conference, &stream, argc, argv, (const char *) body, 0);
+				}
+			}
+#endif
+		} else {
+			stream.write_function(&stream, "No parameters specified.\nTry 'help'\n");
+		}
+	}
+	switch_safe_free(lbuf);
+
+	ci->chat_send(CONF_CHAT_PROTO, to, from, "", stream.data, NULL);
+	switch_safe_free(stream.data);
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+static const switch_chat_interface_t conference_chat_interface = {
+	/*.name */ CONF_CHAT_PROTO,
+	/*.chat_send */ chat_send,
+
+};
+
+static switch_loadable_module_interface_t conference_module_interface = {
+	/*.module_name */ modname,
+	/*.endpoint_interface */ NULL,
+	/*.timer_interface */ NULL,
+	/*.dialplan_interface */ NULL,
+	/*.codec_interface */ NULL,
+	/*.application_interface */ &conference_application_interface,
+	/*.api_interface */ &conf_api_interface,
+	/*.file_interface */ NULL,
+	/*.speech_interface */ NULL,
+	/*.directory_interface */ NULL,
+	/*.chat_interface */ &conference_chat_interface
+};
+
+static switch_status_t conf_default_controls(conference_obj_t * conference)
+{
+	switch_status_t status = SWITCH_STATUS_FALSE;
+	uint32_t i;
+	caller_control_action_t *action;
+
+	assert(conference != NULL);
+
+	for (i = 0, status = SWITCH_STATUS_SUCCESS; status == SWITCH_STATUS_SUCCESS && i < CCFNTBL_QTY; i++) {
+		if (!switch_strlen_zero(ccfntbl[i].digits)) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
+							  "Installing default caller control action '%s' bound to '%s'.\n", ccfntbl[i].key, ccfntbl[i].digits);
+			action = (caller_control_action_t *) switch_core_alloc(conference->pool, sizeof(caller_control_action_t));
+			if (action != NULL) {
+				action->fndesc = &ccfntbl[i];
+				action->data = NULL;
+				status = switch_ivr_digit_stream_parser_set_event(conference->dtmf_parser, ccfntbl[i].digits, action);
+			} else {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+								  "unable to alloc memory for caller control binding '%s' to '%s'\n", ccfntbl[i].key, ccfntbl[i].digits);
+				status = SWITCH_STATUS_MEMERR;
+			}
+		}
+	}
+
+
+	return status;
+}
+
+static switch_status_t conference_new_install_caller_controls_custom(conference_obj_t * conference, switch_xml_t xml_controls, switch_xml_t xml_menus)
+{
+	switch_status_t status = SWITCH_STATUS_FALSE;
+	switch_xml_t xml_kvp;
+
+	assert(conference != NULL);
+	assert(xml_controls != NULL);
+
+	/* parse the controls tree for caller control digit strings */
+	for (xml_kvp = switch_xml_child(xml_controls, "control"); xml_kvp; xml_kvp = xml_kvp->next) {
+		char *key = (char *) switch_xml_attr(xml_kvp, "action");
+		char *val = (char *) switch_xml_attr(xml_kvp, "digits");
+		char *data = (char *) switch_xml_attr_soft(xml_kvp, "data");
+
+		if (!switch_strlen_zero(key) && !switch_strlen_zero(val)) {
+			uint32_t i;
+
+			/* scan through all of the valid actions, and if found, */
+			/* set the new caller control action digit string, then */
+			/* stop scanning the table, and go to the next xml kvp. */
+			for (i = 0, status = SWITCH_STATUS_NOOP; i < CCFNTBL_QTY && status == SWITCH_STATUS_NOOP; i++) {
+
+				if (strcasecmp(ccfntbl[i].key, key) == 0) {
+
+					caller_control_action_t *action;
+
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Installing caller control action '%s' bound to '%s'.\n", key, val);
+					action = (caller_control_action_t *) switch_core_alloc(conference->pool, sizeof(caller_control_action_t));
+					if (action != NULL) {
+						action->fndesc = &ccfntbl[i];
+						action->data = (void *) switch_core_strdup(conference->pool, data);
+						action->binded_dtmf = switch_core_strdup(conference->pool, val);
+						status = switch_ivr_digit_stream_parser_set_event(conference->dtmf_parser, val, action);
+					} else {
+						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+										  "unable to alloc memory for caller control binding '%s' to '%s'\n", ccfntbl[i].key, ccfntbl[i].digits);
+						status = SWITCH_STATUS_MEMERR;
+					}
+				}
+			}
+			if (status == SWITCH_STATUS_NOOP) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid caller control action name '%s'.\n", key);
+			}
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid caller control config entry pair action = '%s' digits = '%s'\n", key, val);
+		}
+	}
+
+	return status;
 }
 
 /* create a new conferene with a specific profile */
 static conference_obj_t *conference_new(char *name, conf_xml_cfg_t cfg, switch_memory_pool_t *pool)
 {
-    conference_obj_t *conference;
-    switch_xml_t xml_kvp;
-    char *rate_name = NULL;
-    char *interval_name = NULL;
-    char *timer_name = NULL;
-    char *domain = NULL;
-    char *tts_engine = NULL;
-    char *tts_voice = NULL;
-    char *enter_sound = NULL;
-    char *sound_prefix = NULL;
-    char *exit_sound = NULL;
-    char *alone_sound = NULL;
-    char *ack_sound = NULL;
-    char *nack_sound = NULL;
-    char *muted_sound = NULL;
-    char *unmuted_sound = NULL;
-    char *locked_sound = NULL;
-    char *is_locked_sound = NULL;
-    char *is_unlocked_sound = NULL;
-    char *kicked_sound = NULL;
-    char *pin = NULL;
-    char *pin_sound = NULL; 
-    char *bad_pin_sound = NULL;
-    char *energy_level = NULL;
-    char *caller_id_name = NULL;
-    char *caller_id_number = NULL;
-    char *caller_controls = NULL;
+	conference_obj_t *conference;
+	switch_xml_t xml_kvp;
+	char *rate_name = NULL;
+	char *interval_name = NULL;
+	char *timer_name = NULL;
+	char *domain = NULL;
+	char *tts_engine = NULL;
+	char *tts_voice = NULL;
+	char *enter_sound = NULL;
+	char *sound_prefix = NULL;
+	char *exit_sound = NULL;
+	char *alone_sound = NULL;
+	char *ack_sound = NULL;
+	char *nack_sound = NULL;
+	char *muted_sound = NULL;
+	char *unmuted_sound = NULL;
+	char *locked_sound = NULL;
+	char *is_locked_sound = NULL;
+	char *is_unlocked_sound = NULL;
+	char *kicked_sound = NULL;
+	char *pin = NULL;
+	char *pin_sound = NULL;
+	char *bad_pin_sound = NULL;
+	char *energy_level = NULL;
+	char *caller_id_name = NULL;
+	char *caller_id_number = NULL;
+	char *caller_controls = NULL;
 	char *member_flags = NULL;
-    uint32_t max_members = 0;
-    uint32_t anounce_count = 0;
-    char *maxmember_sound = NULL;
-    uint32_t rate = 8000, interval = 20;
-    switch_status_t status;
-
-    /* Validate the conference name */
-    if (switch_strlen_zero(name)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Record! no name.\n");
-        return NULL;
-    }
-
-    /* parse the profile tree for param values */
-    for (xml_kvp = switch_xml_child(cfg.profile, "param"); xml_kvp; xml_kvp = xml_kvp->next) {
-        char *var = (char *) switch_xml_attr_soft(xml_kvp, "name");
-        char *val = (char *) switch_xml_attr_soft(xml_kvp, "value");
-        char buf[128] = "";
-        char *p;
-
-        if ((p = strchr(var, '_'))) {
-            switch_copy_string(buf, var, sizeof(buf));
-            for(p = buf; *p; p++) {
-                if (*p == '_') {
-                    *p = '-';
-                }
-            }
-            var = buf;
-        }
-
-        if (!strcasecmp(var, "rate")) {
-            rate_name = val;
-        } else if (!strcasecmp(var, "domain")) {
-            domain = val;
-        } else if (!strcasecmp(var, "interval")) {
-            interval_name = val;
-        } else if (!strcasecmp(var, "timer-name")) {
-            timer_name = val;
-        } else if (!strcasecmp(var, "tts-engine")) {
-            tts_engine = val;
-        } else if (!strcasecmp(var, "tts-voice")) {
-            tts_voice = val;
-        } else if (!strcasecmp(var, "enter-sound")) {
-            enter_sound = val;
-        } else if (!strcasecmp(var, "exit-sound")) {
-            exit_sound = val;
-        } else if (!strcasecmp(var, "alone-sound")) {
-            alone_sound = val;
-        } else if (!strcasecmp(var, "ack-sound")) {
-            ack_sound = val;
-        } else if (!strcasecmp(var, "nack-sound")) {
-            nack_sound = val;
-        } else if (!strcasecmp(var, "muted-sound")) {
-            muted_sound = val;
-        } else if (!strcasecmp(var, "unmuted-sound")) {
-            unmuted_sound = val;
-        } else if (!strcasecmp(var, "locked-sound")) {
-            locked_sound = val;
-        } else if (!strcasecmp(var, "is-locked-sound")) {
-            is_locked_sound = val;
-        } else if (!strcasecmp(var, "is-unlocked-sound")) {
-            is_unlocked_sound = val;
-        } else if (!strcasecmp(var, "member-flags")) {
+	uint32_t max_members = 0;
+	uint32_t anounce_count = 0;
+	char *maxmember_sound = NULL;
+	uint32_t rate = 8000, interval = 20;
+	switch_status_t status;
+
+	/* Validate the conference name */
+	if (switch_strlen_zero(name)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Record! no name.\n");
+		return NULL;
+	}
+
+	/* parse the profile tree for param values */
+	for (xml_kvp = switch_xml_child(cfg.profile, "param"); xml_kvp; xml_kvp = xml_kvp->next) {
+		char *var = (char *) switch_xml_attr_soft(xml_kvp, "name");
+		char *val = (char *) switch_xml_attr_soft(xml_kvp, "value");
+		char buf[128] = "";
+		char *p;
+
+		if ((p = strchr(var, '_'))) {
+			switch_copy_string(buf, var, sizeof(buf));
+			for (p = buf; *p; p++) {
+				if (*p == '_') {
+					*p = '-';
+				}
+			}
+			var = buf;
+		}
+
+		if (!strcasecmp(var, "rate")) {
+			rate_name = val;
+		} else if (!strcasecmp(var, "domain")) {
+			domain = val;
+		} else if (!strcasecmp(var, "interval")) {
+			interval_name = val;
+		} else if (!strcasecmp(var, "timer-name")) {
+			timer_name = val;
+		} else if (!strcasecmp(var, "tts-engine")) {
+			tts_engine = val;
+		} else if (!strcasecmp(var, "tts-voice")) {
+			tts_voice = val;
+		} else if (!strcasecmp(var, "enter-sound")) {
+			enter_sound = val;
+		} else if (!strcasecmp(var, "exit-sound")) {
+			exit_sound = val;
+		} else if (!strcasecmp(var, "alone-sound")) {
+			alone_sound = val;
+		} else if (!strcasecmp(var, "ack-sound")) {
+			ack_sound = val;
+		} else if (!strcasecmp(var, "nack-sound")) {
+			nack_sound = val;
+		} else if (!strcasecmp(var, "muted-sound")) {
+			muted_sound = val;
+		} else if (!strcasecmp(var, "unmuted-sound")) {
+			unmuted_sound = val;
+		} else if (!strcasecmp(var, "locked-sound")) {
+			locked_sound = val;
+		} else if (!strcasecmp(var, "is-locked-sound")) {
+			is_locked_sound = val;
+		} else if (!strcasecmp(var, "is-unlocked-sound")) {
+			is_unlocked_sound = val;
+		} else if (!strcasecmp(var, "member-flags")) {
 			member_flags = val;
-        } else if (!strcasecmp(var, "kicked-sound")) {
-            kicked_sound = val;
-        } else if (!strcasecmp(var, "pin")) {
-            pin = val;
-        } else if (!strcasecmp(var, "pin-sound")) {
-            pin_sound = val;
-        } else if (!strcasecmp(var, "bad-pin-sound")) {
-            bad_pin_sound = val;
-        } else if (!strcasecmp(var, "energy-level")) {
-            energy_level = val;
-        } else if (!strcasecmp(var, "caller-id-name")) {
-            caller_id_name = val;
-        } else if (!strcasecmp(var, "caller-id-number")) {
-            caller_id_number = val;
-        } else if (!strcasecmp(var, "caller-controls")) {
-            caller_controls = val;
-        } else if (!strcasecmp(var, "sound-prefix")) {
-            sound_prefix = val;
-        } else if (!strcasecmp(var, "max-members")) {
-            errno = 0; // sanity first
-            max_members = strtol(val,NULL,0); // base 0 lets 0x... for hex 0... for octal and base 10 otherwise through
-            if(errno == ERANGE || errno == EINVAL || max_members < 0 || max_members == 1) {
-                // a negative wont work well, and its foolish to have a conference limited to 1 person unless the outbound 
-                // stuff is added, see comments above
-                max_members = 0; // set to 0 to disable max counts
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "max-members %s is invalid, not setting a limit\n",val);
-            }
-        } else if(!strcasecmp(var, "max-members-sound")) {
-            maxmember_sound = val;
-        } else if(!strcasecmp(var, "anounce-count")) {
-            errno = 0; // safety first
-            anounce_count = strtol(val,NULL,0);
-            if(errno == ERANGE || errno == EINVAL) {
-                anounce_count = 0;
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "anounce-count is invalid, not anouncing member counts\n");
-            }
-        }
-    }
-
-    /* Set defaults and various paramaters */
-
-    /* Speed in hertz */
-    if (!switch_strlen_zero(rate_name)) {
-        uint32_t r = atoi(rate_name);
-        if (r) {
-            rate = r;
-        }
-    }
-
-    /* Packet Interval in milliseconds */
-    if (!switch_strlen_zero(interval_name)) {
-        uint32_t i = atoi(interval_name);
-        if (i) {
-            interval = i;
-        }
-    }
-
-    /* Timer module to use */
-    if (switch_strlen_zero(timer_name)) {
-        timer_name = "soft";
-    }
-
-    /* Caller ID Name */
-    if (switch_strlen_zero(caller_id_name)) {
-        caller_id_name = (char *) global_app_name;
-    }
-
-    /* Caller ID Number */
-    if (switch_strlen_zero(caller_id_number)) {
-        caller_id_number = "0000000000";
-    }
-
-    if (!pool) {
-        /* Setup a memory pool to use. */
-        if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
-            status = SWITCH_STATUS_TERM;
-            return NULL;
-        }
-    }
-
-    /* Create the conference object. */
-    if (!(conference = switch_core_alloc(pool, sizeof(*conference)))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-        status = SWITCH_STATUS_TERM;
-        return NULL;
-    }
-
-    /* initialize the conference object with settings from the specified profile */
-    conference->pool = pool;
-    conference->timer_name = switch_core_strdup(conference->pool, timer_name);
-    conference->tts_engine = switch_core_strdup(conference->pool, tts_engine);
-    conference->tts_voice = switch_core_strdup(conference->pool, tts_voice);
+		} else if (!strcasecmp(var, "kicked-sound")) {
+			kicked_sound = val;
+		} else if (!strcasecmp(var, "pin")) {
+			pin = val;
+		} else if (!strcasecmp(var, "pin-sound")) {
+			pin_sound = val;
+		} else if (!strcasecmp(var, "bad-pin-sound")) {
+			bad_pin_sound = val;
+		} else if (!strcasecmp(var, "energy-level")) {
+			energy_level = val;
+		} else if (!strcasecmp(var, "caller-id-name")) {
+			caller_id_name = val;
+		} else if (!strcasecmp(var, "caller-id-number")) {
+			caller_id_number = val;
+		} else if (!strcasecmp(var, "caller-controls")) {
+			caller_controls = val;
+		} else if (!strcasecmp(var, "sound-prefix")) {
+			sound_prefix = val;
+		} else if (!strcasecmp(var, "max-members")) {
+			errno = 0;			// sanity first
+			max_members = strtol(val, NULL, 0);	// base 0 lets 0x... for hex 0... for octal and base 10 otherwise through
+			if (errno == ERANGE || errno == EINVAL || max_members < 0 || max_members == 1) {
+				// a negative wont work well, and its foolish to have a conference limited to 1 person unless the outbound 
+				// stuff is added, see comments above
+				max_members = 0;	// set to 0 to disable max counts
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "max-members %s is invalid, not setting a limit\n", val);
+			}
+		} else if (!strcasecmp(var, "max-members-sound")) {
+			maxmember_sound = val;
+		} else if (!strcasecmp(var, "anounce-count")) {
+			errno = 0;			// safety first
+			anounce_count = strtol(val, NULL, 0);
+			if (errno == ERANGE || errno == EINVAL) {
+				anounce_count = 0;
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "anounce-count is invalid, not anouncing member counts\n");
+			}
+		}
+	}
+
+	/* Set defaults and various paramaters */
+
+	/* Speed in hertz */
+	if (!switch_strlen_zero(rate_name)) {
+		uint32_t r = atoi(rate_name);
+		if (r) {
+			rate = r;
+		}
+	}
+
+	/* Packet Interval in milliseconds */
+	if (!switch_strlen_zero(interval_name)) {
+		uint32_t i = atoi(interval_name);
+		if (i) {
+			interval = i;
+		}
+	}
+
+	/* Timer module to use */
+	if (switch_strlen_zero(timer_name)) {
+		timer_name = "soft";
+	}
+
+	/* Caller ID Name */
+	if (switch_strlen_zero(caller_id_name)) {
+		caller_id_name = (char *) global_app_name;
+	}
+
+	/* Caller ID Number */
+	if (switch_strlen_zero(caller_id_number)) {
+		caller_id_number = "0000000000";
+	}
+
+	if (!pool) {
+		/* Setup a memory pool to use. */
+		if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Pool Failure\n");
+			status = SWITCH_STATUS_TERM;
+			return NULL;
+		}
+	}
+
+	/* Create the conference object. */
+	if (!(conference = switch_core_alloc(pool, sizeof(*conference)))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
+		status = SWITCH_STATUS_TERM;
+		return NULL;
+	}
+
+	/* initialize the conference object with settings from the specified profile */
+	conference->pool = pool;
+	conference->timer_name = switch_core_strdup(conference->pool, timer_name);
+	conference->tts_engine = switch_core_strdup(conference->pool, tts_engine);
+	conference->tts_voice = switch_core_strdup(conference->pool, tts_voice);
 
-    conference->caller_id_name = switch_core_strdup(conference->pool, caller_id_name);
-    conference->caller_id_number = switch_core_strdup(conference->pool, caller_id_number);
+	conference->caller_id_name = switch_core_strdup(conference->pool, caller_id_name);
+	conference->caller_id_number = switch_core_strdup(conference->pool, caller_id_number);
 
 	conference->mflags = MFLAG_CAN_SPEAK | MFLAG_CAN_HEAR;
 
 	if (member_flags) {
 		set_mflags(member_flags, &conference->mflags);
-	} 
+	}
 
-    if (sound_prefix) {
-        conference->sound_prefix = switch_core_strdup(conference->pool, sound_prefix);
-    }
-
-    if (!switch_strlen_zero(enter_sound)) {
-        conference->enter_sound = switch_core_strdup(conference->pool, enter_sound);
-    }
-
-    if (!switch_strlen_zero(exit_sound)) {
-        conference->exit_sound = switch_core_strdup(conference->pool, exit_sound);
-    }
-
-    if (!switch_strlen_zero(ack_sound)) {
-        conference->ack_sound = switch_core_strdup(conference->pool, ack_sound);
-    }
-
-    if (!switch_strlen_zero(nack_sound)) {
-        conference->nack_sound = switch_core_strdup(conference->pool, nack_sound);
-    }
-
-    if (!switch_strlen_zero(muted_sound)) {
-        conference->muted_sound = switch_core_strdup(conference->pool, muted_sound);
-    }
-
-    if (!switch_strlen_zero(unmuted_sound)) {
-        conference->unmuted_sound = switch_core_strdup(conference->pool, unmuted_sound);
-    }
-
-    if (!switch_strlen_zero(kicked_sound)) {
-        conference->kicked_sound = switch_core_strdup(conference->pool, kicked_sound);
-    }
-
-    if (!switch_strlen_zero(pin_sound)) {
-        conference->pin_sound = switch_core_strdup(conference->pool, pin_sound);
-    }
-
-    if (!switch_strlen_zero(bad_pin_sound)) {
-        conference->bad_pin_sound = switch_core_strdup(conference->pool, bad_pin_sound);
-    }
-
-    if (!switch_strlen_zero(pin)) {
-        conference->pin = switch_core_strdup(conference->pool, pin);
-    }
-
-    if (!switch_strlen_zero(alone_sound)) {
-        conference->alone_sound = switch_core_strdup(conference->pool, alone_sound);
-    } 
-
-    if (!switch_strlen_zero(locked_sound)) {
-        conference->locked_sound = switch_core_strdup(conference->pool, locked_sound);
-    }
-
-    if (!switch_strlen_zero(is_locked_sound)) {
-        conference->is_locked_sound = switch_core_strdup(conference->pool, is_locked_sound);
-    }
-
-    if (!switch_strlen_zero(is_unlocked_sound)) {
-        conference->is_unlocked_sound = switch_core_strdup(conference->pool, is_unlocked_sound);
-    }
-
-    if (!switch_strlen_zero(energy_level)) {
-        conference->energy_level = atoi(energy_level);
-    }
-
-    if (!switch_strlen_zero(maxmember_sound)) {
-        conference->maxmember_sound = switch_core_strdup(conference->pool, maxmember_sound);
-    }
-
-    // its going to be 0 by default, set to a value otherwise so this should be safe
-    conference->max_members = max_members;
-    conference->anounce_count = anounce_count;
-
-    conference->name = switch_core_strdup(conference->pool, name);
-    if (domain) {
-        conference->domain = switch_core_strdup(conference->pool, domain);
-    } else {
-        conference->domain = "cluecon.com";
-    }
-    conference->rate = rate;
-    conference->interval = interval;
-    conference->dtmf_parser = NULL;
-
-    /* caller control configuration chores */
-    if (switch_ivr_digit_stream_parser_new(conference->pool, &conference->dtmf_parser) == SWITCH_STATUS_SUCCESS) {
-
-        /* if no controls, or default controls specified, install default */
-        if (caller_controls == NULL || *caller_controls == '\0' || strcasecmp(caller_controls, "default") == 0) {
-            status = conf_default_controls(conference);
-        } else if (strcasecmp(caller_controls, "none") != 0) {
-            /* try to build caller control if the group has been specified and != "none" */
-            switch_xml_t xml_controls = switch_xml_find_child(cfg.controls, "group", "name", caller_controls);
-#ifdef OPTION_IVR_MENU_SUPPORT
-            status = conference_new_install_caller_controls_custom(conference, xml_controls, cfg.menus);
-#else
-            status = conference_new_install_caller_controls_custom(conference, xml_controls, NULL);
-#endif
-            if (status != SWITCH_STATUS_SUCCESS) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to install caller controls group '%s'\n", caller_controls);
-            }
-        } else {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "no caller controls intalled.\n");
-        }
-    } else {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to allocate caller control digit parser.\n");
-    }
-
-    /* Activate the conference mutex for exclusivity */
-    switch_mutex_init(&conference->mutex, SWITCH_MUTEX_NESTED, conference->pool);
-    switch_mutex_init(&conference->flag_mutex, SWITCH_MUTEX_NESTED, conference->pool);
-    switch_thread_rwlock_create(&conference->rwlock, conference->pool);
+	if (sound_prefix) {
+		conference->sound_prefix = switch_core_strdup(conference->pool, sound_prefix);
+	}
+
+	if (!switch_strlen_zero(enter_sound)) {
+		conference->enter_sound = switch_core_strdup(conference->pool, enter_sound);
+	}
+
+	if (!switch_strlen_zero(exit_sound)) {
+		conference->exit_sound = switch_core_strdup(conference->pool, exit_sound);
+	}
+
+	if (!switch_strlen_zero(ack_sound)) {
+		conference->ack_sound = switch_core_strdup(conference->pool, ack_sound);
+	}
+
+	if (!switch_strlen_zero(nack_sound)) {
+		conference->nack_sound = switch_core_strdup(conference->pool, nack_sound);
+	}
+
+	if (!switch_strlen_zero(muted_sound)) {
+		conference->muted_sound = switch_core_strdup(conference->pool, muted_sound);
+	}
+
+	if (!switch_strlen_zero(unmuted_sound)) {
+		conference->unmuted_sound = switch_core_strdup(conference->pool, unmuted_sound);
+	}
+
+	if (!switch_strlen_zero(kicked_sound)) {
+		conference->kicked_sound = switch_core_strdup(conference->pool, kicked_sound);
+	}
+
+	if (!switch_strlen_zero(pin_sound)) {
+		conference->pin_sound = switch_core_strdup(conference->pool, pin_sound);
+	}
+
+	if (!switch_strlen_zero(bad_pin_sound)) {
+		conference->bad_pin_sound = switch_core_strdup(conference->pool, bad_pin_sound);
+	}
+
+	if (!switch_strlen_zero(pin)) {
+		conference->pin = switch_core_strdup(conference->pool, pin);
+	}
+
+	if (!switch_strlen_zero(alone_sound)) {
+		conference->alone_sound = switch_core_strdup(conference->pool, alone_sound);
+	}
+
+	if (!switch_strlen_zero(locked_sound)) {
+		conference->locked_sound = switch_core_strdup(conference->pool, locked_sound);
+	}
+
+	if (!switch_strlen_zero(is_locked_sound)) {
+		conference->is_locked_sound = switch_core_strdup(conference->pool, is_locked_sound);
+	}
+
+	if (!switch_strlen_zero(is_unlocked_sound)) {
+		conference->is_unlocked_sound = switch_core_strdup(conference->pool, is_unlocked_sound);
+	}
+
+	if (!switch_strlen_zero(energy_level)) {
+		conference->energy_level = atoi(energy_level);
+	}
+
+	if (!switch_strlen_zero(maxmember_sound)) {
+		conference->maxmember_sound = switch_core_strdup(conference->pool, maxmember_sound);
+	}
+	// its going to be 0 by default, set to a value otherwise so this should be safe
+	conference->max_members = max_members;
+	conference->anounce_count = anounce_count;
+
+	conference->name = switch_core_strdup(conference->pool, name);
+	if (domain) {
+		conference->domain = switch_core_strdup(conference->pool, domain);
+	} else {
+		conference->domain = "cluecon.com";
+	}
+	conference->rate = rate;
+	conference->interval = interval;
+	conference->dtmf_parser = NULL;
+
+	/* caller control configuration chores */
+	if (switch_ivr_digit_stream_parser_new(conference->pool, &conference->dtmf_parser) == SWITCH_STATUS_SUCCESS) {
+
+		/* if no controls, or default controls specified, install default */
+		if (caller_controls == NULL || *caller_controls == '\0' || strcasecmp(caller_controls, "default") == 0) {
+			status = conf_default_controls(conference);
+		} else if (strcasecmp(caller_controls, "none") != 0) {
+			/* try to build caller control if the group has been specified and != "none" */
+			switch_xml_t xml_controls = switch_xml_find_child(cfg.controls, "group", "name", caller_controls);
+			status = conference_new_install_caller_controls_custom(conference, xml_controls, NULL);
+
+			if (status != SWITCH_STATUS_SUCCESS) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to install caller controls group '%s'\n", caller_controls);
+			}
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "no caller controls intalled.\n");
+		}
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to allocate caller control digit parser.\n");
+	}
+
+	/* Activate the conference mutex for exclusivity */
+	switch_mutex_init(&conference->mutex, SWITCH_MUTEX_NESTED, conference->pool);
+	switch_mutex_init(&conference->flag_mutex, SWITCH_MUTEX_NESTED, conference->pool);
+	switch_thread_rwlock_create(&conference->rwlock, conference->pool);
 	switch_mutex_init(&conference->member_mutex, SWITCH_MUTEX_NESTED, conference->pool);
 
-    return conference;
+	return conference;
+}
+
+static void pres_event_handler(switch_event_t *event)
+{
+	char *to = switch_event_get_header(event, "to");
+	char *dup_to = NULL, *conf_name, *e;
+	conference_obj_t *conference;
+
+	if (!to || strncasecmp(to, "conf+", 5)) {
+		return;
+	}
+
+	if (!(dup_to = strdup(to))) {
+		return;
+	}
+
+	conf_name = dup_to + 5;
+
+	if ((e = strchr(conf_name, '@'))) {
+		*e = '\0';
+	}
+
+	if ((conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, conf_name))) {
+		switch_event_t *event;
+
+		if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", conference->name);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", conference->name, conference->domain);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Active (%d caller%s)", conference->count, conference->count == 1 ? "" : "s");
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
+			switch_event_fire(&event);
+		}
+	} else if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", conf_name);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", to);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Idle");
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "idle");
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
+		switch_event_fire(&event);
+	}
+
+	switch_safe_free(dup_to);
 }
 
-static void pres_event_handler(switch_event_t *event) 
-{ 
-    char *to = switch_event_get_header(event, "to"); 
-    char *dup_to = NULL, *conf_name, *e; 
-    conference_obj_t *conference; 
-
-    if (!to || strncasecmp(to, "conf+", 5)) { 
-        return; 
-    } 
-
-    if (!(dup_to = strdup(to))) { 
-        return; 
-    } 
-
-    conf_name = dup_to + 5; 
-
-    if ((e = strchr(conf_name, '@'))) { 
-        *e = '\0'; 
-    } 
-
-    if ((conference = (conference_obj_t *) switch_core_hash_find(globals.conference_hash, conf_name))) { 
-        switch_event_t *event; 
-
-        if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) { 
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO); 
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", conference->name); 
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", conference->name, conference->domain); 
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Active (%d caller%s)", conference->count, conference->count == 1 ? "" : "s"); 
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence"); 
-            switch_event_fire(&event); 
-        } 
-    } else if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) { 
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO); 
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", conf_name); 
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", to); 
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Idle"); 
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "idle"); 
-        switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence"); 
-        switch_event_fire(&event); 
-    } 
-
-    switch_safe_free(dup_to); 
-} 
- 
-static void send_presence(switch_event_types_t id) 
-{ 
-    switch_xml_t cxml, cfg, advertise, room; 
-
-    /* Open the config from the xml registry */ 
-    if (!(cxml = switch_xml_open_cfg(global_cf_name, &cfg, "presence"))) { 
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", global_cf_name); 
-        goto done; 
-    } 
-
-    if ((advertise = switch_xml_child(cfg, "advertise"))) { 
-        for (room = switch_xml_child(advertise, "room"); room; room = room->next) { 
-            char *name = (char *) switch_xml_attr_soft(room, "name"); 
-            char *status = (char *) switch_xml_attr_soft(room, "status"); 
-            switch_event_t *event; 
-
-            if (name && switch_event_create(&event, id) == SWITCH_STATUS_SUCCESS) { 
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO); 
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", name); 
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", name); 
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "%s", status ? status : "Available"); 
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "idle"); 
-                switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence"); 
-                switch_event_fire(&event); 
-            } 
-        } 
-    } 
-
- done: 
-    /* Release the config registry handle */ 
-    if (cxml) { 
-        switch_xml_free(cxml); 
-        cxml = NULL; 
-    } 
-} 
+static void send_presence(switch_event_types_t id)
+{
+	switch_xml_t cxml, cfg, advertise, room;
+
+	/* Open the config from the xml registry */
+	if (!(cxml = switch_xml_open_cfg(global_cf_name, &cfg, "presence"))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", global_cf_name);
+		goto done;
+	}
+
+	if ((advertise = switch_xml_child(cfg, "advertise"))) {
+		for (room = switch_xml_child(advertise, "room"); room; room = room->next) {
+			char *name = (char *) switch_xml_attr_soft(room, "name");
+			char *status = (char *) switch_xml_attr_soft(room, "status");
+			switch_event_t *event;
+
+			if (name && switch_event_create(&event, id) == SWITCH_STATUS_SUCCESS) {
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", CONF_CHAT_PROTO);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", name);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", name);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "%s", status ? status : "Available");
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "idle");
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
+				switch_event_fire(&event);
+			}
+		}
+	}
+
+  done:
+	/* Release the config registry handle */
+	if (cxml) {
+		switch_xml_free(cxml);
+		cxml = NULL;
+	}
+}
 
 /* Called by FreeSWITCH when the module loads */
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
-    uint32_t i;
-    size_t nl, ol = 0;
-    char *p = NULL;
-    switch_status_t status = SWITCH_STATUS_SUCCESS;
-
-    memset(&globals, 0, sizeof(globals));
-
-    /* build api interface help ".syntax" field string */
-    p = strdup("");
-    for (i = 0; i<CONFFUNCAPISIZE; i++) {
-        nl = strlen(conf_api_sub_commands[i].psyntax) + 4;
-        if (p != NULL) {
-            ol = strlen(p);
-        }
-        p = realloc(p, ol+nl);
-        if (p != NULL) {
-            strcat(p, "\t\t");
-            strcat(p, conf_api_sub_commands[i].psyntax);
-            if (i < CONFFUNCAPISIZE-1) {
-                strcat(p, "\n");
-            }
-        }
-		
-    }
-    /* install api interface help ".syntax" field string */
-    if (p != NULL) {
-        conf_api_interface.syntax = p;
-    }
-
-    /* Connect my internal structure to the blank pointer passed to me */
-    *module_interface = &conference_module_interface;
-
-    /* create/register custom event message type */
-    if (switch_event_reserve_subclass(CONF_EVENT_MAINT) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass %s!", CONF_EVENT_MAINT);
-        return SWITCH_STATUS_TERM;
-    }
-
-    /* Setup the pool */
-    if (switch_core_new_memory_pool(&globals.conference_pool) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "OH OH no conference pool\n");
-        return SWITCH_STATUS_TERM;
-    }
-
-    /* Setup a hash to store conferences by name */
-    switch_core_hash_init(&globals.conference_hash, globals.conference_pool);
-    switch_mutex_init(&globals.conference_mutex, SWITCH_MUTEX_NESTED, globals.conference_pool);
-    switch_mutex_init(&globals.id_mutex, SWITCH_MUTEX_NESTED, globals.conference_pool);
-    switch_mutex_init(&globals.hash_mutex, SWITCH_MUTEX_NESTED, globals.conference_pool);
-
-    /* Subscribe to presence request events */
-    if (switch_event_bind((char *) modname, SWITCH_EVENT_PRESENCE_PROBE, SWITCH_EVENT_SUBCLASS_ANY, pres_event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't subscribe to presence request events!\n");
-        return SWITCH_STATUS_GENERR;
-    }
-
-    send_presence(SWITCH_EVENT_PRESENCE_IN);
-
-    globals.running = 1;
-    /* indicate that the module should continue to be loaded */
-    return status;
+	uint32_t i;
+	size_t nl, ol = 0;
+	char *p = NULL;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
+
+	memset(&globals, 0, sizeof(globals));
+
+	/* build api interface help ".syntax" field string */
+	p = strdup("");
+	for (i = 0; i < CONFFUNCAPISIZE; i++) {
+		nl = strlen(conf_api_sub_commands[i].psyntax) + 4;
+		if (p != NULL) {
+			ol = strlen(p);
+		}
+		p = realloc(p, ol + nl);
+		if (p != NULL) {
+			strcat(p, "\t\t");
+			strcat(p, conf_api_sub_commands[i].psyntax);
+			if (i < CONFFUNCAPISIZE - 1) {
+				strcat(p, "\n");
+			}
+		}
+
+	}
+	/* install api interface help ".syntax" field string */
+	if (p != NULL) {
+		conf_api_interface.syntax = p;
+	}
+
+	/* Connect my internal structure to the blank pointer passed to me */
+	*module_interface = &conference_module_interface;
+
+	/* create/register custom event message type */
+	if (switch_event_reserve_subclass(CONF_EVENT_MAINT) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass %s!", CONF_EVENT_MAINT);
+		return SWITCH_STATUS_TERM;
+	}
+
+	/* Setup the pool */
+	if (switch_core_new_memory_pool(&globals.conference_pool) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "OH OH no conference pool\n");
+		return SWITCH_STATUS_TERM;
+	}
+
+	/* Setup a hash to store conferences by name */
+	switch_core_hash_init(&globals.conference_hash, globals.conference_pool);
+	switch_mutex_init(&globals.conference_mutex, SWITCH_MUTEX_NESTED, globals.conference_pool);
+	switch_mutex_init(&globals.id_mutex, SWITCH_MUTEX_NESTED, globals.conference_pool);
+	switch_mutex_init(&globals.hash_mutex, SWITCH_MUTEX_NESTED, globals.conference_pool);
+
+	/* Subscribe to presence request events */
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_PRESENCE_PROBE, SWITCH_EVENT_SUBCLASS_ANY, pres_event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't subscribe to presence request events!\n");
+		return SWITCH_STATUS_GENERR;
+	}
+
+	send_presence(SWITCH_EVENT_PRESENCE_IN);
+
+	globals.running = 1;
+	/* indicate that the module should continue to be loaded */
+	return status;
 }
 
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_shutdown(void)
 {
-    if (globals.running) {
+	if (globals.running) {
 
-        /* signal all threads to shutdown */
-        globals.running = 0;
+		/* signal all threads to shutdown */
+		globals.running = 0;
 
-        /* wait for all threads */
-        while (globals.threads) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Waiting for %d threads\n", globals.threads);
-            switch_yield(100000);
-        }
-
-        /* free api interface help ".syntax" field string */
-        if (conf_api_interface.syntax != NULL) {
-            free((char *)conf_api_interface.syntax);
-        }
-    }
+		/* wait for all threads */
+		while (globals.threads) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Waiting for %d threads\n", globals.threads);
+			switch_yield(100000);
+		}
+
+		/* free api interface help ".syntax" field string */
+		if (conf_api_interface.syntax != NULL) {
+			free((char *) conf_api_interface.syntax);
+		}
+	}
 
-    return SWITCH_STATUS_SUCCESS;
+	return SWITCH_STATUS_SUCCESS;
 }
 
 /* For Emacs:

Modified: freeswitch/branches/cparker/src/mod/applications/mod_dptools/mod_dptools.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_dptools/mod_dptools.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_dptools/mod_dptools.c	Tue Apr 24 10:14:28 2007
@@ -36,6 +36,7 @@
 static const char modname[] = "mod_dptools";
 
 static const switch_application_interface_t detect_speech_application_interface;
+static const switch_application_interface_t exe_application_interface;
 
 static void detect_speech_function(switch_core_session_t *session, char *data)
 {
@@ -43,7 +44,8 @@
 	int argc;
 	char *lbuf = NULL;
 
-	if (data && (lbuf = switch_core_session_strdup(session, data)) && (argc = switch_separate_string(lbuf, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
+	if (data && (lbuf = switch_core_session_strdup(session, data))
+		&& (argc = switch_separate_string(lbuf, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
 		if (!strcasecmp(argv[0], "grammar") && argc >= 1) {
 			switch_ivr_detect_speech_load_grammar(session, argv[1], argv[2]);
 		} else if (!strcasecmp(argv[0], "nogrammar")) {
@@ -60,14 +62,34 @@
 	} else {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Usage: %s\n", detect_speech_application_interface.syntax);
 	}
+
+}
+
+static void exe_function(switch_core_session_t *session, char *data)
+{
+	char *argv[4];
+	int argc;
+	char *lbuf = NULL;
+	char *extension;
+	char *context;
+	char *dialplan;
 	
+	if (data && (lbuf = switch_core_session_strdup(session, data))
+		&& (argc = switch_separate_string(lbuf, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
+		extension = argv[0];
+		dialplan = argv[1];
+		context = argv[2];
+		switch_core_session_execute_exten(session, extension, dialplan, context);
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Usage: %s\n", exe_application_interface.syntax);
+	}
 }
 
 static void ring_ready_function(switch_core_session_t *session, char *data)
 {
 	switch_channel_t *channel;
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 	switch_channel_ring_ready(channel);
 }
 
@@ -84,7 +106,7 @@
 static void transfer_function(switch_core_session_t *session, char *data)
 {
 	int argc;
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	char *mydata;
 
 	if (data && (mydata = switch_core_session_strdup(session, data))) {
@@ -96,6 +118,99 @@
 	}
 }
 
+static void sched_transfer_function(switch_core_session_t *session, char *data)
+{
+	int argc;
+	char *argv[4] = { 0 };
+	char *mydata;
+
+	if (data && (mydata = switch_core_session_strdup(session, data))) {
+		if ((argc = switch_separate_string(mydata, ' ', argv, (sizeof(argv) / sizeof(argv[0])))) >= 2) {
+			time_t when;
+
+			if (*argv[0] == '+') {
+				when = time(NULL) + atol(argv[0] + 1);
+			} else {
+				when = atol(argv[0]);
+			}
+
+			switch_ivr_schedule_transfer(when, switch_core_session_get_uuid(session), argv[1], argv[2], argv[3]);
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Args\n");
+		}
+	}
+}
+
+static void sched_hangup_function(switch_core_session_t *session, char *data)
+{
+	int argc;
+	char *argv[5] = { 0 };
+	char *mydata;
+
+	if (data && (mydata = switch_core_session_strdup(session, data))) {
+		if ((argc = switch_separate_string(mydata, ' ', argv, (sizeof(argv) / sizeof(argv[0])))) >= 1) {
+			time_t when;
+			switch_call_cause_t cause = SWITCH_CAUSE_ALLOTTED_TIMEOUT;
+			switch_bool_t bleg = SWITCH_FALSE;
+
+			if (*argv[0] == '+') {
+				when = time(NULL) + atol(argv[0] + 1);
+			} else {
+				when = atol(argv[0]);
+			}
+
+			if (argv[1]) {
+				cause = switch_channel_str2cause(argv[1]);
+			}
+
+			if (argv[2] && !strcasecmp(argv[2], "bleg")) {
+				bleg = SWITCH_TRUE;
+			}
+
+			switch_ivr_schedule_hangup(when, switch_core_session_get_uuid(session), cause, bleg);
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No time specified.\n");
+		}
+	}
+}
+
+
+static void sched_broadcast_function(switch_core_session_t *session, char *data)
+{
+	int argc;
+	char *argv[6] = { 0 };
+	char *mydata;
+
+	if (data && (mydata = switch_core_session_strdup(session, data))) {
+		if ((argc = switch_separate_string(mydata, ' ', argv, (sizeof(argv) / sizeof(argv[0])))) >= 2) {
+			time_t when;
+			switch_media_flag_t flags = SMF_NONE;
+
+			if (*argv[0] == '+') {
+				when = time(NULL) + atol(argv[0] + 1);
+			} else {
+				when = atol(argv[0]);
+			}
+
+			if (argv[2]) {
+				if (!strcmp(argv[2], "both")) {
+					flags |= (SMF_ECHO_ALEG | SMF_ECHO_BLEG);
+				} else if (!strcmp(argv[2], "aleg")) {
+					flags |= SMF_ECHO_ALEG;
+				} else if (!strcmp(argv[2], "bleg")) {
+					flags |= SMF_ECHO_BLEG;
+				}
+			} else {
+				flags |= SMF_ECHO_ALEG;
+			}
+
+			switch_ivr_schedule_broadcast(when, switch_core_session_get_uuid(session), argv[1], flags);
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Args\n");
+		}
+	}
+}
+
 static void sleep_function(switch_core_session_t *session, char *data)
 {
 
@@ -114,26 +229,26 @@
 
 static void phrase_function(switch_core_session_t *session, char *data)
 {
-    switch_channel_t *channel;
-    char *mydata = NULL;
+	switch_channel_t *channel;
+	char *mydata = NULL;
 
-    channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
-    
-    if ((mydata = switch_core_session_strdup(session, data))) {
-        char *lang;
-        char *macro = mydata;
-        char *mdata = NULL;
-
-        if ((mdata = strchr(macro, ','))) {
-            *mdata++ = '\0';
-        }
-
-        lang = switch_channel_get_variable(channel, "language");
-        
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Execute %s(%s) lang %s\n", macro, mdata, lang);
-        switch_ivr_phrase_macro(session, macro, mdata, lang, NULL);
-    }
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
+
+	if ((mydata = switch_core_session_strdup(session, data))) {
+		char *lang;
+		char *macro = mydata;
+		char *mdata = NULL;
+
+		if ((mdata = strchr(macro, ','))) {
+			*mdata++ = '\0';
+		}
+
+		lang = switch_channel_get_variable(channel, "language");
+
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Execute %s(%s) lang %s\n", macro, mdata, lang);
+		switch_ivr_phrase_macro(session, macro, mdata, lang, NULL);
+	}
 
 }
 
@@ -141,14 +256,14 @@
 static void hangup_function(switch_core_session_t *session, char *data)
 {
 	switch_channel_t *channel;
-    switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
+	switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
-    if (!switch_strlen_zero((char *) data)) {
-        cause = switch_channel_str2cause((char *) data);
-    }
+	if (!switch_strlen_zero((char *) data)) {
+		cause = switch_channel_str2cause((char *) data);
+	}
 
 	switch_channel_hangup(channel, cause);
 }
@@ -158,7 +273,7 @@
 	switch_channel_t *channel;
 	channel = switch_core_session_get_channel(session);
 
-    assert(channel != NULL);
+	assert(channel != NULL);
 	switch_channel_answer(channel);
 }
 
@@ -167,18 +282,30 @@
 	switch_channel_t *channel;
 	channel = switch_core_session_get_channel(session);
 
-    assert(channel != NULL);
+	assert(channel != NULL);
 	switch_channel_pre_answer(channel);
 }
 
 static void redirect_function(switch_core_session_t *session, char *data)
 {
-    switch_core_session_message_t msg = {0};
+	switch_core_session_message_t msg = { 0 };
 
-    /* Tell the channel to redirect */
+	/* Tell the channel to redirect */
 	msg.from = __FILE__;
 	msg.string_arg = data;
-    msg.message_id = SWITCH_MESSAGE_INDICATE_REDIRECT;
+	msg.message_id = SWITCH_MESSAGE_INDICATE_REDIRECT;
+	switch_core_session_receive_message(session, &msg);
+
+}
+
+static void reject_function(switch_core_session_t *session, char *data)
+{
+	switch_core_session_message_t msg = { 0 };
+
+	/* Tell the channel to reject the call */
+	msg.from = __FILE__;
+	msg.string_arg = data;
+	msg.message_id = SWITCH_MESSAGE_INDICATE_REJECT;
 	switch_core_session_receive_message(session, &msg);
 
 }
@@ -190,7 +317,7 @@
 	char *var, *val = NULL;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 	if (switch_strlen_zero(data)) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No variable name specified.\n");
@@ -200,11 +327,11 @@
 
 		if (val) {
 			*val++ = '\0';
-            if (switch_strlen_zero(val)) {
-                val = NULL;
-            }
+			if (switch_strlen_zero(val)) {
+				val = NULL;
+			}
 		}
-		
+
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SET [%s]=[%s]\n", var, val ? val : "UNDEF");
 		switch_channel_set_variable(channel, var, val);
 	}
@@ -216,7 +343,7 @@
 	char *exports, *new_exports = NULL, *new_exports_d = NULL, *var, *val = NULL;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 	if (switch_strlen_zero(data)) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No variable name specified.\n");
@@ -227,11 +354,11 @@
 
 		if (val) {
 			*val++ = '\0';
-            if (switch_strlen_zero(val)) {
-                val = NULL;
-            }
+			if (switch_strlen_zero(val)) {
+				val = NULL;
+			}
 		}
-		
+
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "EXPORT [%s]=[%s]\n", var, val ? val : "UNDEF");
 		switch_channel_set_variable(channel, var, val);
 
@@ -253,7 +380,7 @@
 	switch_channel_t *channel;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 	if (switch_strlen_zero(data)) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No variable name specified.\n");
@@ -266,43 +393,43 @@
 static void log_function(switch_core_session_t *session, char *data)
 {
 	switch_channel_t *channel;
-    char *level, *log_str;
+	char *level, *log_str;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
+
+	if (data && (level = strdup(data))) {
+		switch_event_types_t etype = SWITCH_LOG_DEBUG;
 
-    if (data && (level = strdup(data))) {
-        switch_event_types_t etype = SWITCH_LOG_DEBUG;
-        
-        if ((log_str = strchr(level, ' '))) {
-            *log_str++ = '\0';
-            switch_name_event(level, &etype);
-        } else {
-            log_str = level;
-        }
-
-        switch_log_printf(SWITCH_CHANNEL_LOG, etype, "%s\n", log_str);
-        switch_safe_free(level);
-    }
+		if ((log_str = strchr(level, ' '))) {
+			*log_str++ = '\0';
+			switch_name_event(level, &etype);
+		} else {
+			log_str = level;
+		}
+
+		switch_log_printf(SWITCH_CHANNEL_LOG, etype, "%s\n", log_str);
+		switch_safe_free(level);
+	}
 }
 
 
 static void info_function(switch_core_session_t *session, char *data)
 {
 	switch_channel_t *channel;
-    switch_event_t *event;
-    char *buf;
+	switch_event_t *event;
+	char *buf;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
+
+	if (switch_event_create(&event, SWITCH_EVENT_MESSAGE) == SWITCH_STATUS_SUCCESS) {
+		switch_channel_event_set_data(channel, event);
+		switch_event_serialize(event, &buf);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "CHANNEL_DATA:\n%s\n", buf);
+		switch_event_destroy(&event);
+	}
 
-    if (switch_event_create(&event, SWITCH_EVENT_MESSAGE) == SWITCH_STATUS_SUCCESS) {
-        switch_channel_event_set_data(channel, event);
-        switch_event_serialize(event, &buf);
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "CHANNEL_DATA:\n%s\n", buf);
-        switch_event_destroy(&event);
-    }
-    
 }
 
 static void privacy_function(switch_core_session_t *session, char *data)
@@ -312,8 +439,8 @@
 	char *arg;
 
 	channel = switch_core_session_get_channel(session);
-    	assert(channel != NULL);		
-	
+	assert(channel != NULL);
+
 	caller_profile = switch_channel_get_caller_profile(channel);
 
 	if (switch_strlen_zero(data)) {
@@ -323,7 +450,7 @@
 
 		switch_set_flag(caller_profile, SWITCH_CPF_SCREEN);
 
-		if(!strcasecmp(arg, "no")) {
+		if (!strcasecmp(arg, "no")) {
 			switch_clear_flag(caller_profile, SWITCH_CPF_HIDE_NAME);
 			switch_clear_flag(caller_profile, SWITCH_CPF_HIDE_NUMBER);
 		} else if (!strcasecmp(arg, "yes")) {
@@ -347,7 +474,8 @@
 	int argc;
 	char *lbuf;
 
-	if (data && (lbuf = switch_core_session_strdup(session, data)) && (argc = switch_separate_string(lbuf, '=', argv, (sizeof(argv) / sizeof(argv[0])))) > 1) {
+	if (data && (lbuf = switch_core_session_strdup(session, data))
+		&& (argc = switch_separate_string(lbuf, '=', argv, (sizeof(argv) / sizeof(argv[0])))) > 1) {
 		switch_size_t retsize;
 		switch_time_exp_t tm;
 		char date[80] = "";
@@ -366,26 +494,26 @@
 
 static switch_status_t strepoch_api_function(char *data, switch_core_session_t *session, switch_stream_handle_t *stream)
 {
-    switch_time_t out;
-    
-    if (switch_strlen_zero(data)) {
-        out = switch_time_now();
-    } else {
-        out = switch_str_time(data);
-    }
+	switch_time_t out;
+
+	if (switch_strlen_zero(data)) {
+		out = switch_time_now();
+	} else {
+		out = switch_str_time(data);
+	}
 
-    stream->write_function(stream, "%d", (uint32_t)apr_time_sec(out));
+	stream->write_function(stream, "%d", (uint32_t) ((out) / (int64_t) (1000000)));
 
 	return SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t strftime_api_function(char *fmt, switch_core_session_t *session, switch_stream_handle_t *stream)
 {
-	
+
 	switch_size_t retsize;
 	switch_time_exp_t tm;
 	char date[80] = "";
-	
+
 	switch_time_exp_lt(&tm, switch_time_now());
 	switch_strftime(date, &retsize, sizeof(date), fmt ? fmt : "%Y-%m-%d %T", &tm);
 	stream->write_function(stream, "%s", date);
@@ -400,14 +528,15 @@
 	int argc = 0;
 	switch_event_types_t type = SWITCH_EVENT_PRESENCE_IN;
 
-	if (fmt && (lbuf = strdup(fmt)) && (argc = switch_separate_string(lbuf, '|', argv, (sizeof(argv) / sizeof(argv[0])))) > 0) {
+	if (fmt && (lbuf = strdup(fmt))
+		&& (argc = switch_separate_string(lbuf, '|', argv, (sizeof(argv) / sizeof(argv[0])))) > 0) {
 		if (!strcasecmp(argv[0], "out")) {
 			type = SWITCH_EVENT_PRESENCE_OUT;
 		} else if (argc != 4) {
 			stream->write_function(stream, "Invalid");
 			return SWITCH_STATUS_SUCCESS;
 		}
-		
+
 		if (switch_event_create(&event, type) == SWITCH_STATUS_SUCCESS) {
 			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", "dp");
 			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", __FILE__);
@@ -434,9 +563,10 @@
 	char *lbuf, *argv[4];
 	int argc = 0;
 
-	if (fmt && (lbuf = strdup(fmt)) && (argc = switch_separate_string(lbuf, '|', argv, (sizeof(argv) / sizeof(argv[0])))) == 4) {
+	if (fmt && (lbuf = strdup(fmt))
+		&& (argc = switch_separate_string(lbuf, '|', argv, (sizeof(argv) / sizeof(argv[0])))) == 4) {
 		switch_chat_interface_t *ci;
-		
+
 		if ((ci = switch_loadable_module_get_chat_interface(argv[0]))) {
 			ci->chat_send("dp", argv[1], argv[2], "", argv[3], "");
 			stream->write_function(stream, "Sent");
@@ -446,19 +576,19 @@
 	} else {
 		stream->write_function(stream, "Invalid");
 	}
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
 static char *ivr_cf_name = "ivr.conf";
 
 #ifdef _TEST_CALLBACK_
-static switch_ivr_action_t menu_handler(switch_ivr_menu_t *menu, char *param, char *buf, size_t buflen, void *obj)
+static switch_ivr_action_t menu_handler(switch_ivr_menu_t * menu, char *param, char *buf, size_t buflen, void *obj)
 {
 	switch_ivr_action_t action = SWITCH_IVR_ACTION_NOOP;
 
 	if (param != NULL) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "menu_handler '%s'\n",param);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "menu_handler '%s'\n", param);
 	}
 
 	return action;
@@ -470,7 +600,7 @@
 	switch_channel_t *channel = switch_core_session_get_channel(session);
 	char *params;
 
-	if (channel && data && (params = switch_core_session_strdup(session,data))) {
+	if (channel && data && (params = switch_core_session_strdup(session, data))) {
 		switch_xml_t cxml = NULL, cfg = NULL, xml_menus = NULL, xml_menu = NULL;
 
 		// Open the config from the xml registry
@@ -484,16 +614,15 @@
 					switch_ivr_menu_t *menu_stack = NULL;
 
 					// build a menu tree and execute it
-					if (switch_ivr_menu_stack_xml_init(&xml_ctx,NULL) == SWITCH_STATUS_SUCCESS
+					if (switch_ivr_menu_stack_xml_init(&xml_ctx, NULL) == SWITCH_STATUS_SUCCESS
 #ifdef _TEST_CALLBACK_
 						&& switch_ivr_menu_stack_xml_add_custom(xml_ctx, "custom", &menu_handler) == SWITCH_STATUS_SUCCESS
 #endif
-						&& switch_ivr_menu_stack_xml_build(xml_ctx,&menu_stack,xml_menus,xml_menu) == SWITCH_STATUS_SUCCESS)
-					{
+						&& switch_ivr_menu_stack_xml_build(xml_ctx, &menu_stack, xml_menus, xml_menu) == SWITCH_STATUS_SUCCESS) {
 						switch_xml_free(cxml);
 						cxml = NULL;
 						switch_channel_pre_answer(channel);
-						switch_ivr_menu_execute(session,menu_stack,params,NULL);
+						switch_ivr_menu_execute(session, menu_stack, params, NULL);
 						switch_ivr_menu_stack_free(menu_stack);
 					} else {
 						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to create menu '%s'\n", params);
@@ -509,7 +638,8 @@
 	}
 }
 
-static switch_api_interface_t strepoch_api_interface = {
+
+static const switch_api_interface_t strepoch_api_interface = {
 	/*.interface_name */ "strepoch",
 	/*.desc */ "Convert a date string into epoch time",
 	/*.function */ strepoch_api_function,
@@ -517,7 +647,7 @@
 	/*.next */ NULL
 };
 
-static switch_api_interface_t chat_api_interface = {
+static const switch_api_interface_t chat_api_interface = {
 	/*.interface_name */ "chat",
 	/*.desc */ "chat",
 	/*.function */ chat_api_function,
@@ -525,7 +655,7 @@
 	/*.next */ &strepoch_api_interface
 };
 
-static switch_api_interface_t dptools_api_interface = {
+static const switch_api_interface_t dptools_api_interface = {
 	/*.interface_name */ "strftime",
 	/*.desc */ "strftime",
 	/*.function */ strftime_api_function,
@@ -533,7 +663,7 @@
 	/*.next */ &chat_api_interface
 };
 
-static switch_api_interface_t presence_api_interface = {
+static const switch_api_interface_t presence_api_interface = {
 	/*.interface_name */ "presence",
 	/*.desc */ "presence",
 	/*.function */ presence_api_function,
@@ -541,29 +671,81 @@
 	/*.next */ &dptools_api_interface
 };
 
+
+static const switch_application_interface_t exe_application_interface = {
+	/*.interface_name */ "execute_extension",
+	/*.application_function */ exe_function,
+	/*.long_desc */ "Execute an extension",
+	/*.short_desc */ "Execute an extension",
+	/*.syntax */ "<extension> <dialplan> <context>",
+	/* flags */ SAF_SUPPORT_NOMEDIA,
+	/*.next */
+};
+
+static const switch_application_interface_t sched_transfer_application_interface = {
+	/*.interface_name */ "sched_transfer",
+	/*.application_function */ sched_transfer_function,
+	/*.long_desc */ "Schedule a transfer in the future",
+	/*.short_desc */ "Schedule a transfer in the future",
+	/*.syntax */ "[+]<time> <extension> <dialplan> <context>",
+	/* flags */ SAF_SUPPORT_NOMEDIA,
+	/*.next */ &exe_application_interface
+};
+
+static const switch_application_interface_t sched_broadcast_application_interface = {
+	/*.interface_name */ "sched_broadcast",
+	/*.application_function */ sched_broadcast_function,
+	/*.long_desc */ "Schedule a broadcast in the future",
+	/*.short_desc */ "Schedule a broadcast in the future",
+	/*.syntax */ "[+]<time> <path> [aleg|bleg|both]",
+	/* flags */ SAF_SUPPORT_NOMEDIA,
+	/*.next */ &sched_transfer_application_interface
+};
+
+static const switch_application_interface_t sched_hangup_application_interface = {
+	/*.interface_name */ "sched_hangup",
+	/*.application_function */ sched_hangup_function,
+	/*.long_desc */ "Schedule a hangup in the future",
+	/*.short_desc */ "Schedule a hangup in the future",
+	/*.syntax */ "[+]<time> [<cause>]",
+	/* flags */ SAF_SUPPORT_NOMEDIA,
+	/*.next */ &sched_broadcast_application_interface
+};
+
+
 static const switch_application_interface_t queuedtmf_application_interface = {
 	/*.interface_name */ "queue_dtmf",
-	/*.application_function */ queue_dtmf_function,	
+	/*.application_function */ queue_dtmf_function,
 	/* long_desc */ "Queue dtmf to be sent from a session",
 	/* short_desc */ "Queue dtmf to be sent",
 	/* syntax */ "<dtmf_data>",
 	/* flags */ SAF_SUPPORT_NOMEDIA,
-	/*.next */ NULL
+	/*.next */ &sched_hangup_application_interface
+};
+
+static const switch_application_interface_t reject_application_interface = {
+	/*.interface_name */ "reject",
+	/*.application_function */ reject_function,
+	/* long_desc */ "Send a reject message to a session.",
+	/* short_desc */ "Send session reject",
+	/* syntax */ "<reject_data>",
+	/* flags */ SAF_SUPPORT_NOMEDIA,
+	/*.next */ &queuedtmf_application_interface
 };
 
 static const switch_application_interface_t redirect_application_interface = {
 	/*.interface_name */ "redirect",
-	/*.application_function */ redirect_function,	
+	/*.application_function */ redirect_function,
 	/* long_desc */ "Send a redirect message to a session.",
 	/* short_desc */ "Send session redirect",
 	/* syntax */ "<redirect_data>",
 	/* flags */ SAF_SUPPORT_NOMEDIA,
-	/*.next */ &queuedtmf_application_interface
+	/*.next */ &reject_application_interface
 };
 
 static const switch_application_interface_t ivr_application_interface = {
 	/*.interface_name */ "ivr",
-	/*.application_function */ ivr_application_function,	
+	/*.application_function */ ivr_application_function,
 	/* long_desc */ "Run an ivr menu.",
 	/* short_desc */ "Run an ivr menu",
 	/* syntax */ "<menu_name>",
@@ -573,7 +755,7 @@
 
 static const switch_application_interface_t detect_speech_application_interface = {
 	/*.interface_name */ "detect_speech",
-	/*.application_function */ detect_speech_function,	
+	/*.application_function */ detect_speech_function,
 	/* long_desc */ "Detect speech on a channel.",
 	/* short_desc */ "Detect speech",
 	/* syntax */ "<mod_name> <gram_name> <gram_path> [<addr>] OR grammar <gram_name> [<path>] OR pause OR resume",
@@ -650,7 +832,6 @@
 	/* syntax */ "[<cause>]",
 	/* flags */ SAF_SUPPORT_NOMEDIA,
 	/*.next */ &log_application_interface
-
 };
 
 static const switch_application_interface_t answer_application_interface = {
@@ -661,7 +842,6 @@
 	/* syntax */ "",
 	/* flags */ SAF_SUPPORT_NOMEDIA,
 	/*.next */ &hangup_application_interface
-
 };
 
 static const switch_application_interface_t pre_answer_application_interface = {
@@ -672,7 +852,6 @@
 	/* syntax */ "",
 	/* flags */ SAF_SUPPORT_NOMEDIA,
 	/*.next */ &answer_application_interface
-
 };
 
 static const switch_application_interface_t eval_application_interface = {
@@ -683,7 +862,6 @@
 	/* syntax */ "",
 	/* flags */ SAF_SUPPORT_NOMEDIA,
 	/*.next */ &pre_answer_application_interface
-
 };
 
 static const switch_application_interface_t phrase_application_interface = {
@@ -694,7 +872,6 @@
 	/* syntax */ "<macro_name>,<data>",
 	/* flags */ SAF_NONE,
 	/*.next */ &eval_application_interface
-
 };
 
 static const switch_application_interface_t strftime_application_interface = {
@@ -705,13 +882,13 @@
 	/* syntax */ NULL,
 	/* flags */ SAF_SUPPORT_NOMEDIA,
 	/*.next */ &phrase_application_interface
-
 };
 
 static const switch_application_interface_t sleep_application_interface = {
 	/*.interface_name */ "sleep",
 	/*.application_function */ sleep_function,
-	/* long_desc */ "Pause the channel for a given number of milliseconds, consuming the audio for that period of time.",
+	/* long_desc */
+	"Pause the channel for a given number of milliseconds, consuming the audio for that period of time.",
 	/* short_desc */ "Pause a channel",
 	/* syntax */ "<pausemilliseconds>",
 	/* flags */ SAF_NONE,

Modified: freeswitch/branches/cparker/src/mod/applications/mod_echo/mod_echo.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_echo/mod_echo.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_echo/mod_echo.c	Tue Apr 24 10:14:28 2007
@@ -38,7 +38,7 @@
 	switch_channel_t *channel;
 
 	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);	
+	assert(channel != NULL);
 
 	switch_channel_answer(channel);
 

Modified: freeswitch/branches/cparker/src/mod/applications/mod_enum/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_enum/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_enum/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,21 +1,10 @@
-CFLAGS += -I$(BASE)/libs/udns
-LDFLAGS += -L$(BASE)/libs/udns -ludns
-LINKER=$(CC)
+BASE=../../../..
+UDNS_DIR=$(BASE)/libs/udns
+LOCAL_CFLAGS=-I$(UDNS_DIR) -DHAVE_POLL
+LOCAL_OBJS=$(UDNS_DIR)/udns_dn.o $(UDNS_DIR)/udns_dntosp.o $(UDNS_DIR)/udns_parse.o $(UDNS_DIR)/udns_misc.o \
+$(UDNS_DIR)/udns_rr_a.o $(UDNS_DIR)/udns_rr_ptr.o $(UDNS_DIR)/udns_rr_mx.o $(UDNS_DIR)/udns_rr_txt.o $(UDNS_DIR)/udns_bl.o \
+$(UDNS_DIR)/udns_rr_srv.o $(UDNS_DIR)/udns_rr_naptr.o $(UDNS_DIR)/udns_codes.o $(UDNS_DIR)/udns_resolver.o
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) udns
+include $(BASE)/build/modmake.rules
 
-%.o:  %.c
-	$(CC) -fPIC $(CFLAGS) -c -o $@ $<
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(LINKER) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(MODNAME).o $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/applications/mod_enum/mod_enum.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_enum/mod_enum.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_enum/mod_enum.c	Tue Apr 24 10:14:28 2007
@@ -48,10 +48,10 @@
 typedef struct enum_record enum_record_t;
 
 struct query {
-	const char *name;		/* original query string */
+	const char *name;			/* original query string */
 	char *number;
 	unsigned char dn[DNS_MAXDN];
-	enum dns_type qtyp;		/* type of the query */
+	enum dns_type qtyp;			/* type of the query */
 	enum_record_t *results;
 };
 typedef struct query enum_query_t;
@@ -77,7 +77,7 @@
 SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_root, globals.root)
 
 
-static void add_route(char *service, char *regex, char *replace)
+	 static void add_route(char *service, char *regex, char *replace)
 {
 	enum_route_t *route, *rp;
 
@@ -86,11 +86,11 @@
 	}
 
 	memset(route, 0, sizeof(*route));
-	
+
 	route->service = strdup(service);
 	route->regex = strdup(regex);
 	route->replace = strdup(replace);
-	
+
 	if (!globals.route_order) {
 		globals.route_order = route;
 	} else {
@@ -107,8 +107,8 @@
 static switch_status_t load_config(void)
 {
 	char *cf = "enum.conf";
-    switch_xml_t cfg, xml = NULL, param, settings, route, routes;
-    switch_status_t status = SWITCH_STATUS_SUCCESS;
+	switch_xml_t cfg, xml = NULL, param, settings, route, routes;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
 
 	memset(&globals, 0, sizeof(globals));
 	if (switch_core_new_memory_pool(&globals.pool) != SWITCH_STATUS_SUCCESS) {
@@ -119,39 +119,39 @@
 
 	switch_core_hash_init(&globals.routes, globals.pool);
 
-    if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", cf);
-        status = SWITCH_STATUS_FALSE;
-        goto done;
-    }
-
-    if ((settings = switch_xml_child(cfg, "settings"))) {
-        for (param = switch_xml_child(settings, "param"); param; param = param->next) {
-            char *var = (char *) switch_xml_attr_soft(param, "name");
-            char *val = (char *) switch_xml_attr_soft(param, "value");
-            if (!strcasecmp(var, "default-root")) {
+	if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", cf);
+		status = SWITCH_STATUS_FALSE;
+		goto done;
+	}
+
+	if ((settings = switch_xml_child(cfg, "settings"))) {
+		for (param = switch_xml_child(settings, "param"); param; param = param->next) {
+			char *var = (char *) switch_xml_attr_soft(param, "name");
+			char *val = (char *) switch_xml_attr_soft(param, "value");
+			if (!strcasecmp(var, "default-root")) {
 				set_global_root(val);
-            } else if (!strcasecmp(var, "log-level-trace")) {
-				
-            }
-        }
-    }
-
-    if ((routes = switch_xml_child(cfg, "routes"))) {
-        for (route = switch_xml_child(routes, "route"); route; route = route->next) {
-            char *service = (char *) switch_xml_attr_soft(route, "service");
-            char *regex = (char *) switch_xml_attr_soft(route, "regex");
-            char *replace = (char *) switch_xml_attr_soft(route, "replace");
+			} else if (!strcasecmp(var, "log-level-trace")) {
+
+			}
+		}
+	}
+
+	if ((routes = switch_xml_child(cfg, "routes"))) {
+		for (route = switch_xml_child(routes, "route"); route; route = route->next) {
+			char *service = (char *) switch_xml_attr_soft(route, "service");
+			char *regex = (char *) switch_xml_attr_soft(route, "regex");
+			char *replace = (char *) switch_xml_attr_soft(route, "replace");
 
 			if (service && regex && replace) {
 				add_route(service, regex, replace);
 			} else {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Route!\n");
 			}
-        }
-    }
-	
- done:
+		}
+	}
+
+  done:
 
 	if (xml) {
 		switch_xml_free(xml);
@@ -168,20 +168,20 @@
 
 static char *reverse_number(char *in, char *root)
 {
-    switch_size_t len;
-    char *out = NULL;
-    char *y,*z;
-
-    if (!(in && root)) {
-        return NULL;
-    }
-
-    len = (strlen(in) * 2) + strlen(root) + 1;
-    if ((out = malloc(len))) {
-        memset(out, 0, len);
+	switch_size_t len;
+	char *out = NULL;
+	char *y, *z;
 
-        z = out;
-        for(y = in + (strlen(in) - 1); y; y--) {
+	if (!(in && root)) {
+		return NULL;
+	}
+
+	len = (strlen(in) * 2) + strlen(root) + 1;
+	if ((out = malloc(len))) {
+		memset(out, 0, len);
+
+		z = out;
+		for (y = in + (strlen(in) - 1); y; y--) {
 			if (*y > 47 && *y < 58) {
 				*z++ = *y;
 				*z++ = '.';
@@ -189,21 +189,22 @@
 			if (y == in) {
 				break;
 			}
-        }
-        strcat(z, root);
-    }
+		}
+		strcat(z, root);
+	}
 
 	return out;
 }
 
-static void dnserror(enum_query_t *q, int errnum) {
+static void dnserror(enum_query_t * q, int errnum)
+{
 
-    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "unable to lookup %s record for %s: %s\n",
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "unable to lookup %s record for %s: %s\n",
 					  dns_typename(q->qtyp), dns_dntosp(q->dn), dns_strerror(errnum));
 }
 
 
-static void add_result(enum_query_t *q, int order, int preference, char *service, char *route)
+static void add_result(enum_query_t * q, int order, int preference, char *service, char *route)
 {
 	enum_record_t *new_result, *rp, *prev = NULL;
 
@@ -213,12 +214,12 @@
 	}
 
 	memset(new_result, 0, sizeof(*new_result));
-	
+
 	new_result->order = order;
 	new_result->preference = preference;
 	new_result->service = strdup(service);
 	new_result->route = strdup(route);
-	
+
 
 	if (!q->results) {
 		q->results = new_result;
@@ -227,12 +228,12 @@
 
 	rp = q->results;
 
-	while(rp && strcmp(rp->service, new_result->service)) {
+	while (rp && strcmp(rp->service, new_result->service)) {
 		prev = rp;
 		rp = rp->next;
 	}
 
-	while(rp && !strcmp(rp->service, new_result->service) && new_result->order > rp->order) {
+	while (rp && !strcmp(rp->service, new_result->service) && new_result->order > rp->order) {
 		prev = rp;
 		rp = rp->next;
 	}
@@ -241,7 +242,7 @@
 		prev = rp;
 		rp = rp->next;
 	}
-	
+
 	if (prev) {
 		new_result->next = rp;
 		prev->next = new_result;
@@ -252,11 +253,11 @@
 }
 
 
-static void free_results(enum_record_t **results) 
+static void free_results(enum_record_t ** results)
 {
 	enum_record_t *fp, *rp;
 
-	for(rp = *results; rp;) {
+	for (rp = *results; rp;) {
 		fp = rp;
 		rp = rp->next;
 		switch_safe_free(fp->service);
@@ -266,7 +267,8 @@
 	*results = NULL;
 }
 
-static void parse_rr(const struct dns_parse *p, enum_query_t *q, struct dns_rr *rr) {
+static void parse_rr(const struct dns_parse *p, enum_query_t * q, struct dns_rr *rr)
+{
 	const unsigned char *pkt = p->dnsp_pkt;
 	const unsigned char *end = p->dnsp_end;
 	const unsigned char *dptr = rr->dnsrr_dptr;
@@ -282,25 +284,26 @@
 	char *regex = NULL;
 	char *replace = NULL;
 	int argc = 0;
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	int leap;
 
-	switch(rr->dnsrr_typ) {
+	switch (rr->dnsrr_typ) {
 
-	case DNS_T_NAPTR:	/* prio weight port targetDN */
+	case DNS_T_NAPTR:			/* prio weight port targetDN */
 		c = dptr;
 		c += 2 + 2 + 2;
-		if (dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0 || c != dend) goto xperr;
+		if (dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0 || c != dend)
+			goto xperr;
 		c = dptr;
-		
+
 		leap = *dn;
-		nme = (char *)dn+1;
+		nme = (char *) dn + 1;
 
-		order = dns_get16(c+0);
-		preference = dns_get16(c+2);
-		flags = (char) dns_get16(c+4);		
+		order = dns_get16(c + 0);
+		preference = dns_get16(c + 2);
+		flags = (char) dns_get16(c + 4);
 
-		if ((ptr = nme+leap)) {
+		if ((ptr = nme + leap)) {
 			service = nme;
 			*ptr++ = '\0';
 			argc = switch_separate_string(ptr, '!', argv, (sizeof(argv) / sizeof(argv[0])));
@@ -308,23 +311,23 @@
 			replace = argv[2];
 		}
 
-		for(ptr = replace; ptr && *ptr; ptr++) {
+		for (ptr = replace; ptr && *ptr; ptr++) {
 			if (*ptr == '\\') {
 				*ptr = '$';
 			}
 		}
 
 		if (flags && service && regex && replace) {
-			pcre *re = NULL;
+			switch_regex_t *re = NULL;
 			int proceed = 0, ovector[30];
 			char substituted[1024] = "";
 			char rbuf[1024] = "";
 			char *uri;
 			enum_route_t *route;
 
-			switch_clean_re(re);
+			switch_regex_safe_free(re);
 
-			if ((proceed = switch_perform_regex(q->number, regex, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
+			if ((proceed = switch_regex_perform(q->number, regex, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
 				if (strchr(regex, '(')) {
 					switch_perform_substitution(re, proceed, replace, q->number, substituted, sizeof(substituted), ovector);
 					uri = substituted;
@@ -332,9 +335,9 @@
 					uri = replace;
 				}
 
-				if ((route = (enum_route_t *) switch_core_hash_find(globals.routes, service))){
-					switch_clean_re(re);
-					if ((proceed = switch_perform_regex(uri, route->regex, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
+				if ((route = (enum_route_t *) switch_core_hash_find(globals.routes, service))) {
+					switch_regex_safe_free(re);
+					if ((proceed = switch_regex_perform(uri, route->regex, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
 						if (strchr(route->regex, '(')) {
 							switch_perform_substitution(re, proceed, route->replace, uri, rbuf, sizeof(rbuf), ovector);
 							uri = rbuf;
@@ -343,11 +346,11 @@
 						}
 					}
 				}
-				
+
 				add_result(q, order, preference, service, uri);
 			}
 
-			switch_clean_re(re);
+			switch_regex_safe_free(re);
 		}
 
 		break;
@@ -358,12 +361,13 @@
 
 	return;
 
- xperr:
+  xperr:
 	//printf("<parse error>\n");
 	return;
 }
 
-static void dnscb(struct dns_ctx *ctx, void *result, void *data) {
+static void dnscb(struct dns_ctx *ctx, void *result, void *data)
+{
 	int r = dns_status(ctx);
 	enum_query_t *q = data;
 	struct dns_parse p;
@@ -375,25 +379,24 @@
 		dnserror(q, r);
 		return;
 	}
-	pkt = result; end = pkt + r; cur = dns_payload(pkt);
+	pkt = result;
+	end = pkt + r;
+	cur = dns_payload(pkt);
 	dns_getdn(pkt, &cur, end, dn, sizeof(dn));
 	dns_initparse(&p, NULL, pkt, cur, end);
 	p.dnsp_qcls = p.dnsp_qtyp = 0;
 	qdn = dn;
 	nrr = 0;
-	while((r = dns_nextrr(&p, &rr)) > 0) {
-		if (!dns_dnequal(qdn, rr.dnsrr_dn)) continue;
-		if ((qcls == DNS_C_ANY || qcls == rr.dnsrr_cls) &&
-			(q->qtyp == DNS_T_ANY || q->qtyp == rr.dnsrr_typ))
+	while ((r = dns_nextrr(&p, &rr)) > 0) {
+		if (!dns_dnequal(qdn, rr.dnsrr_dn))
+			continue;
+		if ((qcls == DNS_C_ANY || qcls == rr.dnsrr_cls) && (q->qtyp == DNS_T_ANY || q->qtyp == rr.dnsrr_typ))
 			++nrr;
 		else if (rr.dnsrr_typ == DNS_T_CNAME && !nrr) {
-			if (dns_getdn(pkt, &rr.dnsrr_dptr, end,
-						  p.dnsp_dnbuf, sizeof(p.dnsp_dnbuf)) <= 0 ||
-				rr.dnsrr_dptr != rr.dnsrr_dend) {
+			if (dns_getdn(pkt, &rr.dnsrr_dptr, end, p.dnsp_dnbuf, sizeof(p.dnsp_dnbuf)) <= 0 || rr.dnsrr_dptr != rr.dnsrr_dend) {
 				r = DNS_E_PROTOCOL;
 				break;
-			}
-			else {
+			} else {
 				qdn = p.dnsp_dnbuf;
 			}
 		}
@@ -409,28 +412,28 @@
 	dns_rewind(&p, NULL);
 	p.dnsp_qtyp = q->qtyp;
 	p.dnsp_qcls = qcls;
-	while(dns_nextrr(&p, &rr)) {
+	while (dns_nextrr(&p, &rr)) {
 		parse_rr(&p, q, &rr);
 	}
-  
+
 	free(result);
 }
 
 
-static switch_status_t enum_lookup(char *root, char *in, enum_record_t **results)
+static switch_status_t enum_lookup(char *root, char *in, enum_record_t ** results)
 {
-	switch_status_t sstatus  = SWITCH_STATUS_SUCCESS;
+	switch_status_t sstatus = SWITCH_STATUS_SUCCESS;
 	char *name = NULL;
-	enum_query_t query = {0};
+	enum_query_t query = { 0 };
 	enum dns_type l_qtyp = DNS_T_NAPTR;
 	int i = 0, abs = 0;
-	dns_socket fd = (dns_socket)-1;
+	dns_socket fd = (dns_socket) - 1;
 	fd_set fds;
-	struct timeval tv = {0};
+	struct timeval tv = { 0 };
 	time_t now = 0;
 	struct dns_ctx *nctx = NULL;
 	char *num, *mnum = NULL;
-	
+
 	if (*in != '+') {
 		mnum = switch_mprintf("+%s", in);
 		num = mnum;
@@ -458,7 +461,7 @@
 		goto done;
 	}
 
-	dns_ptodn(name, (unsigned int)strlen(name), query.dn, sizeof(query.dn), &abs);
+	dns_ptodn(name, (unsigned int) strlen(name), query.dn, sizeof(query.dn), &abs);
 	query.name = name;
 	query.number = num;
 	query.qtyp = l_qtyp;
@@ -466,7 +469,7 @@
 	if (abs) {
 		abs = DNS_NOSRCH;
 	}
-	
+
 	if (!dns_submit_dn(nctx, query.dn, qcls, l_qtyp, abs, 0, dnscb, &query)) {
 		dnserror(&query, dns_status(nctx));
 	}
@@ -474,7 +477,7 @@
 	FD_ZERO(&fds);
 	now = 0;
 
-	while((i = dns_timeouts(nctx, -1, now)) > 0) {
+	while ((i = dns_timeouts(nctx, -1, now)) > 0) {
 #ifdef _MSC_VER
 #pragma warning(push)
 #pragma warning(disable: 4389 4127)
@@ -485,9 +488,10 @@
 #endif
 		tv.tv_sec = i;
 		tv.tv_usec = 0;
-		i = select((int)(fd+1), &fds, 0, 0, &tv);
+		i = select((int) (fd + 1), &fds, 0, 0, &tv);
 		now = time(NULL);
-		if (i > 0) dns_ioevent(nctx, now);
+		if (i > 0)
+			dns_ioevent(nctx, now);
 	}
 
 	if (!query.results) {
@@ -497,17 +501,17 @@
 	*results = query.results;
 	query.results = NULL;
 
- done:
+  done:
 
 	if (fd > -1) {
 		closesocket(fd);
-		fd = (dns_socket)-1;
+		fd = (dns_socket) - 1;
 	}
 
 	if (nctx) {
 		dns_free(nctx);
 	}
-	
+
 	switch_safe_free(name);
 	switch_safe_free(mnum);
 
@@ -515,43 +519,44 @@
 }
 
 
-static switch_caller_extension_t *enum_dialplan_hunt(switch_core_session_t *session, void *arg)
+static switch_caller_extension_t *enum_dialplan_hunt(switch_core_session_t *session, void *arg, switch_caller_profile_t *caller_profile)
 {
 	switch_caller_extension_t *extension = NULL;
-	switch_caller_profile_t *caller_profile;
 	enum_record_t *results, *rp;
 	switch_channel_t *channel = switch_core_session_get_channel(session);
 	enum_route_t *rtp;
 	char *dp = (char *) arg;
 
-    assert(channel != NULL);
+	assert(channel != NULL);
+
+	if (!caller_profile) {
+		caller_profile = switch_channel_get_caller_profile(channel);
+	}
 
-	caller_profile = switch_channel_get_caller_profile(channel);
-	
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "ENUM Lookup on %s\n", caller_profile->destination_number);
 
 	if (enum_lookup(switch_strlen_zero(dp) ? globals.root : dp, caller_profile->destination_number, &results) == SWITCH_STATUS_SUCCESS) {
 		if ((extension = switch_caller_extension_new(session, caller_profile->destination_number, caller_profile->destination_number)) == 0) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "memory error!\n");
-			free_results(&results);	
+			free_results(&results);
 			return NULL;
 		}
 		switch_channel_set_variable(channel, SWITCH_HANGUP_AFTER_BRIDGE_VARIABLE, "true");
-		
-		for(rtp = globals.route_order; rtp; rtp = rtp->next) {
-			for(rp = results; rp; rp = rp->next) {
+
+		for (rtp = globals.route_order; rtp; rtp = rtp->next) {
+			for (rp = results; rp; rp = rp->next) {
 				if (!strcmp(rtp->service, rp->service)) {
-					switch_caller_extension_add_application(session, extension, "bridge", rp->route);					
+					switch_caller_extension_add_application(session, extension, "bridge", rp->route);
 				}
 			}
 		}
 
-		free_results(&results);	
+		free_results(&results);
 	}
 
 	if (extension) {
-        switch_channel_set_state(channel, CS_EXECUTE);
-    }
+		switch_channel_set_state(channel, CS_EXECUTE);
+	}
 
 	return extension;
 
@@ -560,7 +565,7 @@
 static void enum_app_function(switch_core_session_t *session, char *data)
 {
 	int argc = 0;
-    char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	char *mydata = NULL;
 	char *dest = NULL, *root = NULL;
 	enum_record_t *results, *rp;
@@ -575,12 +580,12 @@
 	assert(channel != NULL);
 
 	if (!(mydata = switch_core_session_strdup(session, data))) {
-        return;
-    }
+		return;
+	}
 
-    if ((argc = switch_separate_string(mydata, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
+	if ((argc = switch_separate_string(mydata, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
 		dest = argv[0];
-        root = argv[1] ? argv[1] : globals.root;
+		root = argv[1] ? argv[1] : globals.root;
 		if (enum_lookup(root, data, &results) == SWITCH_STATUS_SUCCESS) {
 			switch_hash_index_t *hi;
 			void *vval;
@@ -593,8 +598,8 @@
 				}
 			}
 
-			for(rtp = globals.route_order; rtp; rtp = rtp->next) {
-				for(rp = results; rp; rp = rp->next) {
+			for (rtp = globals.route_order; rtp; rtp = rtp->next) {
+				for (rp = results; rp; rp = rp->next) {
 					if (!strcmp(rtp->service, rp->service)) {
 						snprintf(vbuf, sizeof(vbuf), "enum_route_%d", cnt++);
 						switch_channel_set_variable(channel, vbuf, rp->route);
@@ -608,19 +613,19 @@
 			}
 			snprintf(vbuf, sizeof(vbuf), "%d", cnt);
 			switch_channel_set_variable(channel, "enum_route_count", vbuf);
-			*(rbuf+strlen(rbuf)-1) = '\0';
+			*(rbuf + strlen(rbuf) - 1) = '\0';
 			switch_channel_set_variable(channel, "enum_auto_route", rbuf);
-			free_results(&results);	
+			free_results(&results);
 		}
 	}
-	
+
 }
 
 static switch_status_t enum_function(char *data, switch_core_session_t *session, switch_stream_handle_t *stream)
 {
 
 	int argc = 0;
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	enum_record_t *results, *rp;
 	char *mydata = NULL;
 	char *dest = NULL, *root = NULL;
@@ -639,35 +644,33 @@
 	if ((argc = switch_separate_string(mydata, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
 		dest = argv[0];
 		root = argv[1] ? argv[1] : globals.root;
-		
+
 		if (!enum_lookup(root, data, &results) == SWITCH_STATUS_SUCCESS) {
 			stream->write_function(stream, "No Match!\n");
 			return SWITCH_STATUS_SUCCESS;
 		}
-		
+
 		stream->write_function(stream,
 							   "\nOffered Routes:\n"
-							   "Order\tPref\tService   \tRoute\n"
-							   "==============================================================================\n");
+							   "Order\tPref\tService   \tRoute\n" "==============================================================================\n");
 
-		for(rp = results; rp; rp = rp->next) {
+		for (rp = results; rp; rp = rp->next) {
 			stream->write_function(stream, "%d\t%d\t%-10s\t%s\n", rp->order, rp->preference, rp->service, rp->route);
 		}
-	
+
 
 		stream->write_function(stream,
 							   "\nSupported Routes:\n"
-							   "Order\tPref\tService   \tRoute\n"
-							   "==============================================================================\n");
+							   "Order\tPref\tService   \tRoute\n" "==============================================================================\n");
 
-		for(rtp = globals.route_order; rtp; rtp = rtp->next) {
-			for(rp = results; rp; rp = rp->next) {
+		for (rtp = globals.route_order; rtp; rtp = rtp->next) {
+			for (rp = results; rp; rp = rp->next) {
 				if (!strcmp(rtp->service, rp->service)) {
 					stream->write_function(stream, "%d\t%d\t%-10s\t%s\n", rp->order, rp->preference, rp->service, rp->route);
 				}
 			}
 		}
-		
+
 		free_results(&results);
 	} else {
 		stream->write_function(stream, "Invalid Input!\n");
@@ -678,14 +681,14 @@
 
 
 static const switch_dialplan_interface_t enum_dialplan_interface = {
-    /*.interface_name = */ "enum",
-    /*.hunt_function = */ enum_dialplan_hunt
-    /*.next = NULL */
+	/*.interface_name = */ "enum",
+	/*.hunt_function = */ enum_dialplan_hunt
+		/*.next = NULL */
 };
 
 static const switch_application_interface_t enum_application_interface = {
 	/*.interface_name */ "enum",
-	/*.application_function */ enum_app_function,	
+	/*.application_function */ enum_app_function,
 	/* long_desc */ "Perform an ENUM lookup",
 	/* short_desc */ "Perform an ENUM lookup",
 	/* syntax */ "<number> [<root>]",
@@ -729,5 +732,3 @@
 	/* indicate that the module should continue to be loaded */
 	return SWITCH_STATUS_SUCCESS;
 }
-
-

Modified: freeswitch/branches/cparker/src/mod/applications/mod_ivrtest/mod_ivrtest.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_ivrtest/mod_ivrtest.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_ivrtest/mod_ivrtest.c	Tue Apr 24 10:14:28 2007
@@ -42,13 +42,13 @@
 static switch_status_t on_dtmf(switch_core_session_t *session, void *input, switch_input_type_t itype, void *buf, unsigned int buflen)
 {
 	switch (itype) {
-	case SWITCH_INPUT_TYPE_DTMF: {
-		char *dtmf = (char *) input;
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Digits %s\n", dtmf);
-	
-		switch_copy_string((char *)buf, dtmf, buflen);
-		return SWITCH_STATUS_BREAK;
-	}
+	case SWITCH_INPUT_TYPE_DTMF:{
+			char *dtmf = (char *) input;
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Digits %s\n", dtmf);
+
+			switch_copy_string((char *) buf, dtmf, buflen);
+			return SWITCH_STATUS_BREAK;
+		}
 		break;
 	default:
 		break;
@@ -72,9 +72,8 @@
 	for (team = switch_xml_child(f1, "team"); team; team = team->next) {
 		teamname = switch_xml_attr_soft(team, "name");
 		for (driver = switch_xml_child(team, "driver"); driver; driver = driver->next) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, 
-							  "%s, %s: %s\n", switch_xml_child(driver, "name")->txt, teamname,
-							  switch_xml_child(driver, "points")->txt);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
+							  "%s, %s: %s\n", switch_xml_child(driver, "name")->txt, teamname, switch_xml_child(driver, "points")->txt);
 		}
 	}
 	switch_xml_free(f1);
@@ -84,7 +83,7 @@
 static void ivr_application_function(switch_core_session_t *session, char *data)
 {
 	switch_channel_t *channel = switch_core_session_get_channel(session);
-	char *params = switch_core_session_strdup(session,data);
+	char *params = switch_core_session_strdup(session, data);
 
 	if (channel != NULL && params != NULL) {
 		switch_ivr_menu_t *menu = NULL, *sub_menu = NULL;
@@ -97,26 +96,11 @@
 									  NULL,
 									  "main",
 									  "please enter some numbers so i can figure out if I have any bugs or not",
-									  "enter some numbers",
-									  NULL,
-									  "I have no idea what that is",
-									  "cepstral",
-									  "david",
-									  NULL,
-									  15000, 10, NULL);
+									  "enter some numbers", NULL, "I have no idea what that is", "cepstral", "david", NULL, 15000, 10, NULL);
 
 
 		status = switch_ivr_menu_init(&sub_menu,
-									  menu,
-									  "sub",
-									  "/ram/congrats.wav",
-									  "/ram/extension.wav",
-									  NULL,
-									  "/ram/invalid.wav",
-									  NULL,
-									  NULL,
-									  NULL,
-									  15000, 10, NULL);
+									  menu, "sub", "/ram/congrats.wav", "/ram/extension.wav", NULL, "/ram/invalid.wav", NULL, NULL, NULL, 15000, 10, NULL);
 
 		if (status == SWITCH_STATUS_SUCCESS) {
 			// build the menu
@@ -125,10 +109,10 @@
 			switch_ivr_menu_bind_action(menu, SWITCH_IVR_ACTION_EXECMENU, "sub", "3");
 			//switch_ivr_menu_bind_action(menu, SWITCH_IVR_ACTION_PLAYSOUND, "/usr/local/freeswitch/sounds/3.wav", "3");
 
-			
+
 			switch_ivr_menu_bind_action(sub_menu, SWITCH_IVR_ACTION_PLAYSOUND, "/ram/swimp.raw", "1");
 			switch_ivr_menu_bind_action(sub_menu, SWITCH_IVR_ACTION_BACK, NULL, "2");
-			
+
 
 			// start the menu
 			status = switch_ivr_menu_execute(session, menu, "main", NULL);
@@ -136,11 +120,11 @@
 			// cleaup the menu
 			switch_ivr_menu_stack_free(menu);
 		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to build menu %s\n",params);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "unable to build menu %s\n", params);
 		}
-			
 
-		switch_ivr_play_file(session, NULL,"/ram/goodbye.wav",NULL);
+
+		switch_ivr_play_file(session, NULL, "/ram/goodbye.wav", NULL);
 	}
 }
 
@@ -151,15 +135,10 @@
 	switch_directory_handle_t dh;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 
-	if (switch_core_directory_open(&dh, 
-								   "ldap",
-								   "ldap.freeswitch.org",
-								   "cn=Manager,dc=freeswitch,dc=org",
-								   "test",
-								   NULL) != SWITCH_STATUS_SUCCESS) {
+	if (switch_core_directory_open(&dh, "ldap", "ldap.freeswitch.org", "cn=Manager,dc=freeswitch,dc=org", "test", NULL) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't connect\n");
 		return;
 	}
@@ -181,12 +160,12 @@
 {
 
 	switch (itype) {
-	case SWITCH_INPUT_TYPE_DTMF: {
-		char *dtmf = (char *) input;
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Digits %s\n", dtmf);
+	case SWITCH_INPUT_TYPE_DTMF:{
+			char *dtmf = (char *) input;
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Digits %s\n", dtmf);
 
-		switch_copy_string((char *)buf, dtmf, buflen);
-	}
+			switch_copy_string((char *) buf, dtmf, buflen);
+		}
 		break;
 	default:
 		break;
@@ -203,9 +182,9 @@
 	char buf[10] = "";
 	char *argv[3];
 	int argc;
-    switch_input_args_t args = {0};
+	switch_input_args_t args = { 0 };
 
-	if(!(mydata = switch_core_session_strdup(session, (char *) data))) {
+	if (!(mydata = switch_core_session_strdup(session, (char *) data))) {
 		return;
 	}
 
@@ -221,82 +200,79 @@
 	}
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
-	
-    switch_channel_answer(channel);
+	assert(channel != NULL);
+
+	switch_channel_answer(channel);
 
 	codec = switch_core_session_get_read_codec(session);
-    args.input_callback = show_dtmf;
-    args.buf = buf;
-    args.buflen = sizeof(buf);
+	args.input_callback = show_dtmf;
+	args.buf = buf;
+	args.buflen = sizeof(buf);
 	switch_ivr_speak_text(session, tts_name, voice_name, codec->implementation->samples_per_second, text, &args);
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Done\n");
 }
 
-static void bug_callback(switch_media_bug_t *bug, void *user_data, switch_abc_type_t type)
+#ifdef BUGTEST
+static switch_bool_t bug_callback(switch_media_bug_t *bug, void *user_data, switch_abc_type_t type)
 {
-    switch_frame_t *frame;
+	switch_frame_t *frame;
 
-    switch(type) {
+	switch (type) {
 	case SWITCH_ABC_TYPE_WRITE_REPLACE:
-        frame = switch_core_media_bug_get_replace_frame(bug);
-        switch_core_media_bug_set_replace_frame(bug, frame);
-        printf("W00t\n");
-        break;
-    default:
-        break;
-    }
+		frame = switch_core_media_bug_get_replace_frame(bug);
+		switch_core_media_bug_set_replace_frame(bug, frame);
+		printf("W00t\n");
+		break;
+	default:
+		break;
+	}
 
+	return SWITCH_TRUE;
 }
+#endif
 
 static void bugtest_function(switch_core_session_t *session, char *data)
 {
+#ifdef BUGTEST
 	switch_media_bug_t *bug;
 	switch_channel_t *channel = switch_core_session_get_channel(session);
-    switch_status_t status;
+	switch_status_t status;
 
-	if ((status = switch_core_media_bug_add(session,
-											bug_callback,
-											NULL,
-											SMBF_WRITE_REPLACE,
-											&bug)) != SWITCH_STATUS_SUCCESS) {
+	if ((status = switch_core_media_bug_add(session, bug_callback, NULL, SMBF_WRITE_REPLACE, &bug)) != SWITCH_STATUS_SUCCESS) {
 		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-        return;
+		return;
 	}
-    switch_ivr_play_file(session, NULL, data, NULL);
+#endif
+	//switch_ivr_schedule_broadcast(time(NULL) + 10, switch_core_session_get_uuid(session), "/Users/anthm/sr8k.wav", SMF_ECHO_ALEG);
+	//switch_ivr_schedule_transfer(time(NULL) + 10, switch_core_session_get_uuid(session), "2000", NULL, NULL);
+	//switch_ivr_schedule_hangup(time(NULL) + 10, switch_core_session_get_uuid(session), SWITCH_CAUSE_ALLOTTED_TIMEOUT);
+
+	switch_ivr_play_file(session, NULL, data, NULL);
 }
 
 #if 1
 static void asrtest_function(switch_core_session_t *session, char *data)
 {
-	switch_ivr_detect_speech(session,
-							 "lumenvox",
-							 "demo",
-							 data,
-							 "127.0.0.1",
-							 NULL);
+	switch_ivr_detect_speech(session, "lumenvox", "demo", data, "127.0.0.1", NULL);
 }
 
-#else 
+#else
 static void asrtest_function(switch_core_session_t *session, char *data)
 {
-	switch_asr_handle_t ah = {0};
+	switch_asr_handle_t ah = { 0 };
 	switch_asr_flag_t flags = SWITCH_ASR_FLAG_NONE;
 	switch_channel_t *channel = switch_core_session_get_channel(session);
 	char *codec_name = "L16";
-	switch_codec_t codec = {0}, *read_codec;
-	switch_frame_t write_frame = {0}, *write_frame_p = NULL;
+	switch_codec_t codec = { 0 }, *read_codec;
+	switch_frame_t write_frame = { 0 }, *write_frame_p = NULL;
 	char xdata[1024] = "";
 
 	read_codec = switch_core_session_get_read_codec(session);
 	assert(read_codec != NULL);
-	
+
 
 	if (switch_core_asr_open(&ah, "lumenvox",
-							 read_codec->implementation->iananame,
-							 8000,
-							 "127.0.0.1",
-							 &flags,
+							 read_codec->implementation->iananame, 8000, "127.0.0.1", &flags,
 							 switch_core_session_get_pool(session)) == SWITCH_STATUS_SUCCESS) {
 		if (strcmp(ah.codec, read_codec->implementation->iananame)) {
 			if (switch_core_codec_init(&codec,
@@ -308,36 +284,37 @@
 									   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
 									   NULL, switch_core_session_get_pool(session)) == SWITCH_STATUS_SUCCESS) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activated\n");
-				switch_core_session_set_read_codec(session, &codec);		
+				switch_core_session_set_read_codec(session, &codec);
 				write_frame.data = xdata;
 				write_frame.buflen = sizeof(xdata);
 				write_frame.codec = &codec;
 				write_frame_p = &write_frame;
 			} else {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec Activation Failed %s@%uhz %u channels %dms\n",
-								  codec_name, read_codec->implementation->samples_per_second, read_codec->implementation->number_of_channels,
-								  read_codec->implementation->microseconds_per_frame / 1000);
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+								  "Codec Activation Failed %s@%uhz %u channels %dms\n", codec_name,
+								  read_codec->implementation->samples_per_second,
+								  read_codec->implementation->number_of_channels, read_codec->implementation->microseconds_per_frame / 1000);
 				switch_core_session_reset(session);
 				return;
 			}
 		}
-		
-		
+
+
 		if (switch_core_asr_load_grammar(&ah, "demo", "/opt/lumenvox/engine_7.0/Lang/BuiltinGrammars/ABNFPhone.gram") != SWITCH_STATUS_SUCCESS) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error loading Grammar\n");
 			goto end;
 		}
-		
-		while(switch_channel_ready(channel)) {
+
+		while (switch_channel_ready(channel)) {
 			switch_frame_t *read_frame;
 			switch_status_t status = switch_core_session_read_frame(session, &read_frame, -1, 0);
 			char *xmlstr = NULL;
 			switch_xml_t xml = NULL, result;
- 
+
 			if (!SWITCH_READ_ACCEPTABLE(status)) {
 				break;
 			}
-			
+
 			if (switch_test_flag(read_frame, SFF_CNG)) {
 				continue;
 			}
@@ -346,7 +323,7 @@
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error Feeding Data\n");
 				break;
 			}
-			
+
 			if (switch_core_asr_check_results(&ah, &flags) == SWITCH_STATUS_SUCCESS) {
 				if (switch_core_asr_get_results(&ah, &xmlstr, &flags) != SWITCH_STATUS_SUCCESS) {
 					break;
@@ -359,7 +336,7 @@
 				}
 				switch_safe_free(xmlstr);
 			}
-			
+
 			if (write_frame_p) {
 				write_frame.datalen = read_frame->datalen;
 				switch_core_session_write_frame(session, write_frame_p, -1, 0);
@@ -369,7 +346,7 @@
 			}
 		}
 
-	end:
+	  end:
 		if (write_frame_p) {
 			switch_core_session_set_read_codec(session, read_codec);
 			switch_core_codec_destroy(&codec);
@@ -391,9 +368,9 @@
 	char buf[10] = "";
 	char term;
 	char say[128] = "";
-	
+
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 	switch_channel_answer(channel);
 
@@ -404,15 +381,15 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Enter up to 10 digits, press # to terminate, * to hangup\n");
 
 		if (data) {
-            switch_input_args_t args = {0};
+			switch_input_args_t args = { 0 };
 			/* you could have passed NULL instead of on_dtmf to get this exact behaviour (copy the digits to buf and stop playing)
 			   but you may want to pass the function if you have something cooler to do...
-			*/
-            args.input_callback = on_dtmf;
-            args.buf = buf;
-            args.buflen = sizeof(buf);
+			 */
+			args.input_callback = on_dtmf;
+			args.buf = buf;
+			args.buflen = sizeof(buf);
 			status = switch_ivr_play_file(session, NULL, data, &args);
-			
+
 			if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
 				switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
 				break;
@@ -431,7 +408,7 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, say);
 		switch_ivr_speak_text(session, "cepstral", "david", codec->implementation->samples_per_second, say, NULL);
 	}
-	
+
 }
 
 
@@ -440,7 +417,7 @@
 	switch_channel_t *channel;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "I globally hooked to [%s] on the hangup event\n", switch_channel_get_name(channel));
 	return SWITCH_STATUS_SUCCESS;
@@ -463,7 +440,7 @@
 	/*.application_function */ bugtest_function,
 	NULL, NULL, NULL,
 	/* flags */ SAF_NONE,
-	/*.next*/ NULL
+	/*.next */ NULL
 };
 
 static const switch_application_interface_t ivr_application_interface = {
@@ -471,7 +448,7 @@
 	/*.application_function */ ivr_application_function,
 	NULL, NULL, NULL,
 	/* flags */ SAF_NONE,
-	/*.next*/ &bug_application_interface
+	/*.next */ &bug_application_interface
 };
 
 static const switch_application_interface_t xml_application_interface = {
@@ -479,7 +456,7 @@
 	/*.application_function */ xml_function,
 	NULL, NULL, NULL,
 	/* flags */ SAF_NONE,
-	/*.next*/ &ivr_application_interface
+	/*.next */ &ivr_application_interface
 };
 
 static const switch_application_interface_t disast_application_interface = {
@@ -487,7 +464,7 @@
 	/*.application_function */ disast_function,
 	NULL, NULL, NULL,
 	/* flags */ SAF_SUPPORT_NOMEDIA,
-	/*.next*/ &xml_application_interface
+	/*.next */ &xml_application_interface
 };
 
 static const switch_application_interface_t tts_application_interface = {
@@ -495,7 +472,7 @@
 	/*.application_function */ tts_function,
 	NULL, NULL, NULL,
 	/* flags */ SAF_NONE,
-	/*.next*/ &disast_application_interface
+	/*.next */ &disast_application_interface
 };
 
 static const switch_application_interface_t dirtest_application_interface = {
@@ -503,7 +480,7 @@
 	/*.application_function */ dirtest_function,
 	NULL, NULL, NULL,
 	/* flags */ SAF_SUPPORT_NOMEDIA,
-	/*.next*/ &tts_application_interface
+	/*.next */ &tts_application_interface
 };
 
 static const switch_application_interface_t ivrtest_application_interface = {
@@ -511,7 +488,7 @@
 	/*.application_function */ ivrtest_function,
 	NULL, NULL, NULL,
 	/* flags */ SAF_NONE,
-	/*.next*/ &dirtest_application_interface
+	/*.next */ &dirtest_application_interface
 };
 
 static const switch_application_interface_t asrtest_application_interface = {
@@ -519,7 +496,7 @@
 	/*.application_function */ asrtest_function,
 	NULL, NULL, NULL,
 	/* flags */ SAF_NONE,
-	/*.next*/ &ivrtest_application_interface
+	/*.next */ &ivrtest_application_interface
 };
 
 static const switch_loadable_module_interface_t mod_ivrtest_module_interface = {

Modified: freeswitch/branches/cparker/src/mod/applications/mod_park/mod_park.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_park/mod_park.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_park/mod_park.c	Tue Apr 24 10:14:28 2007
@@ -35,13 +35,13 @@
 static void park_function(switch_core_session_t *session, char *data)
 {
 	switch_ivr_park(session, NULL);
-	
+
 }
 
 static const switch_application_interface_t park_application_interface = {
 	/*.interface_name */ "park",
 	/*.application_function */ park_function,
-	NULL,NULL,NULL,
+	NULL, NULL, NULL,
 	/* flags */ SAF_NONE,
 	NULL
 };

Modified: freeswitch/branches/cparker/src/mod/applications/mod_playback/mod_playback.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_playback/mod_playback.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_playback/mod_playback.c	Tue Apr 24 10:14:28 2007
@@ -41,21 +41,21 @@
 static switch_status_t on_dtmf(switch_core_session_t *session, void *input, switch_input_type_t itype, void *buf, unsigned int buflen)
 {
 
-	
+
 	switch (itype) {
-	case SWITCH_INPUT_TYPE_DTMF: {
-		char *dtmf = (char *) input;
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Digits %s\n", dtmf);
-		
-		if (*dtmf == '*') {
-			return SWITCH_STATUS_BREAK;
+	case SWITCH_INPUT_TYPE_DTMF:{
+			char *dtmf = (char *) input;
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Digits %s\n", dtmf);
+
+			if (*dtmf == '*') {
+				return SWITCH_STATUS_BREAK;
+			}
 		}
-	}
 		break;
 	default:
 		break;
 	}
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -64,28 +64,28 @@
 {
 	switch_channel_t *channel;
 	char buf[10];
-	char *argv[4] = {0};
+	char *argv[4] = { 0 };
 	int argc;
 	char *engine = NULL;
 	char *voice = NULL;
 	char *text = NULL;
 	char *mydata = NULL;
 	switch_codec_t *codec;
-    switch_input_args_t args = {0};
+	switch_input_args_t args = { 0 };
 
 	codec = switch_core_session_get_read_codec(session);
 	assert(codec != NULL);
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 	mydata = switch_core_session_strdup(session, data);
-	argc = switch_separate_string(mydata, '|', argv, sizeof(argv)/sizeof(argv[0]));
+	argc = switch_separate_string(mydata, '|', argv, sizeof(argv) / sizeof(argv[0]));
 
 	engine = argv[0];
 	voice = argv[1];
 	text = argv[2];
-	
+
 	if (!(engine && voice && text)) {
 		if (!engine) {
 			engine = "NULL";
@@ -102,27 +102,27 @@
 
 	switch_channel_pre_answer(channel);
 
-    args.input_callback = on_dtmf;
-    args.buf = buf;
-    args.buflen = sizeof(buf);
+	args.input_callback = on_dtmf;
+	args.buf = buf;
+	args.buflen = sizeof(buf);
 	switch_ivr_speak_text(session, engine, voice, codec->implementation->samples_per_second, text, &args);
-	
+
 }
 
 static void playback_function(switch_core_session_t *session, char *data)
 {
 	switch_channel_t *channel;
 	char *file_name = NULL;
-    switch_input_args_t args = {0};
+	switch_input_args_t args = { 0 };
 
 	file_name = switch_core_session_strdup(session, data);
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 	switch_channel_pre_answer(channel);
 
-    args.input_callback = on_dtmf;
+	args.input_callback = on_dtmf;
 	switch_ivr_play_file(session, NULL, file_name, &args);
 
 }
@@ -132,21 +132,21 @@
 {
 	switch_channel_t *channel;
 	switch_status_t status;
-    uint32_t limit = 0;
-    char *path;
-    char *p;
-    switch_input_args_t args = {0};
+	uint32_t limit = 0;
+	char *path;
+	char *p;
+	switch_input_args_t args = { 0 };
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
-    path = switch_core_session_strdup(session, data);
-    if ((p = strchr(path, '+'))) {
-        *p++ = '\0';
-        limit = atoi(p);
-    }
+	path = switch_core_session_strdup(session, data);
+	if ((p = strchr(path, '+'))) {
+		*p++ = '\0';
+		limit = atoi(p);
+	}
 
-    args.input_callback = on_dtmf;
+	args.input_callback = on_dtmf;
 	status = switch_ivr_record_file(session, NULL, path, &args, limit);
 
 	if (!switch_channel_ready(channel) || (status != SWITCH_STATUS_SUCCESS && !SWITCH_STATUS_IS_BREAK(status))) {
@@ -159,9 +159,9 @@
 {
 	switch_channel_t *channel;
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
-	switch_ivr_record_session(session, data, NULL);	
+	switch_ivr_record_session(session, data, NULL);
 }
 
 
@@ -169,9 +169,9 @@
 {
 	switch_channel_t *channel;
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
-	switch_ivr_stop_record_session(session, data);	
+	switch_ivr_stop_record_session(session, data);
 }
 
 
@@ -223,7 +223,7 @@
 	/* short_desc */ "Playback File",
 	/* syntax */ "<path>",
 	/* flags */ SAF_NONE,
-	/*.next*/	&stop_record_session_application_interface
+	/*.next */ &stop_record_session_application_interface
 };
 
 static const switch_loadable_module_interface_t mod_playback_module_interface = {

Modified: freeswitch/branches/cparker/src/mod/applications/mod_rss/mod_rss.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/applications/mod_rss/mod_rss.c	(original)
+++ freeswitch/branches/cparker/src/mod/applications/mod_rss/mod_rss.c	Tue Apr 24 10:14:28 2007
@@ -68,9 +68,9 @@
 {
 	char tstr[80] = "";
 	uint32_t matches = 0, x = 0;
-	uint32_t len = (uint32_t)strlen(str);
+	uint32_t len = (uint32_t) strlen(str);
 
-	for (x = 0; x < max ; x++) {
+	for (x = 0; x < max; x++) {
 		snprintf(tstr, sizeof(tstr), "%u", x);
 		if (!strncasecmp(str, tstr, len)) {
 			matches++;
@@ -86,67 +86,66 @@
   if you return anything but SWITCH_STATUS_SUCCESS the playback will stop.
 */
 static switch_status_t on_dtmf(switch_core_session_t *session, void *input, switch_input_type_t itype, void *buf, unsigned int buflen)
-
 {
 	switch (itype) {
-	case SWITCH_INPUT_TYPE_DTMF: {
-		char *dtmf = (char *) input;
-		struct dtmf_buffer *dtb;
-		dtb = (struct dtmf_buffer *) buf;
-	
-		switch(*dtmf) {
-		case '#':
-			switch_set_flag(dtb, SFLAG_MAIN);
-			return SWITCH_STATUS_BREAK;
-		case '6':
-			dtb->index++;
-			return SWITCH_STATUS_BREAK;
-		case '4':
-			dtb->index--;
-			return SWITCH_STATUS_BREAK;
-		case '*':
-			if (switch_test_flag(dtb->sh, SWITCH_SPEECH_FLAG_PAUSE)) {
-				switch_clear_flag(dtb->sh, SWITCH_SPEECH_FLAG_PAUSE);
-			} else {
-				switch_set_flag(dtb->sh, SWITCH_SPEECH_FLAG_PAUSE);
-			}
-			break;
-		case '5':
-			switch_core_speech_text_param_tts(dtb->sh, "voice", "next");
-			switch_set_flag(dtb, SFLAG_INFO);
-			return SWITCH_STATUS_BREAK;
-			break;
-		case '9':
-			switch_core_speech_text_param_tts(dtb->sh, "voice", dtb->voice);
-			switch_set_flag(dtb, SFLAG_INFO);
-			return SWITCH_STATUS_BREAK;
-			break;
-		case '2':
-			if (dtb->speed < 260) {
-				dtb->speed += 30;
-				switch_core_speech_numeric_param_tts(dtb->sh, "speech/rate", dtb->speed);
+	case SWITCH_INPUT_TYPE_DTMF:{
+			char *dtmf = (char *) input;
+			struct dtmf_buffer *dtb;
+			dtb = (struct dtmf_buffer *) buf;
+
+			switch (*dtmf) {
+			case '#':
+				switch_set_flag(dtb, SFLAG_MAIN);
+				return SWITCH_STATUS_BREAK;
+			case '6':
+				dtb->index++;
+				return SWITCH_STATUS_BREAK;
+			case '4':
+				dtb->index--;
+				return SWITCH_STATUS_BREAK;
+			case '*':
+				if (switch_test_flag(dtb->sh, SWITCH_SPEECH_FLAG_PAUSE)) {
+					switch_clear_flag(dtb->sh, SWITCH_SPEECH_FLAG_PAUSE);
+				} else {
+					switch_set_flag(dtb->sh, SWITCH_SPEECH_FLAG_PAUSE);
+				}
+				break;
+			case '5':
+				switch_core_speech_text_param_tts(dtb->sh, "voice", "next");
 				switch_set_flag(dtb, SFLAG_INFO);
 				return SWITCH_STATUS_BREAK;
-			}
-			break;
-		case '7':
-			dtb->speed = TTS_MEAN_SPEED;
-			switch_core_speech_numeric_param_tts(dtb->sh, "speech/rate", dtb->speed);
-			switch_set_flag(dtb, SFLAG_INFO);
-			return SWITCH_STATUS_BREAK;
-		case '8':
-			if (dtb->speed > 80) {
-				dtb->speed -= 30;
+				break;
+			case '9':
+				switch_core_speech_text_param_tts(dtb->sh, "voice", dtb->voice);
+				switch_set_flag(dtb, SFLAG_INFO);
+				return SWITCH_STATUS_BREAK;
+				break;
+			case '2':
+				if (dtb->speed < 260) {
+					dtb->speed += 30;
+					switch_core_speech_numeric_param_tts(dtb->sh, "speech/rate", dtb->speed);
+					switch_set_flag(dtb, SFLAG_INFO);
+					return SWITCH_STATUS_BREAK;
+				}
+				break;
+			case '7':
+				dtb->speed = TTS_MEAN_SPEED;
 				switch_core_speech_numeric_param_tts(dtb->sh, "speech/rate", dtb->speed);
 				switch_set_flag(dtb, SFLAG_INFO);
 				return SWITCH_STATUS_BREAK;
+			case '8':
+				if (dtb->speed > 80) {
+					dtb->speed -= 30;
+					switch_core_speech_numeric_param_tts(dtb->sh, "speech/rate", dtb->speed);
+					switch_set_flag(dtb, SFLAG_INFO);
+					return SWITCH_STATUS_BREAK;
+				}
+				break;
+			case '0':
+				switch_set_flag(dtb, SFLAG_INSTRUCT);
+				return SWITCH_STATUS_BREAK;
 			}
-			break;
-		case '0':
-			switch_set_flag(dtb, SFLAG_INSTRUCT);
-			return SWITCH_STATUS_BREAK;
 		}
-	}
 		break;
 	default:
 		break;
@@ -159,9 +158,9 @@
 	switch_channel_t *channel;
 	switch_status_t status;
 	const char *err = NULL;
-	struct dtmf_buffer dtb = {0};
+	struct dtmf_buffer dtb = { 0 };
 	switch_xml_t xml = NULL, item, xchannel = NULL;
-	struct rss_entry entries[TTS_MAX_ENTRIES] = {{0}};
+	struct rss_entry entries[TTS_MAX_ENTRIES] = { {0} };
 	uint32_t i = 0;
 	char *title_txt = "", *description_txt = "", *rights_txt = "";
 	switch_codec_t speech_codec, *codec = switch_core_session_get_read_codec(session);
@@ -169,31 +168,32 @@
 	char *voice = TTS_DEFAULT_VOICE;
 	char *timer_name = NULL;
 	switch_speech_handle_t sh;
-    switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
+	switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
 	switch_core_thread_session_t thread_session;
 	uint32_t rate, interval = 20;
 	int stream_id = 0;
-	switch_timer_t timer = {0}, *timerp = NULL;
+	switch_timer_t timer = { 0 }, *timerp = NULL;
 	uint32_t last;
 	char *mydata = NULL;
 	char *filename = NULL;
-	char *argv[3], *feed_list[TTS_MAX_ENTRIES] = {0} , *feed_names[TTS_MAX_ENTRIES] = {0};
+	char *argv[3], *feed_list[TTS_MAX_ENTRIES] = { 0 }, *feed_names[TTS_MAX_ENTRIES] = {
+	0};
 	int argc, feed_index = 0;
 	char *cf = "rss.conf";
-    switch_xml_t cfg, cxml, feeds, feed;
+	switch_xml_t cfg, cxml, feeds, feed;
 	char buf[1024];
 	int32_t jumpto = -1;
 	uint32_t matches = 0;
-	switch_input_args_t args = {0};
+	switch_input_args_t args = { 0 };
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 
 	if (!(cxml = switch_xml_open_cfg(cf, &cfg, NULL))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", cf);
-        return;
-    }
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", cf);
+		return;
+	}
 
 	if ((feeds = switch_xml_child(cfg, "feeds"))) {
 		for (feed = switch_xml_child(feeds, "feed"); feed; feed = feed->next) {
@@ -210,14 +210,14 @@
 	}
 
 	switch_xml_free(cxml);
-	
+
 	switch_channel_answer(channel);
 
 
 
 	if (!switch_strlen_zero(data)) {
 		if ((mydata = switch_core_session_strdup(session, data))) {
-			argc = switch_separate_string(mydata, ' ', argv, sizeof(argv)/sizeof(argv[0]));
+			argc = switch_separate_string(mydata, ' ', argv, sizeof(argv) / sizeof(argv[0]));
 
 			if (argv[0]) {
 				engine = argv[0];
@@ -244,24 +244,17 @@
 	}
 
 	memset(&sh, 0, sizeof(sh));
-	if (switch_core_speech_open(&sh,
-								engine,
-								voice,
-								rate,
-								&flags,
-								switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
+	if (switch_core_speech_open(&sh, engine, voice, rate, &flags, switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid TTS module!\n");
 		return;
 	}
-	
+
 	if (switch_core_codec_init(&speech_codec,
 							   "L16",
 							   NULL,
-							   (int)rate,
+							   (int) rate,
 							   interval,
-							   1,
-							   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-							   NULL,
+							   1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL,
 							   switch_core_session_get_pool(session)) == SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activated\n");
 	} else {
@@ -270,16 +263,16 @@
 		switch_core_speech_close(&sh, &flags);
 		return;
 	}
-	
+
 	if (timer_name) {
-		if (switch_core_timer_init(&timer, timer_name, interval, (int)(rate / 50), switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
+		if (switch_core_timer_init(&timer, timer_name, interval, (int) (rate / 50), switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "setup timer failed!\n");
 			switch_core_codec_destroy(&speech_codec);
 			flags = 0;
 			switch_core_speech_close(&sh, &flags);
 			return;
 		}
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "setup timer success %u bytes per %d ms!\n", (rate / 50)*2, interval);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "setup timer success %u bytes per %d ms!\n", (rate / 50) * 2, interval);
 
 		/* start a thread to absorb incoming audio */
 		for (stream_id = 0; stream_id < switch_core_session_get_stream_count(session); stream_id++) {
@@ -292,7 +285,7 @@
 	while (switch_channel_ready(channel)) {
 		int32_t len = 0, idx = 0;
 		char cmd[3];
-	main_menu:
+	  main_menu:
 		filename = NULL;
 		len = idx = 0;
 		*cmd = '\0';
@@ -304,36 +297,29 @@
 		} else {
 			switch_core_speech_flush_tts(&sh);
 #ifdef MATCH_COUNT
-			snprintf(buf + len, sizeof(buf) - len, 
+			snprintf(buf + len, sizeof(buf) - len,
 					 ",<break time=\"500ms\"/>Main Menu. <break time=\"600ms\"/> "
-					 "Select one of the following news sources, or press 0 to exit. "
-					 ",<break time=\"600ms\"/>");
+					 "Select one of the following news sources, or press 0 to exit. " ",<break time=\"600ms\"/>");
 #else
-			snprintf(buf + len, sizeof(buf) - len, 
+			snprintf(buf + len, sizeof(buf) - len,
 					 ",<break time=\"500ms\"/>Main Menu. <break time=\"600ms\"/> "
-					 "Select one of the following news sources, followed by the pound key or press 0 to exit. "
-					 ",<break time=\"600ms\"/>");
+					 "Select one of the following news sources, followed by the pound key or press 0 to exit. " ",<break time=\"600ms\"/>");
 #endif
-			len = (int32_t)strlen(buf);
+			len = (int32_t) strlen(buf);
 
 			for (idx = 0; idx < feed_index; idx++) {
 				snprintf(buf + len, sizeof(buf) - len, "%d: %s. <break time=\"600ms\"/>", idx + 1, feed_names[idx]);
-				len = (int32_t)strlen(buf);
+				len = (int32_t) strlen(buf);
 			}
 
 
 			snprintf(buf + len, sizeof(buf) - len, "<break time=\"2000ms\"/>");
-			len = (int32_t)strlen(buf);
+			len = (int32_t) strlen(buf);
 
 			args.input_callback = NULL;
 			args.buf = cmd;
 			args.buflen = sizeof(cmd);
-			status = switch_ivr_speak_text_handle(session,
-												  &sh,
-												  &speech_codec,
-												  timerp,
-												  buf,
-												  &args);
+			status = switch_ivr_speak_text_handle(session, &sh, &speech_codec, timerp, buf, &args);
 			if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
 				goto finished;
 			}
@@ -346,51 +332,46 @@
 				break;
 			}
 
-			if ((p=strchr(cmd, '#'))) {
+			if ((p = strchr(cmd, '#'))) {
 				*p = '\0';
 #ifdef MATCH_COUNT
 				/* Hmmm... I know there are no more matches so I don't *need* them to press pound but 
 				   I already told them to press it.  Will this confuse people or not?  Let's make em press 
 				   pound unless this define is enabled for now.
-				*/
+				 */
 			} else if (match_count(cmd, feed_index) > 1) {
 #else
 			} else {
 #endif
 				char term;
 				char *cp;
-				int blen = sizeof(cmd) - (int)strlen(cmd);
+				int blen = sizeof(cmd) - (int) strlen(cmd);
 
 				cp = cmd + blen;
 				switch_ivr_collect_digits_count(session, cp, blen, blen, "#", &term, 5000);
 			}
-			
+
 			i = atoi(cmd) - 1;
 
 			if (i > -1 && i < feed_index) {
 				filename = feed_list[i];
 			} else if (matches > 1) {
-				
+
 			} else {
 				args.input_callback = NULL;
 				args.buf = NULL;
 				args.buflen = 0;
-				status = switch_ivr_speak_text_handle(session,
-													  &sh,
-													  &speech_codec,
-													  timerp,
-													  "I'm sorry. That is an Invalid Selection. ",
-													  &args);
+				status = switch_ivr_speak_text_handle(session, &sh, &speech_codec, timerp, "I'm sorry. That is an Invalid Selection. ", &args);
 				if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
 					goto finished;
 				}
 			}
 		}
-	
+
 		if (!filename) {
 			continue;
 		}
-		
+
 
 
 		if (!(xml = switch_xml_parse_file(filename))) {
@@ -411,7 +392,7 @@
 			if ((title = switch_xml_child(xchannel, "title"))) {
 				title_txt = title->txt;
 			}
-			
+
 			if ((description = switch_xml_child(xchannel, "description"))) {
 				description_txt = description->txt;
 			}
@@ -444,19 +425,19 @@
 			if ((title = switch_xml_child(item, "title"))) {
 				entries[i].title_txt = title->txt;
 			}
-		
+
 			if ((description = switch_xml_child(item, "description"))) {
 				char *t, *e;
 				entries[i].description_txt = description->txt;
-				for(;;) {
+				for (;;) {
 					if (!(t = strchr(entries[i].description_txt, '<'))) {
 						break;
 					}
 					if (!(e = strchr(t, '>'))) {
 						break;
 					}
-				
-					memset(t, 32, ++e-t);
+
+					memset(t, 32, ++e - t);
 				}
 			}
 
@@ -471,9 +452,8 @@
 			if (entries[i].description_txt && (p = strchr(entries[i].description_txt, '<'))) {
 				*p = '\0';
 			}
-
 #ifdef _STRIP_SOME_CHARS_
-			for(p = entries[i].description_txt; *p; p++) {
+			for (p = entries[i].description_txt; *p; p++) {
 				if (*p == '\'' || *p == '"' || *p == ':') {
 					*p = ' ';
 				}
@@ -493,17 +473,13 @@
 			switch_strftime(date, &retsize, sizeof(date), "%I:%M %p", &tm);
 
 
-			snprintf(buf, sizeof(buf), ",<break time=\"500ms\"/>%s. %s. %s. local time: %s, Press 0 for options, 5 to change voice, or pound to return to the main menu. ", 
+			snprintf(buf, sizeof(buf),
+					 ",<break time=\"500ms\"/>%s. %s. %s. local time: %s, Press 0 for options, 5 to change voice, or pound to return to the main menu. ",
 					 title_txt, description_txt, rights_txt, date);
 			args.input_callback = NULL;
 			args.buf = cmd;
 			args.buflen = sizeof(cmd);
-			status = switch_ivr_speak_text_handle(session,
-												  &sh,
-												  &speech_codec,
-												  timerp,
-												  buf,
-												  &args);
+			status = switch_ivr_speak_text_handle(session, &sh, &speech_codec, timerp, buf, &args);
 			if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
 				goto finished;
 			}
@@ -519,7 +495,7 @@
 			}
 		}
 
-		for(last = 0; last < TTS_MAX_ENTRIES; last++) {
+		for (last = 0; last < TTS_MAX_ENTRIES; last++) {
 			if (!entries[last].inuse) {
 				last--;
 				break;
@@ -531,8 +507,8 @@
 		dtb.speed = TTS_MEAN_SPEED;
 		switch_set_flag(&dtb, SFLAG_INFO);
 		switch_copy_string(dtb.voice, voice, sizeof(dtb.voice));
-		while(entries[0].inuse && switch_channel_ready(channel)) {
-			while(switch_channel_ready(channel)) {
+		while (entries[0].inuse && switch_channel_ready(channel)) {
+			while (switch_channel_ready(channel)) {
 				uint8_t cont = 0;
 
 				if (dtb.index >= TTS_MAX_ENTRIES) {
@@ -556,13 +532,8 @@
 					}
 					if (switch_test_flag(&dtb, SFLAG_INFO)) {
 						switch_clear_flag(&dtb, SFLAG_INFO);
-						snprintf(buf + len, sizeof(buf) - len,
-								 "%s %s. I am speaking at %u words per minute. ",
-								 sh.engine,
-								 sh.voice,
-								 dtb.speed
-								 );
-						len = (uint32_t)strlen(buf);
+						snprintf(buf + len, sizeof(buf) - len, "%s %s. I am speaking at %u words per minute. ", sh.engine, sh.voice, dtb.speed);
+						len = (uint32_t) strlen(buf);
 					}
 
 					if (switch_test_flag(&dtb, SFLAG_INSTRUCT)) {
@@ -577,33 +548,28 @@
 								 "To hear these options again, press zero or press pound to return to the main menu. ");
 					} else {
 						snprintf(buf + len, sizeof(buf) - len, "Story %d. ", dtb.index + 1);
-						len = (uint32_t)strlen(buf);
+						len = (uint32_t) strlen(buf);
 
 						if (entries[dtb.index].subject_txt) {
 							snprintf(buf + len, sizeof(buf) - len, "Subject: %s. ", entries[dtb.index].subject_txt);
-							len = (uint32_t)strlen(buf);
+							len = (uint32_t) strlen(buf);
 						}
-				
+
 						if (entries[dtb.index].dept_txt) {
 							snprintf(buf + len, sizeof(buf) - len, "From the %s department. ", entries[dtb.index].dept_txt);
-							len = (uint32_t)strlen(buf);
+							len = (uint32_t) strlen(buf);
 						}
 
 						if (entries[dtb.index].title_txt) {
 							snprintf(buf + len, sizeof(buf) - len, "%s", entries[dtb.index].title_txt);
-							len = (uint32_t)strlen(buf);
+							len = (uint32_t) strlen(buf);
 						}
 					}
 					switch_core_speech_flush_tts(&sh);
 					args.input_callback = on_dtmf;
 					args.buf = &dtb;
 					args.buflen = sizeof(dtb);
-					status = switch_ivr_speak_text_handle(session,
-														  &sh,
-														  &speech_codec,
-														  timerp,
-														  buf,
-														  &args);
+					status = switch_ivr_speak_text_handle(session, &sh, &speech_codec, timerp, buf, &args);
 					if (status == SWITCH_STATUS_BREAK) {
 						continue;
 					} else if (status != SWITCH_STATUS_SUCCESS) {
@@ -614,17 +580,12 @@
 						cont = 0;
 						continue;
 					}
-					
+
 					if (entries[dtb.index].description_txt) {
 						args.input_callback = on_dtmf;
 						args.buf = &dtb;
 						args.buflen = sizeof(dtb);
-						status = switch_ivr_speak_text_handle(session,
-															  &sh,
-															  &speech_codec,
-															  timerp,
-															  entries[dtb.index].description_txt,
-															  &args);
+						status = switch_ivr_speak_text_handle(session, &sh, &speech_codec, timerp, entries[dtb.index].description_txt, &args);
 					}
 					if (status == SWITCH_STATUS_BREAK) {
 						continue;
@@ -638,7 +599,7 @@
 		}
 	}
 
- finished:
+  finished:
 	switch_core_speech_close(&sh, &flags);
 	switch_core_codec_destroy(&speech_codec);
 
@@ -659,7 +620,7 @@
 	/*.application_function */ rss_function,
 	NULL, NULL, NULL,
 	/* flags */ SAF_NONE,
-	/*.next*/ NULL
+	/*.next */ NULL
 };
 
 

Modified: freeswitch/branches/cparker/src/mod/asr_tts/mod_cepstral/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/asr_tts/mod_cepstral/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/asr_tts/mod_cepstral/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,23 +1,6 @@
-ifeq ($(OSARCH),Darwin)
-CFLAGS += -I/Library/Frameworks/swift.framework/Versions/4/Headers
-LDFLAGS += -framework swift
-else
-LDFLAGS += -L/opt/swift/lib -lswift -lceplex_us -lceplang_en -lm
-CFLAGS += -I/opt/swift/include
-endif
+LOCAL_INSERT_LDFLAGS=if test $$osarch = "Darwin" ; then echo "-framework swift" ; else echo "-L/opt/swift/lib -lswift -lceplex_us -lceplang_en -lm" ; fi ;
 
-LINKER=$(CC)
+LOCAL_INSERT_CFLAGS=test $$osarch = "Darwin" || echo "-I/opt/swift/include";
+LOCAL_CFLAGS=-w
+include ../../../../build/modmake.rules
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(LINKER) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/asr_tts/mod_cepstral/mod_cepstral.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/asr_tts/mod_cepstral/mod_cepstral.c	(original)
+++ freeswitch/branches/cparker/src/mod/asr_tts/mod_cepstral/mod_cepstral.c	Tue Apr 24 10:14:28 2007
@@ -38,13 +38,19 @@
 #ifdef __ICC
 #pragma warning (disable:188)
 #endif
-
+#ifdef MACOSX
+#include <swift/swift.h>
+#else
 #include <swift.h>
+#endif
 #include <switch.h>
 
 #define MY_BUF_LEN 1024 * 32
 #define MY_BLOCK_SIZE MY_BUF_LEN
 
+#undef SWIFT_FAILED
+#define SWIFT_FAILED(r) ((void *)(r) < (void *)0)
+
 static const char modname[] = "mod_cepstral";
 
 static swift_engine *engine;
@@ -63,23 +69,23 @@
 
 
 /* This callback caches the audio in the buffer */
-static swift_result_t write_audio(swift_event *event, swift_event_t type, void *udata)
+static swift_result_t write_audio(swift_event * event, swift_event_t type, void *udata)
 {
 	cepstral_t *cepstral;
-    swift_event_t rv = SWIFT_SUCCESS;
-    void *buf = NULL;
-    int len = 0, i = 0;
-	
+	swift_event_t rv = SWIFT_SUCCESS;
+	void *buf = NULL;
+	int len = 0, i = 0;
+
 	cepstral = udata;
 	assert(cepstral != NULL);
-	
+
 	if (!cepstral->port || cepstral->done || cepstral->done_gen) {
-		return  SWIFT_UNKNOWN_ERROR;
+		return SWIFT_UNKNOWN_ERROR;
 	}
 
 	/* Only proceed when we have success */
-    if (!SWIFT_FAILED((rv = swift_event_get_audio(event, &buf, &len)))) {
-		while(!cepstral->done) {
+	if (!SWIFT_FAILED((rv = swift_event_get_audio(event, &buf, &len)))) {
+		while (!cepstral->done) {
 			switch_mutex_lock(cepstral->audio_lock);
 			if (switch_buffer_write(cepstral->audio_buffer, buf, len) > 0) {
 				switch_mutex_unlock(cepstral->audio_lock);
@@ -94,7 +100,7 @@
 					}
 				}
 			}
-			
+
 		}
 	} else {
 		cepstral->done = 1;
@@ -103,8 +109,8 @@
 	if (cepstral->done) {
 		rv = SWIFT_UNKNOWN_ERROR;
 	}
-	
-    return rv;
+
+	return rv;
 }
 
 static switch_status_t cepstral_speech_open(switch_speech_handle_t *sh, char *voice_name, int rate, switch_speech_flag_t *flags)
@@ -137,7 +143,7 @@
 		goto all_done;
 	}
 
-		
+
 	if (voice_name && SWIFT_FAILED(swift_port_set_voice_by_name(cepstral->port, voice_name))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid voice %s!\n", voice_name);
 		voice_name = NULL;
@@ -151,7 +157,7 @@
 		}
 
 		/* Set the voice found by find_first_voice() as the port's current voice */
-		if ( SWIFT_FAILED(swift_port_set_voice(cepstral->port, cepstral->voice)) ) {
+		if (SWIFT_FAILED(swift_port_set_voice(cepstral->port, cepstral->voice))) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set voice.\n");
 			goto all_done;
 		}
@@ -167,8 +173,8 @@
 
 	sh->private_info = cepstral;
 	return SWITCH_STATUS_SUCCESS;
-	
- all_done:
+
+  all_done:
 	return SWITCH_STATUS_FALSE;
 }
 
@@ -179,18 +185,19 @@
 	assert(sh != NULL);
 	cepstral = sh->private_info;
 	assert(cepstral != NULL);
-	
+
 
 	cepstral->done = 1;
 	cepstral->done_gen = 1;
 	swift_port_stop(cepstral->port, SWIFT_ASYNC_ANY, SWIFT_EVENT_NOW);
 	/* Close the Swift Port and Engine */
-	if (NULL != cepstral->port) swift_port_close(cepstral->port);
+	if (NULL != cepstral->port)
+		swift_port_close(cepstral->port);
 	//if (NULL != cepstral->engine) swift_engine_close(cepstral->engine);
 
 	cepstral->port = NULL;
 	//cepstral->engine = NULL;
-	
+
 	switch_buffer_destroy(&cepstral->audio_buffer);
 
 	return SWITCH_STATUS_SUCCESS;
@@ -200,7 +207,7 @@
 {
 	cepstral_t *cepstral;
 	const char *fp = "file:";
-	int len = (int)strlen(fp);
+	int len = (int) strlen(fp);
 
 	assert(sh != NULL);
 	cepstral = sh->private_info;
@@ -208,7 +215,7 @@
 
 	cepstral->done_gen = 0;
 	cepstral->done = 0;
-	
+
 	cepstral->tts_stream = NULL;
 
 	if (!strncasecmp(text, fp, len)) {
@@ -216,17 +223,17 @@
 		if (switch_strlen_zero(text)) {
 			return SWITCH_STATUS_FALSE;
 		}
-		swift_port_speak_file(cepstral->port, text, NULL, &cepstral->tts_stream, NULL); 
+		swift_port_speak_file(cepstral->port, text, NULL, &cepstral->tts_stream, NULL);
 	} else {
-        char *to_say;
+		char *to_say;
 		if (switch_strlen_zero(text)) {
 			return SWITCH_STATUS_FALSE;
 		}
 
-        if ((to_say = switch_mprintf("<break time=\"500ms\"/> %s <break time=\"500ms\"/>", text))) {
-            swift_port_speak_text(cepstral->port, to_say, 0, NULL, &cepstral->tts_stream, NULL); 
-            switch_safe_free(to_say);
-        }
+		if ((to_say = switch_mprintf("<break time=\"500ms\"/> %s <break time=\"500ms\"/>", text))) {
+			swift_port_speak_text(cepstral->port, to_say, 0, NULL, &cepstral->tts_stream, NULL);
+			switch_safe_free(to_say);
+		}
 	}
 
 	return SWITCH_STATUS_SUCCESS;
@@ -237,10 +244,10 @@
 	cepstral_t *cepstral;
 
 	cepstral = sh->private_info;
-    assert(cepstral != NULL);
+	assert(cepstral != NULL);
 
 	cepstral->done_gen = 1;
-    cepstral->done = 1;
+	cepstral->done = 1;
 	if (cepstral->audio_buffer) {
 		switch_mutex_lock(cepstral->audio_lock);
 		switch_buffer_zero(cepstral->audio_buffer);
@@ -249,11 +256,7 @@
 	swift_port_stop(cepstral->port, SWIFT_ASYNC_ANY, SWIFT_EVENT_NOW);
 }
 
-static switch_status_t cepstral_speech_read_tts(switch_speech_handle_t *sh,
-												void *data,
-												size_t *datalen,
-												uint32_t *rate,
-												switch_speech_flag_t *flags) 
+static switch_status_t cepstral_speech_read_tts(switch_speech_handle_t *sh, void *data, size_t *datalen, uint32_t * rate, switch_speech_flag_t *flags)
 {
 	cepstral_t *cepstral;
 	size_t desired = *datalen;
@@ -264,7 +267,7 @@
 	cepstral = sh->private_info;
 	assert(cepstral != NULL);
 
-	while(!cepstral->done) {
+	while (!cepstral->done) {
 		if (!cepstral->done_gen) {
 			int check = swift_port_status(cepstral->port, cepstral->tts_stream);
 
@@ -276,8 +279,8 @@
 		switch_mutex_lock(cepstral->audio_lock);
 		used = switch_buffer_inuse(cepstral->audio_buffer);
 		switch_mutex_unlock(cepstral->audio_lock);
-		
-		
+
+
 		if (!used && cepstral->done_gen) {
 
 			status = SWITCH_STATUS_BREAK;
@@ -298,15 +301,15 @@
 			switch_yield(1000);
 			continue;
 		}
-		
+
 		/* There is enough, read it and return */
 		switch_mutex_lock(cepstral->audio_lock);
 		*datalen = switch_buffer_read(cepstral->audio_buffer, data, desired);
 		if (padding) {
 			size_t x = 0;
 			unsigned char *p = data;
-			
-			for(x = 0; x < padding; x++) {
+
+			for (x = 0; x < padding; x++) {
 				*(p + x) = 0;
 				(*datalen)++;
 			}
@@ -317,7 +320,7 @@
 
 		break;
 	}
-	
+
 	return status;
 }
 
@@ -332,7 +335,7 @@
 		char *voice_name = val;
 		if (!strcasecmp(voice_name, "next")) {
 			if ((cepstral->voice = swift_port_find_next_voice(cepstral->port))) {
-				if ( SWIFT_FAILED(swift_port_set_voice(cepstral->port, cepstral->voice)) ) {
+				if (SWIFT_FAILED(swift_port_set_voice(cepstral->port, cepstral->voice))) {
 					cepstral->done = cepstral->done_gen = 1;
 					return;
 				}
@@ -348,22 +351,22 @@
 		}
 
 		if (!voice_name) {
-            /* Find the first voice on the system */
-            if ((cepstral->voice = swift_port_find_first_voice(cepstral->port, NULL, NULL)) == NULL) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to find any voices!\n");
+			/* Find the first voice on the system */
+			if ((cepstral->voice = swift_port_find_first_voice(cepstral->port, NULL, NULL)) == NULL) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to find any voices!\n");
 				cepstral->done = cepstral->done_gen = 1;
 				return;
-            }
+			}
 
-            /* Set the voice found by find_first_voice() as the port's current voice */
-            if ( SWIFT_FAILED(swift_port_set_voice(cepstral->port, cepstral->voice)) ) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set voice.\n");
+			/* Set the voice found by find_first_voice() as the port's current voice */
+			if (SWIFT_FAILED(swift_port_set_voice(cepstral->port, cepstral->voice))) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to set voice.\n");
 				cepstral->done = cepstral->done_gen = 1;
 				return;
-            }
+			}
 
 			voice_name = (char *) swift_voice_get_attribute(cepstral->voice, "name");
-        } 
+		}
 
 		if (voice_name) {
 			switch_copy_string(sh->voice, voice_name, sizeof(sh->voice));
@@ -399,15 +402,15 @@
 }
 
 static const switch_speech_interface_t cepstral_speech_interface = {
-	/*.interface_name*/			"cepstral",
-	/*.speech_open*/			cepstral_speech_open,
-	/*.speech_close*/			cepstral_speech_close,
-	/*.speech_feed_tts*/		cepstral_speech_feed_tts,
-	/*.speech_read_tts*/		cepstral_speech_read_tts,
-	/*.speech_flush_tts*/		cepstral_speech_flush_tts,
-	/*.speech_text_param_tts*/  cepstral_text_param_tts,
-	/*.speech_numeric_param_tts*/  cepstral_numeric_param_tts,
-	/*.speech_numeric_param_tts*/  cepstral_float_param_tts
+	/*.interface_name */ "cepstral",
+	/*.speech_open */ cepstral_speech_open,
+	/*.speech_close */ cepstral_speech_close,
+	/*.speech_feed_tts */ cepstral_speech_feed_tts,
+	/*.speech_read_tts */ cepstral_speech_read_tts,
+	/*.speech_flush_tts */ cepstral_speech_flush_tts,
+	/*.speech_text_param_tts */ cepstral_text_param_tts,
+	/*.speech_numeric_param_tts */ cepstral_numeric_param_tts,
+	/*.speech_numeric_param_tts */ cepstral_float_param_tts
 };
 
 static const switch_loadable_module_interface_t cepstral_module_interface = {
@@ -427,11 +430,11 @@
 {
 
 	/* Open the Swift TTS Engine */
-	if ( SWIFT_FAILED(engine = swift_engine_open(NULL)) ) {
+	if (SWIFT_FAILED(engine = swift_engine_open(NULL))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to open Swift Engine.");
 		return SWITCH_STATUS_GENERR;
 	}
-	
+
 	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &cepstral_module_interface;
 

Modified: freeswitch/branches/cparker/src/mod/asr_tts/mod_lumenvox/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/asr_tts/mod_lumenvox/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/asr_tts/mod_lumenvox/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,18 +1,11 @@
-LDFLAGS += -L/opt/lumenvox/engine_7.0/lib -llv_lvspeechport
-CFLAGS += -fpermissive -Wno-deprecated -Wno-conversion -fpermissive -Wno-unused -Wno-comment -Wno-sign-compare -Wno-conversion -Wno-reorder -I/opt/lumenvox/engine_7.0/include
-LINKER=g++
-CC=g++
+# define these targets in your makefile if you wish
+# local_all local_depend local_clean depend_install local_install local_distclean local_extraclean:
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+# and define these variables to impact your build
 
-depends:
+LVENGINE_DIR=/opt/lumenvox/engine_7.0
+LOCAL_CFLAGS= -fpermissive -Wno-deprecated -Wno-conversion -fpermissive -Wno-unused
+LOCAL_CFLAGS+= -Wno-comment -Wno-sign-compare -Wno-conversion -Wno-reorder -I$(LVINCLUDE)
+LOCAL_LDFLAGS= -L$(LVLIB) -llv_lvspeechport
+include ../../../../build/modmake.rules
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).cpp
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).cpp -o $(MODNAME).o 
-	$(LINKER) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_amr/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_amr/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_amr/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,24 +1,10 @@
-ifeq ($(shell ls -d $(BASE)/libs/amr),$(BASE)/libs/amr)
+BASE=../../../..
 
-CFLAGS += -I$(PREFIX)/include/amr
-LDFLAGS +=-lamr
+AMR_DIR=$(BASE)/libs/amr
+AMR_A=$(AMR_DIR)/libamr.a
 
-else
+LOCAL_INSERT_CFLAGS=if test -d $(AMR_DIR); then echo "-I$(AMR_DIR)" ; else echo "-DAMR_PASSTHROUGH" ; fi ;
+LOCAL_INSERT_LDFLAGS=test ! -d $(AMR_DIR) || echo "$(AMR_A)";
 
-CFLAGS += -DAMR_PASSTHROUGH
 
-endif
-
-all:	$(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+include $(BASE)/build/modmake.rules

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_amr/mod_amr.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_amr/mod_amr.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_amr/mod_amr.c	Tue Apr 24 10:14:28 2007
@@ -30,7 +30,7 @@
  *
  * mod_amr.c -- GSM-AMR Codec Module
  *
- */  
+ */
 #include "switch.h"
 static const char modname[] = "mod_amr";
 
@@ -113,15 +113,14 @@
 
 #endif
 
-static switch_status_t switch_amr_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									  const switch_codec_settings_t *codec_settings) 
+static switch_status_t switch_amr_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 
 #ifdef AMR_PASSTHROUGH
 	codec->flags |= SWITCH_CODEC_FLAG_PASSTHROUGH;
-    if (codec->fmtp_in) {
-        codec->fmtp_out = switch_core_strdup(codec->memory_pool, codec->fmtp_in);
-    }
+	if (codec->fmtp_in) {
+		codec->fmtp_out = switch_core_strdup(codec->memory_pool, codec->fmtp_in);
+	}
 	return SWITCH_STATUS_SUCCESS;
 #else
 	struct amr_context *context = NULL;
@@ -139,10 +138,10 @@
 
 		if (codec->fmtp_in) {
 			argc = switch_separate_string(codec->fmtp_in, ';', argv, (sizeof(argv) / sizeof(argv[0])));
-			for(x = 0; x < argc; x++) {
+			for (x = 0; x < argc; x++) {
 				char *data = argv[x];
 				char *arg;
-				while(*data && *data == ' ') {
+				while (*data && *data == ' ') {
 					data++;
 				}
 				if ((arg = strchr(data, '='))) {
@@ -171,16 +170,16 @@
 					} else if (!strcasecmp(data, "mode-change-period")) {
 						context->change_period = atoi(arg);
 					} else if (!strcasecmp(data, "ptime")) {
-						context->ptime = (switch_byte_t)atoi(arg);
+						context->ptime = (switch_byte_t) atoi(arg);
 					} else if (!strcasecmp(data, "channels")) {
-						context->channels = (switch_byte_t)atoi(arg);
+						context->channels = (switch_byte_t) atoi(arg);
 					} else if (!strcasecmp(data, "maxptime")) {
-						context->max_ptime = (switch_byte_t)atoi(arg);
+						context->max_ptime = (switch_byte_t) atoi(arg);
 					} else if (!strcasecmp(data, "mode-set")) {
 						int y, m_argc;
 						char *m_argv[7];
 						m_argc = switch_separate_string(arg, ',', m_argv, (sizeof(m_argv) / sizeof(m_argv[0])));
-						for(y = 0; y < m_argc; y++) {
+						for (y = 0; y < m_argc; y++) {
 							context->enc_modes |= (1 << atoi(m_argv[y]));
 						}
 					}
@@ -192,7 +191,7 @@
 		if (context->enc_modes) {
 			for (i = 7; i > -1; i++) {
 				if (context->enc_modes & (1 << i)) {
-					context->enc_mode = (switch_byte_t)i;
+					context->enc_mode = (switch_byte_t) i;
 					break;
 				}
 			}
@@ -201,10 +200,10 @@
 		if (!context->enc_mode) {
 			context->enc_mode = globals.default_bitrate;
 		}
-		
+
 		snprintf(fmtptmp, sizeof(fmtptmp), "octet-align=%d; mode-set=%d", switch_test_flag(context, AMR_OPT_OCTET_ALIGN) ? 1 : 0, context->enc_mode);
 		codec->fmtp_out = switch_core_strdup(codec->memory_pool, fmtptmp);
-		
+
 		context->enc_mode = AMR_DEFAULT_BITRATE;
 		context->encoder_state = NULL;
 		context->decoder_state = NULL;
@@ -224,7 +223,7 @@
 #endif
 }
 
-static switch_status_t switch_amr_destroy(switch_codec_t *codec) 
+static switch_status_t switch_amr_destroy(switch_codec_t *codec)
 {
 #ifndef AMR_PASSTHROUGH
 	struct amr_context *context = codec->private_info;
@@ -240,45 +239,35 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t switch_amr_encode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *decoded_data,
-
-										uint32_t decoded_data_len, 
-										uint32_t decoded_rate, 
-										void *encoded_data,
-
-										uint32_t *encoded_data_len, 
-										uint32_t *encoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_amr_encode(switch_codec_t *codec,
+										 switch_codec_t *other_codec,
+										 void *decoded_data,
+										 uint32_t decoded_data_len,
+										 uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										 unsigned int *flag)
 {
 #ifdef AMR_PASSTHROUGH
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "This codec is only usable in passthrough mode!\n");
 	return SWITCH_STATUS_FALSE;
 #else
 	struct amr_context *context = codec->private_info;
-	
+
 	if (!context) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
-	*encoded_data_len = Encoder_Interface_Encode( context->encoder_state, context->enc_mode, (int16_t *)decoded_data, (switch_byte_t *) encoded_data, 0);
+
+	*encoded_data_len = Encoder_Interface_Encode(context->encoder_state, context->enc_mode, (int16_t *) decoded_data, (switch_byte_t *) encoded_data, 0);
 
 	return SWITCH_STATUS_SUCCESS;
 #endif
 }
 
-static switch_status_t switch_amr_decode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *encoded_data,
-
-										uint32_t encoded_data_len, 
-										uint32_t encoded_rate, 
-										void *decoded_data,
-
-										uint32_t *decoded_data_len, 
-										uint32_t *decoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_amr_decode(switch_codec_t *codec,
+										 switch_codec_t *other_codec,
+										 void *encoded_data,
+										 uint32_t encoded_data_len,
+										 uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										 unsigned int *flag)
 {
 #ifdef AMR_PASSTHROUGH
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "This codec is only usable in passthrough mode!\n");
@@ -290,51 +279,50 @@
 		return SWITCH_STATUS_FALSE;
 	}
 
-	Decoder_Interface_Decode(context->decoder_state, (unsigned char *)encoded_data, (int16_t *)decoded_data, 0);
+	Decoder_Interface_Decode(context->decoder_state, (unsigned char *) encoded_data, (int16_t *) decoded_data, 0);
 	*decoded_data_len = codec->implementation->bytes_per_frame;
 
 	return SWITCH_STATUS_SUCCESS;
 #endif
 }
 
-/* Registration */ 
+/* Registration */
 
-static const switch_codec_implementation_t amr_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 96, 
-	/*.iananame */ "AMR", 
+static const switch_codec_implementation_t amr_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 96,
+	/*.iananame */ "AMR",
 	/*.fmtp */ "octet-align=0",
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 0, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 0,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
 	/*.bytes_per_frame */ 320,
-	/*.encoded_bytes_per_frame */ 0, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_amr_init, 
-	/*.encode */ switch_amr_encode, 
-	/*.decode */ switch_amr_decode, 
-	/*.destroy */ switch_amr_destroy, 
+	/*.encoded_bytes_per_frame */ 0,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_amr_init,
+	/*.encode */ switch_amr_encode,
+	/*.decode */ switch_amr_decode,
+	/*.destroy */ switch_amr_destroy,
 };
 
-static const switch_codec_interface_t amr_codec_interface = { 
-	/*.interface_name */ "GSM-AMR", 
-	/*.implementations */ &amr_implementation, 
+static const switch_codec_interface_t amr_codec_interface = {
+	/*.interface_name */ "GSM-AMR",
+	/*.implementations */ &amr_implementation,
 };
 
-static switch_loadable_module_interface_t amr_module_interface = { 
-	/*.module_name */ modname, 
-	/*.endpoint_interface */ NULL, 
-	/*.timer_interface */ NULL, 
-	/*.dialplan_interface */ NULL, 
-	/*.codec_interface */ &amr_codec_interface, 
-	/*.application_interface */ NULL 
+static switch_loadable_module_interface_t amr_module_interface = {
+	/*.module_name */ modname,
+	/*.endpoint_interface */ NULL,
+	/*.timer_interface */ NULL,
+	/*.dialplan_interface */ NULL,
+	/*.codec_interface */ &amr_codec_interface,
+	/*.application_interface */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface,
-													 char *filename)
+SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
 #ifndef AMR_PASSTHROUGH
 	char *cf = "amr.conf";
@@ -349,17 +337,16 @@
 				char *var = (char *) switch_xml_attr_soft(param, "name");
 				char *val = (char *) switch_xml_attr_soft(param, "value");
 				if (!strcasecmp(var, "default-bitrate")) {
-					globals.default_bitrate = (switch_byte_t)atoi(val);
+					globals.default_bitrate = (switch_byte_t) atoi(val);
 				}
 			}
 		}
 	}
-
 #endif
 
-	/* connect my internal structure to the blank pointer passed to me */ 
+	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &amr_module_interface;
 
-	/* indicate that the module should continue to be loaded */ 
+	/* indicate that the module should continue to be loaded */
 	return SWITCH_STATUS_SUCCESS;
 }

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g711/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g711/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g711/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,15 +1,5 @@
-CFLAGS += -I$(BASE)/libs/codec/g7xx/src/include
-all:	$(MODNAME).$(DYNAMIC_LIB_EXTEN)
+BASE=../../../..
+LOCAL_CFLAGS=-I$(BASE)/libs/codec/g7xx/src/include
+include $(BASE)/build/modmake.rules
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
-
-
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
 

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g711/mod_g711.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g711/mod_g711.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g711/mod_g711.c	Tue Apr 24 10:14:28 2007
@@ -36,8 +36,7 @@
 static const char modname[] = "mod_g711";
 
 
-static switch_status_t switch_g711u_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									   const switch_codec_settings_t *codec_settings)
+static switch_status_t switch_g711u_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 	int encoding, decoding;
 
@@ -53,12 +52,11 @@
 
 
 static switch_status_t switch_g711u_encode(switch_codec_t *codec,
-										 switch_codec_t *other_codec,
-										 void *decoded_data,
-										 uint32_t decoded_data_len,
-										 uint32_t decoded_rate,
-										 void *encoded_data,
-										 uint32_t *encoded_data_len, uint32_t *encoded_rate, unsigned int *flag)
+										   switch_codec_t *other_codec,
+										   void *decoded_data,
+										   uint32_t decoded_data_len,
+										   uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										   unsigned int *flag)
 {
 	short *dbuf;
 	unsigned char *ebuf;
@@ -77,12 +75,11 @@
 }
 
 static switch_status_t switch_g711u_decode(switch_codec_t *codec,
-										 switch_codec_t *other_codec,
-										 void *encoded_data,
-										 uint32_t encoded_data_len,
-										 uint32_t encoded_rate,
-										 void *decoded_data,
-										 uint32_t *decoded_data_len, uint32_t *decoded_rate, unsigned int *flag)
+										   switch_codec_t *other_codec,
+										   void *encoded_data,
+										   uint32_t encoded_data_len,
+										   uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										   unsigned int *flag)
 {
 	short *dbuf;
 	unsigned char *ebuf;
@@ -111,8 +108,7 @@
 }
 
 
-static switch_status_t switch_g711a_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									   const switch_codec_settings_t *codec_settings)
+static switch_status_t switch_g711a_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 	int encoding, decoding;
 
@@ -128,12 +124,11 @@
 
 
 static switch_status_t switch_g711a_encode(switch_codec_t *codec,
-										 switch_codec_t *other_codec,
-										 void *decoded_data,
-										 uint32_t decoded_data_len,
-										 uint32_t decoded_rate,
-										 void *encoded_data,
-										 uint32_t *encoded_data_len, uint32_t *encoded_rate, unsigned int *flag)
+										   switch_codec_t *other_codec,
+										   void *decoded_data,
+										   uint32_t decoded_data_len,
+										   uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										   unsigned int *flag)
 {
 	short *dbuf;
 	unsigned char *ebuf;
@@ -152,12 +147,11 @@
 }
 
 static switch_status_t switch_g711a_decode(switch_codec_t *codec,
-										 switch_codec_t *other_codec,
-										 void *encoded_data,
-										 uint32_t encoded_data_len,
-										 uint32_t encoded_rate,
-										 void *decoded_data,
-										 uint32_t *decoded_data_len, uint32_t *decoded_rate, unsigned int *flag)
+										   switch_codec_t *other_codec,
+										   void *encoded_data,
+										   uint32_t encoded_data_len,
+										   uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										   unsigned int *flag)
 {
 	short *dbuf;
 	unsigned char *ebuf;
@@ -226,7 +220,7 @@
 	/*.encode */ switch_g711u_encode,
 	/*.decode */ switch_g711u_decode,
 	/*.destroy */ switch_g711u_destroy,
-	/*.next*/ &g711u_8k_120ms_implementation
+	/*.next */ &g711u_8k_120ms_implementation
 };
 
 static const switch_codec_implementation_t g711u_8k_30ms_implementation = {
@@ -247,7 +241,7 @@
 	/*.encode */ switch_g711u_encode,
 	/*.decode */ switch_g711u_decode,
 	/*.destroy */ switch_g711u_destroy,
-	/*.next*/ &g711u_8k_60ms_implementation
+	/*.next */ &g711u_8k_60ms_implementation
 };
 
 static const switch_codec_implementation_t g711u_8k_20ms_implementation = {
@@ -268,7 +262,7 @@
 	/*.encode */ switch_g711u_encode,
 	/*.decode */ switch_g711u_decode,
 	/*.destroy */ switch_g711u_destroy,
-	/*.next*/ &g711u_8k_30ms_implementation
+	/*.next */ &g711u_8k_30ms_implementation
 };
 
 static const switch_codec_implementation_t g711u_8k_10ms_implementation = {
@@ -289,7 +283,7 @@
 	/*.encode */ switch_g711u_encode,
 	/*.decode */ switch_g711u_decode,
 	/*.destroy */ switch_g711u_destroy,
-	/*.next*/ &g711u_8k_20ms_implementation
+	/*.next */ &g711u_8k_20ms_implementation
 };
 
 
@@ -332,7 +326,7 @@
 	/*.encode */ switch_g711a_encode,
 	/*.decode */ switch_g711a_decode,
 	/*.destroy */ switch_g711a_destroy,
-    /*.next*/ &g711a_8k_120ms_implementation
+	/*.next */ &g711a_8k_120ms_implementation
 };
 
 static const switch_codec_implementation_t g711a_8k_30ms_implementation = {
@@ -353,7 +347,7 @@
 	/*.encode */ switch_g711a_encode,
 	/*.decode */ switch_g711a_decode,
 	/*.destroy */ switch_g711a_destroy,
-    /*.next*/ &g711a_8k_60ms_implementation
+	/*.next */ &g711a_8k_60ms_implementation
 };
 
 static const switch_codec_implementation_t g711a_8k_20ms_implementation = {
@@ -374,7 +368,7 @@
 	/*.encode */ switch_g711a_encode,
 	/*.decode */ switch_g711a_decode,
 	/*.destroy */ switch_g711a_destroy,
-    /*.next*/ &g711a_8k_30ms_implementation
+	/*.next */ &g711a_8k_30ms_implementation
 };
 
 static const switch_codec_implementation_t g711a_8k_10ms_implementation = {
@@ -395,7 +389,7 @@
 	/*.encode */ switch_g711a_encode,
 	/*.decode */ switch_g711a_decode,
 	/*.destroy */ switch_g711a_destroy,
-    /*.next*/ &g711a_8k_20ms_implementation
+	/*.next */ &g711a_8k_20ms_implementation
 };
 
 

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g722/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g722/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g722/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,16 +1,10 @@
-LDFLAGS +=-lg7xx
+BASE=../../../..
+G7XX_DIR=$(BASE)/libs/codec/g7xx
+G7XXLA=$(G7XX_DIR)/libg7xx.la
+LOCAL_CFLAGS=-I$(G7XX_DIR)/src/include/
+LOCAL_LIBADD=$(G7XXLA)
+include $(BASE)/build/modmake.rules
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install codec/g7xx --prefix=$(PREFIX)
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c 
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(G7XXLA): $(G7XX_DIR) $(G7XX_DIR)/.update
+	cd $(G7XX_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g722/mod_g722.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g722/mod_g722.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g722/mod_g722.c	Tue Apr 24 10:14:28 2007
@@ -40,8 +40,7 @@
 	g722_encode_state_t encoder_object;
 };
 
-static switch_status_t switch_g722_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									   const switch_codec_settings_t *codec_settings)
+static switch_status_t switch_g722_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 	int encoding, decoding;
 	struct g722_context *context = NULL;
@@ -50,18 +49,18 @@
 	encoding = (flags & SWITCH_CODEC_FLAG_ENCODE);
 	decoding = (flags & SWITCH_CODEC_FLAG_DECODE);
 
-	if (!(encoding || decoding) || (!(context = switch_core_alloc(codec->memory_pool, sizeof(struct g722_context))))) { 
+	if (!(encoding || decoding) || (!(context = switch_core_alloc(codec->memory_pool, sizeof(struct g722_context))))) {
 		return SWITCH_STATUS_FALSE;
 	} else {
 		if (encoding) {
-			if(codec->implementation->samples_per_second == 16000){
+			if (codec->implementation->samples_per_second == 16000) {
 				g722_encode_init(&context->encoder_object, 64000, G722_PACKED);
 			} else {
 				g722_encode_init(&context->encoder_object, 64000, G722_SAMPLE_RATE_8000);
 			}
 		}
 		if (decoding) {
-			if(codec->implementation->samples_per_second == 16000){
+			if (codec->implementation->samples_per_second == 16000) {
 				g722_decode_init(&context->decoder_object, 64000, G722_PACKED);
 			} else {
 				g722_decode_init(&context->decoder_object, 64000, G722_SAMPLE_RATE_8000);
@@ -70,44 +69,42 @@
 	}
 
 	codec->private_info = context;
-	return SWITCH_STATUS_SUCCESS;	
+	return SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t switch_g722_encode(switch_codec_t *codec,
-										 switch_codec_t *other_codec,
-										 void *decoded_data,
-										 uint32_t decoded_data_len,
-										 uint32_t decoded_rate,
-										 void *encoded_data,
-										 uint32_t *encoded_data_len, uint32_t *encoded_rate, unsigned int *flag)
+										  switch_codec_t *other_codec,
+										  void *decoded_data,
+										  uint32_t decoded_data_len,
+										  uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										  unsigned int *flag)
 {
 	struct g722_context *context = codec->private_info;
 
 	if (!context) {
-		return SWITCH_STATUS_FALSE; 
+		return SWITCH_STATUS_FALSE;
 	}
 
 	*encoded_data_len = g722_encode(&context->encoder_object, (uint8_t *) encoded_data, (int16_t *) decoded_data, decoded_data_len / 2);
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t switch_g722_decode(switch_codec_t *codec,
-										 switch_codec_t *other_codec,
-										 void *encoded_data,
-										 uint32_t encoded_data_len,
-										 uint32_t encoded_rate,
-										 void *decoded_data,
-										 uint32_t *decoded_data_len, uint32_t *decoded_rate, unsigned int *flag)
+										  switch_codec_t *other_codec,
+										  void *encoded_data,
+										  uint32_t encoded_data_len,
+										  uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										  unsigned int *flag)
 {
 	struct g722_context *context = codec->private_info;
 
 	if (!context) {
-		return SWITCH_STATUS_FALSE; 
+		return SWITCH_STATUS_FALSE;
 	}
 
 	*decoded_data_len = (2 * g722_decode(&context->decoder_object, (int16_t *) decoded_data, (uint8_t *) encoded_data, encoded_data_len));
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -122,8 +119,8 @@
 
 static const switch_codec_implementation_t g722_8k_implementation = {
 	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
-	/*.ianacode */ 9,
-	/*.iananame */ "G722",
+	/*.ianacode */ 109,
+	/*.iananame */ "G722_8",
 	/*.fmtp */ NULL,
 	/*.samples_per_second */ 8000,
 	/*.bits_per_second */ 64000,

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g723_1/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g723_1/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g723_1/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,23 +1,8 @@
-ifeq ($(shell ls -d $(BASE)/libs/libg723_1),$(BASE)/libs/libg723_1)
+BASE=../../../..
+DIR=$(BASE)/libs/libg723_1
+A=$(DIR)/.libs/libg723.a
 
-CFLAGS += -I$(PREFIX)/include/g723
-LDFLAGS +=-lg723
+LOCAL_INSERT_CFLAGS=if test -f $(A); then echo "-I$(DIR)/src/include" ; else echo "-DG723_PASSTHROUGH" ; fi ;
+LOCAL_INSERT_LDFLAGS=test ! -f $(A) || echo $(A) 
 
-else
-
-CFLAGS += -DG723_PASSTHROUGH
-endif
-
-all:	$(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+include $(BASE)/build/modmake.rules

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g723_1/mod_g723_1.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g723_1/mod_g723_1.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g723_1/mod_g723_1.c	Tue Apr 24 10:14:28 2007
@@ -30,7 +30,7 @@
  *
  * mod_g723.c -- G723.1 Codec Module
  *
- */  
+ */
 #include "switch.h"
 
 #ifndef G723_PASSTHROUGH
@@ -60,12 +60,11 @@
 };
 #endif
 
-static switch_status_t switch_g723_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									  const switch_codec_settings_t *codec_settings) 
+static switch_status_t switch_g723_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 #ifdef G723_PASSTHROUGH
 	codec->flags |= SWITCH_CODEC_FLAG_PASSTHROUGH;
-	return  SWITCH_STATUS_FALSE;
+	return SWITCH_STATUS_FALSE;
 #else
 	struct g723_context *context = NULL;
 	int encoding, decoding;
@@ -79,10 +78,10 @@
 
 		if (encoding) {
 			Init_Coder(&context->encoder_object);
-			if( UseVx ) {
+			if (UseVx) {
 				Init_Vad(&context->encoder_object);
 				Init_Cod_Cng(&context->encoder_object);
-			}		   
+			}
 		}
 
 		if (decoding) {
@@ -98,7 +97,7 @@
 }
 
 
-static switch_status_t switch_g723_destroy(switch_codec_t *codec) 
+static switch_status_t switch_g723_destroy(switch_codec_t *codec)
 {
 #ifndef G723_PASSTHROUGH
 	codec->private_info = NULL;
@@ -106,17 +105,12 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t switch_g723_encode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *decoded_data,
-
-										uint32_t decoded_data_len, 
-										uint32_t decoded_rate, 
-										void *encoded_data,
-
-										uint32_t *encoded_data_len, 
-										uint32_t *encoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_g723_encode(switch_codec_t *codec,
+										  switch_codec_t *other_codec,
+										  void *decoded_data,
+										  uint32_t decoded_data_len,
+										  uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										  unsigned int *flag)
 {
 #ifdef G723_PASSTHROUGH
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "This codec is only usable in passthrough mode!\n");
@@ -131,28 +125,23 @@
 		return SWITCH_STATUS_FALSE;
 	}
 
-	for(x = 0; x < Frame; x++) {
+	for (x = 0; x < Frame; x++) {
 		context->cod_float_buf[x] = decoded_slin_buf[x];
 	}
 
-	Coder(&context->encoder_object, (FLOAT *)context->cod_float_buf, ebuf);
+	Coder(&context->encoder_object, (FLOAT *) context->cod_float_buf, ebuf);
 	*encoded_data_len = codec->implementation->encoded_bytes_per_frame;
 
 	return SWITCH_STATUS_SUCCESS;
 #endif
 }
 
-static switch_status_t switch_g723_decode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *encoded_data,
-
-										uint32_t encoded_data_len, 
-										uint32_t encoded_rate, 
-										void *decoded_data,
-
-										uint32_t *decoded_data_len, 
-										uint32_t *decoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_g723_decode(switch_codec_t *codec,
+										  switch_codec_t *other_codec,
+										  void *encoded_data,
+										  uint32_t encoded_data_len,
+										  uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										  unsigned int *flag)
 {
 #ifdef G723_PASSTHROUGH
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "This codec is only usable in passthrough mode!\n");
@@ -165,10 +154,10 @@
 	if (!context) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	Decod(&context->decoder_object, (FLOAT *) context->dec_float_buf, (char *) decoded_data, 0);
 
-	for (x=0;x<Frame;x++) {
+	for (x = 0; x < Frame; x++) {
 		to_slin_buf[x] = context->dec_float_buf[x];
 	}
 	*decoded_data_len = codec->implementation->bytes_per_frame;
@@ -177,49 +166,48 @@
 #endif
 }
 
-/* Registration */ 
+/* Registration */
 
-static const switch_codec_implementation_t g723_1_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 4, 
-	/*.iananame */ "G723", 
+static const switch_codec_implementation_t g723_1_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 4,
+	/*.iananame */ "G723",
 	/*.fmtp */ NULL,
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 6300, 
-	/*.microseconds_per_frame */ 30000, 
-	/*.samples_per_frame */ 240, 
-	/*.bytes_per_frame */ 480, 
-	/*.encoded_bytes_per_frame */ 24, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 4, 
-	/*.init */ switch_g723_init, 
-	/*.encode */ switch_g723_encode, 
-	/*.decode */ switch_g723_decode, 
-	/*.destroy */ switch_g723_destroy, 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 6300,
+	/*.microseconds_per_frame */ 30000,
+	/*.samples_per_frame */ 240,
+	/*.bytes_per_frame */ 480,
+	/*.encoded_bytes_per_frame */ 24,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 4,
+	/*.init */ switch_g723_init,
+	/*.encode */ switch_g723_encode,
+	/*.decode */ switch_g723_decode,
+	/*.destroy */ switch_g723_destroy,
 };
 
-static const switch_codec_interface_t g723_1_codec_interface = { 
-	/*.interface_name */ "g723.1 6.3k", 
-	/*.implementations */ &g723_1_implementation, 
+static const switch_codec_interface_t g723_1_codec_interface = {
+	/*.interface_name */ "g723.1 6.3k",
+	/*.implementations */ &g723_1_implementation,
 };
 
-static switch_loadable_module_interface_t g723_module_interface = { 
-	/*.module_name */ modname, 
-	/*.endpoint_interface */ NULL, 
-	/*.timer_interface */ NULL, 
-	/*.dialplan_interface */ NULL, 
-	/*.codec_interface */ &g723_1_codec_interface, 
-	/*.application_interface */ NULL 
+static switch_loadable_module_interface_t g723_module_interface = {
+	/*.module_name */ modname,
+	/*.endpoint_interface */ NULL,
+	/*.timer_interface */ NULL,
+	/*.dialplan_interface */ NULL,
+	/*.codec_interface */ &g723_1_codec_interface,
+	/*.application_interface */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface,
-													 char *filename)
+SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
-	/* connect my internal structure to the blank pointer passed to me */ 
+	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &g723_module_interface;
 
-	/* indicate that the module should continue to be loaded */ 
+	/* indicate that the module should continue to be loaded */
 	return SWITCH_STATUS_SUCCESS;
 }
 

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g726/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g726/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g726/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,16 +1,10 @@
-LDFLAGS +=-lg726
+BASE=../../../..
+G726_DIR=$(BASE)/libs/codec/g726
+G726LA=$(G726_DIR)/libg726.la
+LOCAL_CFLAGS=-I$(G726_DIR)/src
+LOCAL_LIBADD=$(G726LA)
+include $(BASE)/build/modmake.rules
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install codec/g726 --prefix=$(PREFIX)
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c ../../../include/switch_bitpack.h
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(G726LA): $(G726_DIR) $(G726_DIR)/.update
+	cd $(G726_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g726/mod_g726.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g726/mod_g726.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g726/mod_g726.c	Tue Apr 24 10:14:28 2007
@@ -28,15 +28,15 @@
  *
  * mod_g726.c -- G726 Codec Module
  *
- */  
+ */
 #include "switch.h"
 #include "g72x.h"
 #include "switch_bitpack.h"
 
 static const char modname[] = "mod_g726";
 
-typedef int (*encoder_t)(int, int, g726_state *);
-typedef int (*decoder_t)(int, int, g726_state *);
+typedef int (*encoder_t) (int, int, g726_state *);
+typedef int (*decoder_t) (int, int, g726_state *);
 
 
 typedef struct {
@@ -52,8 +52,7 @@
 	switch_byte_t buf[160];
 } g726_handle_t;
 
-static switch_status_t switch_g726_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									  const switch_codec_settings_t *codec_settings) 
+static switch_status_t switch_g726_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 	uint32_t encoding, decoding;
 	g726_handle_t *handle;
@@ -65,8 +64,8 @@
 		return SWITCH_STATUS_FALSE;
 	} else {
 		handle->bytes = (switch_byte_t) codec->implementation->encoded_bytes_per_frame;
-		
-		switch(handle->bytes) {
+
+		switch (handle->bytes) {
 		case 100:
 			handle->encoder = g726_40_encoder;
 			handle->decoder = g726_40_decoder;
@@ -96,14 +95,14 @@
 		g726_init_state(&handle->context);
 		codec->private_info = handle;
 		handle->bits_per_frame = (switch_byte_t) (codec->implementation->bits_per_second / (codec->implementation->samples_per_second));
-		handle->mode = (flags & SWITCH_CODEC_FLAG_AAL2 || strstr(codec->implementation->iananame, "AAL2")) 
+		handle->mode = (flags & SWITCH_CODEC_FLAG_AAL2 || strstr(codec->implementation->iananame, "AAL2"))
 			? SWITCH_BITPACK_MODE_AAL2 : SWITCH_BITPACK_MODE_RFC3551;
 		return SWITCH_STATUS_SUCCESS;
 	}
 }
 
 
-static switch_status_t switch_g726_destroy(switch_codec_t *codec) 
+static switch_status_t switch_g726_destroy(switch_codec_t *codec)
 {
 	codec->private_info = NULL;
 	return SWITCH_STATUS_SUCCESS;
@@ -111,17 +110,12 @@
 
 
 
-static switch_status_t switch_g726_encode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *decoded_data,
-
-										uint32_t decoded_data_len, 
-										uint32_t decoded_rate, 
-										void *encoded_data,
-
-										uint32_t *encoded_data_len, 
-										uint32_t *encoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_g726_encode(switch_codec_t *codec,
+										  switch_codec_t *other_codec,
+										  void *decoded_data,
+										  uint32_t decoded_data_len,
+										  uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										  unsigned int *flag)
 {
 
 	g726_handle_t *handle = codec->private_info;
@@ -163,17 +157,12 @@
 
 
 
-static switch_status_t switch_g726_decode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *encoded_data,
-
-										uint32_t encoded_data_len, 
-										uint32_t encoded_rate, 
-										void *decoded_data,
-
-										uint32_t *decoded_data_len, 
-										uint32_t *decoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_g726_decode(switch_codec_t *codec,
+										  switch_codec_t *other_codec,
+										  void *encoded_data,
+										  uint32_t encoded_data_len,
+										  uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										  unsigned int *flag)
 {
 
 	g726_handle_t *handle = codec->private_info;
@@ -192,13 +181,13 @@
 		for (y = 0; y < handle->loops; y++) {
 			switch_bitpack_out(&handle->unpack, in[z++]);
 		}
-		for(y = 0; y < handle->bytes; y++) {
+		for (y = 0; y < handle->bytes; y++) {
 			*ddp++ = (int16_t) handle->decoder(handle->buf[y], AUDIO_ENCODING_LINEAR, context);
-            new_len += 2;
+			new_len += 2;
 		}
 		switch_bitpack_done(&handle->unpack);
 	}
-	
+
 	if (new_len <= *decoded_data_len) {
 		*decoded_data_len = new_len;
 	} else {
@@ -213,239 +202,238 @@
 
 
 
-/* Registration */ 
+/* Registration */
 
-static const switch_codec_implementation_t g726_16k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 127, 
-	/*.iananame */ "G726-16", 
+static const switch_codec_implementation_t g726_16k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 127,
+	/*.iananame */ "G726-16",
 	/*.fmtp */ NULL,
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 16000, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
-	/*.bytes_per_frame */ 320, 
-	/*.encoded_bytes_per_frame */ 40, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g726_init, 
-	/*.encode */ switch_g726_encode, 
-	/*.decode */ switch_g726_decode, 
-	/*.destroy */ switch_g726_destroy, 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 16000,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 40,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g726_init,
+	/*.encode */ switch_g726_encode,
+	/*.decode */ switch_g726_decode,
+	/*.destroy */ switch_g726_destroy,
 };
 
 
-static const switch_codec_implementation_t g726_24k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 126, 
-	/*.iananame */ "G726-24", 
+static const switch_codec_implementation_t g726_24k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 126,
+	/*.iananame */ "G726-24",
 	/*.fmtp */ NULL,
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 24000, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
-	/*.bytes_per_frame */ 320, 
-	/*.encoded_bytes_per_frame */ 60, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g726_init, 
-	/*.encode */ switch_g726_encode, 
-	/*.decode */ switch_g726_decode, 
-	/*.destroy */ switch_g726_destroy, 
-};
-
-static const switch_codec_implementation_t g726_32k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 2, 
-	/*.iananame */ "G726-32", 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 24000,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 60,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g726_init,
+	/*.encode */ switch_g726_encode,
+	/*.decode */ switch_g726_decode,
+	/*.destroy */ switch_g726_destroy,
+};
+
+static const switch_codec_implementation_t g726_32k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 2,
+	/*.iananame */ "G726-32",
 	/*.fmtp */ NULL,
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 32000, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
-	/*.bytes_per_frame */ 320, 
-	/*.encoded_bytes_per_frame */ 80, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g726_init, 
-	/*.encode */ switch_g726_encode, 
-	/*.decode */ switch_g726_decode, 
-	/*.destroy */ switch_g726_destroy, 
-};
-
-static const switch_codec_implementation_t g726_40k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 125, 
-	/*.iananame */ "G726-40", 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 32000,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 80,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g726_init,
+	/*.encode */ switch_g726_encode,
+	/*.decode */ switch_g726_decode,
+	/*.destroy */ switch_g726_destroy,
+};
+
+static const switch_codec_implementation_t g726_40k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 125,
+	/*.iananame */ "G726-40",
 	/*.fmtp */ NULL,
 	/*.samples_per_second */ 8000,
-	/*.bits_per_second */ 40000, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
-	/*.bytes_per_frame */ 320, 
-	/*.encoded_bytes_per_frame */ 100, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g726_init, 
-	/*.encode */ switch_g726_encode, 
-	/*.decode */ switch_g726_decode, 
-	/*.destroy */ switch_g726_destroy, 
+	/*.bits_per_second */ 40000,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 100,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g726_init,
+	/*.encode */ switch_g726_encode,
+	/*.decode */ switch_g726_decode,
+	/*.destroy */ switch_g726_destroy,
 };
 
 
 
-static const switch_codec_implementation_t aal2_g726_16k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 124, 
-	/*.iananame */ "AAL2-G726-16", 
+static const switch_codec_implementation_t aal2_g726_16k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 124,
+	/*.iananame */ "AAL2-G726-16",
 	/*.fmtp */ NULL,
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 16000, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
-	/*.bytes_per_frame */ 320, 
-	/*.encoded_bytes_per_frame */ 40, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g726_init, 
-	/*.encode */ switch_g726_encode, 
-	/*.decode */ switch_g726_decode, 
-	/*.destroy */ switch_g726_destroy, 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 16000,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 40,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g726_init,
+	/*.encode */ switch_g726_encode,
+	/*.decode */ switch_g726_decode,
+	/*.destroy */ switch_g726_destroy,
 };
 
 
-static const switch_codec_implementation_t aal2_g726_24k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 123, 
-	/*.iananame */ "AAL2-G726-24", 
+static const switch_codec_implementation_t aal2_g726_24k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 123,
+	/*.iananame */ "AAL2-G726-24",
 	/*.fmtp */ NULL,
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 24000, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
-	/*.bytes_per_frame */ 320, 
-	/*.encoded_bytes_per_frame */ 60, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g726_init, 
-	/*.encode */ switch_g726_encode, 
-	/*.decode */ switch_g726_decode, 
-	/*.destroy */ switch_g726_destroy, 
-};
-
-static const switch_codec_implementation_t aal2_g726_32k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 2, 
-	/*.iananame */ "AAL2-G726-32", 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 24000,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 60,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g726_init,
+	/*.encode */ switch_g726_encode,
+	/*.decode */ switch_g726_decode,
+	/*.destroy */ switch_g726_destroy,
+};
+
+static const switch_codec_implementation_t aal2_g726_32k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 2,
+	/*.iananame */ "AAL2-G726-32",
 	/*.fmtp */ NULL,
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 32000, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
-	/*.bytes_per_frame */ 320, 
-	/*.encoded_bytes_per_frame */ 80, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g726_init, 
-	/*.encode */ switch_g726_encode, 
-	/*.decode */ switch_g726_decode, 
-	/*.destroy */ switch_g726_destroy, 
-};
-
-static const switch_codec_implementation_t aal2_g726_40k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 122, 
-	/*.iananame */ "AAL2-G726-40", 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 32000,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 80,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g726_init,
+	/*.encode */ switch_g726_encode,
+	/*.decode */ switch_g726_decode,
+	/*.destroy */ switch_g726_destroy,
+};
+
+static const switch_codec_implementation_t aal2_g726_40k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 122,
+	/*.iananame */ "AAL2-G726-40",
 	/*.fmtp */ NULL,
 	/*.samples_per_second */ 8000,
-	/*.bits_per_second */ 40000, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
-	/*.bytes_per_frame */ 320, 
-	/*.encoded_bytes_per_frame */ 100, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g726_init, 
-	/*.encode */ switch_g726_encode, 
-	/*.decode */ switch_g726_decode, 
-	/*.destroy */ switch_g726_destroy, 
-};
-
-const switch_codec_interface_t g726_16k_codec_interface = { 
-	/*.interface_name */ "G.726 16k", 
-	/*.implementations */ &g726_16k_implementation, 
-};
-
-const switch_codec_interface_t g726_24k_codec_interface = { 
-	/*.interface_name */ "G.726 24k", 
-	/*.implementations */ &g726_24k_implementation, 
+	/*.bits_per_second */ 40000,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 100,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g726_init,
+	/*.encode */ switch_g726_encode,
+	/*.decode */ switch_g726_decode,
+	/*.destroy */ switch_g726_destroy,
+};
+
+const switch_codec_interface_t g726_16k_codec_interface = {
+	/*.interface_name */ "G.726 16k",
+	/*.implementations */ &g726_16k_implementation,
+};
+
+const switch_codec_interface_t g726_24k_codec_interface = {
+	/*.interface_name */ "G.726 24k",
+	/*.implementations */ &g726_24k_implementation,
 	/*.next */ &g726_16k_codec_interface
 };
 
-const switch_codec_interface_t g726_32k_codec_interface = { 
-	/*.interface_name */ "G.726 32k", 
-	/*.implementations */ &g726_32k_implementation, 
+const switch_codec_interface_t g726_32k_codec_interface = {
+	/*.interface_name */ "G.726 32k",
+	/*.implementations */ &g726_32k_implementation,
 	/*.next */ &g726_24k_codec_interface
 };
 
-const switch_codec_interface_t g726_40k_codec_interface = { 
-	/*.interface_name */ "G.726 40k", 
-	/*.implementations */ &g726_40k_implementation, 
+const switch_codec_interface_t g726_40k_codec_interface = {
+	/*.interface_name */ "G.726 40k",
+	/*.implementations */ &g726_40k_implementation,
 	/*.next */ &g726_32k_codec_interface
 };
 
 
 
-const switch_codec_interface_t aal2_g726_16k_codec_interface = { 
-	/*.interface_name */ "G.726 16k (aal2)", 
-	/*.implementations */ &aal2_g726_16k_implementation, 
+const switch_codec_interface_t aal2_g726_16k_codec_interface = {
+	/*.interface_name */ "G.726 16k (aal2)",
+	/*.implementations */ &aal2_g726_16k_implementation,
 	/*.next */ &g726_40k_codec_interface
 };
 
-const switch_codec_interface_t aal2_g726_24k_codec_interface = { 
-	/*.interface_name */ "G.726 24k (aal2)", 
-	/*.implementations */ &aal2_g726_24k_implementation, 
+const switch_codec_interface_t aal2_g726_24k_codec_interface = {
+	/*.interface_name */ "G.726 24k (aal2)",
+	/*.implementations */ &aal2_g726_24k_implementation,
 	/*.next */ &aal2_g726_16k_codec_interface
 };
 
-const switch_codec_interface_t aal2_g726_32k_codec_interface = { 
-	/*.interface_name */ "G.726 32k (aal2)", 
-	/*.implementations */ &aal2_g726_32k_implementation, 
+const switch_codec_interface_t aal2_g726_32k_codec_interface = {
+	/*.interface_name */ "G.726 32k (aal2)",
+	/*.implementations */ &aal2_g726_32k_implementation,
 	/*.next */ &aal2_g726_24k_codec_interface
 };
 
-const switch_codec_interface_t aal2_g726_40k_codec_interface = { 
-	/*.interface_name */ "G.726 40k (aal2)", 
-	/*.implementations */ &aal2_g726_40k_implementation, 
+const switch_codec_interface_t aal2_g726_40k_codec_interface = {
+	/*.interface_name */ "G.726 40k (aal2)",
+	/*.implementations */ &aal2_g726_40k_implementation,
 	/*.next */ &aal2_g726_32k_codec_interface
 };
 
 
 
-static switch_loadable_module_interface_t g726_module_interface = { 
-	/*.module_name */ modname, 
-	/*.endpoint_interface */ NULL, 
-	/*.timer_interface */ NULL, 
-	/*.dialplan_interface */ NULL, 
-	/*.codec_interface */ &aal2_g726_40k_codec_interface, 
-	/*.application_interface */ NULL 
+static switch_loadable_module_interface_t g726_module_interface = {
+	/*.module_name */ modname,
+	/*.endpoint_interface */ NULL,
+	/*.timer_interface */ NULL,
+	/*.dialplan_interface */ NULL,
+	/*.codec_interface */ &aal2_g726_40k_codec_interface,
+	/*.application_interface */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface,
-													 char *filename)
+SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
-	/* connect my internal structure to the blank pointer passed to me */ 
+	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &g726_module_interface;
 
-	/* indicate that the module should continue to be loaded */ 
+	/* indicate that the module should continue to be loaded */
 	return SWITCH_STATUS_SUCCESS;
 }
 

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g729/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g729/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g729/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,24 +1,7 @@
-ifeq ($(shell ls -d $(BASE)/libs/libg729),$(BASE)/libs/libg729)
-
-CFLAGS += -I$(PREFIX)/include/libg729
-LDFLAGS +=-lg729
-
-else
-
-CFLAGS += -DG729_PASSTHROUGH
-
-endif
-
-all:	$(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+BASE=../../../..
+DIR=$(BASE)/libs/libg729
+A=$(DIR)/.libs/libg729.a
+
+LOCAL_INSERT_CFLAGS=if test -f $(A); then echo "-I$(DIR)/src/include" ; else echo "-DG729_PASSTHROUGH" ; fi ;
+LOCAL_INSERT_LDFLAGS=test ! -f $(A) || echo $(A) 
+include $(BASE)/build/modmake.rules

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_g729/mod_g729.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_g729/mod_g729.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_g729/mod_g729.c	Tue Apr 24 10:14:28 2007
@@ -30,7 +30,7 @@
  *
  * mod_g729.c -- G729 Codec Module
  *
- */  
+ */
 
 static const char modname[] = "mod_g729";
 
@@ -45,16 +45,15 @@
 };
 #endif
 
-static switch_status_t switch_g729_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									  const switch_codec_settings_t *codec_settings) 
+static switch_status_t switch_g729_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 #ifdef G729_PASSTHROUGH
 	codec->flags |= SWITCH_CODEC_FLAG_PASSTHROUGH;
-    if (codec->fmtp_in) {
-        codec->fmtp_out = switch_core_strdup(codec->memory_pool, codec->fmtp_in);
-    }
+	if (codec->fmtp_in) {
+		codec->fmtp_out = switch_core_strdup(codec->memory_pool, codec->fmtp_in);
+	}
 	return SWITCH_STATUS_SUCCESS;
-#else 
+#else
 	struct g729_context *context = NULL;
 	int encoding, decoding;
 
@@ -64,9 +63,9 @@
 	if (!(encoding || decoding) || (!(context = switch_core_alloc(codec->memory_pool, sizeof(struct g729_context))))) {
 		return SWITCH_STATUS_FALSE;
 	} else {
-        if (codec->fmtp_in) {
-            codec->fmtp_out = switch_core_strdup(codec->memory_pool, codec->fmtp_in);
-        }
+		if (codec->fmtp_in) {
+			codec->fmtp_out = switch_core_strdup(codec->memory_pool, codec->fmtp_in);
+		}
 
 		if (encoding) {
 			g729_init_coder(&context->encoder_object, 0);
@@ -84,7 +83,7 @@
 #endif
 }
 
-static switch_status_t switch_g729_destroy(switch_codec_t *codec) 
+static switch_status_t switch_g729_destroy(switch_codec_t *codec)
 {
 #ifndef G729_PASSTHROUGH
 	codec->private_info = NULL;
@@ -92,17 +91,12 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t switch_g729_encode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *decoded_data,
-
-										uint32_t decoded_data_len, 
-										uint32_t decoded_rate, 
-										void *encoded_data,
-
-										uint32_t *encoded_data_len, 
-										uint32_t *encoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_g729_encode(switch_codec_t *codec,
+										  switch_codec_t *other_codec,
+										  void *decoded_data,
+										  uint32_t decoded_data_len,
+										  uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										  unsigned int *flag)
 {
 #ifdef G729_PASSTHROUGH
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "This codec is only usable in passthrough mode!\n");
@@ -117,7 +111,7 @@
 
 	if (decoded_data_len % 160 == 0) {
 		uint32_t new_len = 0;
-		INT16 * ddp = decoded_data;
+		INT16 *ddp = decoded_data;
 		char *edp = encoded_data;
 		int x;
 		int loops = (int) decoded_data_len / 160;
@@ -140,17 +134,12 @@
 #endif
 }
 
-static switch_status_t switch_g729_decode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *encoded_data,
-
-										uint32_t encoded_data_len, 
-										uint32_t encoded_rate, 
-										void *decoded_data,
-
-										uint32_t *decoded_data_len, 
-										uint32_t *decoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_g729_decode(switch_codec_t *codec,
+										  switch_codec_t *other_codec,
+										  void *encoded_data,
+										  uint32_t encoded_data_len,
+										  uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										  unsigned int *flag)
 {
 #ifdef G729_PASSTHROUGH
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "This codec is only usable in passthrough mode!\n");
@@ -165,10 +154,9 @@
 
 	}
 
-
 	if (encoded_data_len % 2 == 0) {
-
-		if (encoded_data_len % 12 == 0) {
+		
+		if (encoded_data_len == 2 || encoded_data_len % 12 == 0) {
 			return SWITCH_STATUS_BREAK;
 			//divisor = 12;
 			//plen = 10;
@@ -189,7 +177,7 @@
 			uint32_t new_len = 0;
 
 			test = (uint8_t *) encoded_data;
-			if (*test == 0 && *(test+1) == 0) {
+			if (*test == 0 && *(test + 1) == 0) {
 				*decoded_data_len = (encoded_data_len / divisor) * 160;
 				memset(decoded_data, 0, *decoded_data_len);
 				return SWITCH_STATUS_SUCCESS;
@@ -213,7 +201,7 @@
 				return SWITCH_STATUS_FALSE;
 
 			}
-		} 
+		}
 	} else {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "yo this frame is an odd size [%d]\n", encoded_data_len);
 		return SWITCH_STATUS_FALSE;
@@ -222,46 +210,88 @@
 #endif
 }
 
-/* Registration */ 
+/* Registration */
+
+static const switch_codec_implementation_t g729_40ms_8k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 18,
+	/*.iananame */ "G729",
+	/*.fmtp */ NULL,
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 128000,
+	/*.microseconds_per_frame */ 40000,
+	/*.samples_per_frame */ 320,
+	/*.bytes_per_frame */ 640,
+	/*.encoded_bytes_per_frame */ 40,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g729_init,
+	/*.encode */ switch_g729_encode,
+	/*.decode */ switch_g729_decode,
+	/*.destroy */ switch_g729_destroy,
+};
+
+static const switch_codec_implementation_t g729_30ms_8k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 18,
+	/*.iananame */ "G729",
+	/*.fmtp */ NULL,
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 96000,
+	/*.microseconds_per_frame */ 30000,
+	/*.samples_per_frame */ 240,
+	/*.bytes_per_frame */ 480,
+	/*.encoded_bytes_per_frame */ 30,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g729_init,
+	/*.encode */ switch_g729_encode,
+	/*.decode */ switch_g729_decode,
+	/*.destroy */ switch_g729_destroy,
+	&g729_40ms_8k_implementation
+};
 
-static const switch_codec_implementation_t g729_10ms_8k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 18, 
-	/*.iananame */ "G729", 
+static const switch_codec_implementation_t g729_10ms_8k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 18,
+	/*.iananame */ "G729",
 	/*.fmtp */ NULL,
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 32000, 
-	/*.microseconds_per_frame */ 10000, 
-	/*.samples_per_frame */ 80, 
-	/*.bytes_per_frame */ 160, 
-	/*.encoded_bytes_per_frame */ 10, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g729_init, 
-	/*.encode */ switch_g729_encode, 
-	/*.decode */ switch_g729_decode, 
-	/*.destroy */ switch_g729_destroy, 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 32000,
+	/*.microseconds_per_frame */ 10000,
+	/*.samples_per_frame */ 80,
+	/*.bytes_per_frame */ 160,
+	/*.encoded_bytes_per_frame */ 10,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g729_init,
+	/*.encode */ switch_g729_encode,
+	/*.decode */ switch_g729_decode,
+	/*.destroy */ switch_g729_destroy,
+	&g729_30ms_8k_implementation
 };
 
-static const switch_codec_implementation_t g729_8k_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 18, 
-	/*.iananame */ "G729", 
+static const switch_codec_implementation_t g729_8k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 18,
+	/*.iananame */ "G729",
 	/*.fmtp */ NULL,
-	/*.samples_per_second */ 8000, 
-	/*.bits_per_second */ 64000, 
-	/*.microseconds_per_frame */ 20000, 
-	/*.samples_per_frame */ 160, 
-	/*.bytes_per_frame */ 320, 
-	/*.encoded_bytes_per_frame */ 20, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_g729_init, 
-	/*.encode */ switch_g729_encode, 
-	/*.decode */ switch_g729_decode, 
-	/*.destroy */ switch_g729_destroy, 
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 64000,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 20,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_g729_init,
+	/*.encode */ switch_g729_encode,
+	/*.decode */ switch_g729_decode,
+	/*.destroy */ switch_g729_destroy,
 	&g729_10ms_8k_implementation
 };
 
@@ -271,22 +301,21 @@
 	/*.next */ NULL
 };
 
-static switch_loadable_module_interface_t g729_module_interface = { 
+static switch_loadable_module_interface_t g729_module_interface = {
 	/*.module_name */ "g729",
-	/*.endpoint_interface */ NULL, 
-	/*.timer_interface */ NULL, 
-	/*.dialplan_interface */ NULL, 
-	/*.codec_interface */ &g729_codec_interface, 
-	/*.application_interface */ NULL 
+	/*.endpoint_interface */ NULL,
+	/*.timer_interface */ NULL,
+	/*.dialplan_interface */ NULL,
+	/*.codec_interface */ &g729_codec_interface,
+	/*.application_interface */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface,
-													 char *filename)
+SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
-	/* connect my internal structure to the blank pointer passed to me */ 
+	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &g729_module_interface;
 
-	/* indicate that the module should continue to be loaded */ 
+	/* indicate that the module should continue to be loaded */
 	return SWITCH_STATUS_SUCCESS;
 }
 

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_gsm/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_gsm/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_gsm/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,16 +1,10 @@
-LDFLAGS +=-lgsm
+BASE=../../../..
+GSM_DIR=$(BASE)/libs/codec/gsm
+GSMLA=$(GSM_DIR)/libgsm.la
+LOCAL_CFLAGS=-I$(GSM_DIR)/inc
+LOCAL_LIBADD=$(GSMLA)
+include $(BASE)/build/modmake.rules
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install codec/gsm --prefix=$(PREFIX)
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(GSMLA): $(GSM_DIR) $(GSM_DIR)/.update
+	cd $(GSM_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_gsm/mod_gsm.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_gsm/mod_gsm.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_gsm/mod_gsm.c	Tue Apr 24 10:14:28 2007
@@ -28,7 +28,7 @@
  *
  * mod_codec_gsm.c -- gsm Codec Module
  *
- */  
+ */
 #include "switch.h"
 #include "gsm.h"
 static const char modname[] = "mod_gsm";
@@ -36,8 +36,7 @@
 	gsm encoder;
 	gsm decoder;
 };
-static switch_status_t switch_gsm_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									   const switch_codec_settings_t *codec_settings) 
+static switch_status_t switch_gsm_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 	struct gsm_context *context;
 	int encoding, decoding;
@@ -55,7 +54,7 @@
 	codec->private_info = context;
 	return SWITCH_STATUS_SUCCESS;
 }
-static switch_status_t switch_gsm_destroy(switch_codec_t *codec) 
+static switch_status_t switch_gsm_destroy(switch_codec_t *codec)
 {
 	struct gsm_context *context = codec->private_info;
 	int encoding = (codec->flags & SWITCH_CODEC_FLAG_ENCODE);
@@ -68,8 +67,8 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 static switch_status_t switch_gsm_encode(switch_codec_t *codec, switch_codec_t *other_codec, void *decoded_data,
-										  uint32_t decoded_data_len, uint32_t decoded_rate, void *encoded_data,
-										  uint32_t *encoded_data_len, uint32_t *encoded_rate, unsigned int *flag) 
+										 uint32_t decoded_data_len, uint32_t decoded_rate, void *encoded_data,
+										 uint32_t * encoded_data_len, uint32_t * encoded_rate, unsigned int *flag)
 {
 	struct gsm_context *context = codec->private_info;
 	if (!context) {
@@ -77,8 +76,8 @@
 	}
 	if (decoded_data_len % 320 == 0) {
 		uint32_t new_len = 0;
-		gsm_signal * ddp = decoded_data;
-		gsm_byte * edp = encoded_data;
+		gsm_signal *ddp = decoded_data;
+		gsm_byte *edp = encoded_data;
 		int x;
 		int loops = (int) decoded_data_len / 320;
 		for (x = 0; x < loops && new_len < *encoded_data_len; x++) {
@@ -97,8 +96,8 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 static switch_status_t switch_gsm_decode(switch_codec_t *codec, switch_codec_t *other_codec, void *encoded_data,
-										  uint32_t encoded_data_len, uint32_t encoded_rate, void *decoded_data,
-										  uint32_t *decoded_data_len, uint32_t *decoded_rate, unsigned int *flag) 
+										 uint32_t encoded_data_len, uint32_t encoded_rate, void *decoded_data,
+										 uint32_t * decoded_data_len, uint32_t * decoded_rate, unsigned int *flag)
 {
 	struct gsm_context *context = codec->private_info;
 	if (!context) {
@@ -107,8 +106,8 @@
 
 	if (encoded_data_len % 33 == 0) {
 		int loops = (int) encoded_data_len / 33;
-		gsm_byte * edp = encoded_data;
-		gsm_signal * ddp = decoded_data;
+		gsm_byte *edp = encoded_data;
+		gsm_signal *ddp = decoded_data;
 		int x;
 		uint32_t new_len = 0;
 
@@ -131,47 +130,46 @@
 }
 
 
-/* Registration */ 
-static const switch_codec_implementation_t gsm_8k_implementation = { 
-		/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-		/*.ianacode */ 3, 
-		/*.iananame */ "GSM", 
-		/*.fmtp */ NULL,
-		/*.samples_per_second */ 8000, 
-		/*.bits_per_second */ 13200, 
-		/*.microseconds_per_frame */ 20000, 
-		/*.samples_per_frame */ 160, 
-		/*.bytes_per_frame */ 320, 
-		/*.encoded_bytes_per_frame */ 33, 
-		/*.number_of_channels */ 1, 
-		/*.pref_frames_per_packet */ 1, 
-		/*.max_frames_per_packet */ 1, 
-		/*.init */ switch_gsm_init, 
-		/*.encode */ switch_gsm_encode, 
-		/*.decode */ switch_gsm_decode, 
-		/*.destroy */ switch_gsm_destroy, 
+/* Registration */
+static const switch_codec_implementation_t gsm_8k_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 3,
+	/*.iananame */ "GSM",
+	/*.fmtp */ NULL,
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ 13200,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ 33,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_gsm_init,
+	/*.encode */ switch_gsm_encode,
+	/*.decode */ switch_gsm_decode,
+	/*.destroy */ switch_gsm_destroy,
 };
-static const switch_codec_interface_t gsm_codec_interface = { 
-		/*.interface_name */ "gsm", 
-		/*.implementations */ &gsm_8k_implementation, 
+static const switch_codec_interface_t gsm_codec_interface = {
+	/*.interface_name */ "gsm",
+	/*.implementations */ &gsm_8k_implementation,
 };
-static switch_loadable_module_interface_t gsm_module_interface = { 
-		/*.module_name */ modname, 
-		/*.endpoint_interface */ NULL, 
-		/*.timer_interface */ NULL, 
-		/*.dialplan_interface */ NULL, 
-		/*.codec_interface */ &gsm_codec_interface, 
-		/*.application_interface */ NULL 
+static switch_loadable_module_interface_t gsm_module_interface = {
+	/*.module_name */ modname,
+	/*.endpoint_interface */ NULL,
+	/*.timer_interface */ NULL,
+	/*.dialplan_interface */ NULL,
+	/*.codec_interface */ &gsm_codec_interface,
+	/*.application_interface */ NULL
 };
-SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface,
-														char *filename)
+SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
-	
-		/* connect my internal structure to the blank pointer passed to me */ 
-		*module_interface = &gsm_module_interface;
-	
-		/* indicate that the module should continue to be loaded */ 
-		return SWITCH_STATUS_SUCCESS;
+
+	/* connect my internal structure to the blank pointer passed to me */
+	*module_interface = &gsm_module_interface;
+
+	/* indicate that the module should continue to be loaded */
+	return SWITCH_STATUS_SUCCESS;
 }
 
 /* For Emacs:

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_ilbc/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_ilbc/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_ilbc/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,16 +1,10 @@
-LDFLAGS +=-lilbc
+BASE=../../../..
+ILBC_DIR=$(BASE)/libs/codec/ilbc
+ILBCLA=$(ILBC_DIR)/libilbc.la
+LOCAL_CFLAGS=-I$(ILBC_DIR)/src
+LOCAL_LIBADD=$(ILBCLA)
+include $(BASE)/build/modmake.rules
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install codec/ilbc --prefix=$(PREFIX) --disable-shared
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(ILBCLA): $(ILBC_DIR) $(ILBC_DIR)/.update
+	cd $(ILBC_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_ilbc/mod_ilbc.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_ilbc/mod_ilbc.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_ilbc/mod_ilbc.c	Tue Apr 24 10:14:28 2007
@@ -28,7 +28,7 @@
  *
  * mod_ilbc.c -- ilbc Codec Module
  *
- */  
+ */
 #include "switch.h"
 #include "iLBC_encode.h"
 #include "iLBC_decode.h"
@@ -44,12 +44,11 @@
 	uint16_t dbytes;
 };
 
-static switch_status_t switch_ilbc_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									  const switch_codec_settings_t *codec_settings) 
+static switch_status_t switch_ilbc_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 	struct ilbc_context *context;
 	int encoding, decoding;
-	uint8_t ms = (uint8_t)(codec->implementation->microseconds_per_frame / 1000);
+	uint8_t ms = (uint8_t) (codec->implementation->microseconds_per_frame / 1000);
 
 
 	if (ms != 20 && ms != 30) {
@@ -82,13 +81,13 @@
 	}
 
 	codec->fmtp_out = switch_core_strdup(codec->memory_pool, codec->implementation->fmtp);
-	
+
 	codec->private_info = context;
 	return SWITCH_STATUS_SUCCESS;
 }
 
 
-static switch_status_t switch_ilbc_destroy(switch_codec_t *codec) 
+static switch_status_t switch_ilbc_destroy(switch_codec_t *codec)
 {
 	codec->private_info = NULL;
 	return SWITCH_STATUS_SUCCESS;
@@ -96,14 +95,11 @@
 
 
 static switch_status_t switch_ilbc_encode(switch_codec_t *codec,
-										 switch_codec_t *other_codec,
-										 void *decoded_data,
-										 uint32_t decoded_data_len,
-										 uint32_t decoded_rate,
-										 void *encoded_data,
-										 uint32_t *encoded_data_len, 
-										 uint32_t *encoded_rate,
-										 unsigned int *flag)
+										  switch_codec_t *other_codec,
+										  void *decoded_data,
+										  uint32_t decoded_data_len,
+										  uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										  unsigned int *flag)
 {
 	struct ilbc_context *context = codec->private_info;
 
@@ -120,7 +116,7 @@
 		float buf[240];
 
 		for (x = 0; x < loops && new_len < *encoded_data_len; x++) {
-			for(y = 0; y < context->dbytes / sizeof(short) ; y++) {
+			for (y = 0; y < context->dbytes / sizeof(short); y++) {
 				buf[y] = ddp[y];
 			}
 			iLBC_encode(edp, buf, &context->encoder);
@@ -139,14 +135,11 @@
 }
 
 static switch_status_t switch_ilbc_decode(switch_codec_t *codec,
-										switch_codec_t *other_codec,
-										void *encoded_data,
-										uint32_t encoded_data_len,
-										uint32_t encoded_rate,
-										void *decoded_data,
-										uint32_t *decoded_data_len, 
-										uint32_t *decoded_rate, 
-										unsigned int *flag)
+										  switch_codec_t *other_codec,
+										  void *encoded_data,
+										  uint32_t encoded_data_len,
+										  uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										  unsigned int *flag)
 {
 	struct ilbc_context *context = codec->private_info;
 
@@ -165,8 +158,8 @@
 
 		for (x = 0; x < loops && new_len < *decoded_data_len; x++) {
 			iLBC_decode(buf, edp, &context->decoder, 1);
-			for(y = 0; y < context->dbytes / sizeof(short) ; y++) {
-				ddp[y] = (short)buf[y];
+			for (y = 0; y < context->dbytes / sizeof(short); y++) {
+				ddp[y] = (short) buf[y];
 			}
 			ddp += context->dbytes / sizeof(short);
 			edp += context->bytes;
@@ -186,153 +179,152 @@
 }
 
 
-/* Registration */ 
+/* Registration */
 
-static const switch_codec_implementation_t ilbc_8k_30ms_implementation = { 
-		/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-		/*.ianacode */ 97, 
-		/*.iananame */ "iLBC", 
-		/*.fmtp */ "mode=30",
-		/*.samples_per_second */ 8000, 
-		/*.bits_per_second */ NO_OF_BYTES_30MS*8*8000/BLOCKL_30MS,
-		/*.microseconds_per_frame */ 30000,
-		/*.samples_per_frame */ 240,
-		/*.bytes_per_frame */ 480,
-		/*.encoded_bytes_per_frame */ NO_OF_BYTES_30MS,
-		/*.number_of_channels */ 1,
-		/*.pref_frames_per_packet */ 1,
-		/*.max_frames_per_packet */ 1,
-		/*.init */ switch_ilbc_init,
-		/*.encode */ switch_ilbc_encode,
-		/*.decode */ switch_ilbc_decode,
-		/*.destroy */ switch_ilbc_destroy
+static const switch_codec_implementation_t ilbc_8k_30ms_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 97,
+	/*.iananame */ "iLBC",
+	/*.fmtp */ "mode=30",
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ NO_OF_BYTES_30MS * 8 * 8000 / BLOCKL_30MS,
+	/*.microseconds_per_frame */ 30000,
+	/*.samples_per_frame */ 240,
+	/*.bytes_per_frame */ 480,
+	/*.encoded_bytes_per_frame */ NO_OF_BYTES_30MS,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_ilbc_init,
+	/*.encode */ switch_ilbc_encode,
+	/*.decode */ switch_ilbc_decode,
+	/*.destroy */ switch_ilbc_destroy
 };
 
-static const switch_codec_implementation_t ilbc_8k_20ms_implementation = { 
-		/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-		/*.ianacode */ 97, 
-		/*.iananame */ "iLBC", 
-		/*.fmtp */ "mode=20",
-		/*.samples_per_second */ 8000, 
-		/*.bits_per_second */ NO_OF_BYTES_20MS*8*8000/BLOCKL_20MS, 
-		/*.microseconds_per_frame */ 20000,
-		/*.samples_per_frame */ 160,
-		/*.bytes_per_frame */ 320,
-		/*.encoded_bytes_per_frame */ NO_OF_BYTES_20MS, 
-		/*.number_of_channels */ 1,
-		/*.pref_frames_per_packet */ 1,
-		/*.max_frames_per_packet */ 1,
-		/*.init */ switch_ilbc_init,
-		/*.encode */ switch_ilbc_encode,
-		/*.decode */ switch_ilbc_decode,
-		/*.destroy */ switch_ilbc_destroy,
-		/*.next */ &ilbc_8k_30ms_implementation
+static const switch_codec_implementation_t ilbc_8k_20ms_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 97,
+	/*.iananame */ "iLBC",
+	/*.fmtp */ "mode=20",
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ NO_OF_BYTES_20MS * 8 * 8000 / BLOCKL_20MS,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ NO_OF_BYTES_20MS,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_ilbc_init,
+	/*.encode */ switch_ilbc_encode,
+	/*.decode */ switch_ilbc_decode,
+	/*.destroy */ switch_ilbc_destroy,
+	/*.next */ &ilbc_8k_30ms_implementation
 };
 
 
 
-static const switch_codec_implementation_t ilbc_102_8k_30ms_implementation = { 
-		/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-		/*.ianacode */ 102, 
-		/*.iananame */ "iLBC", 
-		/*.fmtp */ "mode=30",
-		/*.samples_per_second */ 8000, 
-		/*.bits_per_second */ NO_OF_BYTES_30MS*8*8000/BLOCKL_30MS,
-		/*.microseconds_per_frame */ 30000,
-		/*.samples_per_frame */ 240,
-		/*.bytes_per_frame */ 480,
-		/*.encoded_bytes_per_frame */ NO_OF_BYTES_30MS,
-		/*.number_of_channels */ 1,
-		/*.pref_frames_per_packet */ 1,
-		/*.max_frames_per_packet */ 1,
-		/*.init */ switch_ilbc_init,
-		/*.encode */ switch_ilbc_encode,
-		/*.decode */ switch_ilbc_decode,
-		/*.destroy */ switch_ilbc_destroy
+static const switch_codec_implementation_t ilbc_102_8k_30ms_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 102,
+	/*.iananame */ "iLBC",
+	/*.fmtp */ "mode=30",
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ NO_OF_BYTES_30MS * 8 * 8000 / BLOCKL_30MS,
+	/*.microseconds_per_frame */ 30000,
+	/*.samples_per_frame */ 240,
+	/*.bytes_per_frame */ 480,
+	/*.encoded_bytes_per_frame */ NO_OF_BYTES_30MS,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_ilbc_init,
+	/*.encode */ switch_ilbc_encode,
+	/*.decode */ switch_ilbc_decode,
+	/*.destroy */ switch_ilbc_destroy
 };
 
-static const switch_codec_implementation_t ilbc_102_8k_20ms_implementation = { 
-		/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-		/*.ianacode */ 102, 
-		/*.iananame */ "iLBC102", 
-		/*.fmtp */ "mode=20",
-		/*.samples_per_second */ 8000, 
-		/*.bits_per_second */ NO_OF_BYTES_20MS*8*8000/BLOCKL_20MS, 
-		/*.microseconds_per_frame */ 20000,
-		/*.samples_per_frame */ 160,
-		/*.bytes_per_frame */ 320,
-		/*.encoded_bytes_per_frame */ NO_OF_BYTES_20MS, 
-		/*.number_of_channels */ 1,
-		/*.pref_frames_per_packet */ 1,
-		/*.max_frames_per_packet */ 1,
-		/*.init */ switch_ilbc_init,
-		/*.encode */ switch_ilbc_encode,
-		/*.decode */ switch_ilbc_decode,
-		/*.destroy */ switch_ilbc_destroy,
-		/*.next */ &ilbc_102_8k_30ms_implementation
+static const switch_codec_implementation_t ilbc_102_8k_20ms_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 102,
+	/*.iananame */ "iLBC102",
+	/*.fmtp */ "mode=20",
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ NO_OF_BYTES_20MS * 8 * 8000 / BLOCKL_20MS,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ NO_OF_BYTES_20MS,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_ilbc_init,
+	/*.encode */ switch_ilbc_encode,
+	/*.decode */ switch_ilbc_decode,
+	/*.destroy */ switch_ilbc_destroy,
+	/*.next */ &ilbc_102_8k_30ms_implementation
 };
 
 
-static const switch_codec_implementation_t ilbc_8k_20ms_nonext_implementation = { 
-		/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-		/*.ianacode */ 97, 
-		/*.iananame */ "iLBC20ms",
-		/*.fmtp */ "mode=20",
-		/*.samples_per_second */ 8000, 
-		/*.bits_per_second */ NO_OF_BYTES_20MS*8*8000/BLOCKL_20MS, 
-		/*.microseconds_per_frame */ 20000,
-		/*.samples_per_frame */ 160,
-		/*.bytes_per_frame */ 320,
-		/*.encoded_bytes_per_frame */ NO_OF_BYTES_20MS, 
-		/*.number_of_channels */ 1,
-		/*.pref_frames_per_packet */ 1,
-		/*.max_frames_per_packet */ 1,
-		/*.init */ switch_ilbc_init,
-		/*.encode */ switch_ilbc_encode,
-		/*.decode */ switch_ilbc_decode,
-		/*.destroy */ switch_ilbc_destroy
+static const switch_codec_implementation_t ilbc_8k_20ms_nonext_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 97,
+	/*.iananame */ "iLBC20ms",
+	/*.fmtp */ "mode=20",
+	/*.samples_per_second */ 8000,
+	/*.bits_per_second */ NO_OF_BYTES_20MS * 8 * 8000 / BLOCKL_20MS,
+	/*.microseconds_per_frame */ 20000,
+	/*.samples_per_frame */ 160,
+	/*.bytes_per_frame */ 320,
+	/*.encoded_bytes_per_frame */ NO_OF_BYTES_20MS,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_ilbc_init,
+	/*.encode */ switch_ilbc_encode,
+	/*.decode */ switch_ilbc_decode,
+	/*.destroy */ switch_ilbc_destroy
 };
 
 
-static const switch_codec_interface_t ilbc_20ms_codec_interface = { 
-		/*.interface_name */ "ilbc", 
-		/*.implementations */ &ilbc_8k_20ms_nonext_implementation
+static const switch_codec_interface_t ilbc_20ms_codec_interface = {
+	/*.interface_name */ "ilbc",
+	/*.implementations */ &ilbc_8k_20ms_nonext_implementation
 };
 
-static const switch_codec_interface_t ilbc_102_codec_interface = { 
-		/*.interface_name */ "ilbc", 
-		/*.implementations */ &ilbc_102_8k_20ms_implementation, 
-		/*.next*/ &ilbc_20ms_codec_interface
+static const switch_codec_interface_t ilbc_102_codec_interface = {
+	/*.interface_name */ "ilbc",
+	/*.implementations */ &ilbc_102_8k_20ms_implementation,
+	/*.next */ &ilbc_20ms_codec_interface
 };
 
-static const switch_codec_interface_t ilbc_codec_interface = { 
-		/*.interface_name */ "ilbc", 
-		/*.implementations */ &ilbc_8k_20ms_implementation, 
-		/*.next*/ &ilbc_102_codec_interface
+static const switch_codec_interface_t ilbc_codec_interface = {
+	/*.interface_name */ "ilbc",
+	/*.implementations */ &ilbc_8k_20ms_implementation,
+	/*.next */ &ilbc_102_codec_interface
 };
 
 
-static switch_loadable_module_interface_t ilbc_module_interface = { 
-		/*.module_name */ modname, 
-		/*.endpoint_interface */ NULL, 
-		/*.timer_interface */ NULL, 
-		/*.dialplan_interface */ NULL, 
-		/*.codec_interface */ &ilbc_codec_interface, 
-		/*.application_interface */ NULL 
+static switch_loadable_module_interface_t ilbc_module_interface = {
+	/*.module_name */ modname,
+	/*.endpoint_interface */ NULL,
+	/*.timer_interface */ NULL,
+	/*.dialplan_interface */ NULL,
+	/*.codec_interface */ &ilbc_codec_interface,
+	/*.application_interface */ NULL
 };
 
 
 
-SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface,
-														char *filename)
+SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
-	
-		/* connect my internal structure to the blank pointer passed to me */ 
-		*module_interface = &ilbc_module_interface;
-	
 
-		/* indicate that the module should continue to be loaded */ 
-		return SWITCH_STATUS_SUCCESS;
+	/* connect my internal structure to the blank pointer passed to me */
+	*module_interface = &ilbc_module_interface;
+
+
+	/* indicate that the module should continue to be loaded */
+	return SWITCH_STATUS_SUCCESS;
 
 }
 

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_l16/mod_l16.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_l16/mod_l16.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_l16/mod_l16.c	Tue Apr 24 10:14:28 2007
@@ -34,8 +34,7 @@
 static const char modname[] = "mod_l16";
 
 
-static switch_status_t switch_raw_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									 const switch_codec_settings_t *codec_settings)
+static switch_status_t switch_raw_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 	int encoding, decoding;
 
@@ -50,12 +49,11 @@
 }
 
 static switch_status_t switch_raw_encode(switch_codec_t *codec,
-									   switch_codec_t *other_codec,
-									   void *decoded_data,
-									   uint32_t decoded_data_len,
-									   uint32_t decoded_rate,
-									   void *encoded_data,
-									   uint32_t *encoded_data_len, uint32_t *encoded_rate, unsigned int *flag)
+										 switch_codec_t *other_codec,
+										 void *decoded_data,
+										 uint32_t decoded_data_len,
+										 uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										 unsigned int *flag)
 {
 	/* NOOP indicates that the audio in is already the same as the audio out, so no conversion was necessary. */
 	if (codec && other_codec && codec->implementation->samples_per_second != other_codec->implementation->samples_per_second) {
@@ -67,12 +65,11 @@
 }
 
 static switch_status_t switch_raw_decode(switch_codec_t *codec,
-									   switch_codec_t *other_codec,
-									   void *encoded_data,
-									   uint32_t encoded_data_len,
-									   uint32_t encoded_rate,
-									   void *decoded_data,
-									   uint32_t *decoded_data_len, uint32_t *decoded_rate, unsigned int *flag)
+										 switch_codec_t *other_codec,
+										 void *encoded_data,
+										 uint32_t encoded_data_len,
+										 uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										 unsigned int *flag)
 {
 	if (codec && other_codec && codec->implementation->samples_per_second != other_codec->implementation->samples_per_second) {
 		memcpy(decoded_data, encoded_data, encoded_data_len);
@@ -107,7 +104,7 @@
 	/*.encode = */ switch_raw_encode,
 	/*.decode = */ switch_raw_decode,
 	/*.destroy = */ switch_raw_destroy
-	/*.next = */ 
+		/*.next = */
 };
 
 static const switch_codec_implementation_t raw_32k_30ms_implementation = {
@@ -298,6 +295,7 @@
 	/*.destroy = */ switch_raw_destroy,
 	/*.next = */ &raw_16k_20ms_implementation
 };
+
 ///////////////////////////////
 
 

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_lpc10/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_lpc10/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_lpc10/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,16 +1,9 @@
-LDFLAGS +=-llpc10
+BASE=../../../..
+LPC10_DIR=$(BASE)/libs/codec/lpc10
+LPC10LA=$(LPC10_DIR)/liblpc10.la
+LOCAL_CFLAGS=-I$(LPC10_DIR)/src
+LOCAL_LIBADD=$(LPC10LA)
+include $(BASE)/build/modmake.rules
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install codec/lpc10 --prefix=$(PREFIX)
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c ../../../include/switch_bitpack.h
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(LPC10LA): $(LPC10_DIR) $(LPC10_DIR)/.update
+	cd $(LPC10_DIR) && $(MAKE)

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_lpc10/mod_lpc10.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_lpc10/mod_lpc10.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_lpc10/mod_lpc10.c	Tue Apr 24 10:14:28 2007
@@ -28,16 +28,16 @@
  *
  * mod_lpc10.c -- LPC10 Codec Module
  *
- */  
+ */
 
 #include "switch.h"
-#include "lpc10/lpc10.h"
+#include "lpc10.h"
 
 enum {
 	SamplesPerFrame = 180,
-	BitsPerFrame    = 54,
-	BytesPerFrame   = (BitsPerFrame+7)/8,
-	BitsPerSecond   = 2400
+	BitsPerFrame = 54,
+	BytesPerFrame = (BitsPerFrame + 7) / 8,
+	BitsPerSecond = 2400
 };
 
 #define   SampleValueScale 32768.0
@@ -51,8 +51,7 @@
 	struct lpc10_decoder_state decoder_object;
 };
 
-static switch_status_t switch_lpc10_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									  const switch_codec_settings_t *codec_settings) 
+static switch_status_t switch_lpc10_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 	uint32_t encoding, decoding;
 	struct lpc10_context *context = NULL;
@@ -78,44 +77,39 @@
 	}
 }
 
-static switch_status_t switch_lpc10_destroy(switch_codec_t *codec) 
+static switch_status_t switch_lpc10_destroy(switch_codec_t *codec)
 {
 	codec->private_info = NULL;
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t switch_lpc10_encode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *decoded_data,
-
-										uint32_t decoded_data_len, 
-										uint32_t decoded_rate, 
-										void *encoded_data,
-
-										uint32_t *encoded_data_len, 
-										uint32_t *encoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_lpc10_encode(switch_codec_t *codec,
+										   switch_codec_t *other_codec,
+										   void *decoded_data,
+										   uint32_t decoded_data_len,
+										   uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										   unsigned int *flag)
 {
 	struct lpc10_context *context = codec->private_info;
 	uint8_t i;
 	int32_t bits[BitsPerFrame];
 	real speech[SamplesPerFrame];
-	const short *sampleBuffer = (const short *)decoded_data;
-	unsigned char *buffer = (unsigned char *)encoded_data;
+	const short *sampleBuffer = (const short *) decoded_data;
+	unsigned char *buffer = (unsigned char *) encoded_data;
 
 	if (!context) {
 		return SWITCH_STATUS_FALSE;
 	}
 
 	for (i = 0; i < SamplesPerFrame; i++)
-		speech[i] = (real)(sampleBuffer[i]/SampleValueScale);
+		speech[i] = (real) (sampleBuffer[i] / SampleValueScale);
 
 	lpc10_encode(speech, bits, &context->encoder_object);
 
 	memset(encoded_data, 0, BytesPerFrame);
 	for (i = 0; i < BitsPerFrame; i++) {
 		if (bits[i])
-			buffer[i>>3] |= 1 << (i&7);
+			buffer[i >> 3] |= 1 << (i & 7);
 	}
 
 	*encoded_data_len = BytesPerFrame;
@@ -123,91 +117,85 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t switch_lpc10_decode(switch_codec_t *codec, 
-										switch_codec_t *other_codec, 
-										void *encoded_data,
-
-										uint32_t encoded_data_len, 
-										uint32_t encoded_rate, 
-										void *decoded_data,
-
-										uint32_t *decoded_data_len, 
-										uint32_t *decoded_rate, 
-										unsigned int *flag) 
+static switch_status_t switch_lpc10_decode(switch_codec_t *codec,
+										   switch_codec_t *other_codec,
+										   void *encoded_data,
+										   uint32_t encoded_data_len,
+										   uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										   unsigned int *flag)
 {
 	struct lpc10_context *context = codec->private_info;
 	int i;
 	INT32 bits[BitsPerFrame];
 	real speech[SamplesPerFrame];
-	short *sampleBuffer = (short *)decoded_data;
-	const unsigned char *buffer = (const unsigned char *)encoded_data;
+	short *sampleBuffer = (short *) decoded_data;
+	const unsigned char *buffer = (const unsigned char *) encoded_data;
 
 	if (!context) {
 		return SWITCH_STATUS_FALSE;
 	}
 
 	for (i = 0; i < BitsPerFrame; i++)
-		bits[i] = (buffer[i>>3]&(1<<(i&7))) != 0;
+		bits[i] = (buffer[i >> 3] & (1 << (i & 7))) != 0;
 
 	lpc10_decode(bits, speech, &context->decoder_object);
 
 	for (i = 0; i < SamplesPerFrame; i++) {
-		real sample = (real)(speech[i]*SampleValueScale);
+		real sample = (real) (speech[i] * SampleValueScale);
 		if (sample < MinSampleValue)
 			sample = MinSampleValue;
 		else if (sample > MaxSampleValue)
 			sample = MaxSampleValue;
-		sampleBuffer[i] = (short)sample;
+		sampleBuffer[i] = (short) sample;
 	}
 
-	*decoded_data_len = SamplesPerFrame*2;
+	*decoded_data_len = SamplesPerFrame * 2;
 
 	return SWITCH_STATUS_SUCCESS;
 }
 
-/* Registration */ 
+/* Registration */
 
-static const switch_codec_implementation_t lpc10_implementation = { 
-	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO, 
-	/*.ianacode */ 7, 
-	/*.iananame */ "LPC", 
+static const switch_codec_implementation_t lpc10_implementation = {
+	/*.codec_type */ SWITCH_CODEC_TYPE_AUDIO,
+	/*.ianacode */ 7,
+	/*.iananame */ "LPC",
 	/*.fmtp */ NULL,
 	/*.samples_per_second */ 8000,
-	/*.bits_per_second */ 240, 
-	/*.microseconds_per_frame */ 22500, 
-	/*.samples_per_frame */ 180, 
-	/*.bytes_per_frame */ 360, 
-	/*.encoded_bytes_per_frame */ 7, 
-	/*.number_of_channels */ 1, 
-	/*.pref_frames_per_packet */ 1, 
-	/*.max_frames_per_packet */ 1, 
-	/*.init */ switch_lpc10_init, 
-	/*.encode */ switch_lpc10_encode, 
-	/*.decode */ switch_lpc10_decode, 
-	/*.destroy */ switch_lpc10_destroy, 
+	/*.bits_per_second */ 240,
+	/*.microseconds_per_frame */ 22500,
+	/*.samples_per_frame */ 180,
+	/*.bytes_per_frame */ 360,
+	/*.encoded_bytes_per_frame */ 7,
+	/*.number_of_channels */ 1,
+	/*.pref_frames_per_packet */ 1,
+	/*.max_frames_per_packet */ 1,
+	/*.init */ switch_lpc10_init,
+	/*.encode */ switch_lpc10_encode,
+	/*.decode */ switch_lpc10_decode,
+	/*.destroy */ switch_lpc10_destroy,
 };
 
-const switch_codec_interface_t lpc10_codec_interface = { 
-	/*.interface_name */ "LPC-10 2.4kbps", 
-	/*.implementations */ &lpc10_implementation, 
+const switch_codec_interface_t lpc10_codec_interface = {
+	/*.interface_name */ "LPC-10 2.4kbps",
+	/*.implementations */ &lpc10_implementation,
 };
 
-static switch_loadable_module_interface_t lpc10_module_interface = { 
-	/*.module_name */ modname, 
-	/*.endpoint_interface */ NULL, 
-	/*.timer_interface */ NULL, 
-	/*.dialplan_interface */ NULL, 
-	/*.codec_interface */ &lpc10_codec_interface, 
-	/*.application_interface */ NULL 
+static switch_loadable_module_interface_t lpc10_module_interface = {
+	/*.module_name */ modname,
+	/*.endpoint_interface */ NULL,
+	/*.timer_interface */ NULL,
+	/*.dialplan_interface */ NULL,
+	/*.codec_interface */ &lpc10_codec_interface,
+	/*.application_interface */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface,
-													 char *filename)
+SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
-	/* connect my internal structure to the blank pointer passed to me */ 
+	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &lpc10_module_interface;
 
-	/* indicate that the module should continue to be loaded */ 
+	/* indicate that the module should continue to be loaded */
 	return SWITCH_STATUS_SUCCESS;
 }
 

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_speex/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_speex/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_speex/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,14 +1,12 @@
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+BASE=../../../..
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install speex --prefix=$(PREFIX) --disable-shared --with-pic
+SPEEX_DIR=$(BASE)/libs/speex
+SPEEXLA=$(SPEEX_DIR)/libspeex/libspeex.la
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS) -lspeex
+LOCAL_CFLAGS=-I$(SPEEX_DIR)/include
+LOCAL_LIBADD=$(SPEEXLA)
+include $(BASE)/build/modmake.rules
 
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(SPEEXLA): $(SPEEX_DIR) $(SPEEX_DIR)/.update
+	cd $(SPEEX_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/codecs/mod_speex/mod_speex.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/codecs/mod_speex/mod_speex.c	(original)
+++ freeswitch/branches/cparker/src/mod/codecs/mod_speex/mod_speex.c	Tue Apr 24 10:14:28 2007
@@ -72,8 +72,7 @@
 	int decoder_mode;
 };
 
-static switch_status_t switch_speex_init(switch_codec_t *codec, switch_codec_flag_t flags,
-									   const switch_codec_settings_t *codec_settings)
+static switch_status_t switch_speex_init(switch_codec_t *codec, switch_codec_flag_t flags, const switch_codec_settings_t *codec_settings)
 {
 	struct speex_context *context = NULL;
 	int encoding, decoding;
@@ -111,17 +110,14 @@
 			speex_encoder_ctl(context->encoder_state, SPEEX_GET_FRAME_SIZE, &context->encoder_frame_size);
 			speex_encoder_ctl(context->encoder_state, SPEEX_SET_COMPLEXITY, &codec->codec_settings.complexity);
 			if (codec->codec_settings.preproc) {
-				context->pp =
-					speex_preprocess_state_init(context->encoder_frame_size, codec->implementation->samples_per_second);
+				context->pp = speex_preprocess_state_init(context->encoder_frame_size, codec->implementation->samples_per_second);
 				speex_preprocess_ctl(context->pp, SPEEX_PREPROCESS_SET_VAD, &codec->codec_settings.pp_vad);
 				speex_preprocess_ctl(context->pp, SPEEX_PREPROCESS_SET_AGC, &codec->codec_settings.pp_agc);
 				speex_preprocess_ctl(context->pp, SPEEX_PREPROCESS_SET_AGC_LEVEL, &codec->codec_settings.pp_agc_level);
 				speex_preprocess_ctl(context->pp, SPEEX_PREPROCESS_SET_DENOISE, &codec->codec_settings.pp_denoise);
 				speex_preprocess_ctl(context->pp, SPEEX_PREPROCESS_SET_DEREVERB, &codec->codec_settings.pp_dereverb);
-				speex_preprocess_ctl(context->pp, SPEEX_PREPROCESS_SET_DEREVERB_DECAY,
-									 &codec->codec_settings.pp_dereverb_decay);
-				speex_preprocess_ctl(context->pp, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL,
-									 &codec->codec_settings.pp_dereverb_level);
+				speex_preprocess_ctl(context->pp, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &codec->codec_settings.pp_dereverb_decay);
+				speex_preprocess_ctl(context->pp, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &codec->codec_settings.pp_dereverb_level);
 			}
 
 			if (!codec->codec_settings.abr && !codec->codec_settings.vbr) {
@@ -158,12 +154,11 @@
 }
 
 static switch_status_t switch_speex_encode(switch_codec_t *codec,
-										 switch_codec_t *other_codec,
-										 void *decoded_data,
-										 uint32_t decoded_data_len,
-										 uint32_t decoded_rate,
-										 void *encoded_data,
-										 uint32_t *encoded_data_len, uint32_t *encoded_rate, unsigned int *flag)
+										   switch_codec_t *other_codec,
+										   void *decoded_data,
+										   uint32_t decoded_data_len,
+										   uint32_t decoded_rate, void *encoded_data, uint32_t * encoded_data_len, uint32_t * encoded_rate,
+										   unsigned int *flag)
 {
 	struct speex_context *context = codec->private_info;
 	short *buf;
@@ -211,12 +206,11 @@
 }
 
 static switch_status_t switch_speex_decode(switch_codec_t *codec,
-										 switch_codec_t *other_codec,
-										 void *encoded_data,
-										 uint32_t encoded_data_len,
-										 uint32_t encoded_rate,
-										 void *decoded_data,
-										 uint32_t *decoded_data_len, uint32_t *decoded_rate, unsigned int *flag)
+										   switch_codec_t *other_codec,
+										   void *encoded_data,
+										   uint32_t encoded_data_len,
+										   uint32_t encoded_rate, void *decoded_data, uint32_t * decoded_data_len, uint32_t * decoded_rate,
+										   unsigned int *flag)
 {
 	struct speex_context *context = codec->private_info;
 	short *buf;

Modified: freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_directory/mod_dialplan_directory.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_directory/mod_dialplan_directory.c	(original)
+++ freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_directory/mod_dialplan_directory.c	Tue Apr 24 10:14:28 2007
@@ -46,12 +46,12 @@
 } globals;
 
 SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_directory_name, globals.directory_name)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_host, globals.host)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_dn, globals.dn)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_pass, globals.pass)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_base, globals.base)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_host, globals.host)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_dn, globals.dn)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_pass, globals.pass)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_base, globals.base)
 
-static void load_config(void)
+	 static void load_config(void)
 {
 	char *cf = "dialplan_directory.conf";
 	switch_xml_t cfg, xml, settings, param;
@@ -83,9 +83,8 @@
 	switch_xml_free(xml);
 }
 
-static switch_caller_extension_t *directory_dialplan_hunt(switch_core_session_t *session, void *arg)
+static switch_caller_extension_t *directory_dialplan_hunt(switch_core_session_t *session, void *arg, switch_caller_profile_t *caller_profile)
 {
-	switch_caller_profile_t *caller_profile;
 	switch_caller_extension_t *extension = NULL;
 	switch_channel_t *channel;
 	char *var, *val;
@@ -97,22 +96,19 @@
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
 
-	caller_profile = switch_channel_get_caller_profile(channel);
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Hello %s You Dialed %s!\n", caller_profile->caller_id_name,
-						  caller_profile->destination_number);
-	
+	if (!caller_profile) {
+		caller_profile = switch_channel_get_caller_profile(channel);
+	}
 	
-	if (! (globals.directory_name && globals.host && globals.dn && globals.base && globals.pass)) {
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Hello %s You Dialed %s!\n", caller_profile->caller_id_name,
+					  caller_profile->destination_number);
+
+
+	if (!(globals.directory_name && globals.host && globals.dn && globals.base && globals.pass)) {
 		return NULL;
 	}
 
-	if (switch_core_directory_open(&dh, 
-								   globals.directory_name,
-								   globals.host,
-								   globals.dn,
-								   globals.pass,
-								   NULL) != SWITCH_STATUS_SUCCESS) {
+	if (switch_core_directory_open(&dh, globals.directory_name, globals.host, globals.dn, globals.pass, NULL) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't connect\n");
 		return NULL;
 	}
@@ -127,10 +123,9 @@
 	while (switch_core_directory_next(&dh) == SWITCH_STATUS_SUCCESS) {
 		while (switch_core_directory_next_pair(&dh, &var, &val) == SWITCH_STATUS_SUCCESS) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "DIRECTORY VALUE [%s]=[%s]\n", var, val);
-			if(!strcasecmp(var, "callflow")) {
+			if (!strcasecmp(var, "callflow")) {
 				if (!extension) {
-					if ((extension = switch_caller_extension_new(session, caller_profile->destination_number,
-																  caller_profile->destination_number)) == 0) {
+					if ((extension = switch_caller_extension_new(session, caller_profile->destination_number, caller_profile->destination_number)) == 0) {
 						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "memory error!\n");
 						goto out;
 					}
@@ -143,11 +138,11 @@
 			}
 		}
 	}
- out:
-	
+  out:
+
 	switch_core_directory_close(&dh);
 
-	
+
 	if (extension) {
 		switch_channel_set_state(channel, CS_EXECUTE);
 	}
@@ -159,7 +154,7 @@
 static const switch_dialplan_interface_t directory_dialplan_interface = {
 	/*.interface_name = */ "directory",
 	/*.hunt_function = */ directory_dialplan_hunt
-	/*.next = NULL */
+		/*.next = NULL */
 };
 
 static const switch_loadable_module_interface_t directory_dialplan_module_interface = {

Modified: freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_xml/mod_dialplan_xml.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_xml/mod_dialplan_xml.c	(original)
+++ freeswitch/branches/cparker/src/mod/dialplans/mod_dialplan_xml/mod_dialplan_xml.c	Tue Apr 24 10:14:28 2007
@@ -34,11 +34,8 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 
-
 static const char modname[] = "mod_dialplan_xml";
 
-
-
 typedef enum {
 	BREAK_ON_TRUE,
 	BREAK_ON_FALSE,
@@ -46,27 +43,25 @@
 	BREAK_NEVER
 } break_t;
 
-static int parse_exten(switch_core_session_t *session, switch_xml_t xexten, switch_caller_extension_t **extension)
+static int parse_exten(switch_core_session_t *session, switch_caller_profile_t *caller_profile, switch_xml_t xexten, switch_caller_extension_t **extension)
 {
 	switch_xml_t xcond, xaction;
-	switch_caller_profile_t *caller_profile;
 	switch_channel_t *channel;
 	char *exten_name = (char *) switch_xml_attr_soft(xexten, "name");
 	int proceed = 0;
-    switch_stream_handle_t stream = {0};
+	switch_stream_handle_t stream = { 0 };
 
 	channel = switch_core_session_get_channel(session);
-	caller_profile = switch_channel_get_caller_profile(channel);
 
 	for (xcond = switch_xml_child(xexten, "condition"); xcond; xcond = xcond->next) {
 		char *field = NULL;
 		char *do_break_a = NULL;
 		char *expression = NULL;
 		char *field_data = NULL;
-		pcre *re = NULL;
+		switch_regex_t *re = NULL;
 		int ovector[30];
 		break_t do_break_i = BREAK_ON_FALSE;
-		
+
 		field = (char *) switch_xml_attr(xcond, "field");
 
 		expression = (char *) switch_xml_attr_soft(xcond, "expression");
@@ -86,54 +81,53 @@
 		if (field) {
 			if (*field == '$') {
 				char *cmd = switch_core_session_strdup(session, field + 1);
-				char *e, *arg;                
-                field = cmd;
-                field_data = "";
-
-                if (*field == '{') {
-                    field++;
-                    if ((e = strchr(field, '}'))) {
-                        *e = '\0';
-                        field_data = switch_channel_get_variable(channel, field);
-                    }
-                } else {
-                    switch_safe_free(stream.data);
-                    memset(&stream, 0, sizeof(stream));
-                    SWITCH_STANDARD_STREAM(stream);
-
-                    if ((arg = strchr(cmd, '('))) {
-                        *arg++ = '\0';
-                        if ((e = strchr(arg, ')'))) {
-                            *e = '\0';
-                            if (switch_api_execute(cmd, arg, session, &stream) == SWITCH_STATUS_SUCCESS) {
-                                field_data = stream.data;
-                            }
-                        }
-                    }
-                }
-            } else {
+				char *e, *arg;
+				field = cmd;
+				field_data = "";
+
+				if (*field == '{') {
+					field++;
+					if ((e = strchr(field, '}'))) {
+						*e = '\0';
+						field_data = switch_channel_get_variable(channel, field);
+					}
+				} else {
+					switch_safe_free(stream.data);
+					memset(&stream, 0, sizeof(stream));
+					SWITCH_STANDARD_STREAM(stream);
+
+					if ((arg = strchr(cmd, '('))) {
+						*arg++ = '\0';
+						if ((e = strchr(arg, ')'))) {
+							*e = '\0';
+							if (switch_api_execute(cmd, arg, session, &stream) == SWITCH_STATUS_SUCCESS) {
+								field_data = stream.data;
+							}
+						}
+					}
+				}
+			} else {
 				field_data = switch_caller_get_field_by_name(caller_profile, field);
 			}
 			if (!field_data) {
 				field_data = "";
 			}
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "test conditions %s(%s) =~ /%s/\n", field, field_data, expression);
-			if (!(proceed = switch_perform_regex(field_data, expression, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
+			if (!(proceed = switch_regex_perform(field_data, expression, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Regex mismatch\n");
 
 				for (xaction = switch_xml_child(xcond, "anti-action"); xaction; xaction = xaction->next) {
-					char *application = (char*) switch_xml_attr_soft(xaction, "application");
+					char *application = (char *) switch_xml_attr_soft(xaction, "application");
 					char *data = (char *) switch_xml_attr_soft(xaction, "data");
 
 					if (!*extension) {
-						if ((*extension =
-							 switch_caller_extension_new(session, exten_name, caller_profile->destination_number)) == 0) {
+						if ((*extension = switch_caller_extension_new(session, exten_name, caller_profile->destination_number)) == 0) {
 							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "memory error!\n");
-                            proceed = 0;
-                            goto done;
+							proceed = 0;
+							goto done;
 						}
 					}
-					
+
 					switch_caller_extension_add_application(session, *extension, application, data);
 				}
 
@@ -148,20 +142,20 @@
 
 
 		for (xaction = switch_xml_child(xcond, "action"); xaction; xaction = xaction->next) {
-			char *application = (char*) switch_xml_attr_soft(xaction, "application");
+			char *application = (char *) switch_xml_attr_soft(xaction, "application");
 			char *data = (char *) switch_xml_attr_soft(xaction, "data");
 			char *substituted = NULL;
-            uint32_t len = 0;
+			uint32_t len = 0;
 			char *app_data = NULL;
 
 			if (field && strchr(expression, '(')) {
-                len = (uint32_t)(strlen(data) + strlen(field_data) + 10);
-                if (!(substituted = malloc(len))) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "memory error!\n");
-                    proceed = 0;
-                    goto done;
-                }
-                memset(substituted, 0, len);
+				len = (uint32_t) (strlen(data) + strlen(field_data) + 10);
+				if (!(substituted = malloc(len))) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "memory error!\n");
+					proceed = 0;
+					goto done;
+				}
+				memset(substituted, 0, len);
 				switch_perform_substitution(re, proceed, data, field_data, substituted, len, ovector);
 				app_data = substituted;
 			} else {
@@ -169,177 +163,196 @@
 			}
 
 			if (!*extension) {
-				if ((*extension =
-					 switch_caller_extension_new(session, exten_name, caller_profile->destination_number)) == 0) {
+				if ((*extension = switch_caller_extension_new(session, exten_name, caller_profile->destination_number)) == 0) {
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "memory error!\n");
-                    proceed = 0;
-                    goto done;
+					proceed = 0;
+					goto done;
 				}
 			}
 
 			switch_caller_extension_add_application(session, *extension, application, app_data);
-            switch_safe_free(substituted);
+			switch_safe_free(substituted);
 		}
-        
-		switch_clean_re(re);
+
+		switch_regex_safe_free(re);
 
 		if (do_break_i == BREAK_ON_TRUE || do_break_i == BREAK_ALWAYS) {
 			break;
 		}
 	}
 
- done:
-    switch_safe_free(stream.data);
+  done:
+	switch_safe_free(stream.data);
 	return proceed;
 }
 
-static switch_caller_extension_t *dialplan_hunt(switch_core_session_t *session, void *arg)
+static switch_status_t dialplan_xml_locate(switch_core_session_t *session, switch_caller_profile_t *caller_profile, switch_xml_t * root,
+										   switch_xml_t * node)
 {
-	switch_caller_profile_t *caller_profile;
-	switch_caller_extension_t *extension = NULL;
+	switch_status_t status = SWITCH_STATUS_GENERR;
 	switch_channel_t *channel;
-	switch_xml_t alt_root = NULL, cfg, xml, xcontext, xexten;
-	char *context = NULL;
-    switch_stream_handle_t stream = {0};
-    switch_size_t encode_len = 1024, new_len = 0;
-    char *encode_buf = NULL;
-    char *prof[12] = {0}, *prof_names[12] = {0}, *e = NULL;
-    switch_hash_index_t *hi;
-    uint32_t x = 0;
-    char *alt_path = (char *) arg;
+	switch_stream_handle_t stream = { 0 };
+	switch_size_t encode_len = 1024, new_len = 0;
+	char *encode_buf = NULL;
+	char *prof[12] = { 0 }, *prof_names[12] = {
+	0}, *e = NULL;
+	switch_hash_index_t *hi;
+	uint32_t x = 0;
 
 	channel = switch_core_session_get_channel(session);
-	if ((caller_profile = switch_channel_get_caller_profile(channel))) {
-		context = caller_profile->context ? caller_profile->context : "default";
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Obtaining Profile!\n");
-		return NULL;
+
+	SWITCH_STANDARD_STREAM(stream);
+
+	if (!(encode_buf = malloc(encode_len))) {
+		goto done;
 	}
 
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Processing %s->%s!\n", caller_profile->caller_id_name,
-					  caller_profile->destination_number);
+	prof[0] = caller_profile->context;
+	prof[1] = caller_profile->destination_number;
+	prof[2] = caller_profile->caller_id_name;
+	prof[3] = caller_profile->caller_id_number;
+	prof[4] = caller_profile->network_addr;
+	prof[5] = caller_profile->ani;
+	prof[6] = caller_profile->aniii;
+	prof[7] = caller_profile->rdnis;
+	prof[8] = caller_profile->source;
+	prof[9] = caller_profile->chan_name;
+	prof[10] = caller_profile->uuid;
+
+	prof_names[0] = "context";
+	prof_names[1] = "destination_number";
+	prof_names[2] = "caller_id_name";
+	prof_names[3] = "caller_id_number";
+	prof_names[4] = "network_addr";
+	prof_names[5] = "ani";
+	prof_names[6] = "aniii";
+	prof_names[7] = "rdnis";
+	prof_names[8] = "source";
+	prof_names[9] = "chan_name";
+	prof_names[10] = "uuid";
+
+	for (x = 0; prof[x]; x++) {
+		if (switch_strlen_zero(prof[x])) {
+			continue;
+		}
+		new_len = (strlen(prof[x]) * 3) + 1;
+		if (encode_len < new_len) {
+			char *tmp;
+
+			encode_len = new_len;
 
-    SWITCH_STANDARD_STREAM(stream);
-    
-    if (!(encode_buf = malloc(encode_len))) {
-        return NULL;
-    }
-    
-    prof[0] = caller_profile->context;
-    prof[1] = caller_profile->destination_number;
-    prof[2] = caller_profile->caller_id_name;
-    prof[3] = caller_profile->caller_id_number;
-    prof[4] = caller_profile->network_addr;
-    prof[5] = caller_profile->ani;
-    prof[6] = caller_profile->aniii;
-    prof[7] = caller_profile->rdnis;
-    prof[8] = caller_profile->source;
-    prof[9] = caller_profile->chan_name;
-    prof[10] = caller_profile->uuid;
-
-    prof_names[0] = "context";
-    prof_names[1] = "destination_number";
-    prof_names[2] = "caller_id_name";
-    prof_names[3] = "caller_id_number";
-    prof_names[4] = "network_addr";
-    prof_names[5] = "ani";
-    prof_names[6] = "aniii";
-    prof_names[7] = "rdnis";
-    prof_names[8] = "source";
-    prof_names[9] = "chan_name";
-    prof_names[10] = "uuid";
-
-    for (x = 0; prof[x]; x++) {
-        new_len = (strlen(prof[x]) * 3) + 1;
-        if (encode_len < new_len) {
-            char *tmp;
-            
-            encode_len = new_len;
-
-            if (!(tmp = realloc(encode_buf, encode_len))) {
-                switch_safe_free(encode_buf);
-                return NULL;
-            }
-
-            encode_buf = tmp;
-        }
-        switch_url_encode(prof[x], encode_buf, encode_len - 1);
-        stream.write_function(&stream, "%s=%s&", prof_names[x], encode_buf);
-    }
+			if (!(tmp = realloc(encode_buf, encode_len))) {
+				goto done;
+			}
+
+			encode_buf = tmp;
+		}
+		switch_url_encode(prof[x], encode_buf, encode_len - 1);
+		stream.write_function(&stream, "%s=%s&", prof_names[x], encode_buf);
+	}
 
 
 	for (hi = switch_channel_variable_first(channel, switch_core_session_get_pool(session)); hi; hi = switch_hash_next(hi)) {
-        void *val;
-        const void *var;
+		void *val;
+		const void *var;
 		switch_hash_this(hi, &var, NULL, &val);
-        
-        new_len = (strlen((char *) var) * 3) + 1;
-        if (encode_len < new_len) {
-            char *tmp;
-            
-            encode_len = new_len;
-
-            if (!(tmp = realloc(encode_buf, encode_len))) {
-                switch_safe_free(encode_buf);
-                return NULL;
-            }
-
-            encode_buf = tmp;
-        }
-
-        switch_url_encode((char *) val, encode_buf, encode_len - 1);
-        stream.write_function(&stream, "%s=%s&", (char *) var, encode_buf);
-        
-	}
-    
-    e = (char *)stream.data + (strlen((char *)stream.data) - 1);
-
-    if (e && *e == '&') {
-        *e = '\0';
-    }
-
-    if (!switch_strlen_zero(alt_path)) {
-        switch_xml_t conf = NULL, tag = NULL;
-        if (!(alt_root = switch_xml_parse_file(alt_path))) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of [%s] failed\n", alt_path);
-            return NULL;
-        }
-        
-		if ((conf = switch_xml_find_child(alt_root, "section", "name", "dialplan")) && 
-			(tag = switch_xml_find_child(conf, "dialplan", NULL, NULL))) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Getting dialplan from alternate path: %s\n", alt_path);
-            xml = alt_root;
-            cfg = tag;
-        } else {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of dialplan failed\n");
-            return NULL;
-        }
-    } else if (switch_xml_locate("dialplan", NULL, NULL, NULL, &xml, &cfg, stream.data) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of dialplan failed\n");
-        return NULL;
-    }
-    
+
+		new_len = (strlen((char *) var) * 3) + 1;
+		if (encode_len < new_len) {
+			char *tmp;
+
+			encode_len = new_len;
+
+			if (!(tmp = realloc(encode_buf, encode_len))) {
+				goto done;
+			}
+
+			encode_buf = tmp;
+		}
+
+		switch_url_encode((char *) val, encode_buf, encode_len - 1);
+		stream.write_function(&stream, "%s=%s&", (char *) var, encode_buf);
+
+	}
+
+	e = (char *) stream.data + (strlen((char *) stream.data) - 1);
+
+	if (e && *e == '&') {
+		*e = '\0';
+	}
+
+	status = switch_xml_locate("dialplan", NULL, NULL, NULL, root, node, stream.data);
+
+  done:
+	switch_safe_free(stream.data);
+	switch_safe_free(encode_buf);
+	return status;
+}
+
+static switch_caller_extension_t *dialplan_hunt(switch_core_session_t *session, void *arg, switch_caller_profile_t *caller_profile)
+{
+	switch_caller_extension_t *extension = NULL;
+	switch_channel_t *channel;
+	switch_xml_t alt_root = NULL, cfg, xml = NULL, xcontext, xexten;
+	char *alt_path = (char *) arg;
 	
-    switch_safe_free(stream.data);
-    switch_safe_free(encode_buf);
-    
-	if (!(xcontext = switch_xml_find_child(cfg, "context", "name", context))) {
-		if (!(xcontext = switch_xml_find_child(cfg, "context", "name", "global"))) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "context %s not found\n", context);
-			switch_xml_free(xml);
-			return NULL;
+	channel = switch_core_session_get_channel(session);
+
+	if (!caller_profile) {
+		if (!(caller_profile = switch_channel_get_caller_profile(channel))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Obtaining Profile!\n");
+			goto done;
 		}
 	}
 	
+	if (!caller_profile->context) {
+		caller_profile->context = "default";
+	}
+	
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Processing %s->%s!\n", caller_profile->caller_id_name, caller_profile->destination_number);
+
+	/* get our handle to the "dialplan" section of the config */
+
+	if (!switch_strlen_zero(alt_path)) {
+		switch_xml_t conf = NULL, tag = NULL;
+		if (!(alt_root = switch_xml_parse_file_simple(alt_path))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of [%s] failed\n", alt_path);
+			goto done;
+		}
+
+		if ((conf = switch_xml_find_child(alt_root, "section", "name", "dialplan")) && (tag = switch_xml_find_child(conf, "dialplan", NULL, NULL))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Getting dialplan from alternate path: %s\n", alt_path);
+			xml = alt_root;
+			cfg = tag;
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of dialplan failed\n");
+			goto done;
+		}
+	} else {
+		if (dialplan_xml_locate(session, caller_profile, &xml, &cfg) != SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of dialplan failed\n");
+			goto done;
+		}
+	}
+
+	/* get a handle to the context tag */
+	if (!(xcontext = switch_xml_find_child(cfg, "context", "name", caller_profile->context))) {
+		if (!(xcontext = switch_xml_find_child(cfg, "context", "name", "global"))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "context %s not found\n", caller_profile->context);
+			goto done;
+		}
+	}
+
 	if (!(xexten = switch_xml_find_child(xcontext, "extension", "name", caller_profile->destination_number))) {
 		xexten = switch_xml_child(xcontext, "extension");
 	}
-	
-	while(xexten) {
+
+	while (xexten) {
 		int proceed = 0;
 		char *cont = (char *) switch_xml_attr_soft(xexten, "continue");
 
-		proceed = parse_exten(session, xexten, &extension);
+		proceed = parse_exten(session, caller_profile, xexten, &extension);
 
 		if (proceed && !switch_true(cont)) {
 			break;
@@ -350,11 +363,14 @@
 
 
 	switch_xml_free(xml);
+	xml = NULL;
 
 	if (extension) {
 		switch_channel_set_state(channel, CS_EXECUTE);
 	}
 
+  done:
+	switch_xml_free(xml);
 	return extension;
 }
 
@@ -362,7 +378,7 @@
 static const switch_dialplan_interface_t dialplan_interface = {
 	/*.interface_name = */ "XML",
 	/*.hunt_function = */ dialplan_hunt
-	/*.next = NULL */
+		/*.next = NULL */
 };
 
 static const switch_loadable_module_interface_t dialplan_module_interface = {

Modified: freeswitch/branches/cparker/src/mod/directories/mod_ldap/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/directories/mod_ldap/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/directories/mod_ldap/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,20 +1,23 @@
-CFLAGS += -DWITH_OPENLDAP -DLDAP_DEPRECATED
-LDFLAGS += -lldap_r -llber
+switch_srcdir=../../../..
 
-LINKER=$(CC)
+LDAP=openldap-2.3.19
+LDAP_DIR=$(switch_srcdir)/libs/$(LDAP)
 
+LDAPLA=$(LDAP_DIR)/libraries/libldap_r/libldap_r.la
+LIBLBERLA=$(LDAP_DIR)/libraries/liblber/liblber.la
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+LOCAL_CFLAGS=-DWITH_OPENLDAP -DLDAP_DEPRECATED -I$(LDAP_DIR)/include
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install openldap-2.3.19.tgz --prefix=$(PREFIX) --disable-bdb --disable-hdb
+DEFAULT_ARGS=--prefix=$(PREFIX) --disable-shared --with-pic
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(LINKER) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
+LOCAL_LIBADD=$(LDAPLA) $(LIBLBERLA)
 
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+include $(switch_srcdir)/build/modmake.rules
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(LDAP_DIR):
+	$(GETLIB) $(LDAP).tgz
+	cd $(LDAP_DIR) && ./configure $(DEFAULT_ARGS) --disable-bdb --disable-hdb
+
+$(LDAPLA) $(LIBLBERLA): $(LDAP_DIR)
+	cd $(LDAP_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/directories/mod_ldap/mod_ldap.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/directories/mod_ldap/mod_ldap.c	(original)
+++ freeswitch/branches/cparker/src/mod/directories/mod_ldap/mod_ldap.c	Tue Apr 24 10:14:28 2007
@@ -44,10 +44,10 @@
 
 struct ldap_context {
 	LDAP *ld;
-	LDAPMessage* msg;
-	LDAPMessage* entry;
-	BerElement* ber;
-	char* attr;
+	LDAPMessage *msg;
+	LDAPMessage *entry;
+	BerElement *ber;
+	char *attr;
 	char *var;
 	char *val;
 	char **vals;
@@ -60,14 +60,14 @@
 static switch_status_t mod_ldap_open(switch_directory_handle_t *dh, char *source, char *dsn, char *passwd)
 {
 	struct ldap_context *context;
-	int  auth_method = LDAP_AUTH_SIMPLE;
+	int auth_method = LDAP_AUTH_SIMPLE;
 	int desired_version = LDAP_VERSION3;
 
 	if ((context = switch_core_alloc(dh->memory_pool, sizeof(*context))) == 0) {
 		return SWITCH_STATUS_MEMERR;
 	}
-	
-	if ((context->ld = ldap_init(source, LDAP_PORT)) == NULL ) {
+
+	if ((context->ld = ldap_init(source, LDAP_PORT)) == NULL) {
 		return SWITCH_STATUS_FALSE;
 	}
 
@@ -76,11 +76,11 @@
 		return SWITCH_STATUS_FALSE;
 	}
 
-	if (ldap_bind_s(context->ld, dsn, passwd, auth_method) != LDAP_SUCCESS ) {
+	if (ldap_bind_s(context->ld, dsn, passwd, auth_method) != LDAP_SUCCESS) {
 		return SWITCH_STATUS_FALSE;
 	}
 
-	
+
 	dh->private_info = context;
 
 	return SWITCH_STATUS_SUCCESS;
@@ -112,7 +112,7 @@
 	if (ldap_count_entries(context->ld, context->msg) <= 0) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -161,7 +161,7 @@
 		*val = context->val;
 		return SWITCH_STATUS_SUCCESS;
 	} else {
-	itter:
+	  itter:
 		if (context->attr && context->vals) {
 			if ((*val = context->vals[context->vi++])) {
 				*var = context->attr;
@@ -177,7 +177,7 @@
 			ldap_memfree(context->val);
 			context->val = NULL;
 			if (context->ber) {
-				ber_free(context->ber,0);
+				ber_free(context->ber, 0);
 				context->ber = NULL;
 			}
 			context->attr = ldap_first_attribute(context->ld, context->entry, &context->ber);
@@ -192,18 +192,18 @@
 			goto itter;
 		}
 	}
-	
+
 	return SWITCH_STATUS_FALSE;
 }
 
 
 static const switch_directory_interface_t ldap_directory_interface = {
-    /*.interface_name */ "ldap",
-	/*.directory_open*/ mod_ldap_open,
-	/*.directory_close*/ mod_ldap_close,
-	/*.directory_query*/ mod_ldap_query,
-	/*.directory_next*/ mod_ldap_next,
-	/*.directory_next_pair*/ mod_ldap_next_pair
+	/*.interface_name */ "ldap",
+	/*.directory_open */ mod_ldap_open,
+	/*.directory_close */ mod_ldap_close,
+	/*.directory_query */ mod_ldap_query,
+	/*.directory_next */ mod_ldap_next,
+	/*.directory_next_pair */ mod_ldap_next_pair
 };
 
 

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_dingaling/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_dingaling/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_dingaling/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,19 +1,22 @@
-LDFLAGS += -ldingaling
+BASE=../../../..
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+LOCAL_CFLAGS     = `$(BASE)/libs/apr/apr-1-config --cflags --cppflags --includes`
+LOCAL_CFLAGS    += `$(BASE)/libs/apr-util/apu-1-config --includes`
+LOCAL_CFLAGS += `if test -f $(BASE)/.libs/libfreeswitch_la-switch_odbc.o ; then echo -DSWITCH_HAVE_ODBC; fi ;`
+#LOCAL_CFLAGS += -w
+
+IKS_DIR=$(BASE)/libs/iksemel
+IKS_LA=$(IKS_DIR)/src/libiksemel.la
+DING_DIR=$(BASE)/libs/libdingaling
+LOCAL_CFLAGS += -I$(DING_DIR)/src -I$(BASE)/libs/iksemel/include
+LOCAL_OBJS=$(DING_DIR)/src/libdingaling.o $(DING_DIR)/src/sha1.o $(IKS_LA)
+LOCAL_SOURCES=$(DING_DIR)/src/libdingaling.c $(DING_DIR)/src/sha1.c
+include $(BASE)/build/modmake.rules
+
+$(IKS_LA): $(IKS_DIR) $(IKS_DIR)/.update
+	@cd $(IKS_DIR) && $(MAKE)
+	@$(TOUCH_TARGET)
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install iksemel --prefix=$(PREFIX)
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install libdingaling --prefix=$(PREFIX)
 
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
 
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~ *.so
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_dingaling/mod_dingaling.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_dingaling/mod_dingaling.c	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_dingaling/mod_dingaling.c	Tue Apr 24 10:14:28 2007
@@ -31,6 +31,9 @@
  */
 #include <switch.h>
 #include <libdingaling.h>
+#ifdef SWITCH_HAVE_ODBC
+#include <switch_odbc.h>
+#endif
 
 #define DL_CAND_WAIT 10000000
 #define DL_CAND_INITIAL_WAIT 2000000
@@ -45,12 +48,12 @@
 static switch_memory_pool_t *module_pool = NULL;
 
 static char sub_sql[] =
-"CREATE TABLE subscriptions (\n"
-"   sub_from            VARCHAR(255),\n"
-"   sub_to          VARCHAR(255),\n"
-"   show          VARCHAR(255),\n"
-"   status          VARCHAR(255)\n"
-");\n";
+	"CREATE TABLE jabber_subscriptions (\n"
+	"   sub_from      VARCHAR(255),\n" 
+	"   sub_to        VARCHAR(255),\n" 
+	"   show_pres     VARCHAR(255),\n" 
+	"   status        VARCHAR(255)\n"
+	");\n";
 
 
 typedef enum {
@@ -65,16 +68,16 @@
 	TFLAG_CODEC_READY = (1 << 8),
 	TFLAG_TRANSPORT = (1 << 9),
 	TFLAG_ANSWER = (1 << 10),
-	TFLAG_VAD_IN = ( 1 << 11),
-	TFLAG_VAD_OUT = ( 1 << 12),
-	TFLAG_VAD = ( 1 << 13),
-	TFLAG_DO_CAND = ( 1 << 14),
+	TFLAG_VAD_IN = (1 << 11),
+	TFLAG_VAD_OUT = (1 << 12),
+	TFLAG_VAD = (1 << 13),
+	TFLAG_DO_CAND = (1 << 14),
 	TFLAG_DO_DESC = (1 << 15),
 	TFLAG_LANADDR = (1 << 16),
 	TFLAG_AUTO = (1 << 17),
 	TFLAG_DTMF = (1 << 18),
-	TFLAG_TIMER = ( 1 << 19),
-	TFLAG_TERM = ( 1 << 20),
+	TFLAG_TIMER = (1 << 19),
+	TFLAG_TERM = (1 << 20),
 	TFLAG_TRANSPORT_ACCEPT = (1 << 21),
 	TFLAG_READY = (1 << 22),
 } TFLAGS;
@@ -97,36 +100,51 @@
 	switch_hash_t *profile_hash;
 	int running;
 	int handles;
-    char guess_ip[80];
+	char guess_ip[80];
 } globals;
 
 struct mdl_profile {
-    char *name;
-    char *login;
-    char *password;
-    char *message;
+	char *name;
+	char *login;
+	char *password;
+	char *message;
+#ifdef AUTO_REPLY
 	char *auto_reply;
-    char *dialplan;
-    char *ip;
-    char *extip;
-    char *lanaddr;
+#endif
+	char *dialplan;
+	char *ip;
+	char *extip;
+	char *lanaddr;
 	char *server;
-    char *exten;
-    char *context;
+	char *exten;
+	char *context;
 	char *timer_name;
 	char *dbname;
+	char *avatar;
+#ifdef SWITCH_HAVE_ODBC
+	char *odbc_dsn;
+	char *odbc_user;
+	char *odbc_pass;
+	switch_odbc_handle_t *master_odbc;
+#else
+	void *filler1;
+	void *filler2;
+	void *filler3;
+	void *filler4;
+#endif
 	switch_mutex_t *mutex;
-    ldl_handle_t *handle;
-    uint32_t flags;
-    uint32_t user_flags;
+	ldl_handle_t *handle;
+	uint32_t flags;
+	uint32_t user_flags;
 };
+typedef struct mdl_profile mdl_profile_t;
 
 struct private_object {
 	unsigned int flags;
 	switch_codec_t read_codec;
 	switch_codec_t write_codec;
 	switch_frame_t read_frame;
-	struct mdl_profile *profile;
+	mdl_profile_t *profile;
 	switch_core_session_t *session;
 	switch_caller_profile_t *caller_profile;
 	unsigned short samprate;
@@ -147,7 +165,7 @@
 	unsigned int cand_id;
 	unsigned int desc_id;
 	unsigned int dc;
-	int32_t timestamp_send;
+	uint32_t timestamp_send;
 	int32_t timestamp_recv;
 	uint32_t last_read;
 	char *codec_name;
@@ -175,21 +193,23 @@
 
 static switch_status_t dl_login(char *arg, switch_core_session_t *session, switch_stream_handle_t *stream);
 static switch_status_t dl_logout(char *profile_name, switch_core_session_t *session, switch_stream_handle_t *stream);
+static switch_status_t dl_pres(char *profile_name, switch_core_session_t *session, switch_stream_handle_t *stream);
+static switch_status_t dl_debug(char *profile_name, switch_core_session_t *session, switch_stream_handle_t *stream);
 static switch_status_t channel_on_init(switch_core_session_t *session);
 static switch_status_t channel_on_hangup(switch_core_session_t *session);
 static switch_status_t channel_on_ring(switch_core_session_t *session);
 static switch_status_t channel_on_loopback(switch_core_session_t *session);
 static switch_status_t channel_on_transmit(switch_core_session_t *session);
-static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-													switch_core_session_t **new_session, switch_memory_pool_t *pool);
-static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-										  switch_io_flag_t flags, int stream_id);
-static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-										   switch_io_flag_t flags, int stream_id);
+static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session,
+													switch_caller_profile_t *outbound_profile,
+													switch_core_session_t **new_session, switch_memory_pool_t **pool);
+static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id);
+static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id);
 static switch_status_t channel_kill_channel(switch_core_session_t *session, int sig);
 
-static ldl_status handle_signalling(ldl_handle_t *handle, ldl_session_t *dlsession, ldl_signal_t dl_signal, char *to, char *from, char *subject, char *msg);
-static ldl_status handle_response(ldl_handle_t *handle, char *id);
+static ldl_status handle_signalling(ldl_handle_t * handle, ldl_session_t * dlsession, ldl_signal_t dl_signal,
+									char *to, char *from, char *subject, char *msg);
+static ldl_status handle_response(ldl_handle_t * handle, char *id);
 static switch_status_t load_config(void);
 static int sin_callback(void *pArg, int argc, char **argv, char **columnNames);
 
@@ -210,7 +230,7 @@
 	if (!in) {
 		return NULL;
 	}
-	
+
 	if (!strcasecmp(in, "busy")) {
 		r = "dnd";
 	}
@@ -228,13 +248,113 @@
 	} else if (ext && !strcasecmp(ext, "away")) {
 		r = "away";
 	}
-	
+
 	return r;
 }
 
+
+
+
+static void mdl_execute_sql(mdl_profile_t *profile, char *sql, switch_mutex_t *mutex)
+{
+	switch_core_db_t *db;
+
+	if (mutex) {
+		switch_mutex_lock(mutex);
+	}
+
+#ifdef SWITCH_HAVE_ODBC
+    if (profile->odbc_dsn) {
+		SQLHSTMT stmt;
+		if (switch_odbc_handle_exec(profile->master_odbc, sql, &stmt) != SWITCH_ODBC_SUCCESS) {
+			char *err_str;
+			err_str = switch_odbc_handle_get_error(profile->master_odbc, stmt);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(err_str));
+			switch_safe_free(err_str);
+		}
+		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+	} else {
+#endif
+		if (!(db = switch_core_db_open_file(profile->dbname))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
+			goto end;
+		}
+
+		switch_core_db_persistant_execute(db, sql, 25);
+		switch_core_db_close(db);
+
+#ifdef SWITCH_HAVE_ODBC
+    }
+#endif
+
+
+ end:
+	if (mutex) {
+		switch_mutex_unlock(mutex);
+	}
+}
+
+
+static switch_bool_t mdl_execute_sql_callback(mdl_profile_t *profile,
+											  switch_mutex_t *mutex,
+											  char *sql,
+											  switch_core_db_callback_func_t callback,
+											  void *pdata)
+{
+	switch_bool_t ret = SWITCH_FALSE;
+	switch_core_db_t *db;
+	char *errmsg = NULL;
+	
+	if (mutex) {
+        switch_mutex_lock(mutex);
+    }
+
+
+#ifdef SWITCH_HAVE_ODBC
+    if (profile->odbc_dsn) {
+		switch_odbc_handle_callback_exec(profile->master_odbc, sql, callback, pdata);
+	} else {
+#endif
+
+
+
+		if (!(db = switch_core_db_open_file(profile->dbname))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
+			goto end;
+		}
+
+	
+		switch_core_db_exec(db, sql, callback, pdata, &errmsg);
+
+		if (errmsg) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "SQL ERR: [%s] %s\n", sql, errmsg);
+			free(errmsg);
+		}
+
+		if (db) {
+			switch_core_db_close(db);
+		}
+
+#ifdef SWITCH_HAVE_ODBC
+    }
+#endif
+
+
+ end:
+
+	if (mutex) {
+        switch_mutex_unlock(mutex);
+    }
+	
+
+
+	return ret;
+
+}
+
 static int sub_callback(void *pArg, int argc, char **argv, char **columnNames)
 {
-	struct mdl_profile *profile = (struct mdl_profile *) pArg;
+	mdl_profile_t *profile = (mdl_profile_t *) pArg;
 
 	char *sub_from = argv[0];
 	char *sub_to = argv[1];
@@ -242,7 +362,7 @@
 	char *rpid = argv[3];
 	char *status = argv[4];
 	//char *proto = argv[5];
-	
+
 	if (switch_strlen_zero(type)) {
 		type = NULL;
 	} else if (!strcasecmp(type, "unavailable")) {
@@ -251,7 +371,7 @@
 	rpid = translate_rpid(rpid, status);
 
 	//ldl_handle_send_presence(profile->handle, sub_to, sub_from, "probe", rpid, status);
-	ldl_handle_send_presence(profile->handle, sub_to, sub_from, type, rpid, status);
+	ldl_handle_send_presence(profile->handle, sub_to, sub_from, type, rpid, status, profile->avatar);
 
 
 	return 0;
@@ -259,7 +379,7 @@
 
 static int rost_callback(void *pArg, int argc, char **argv, char **columnNames)
 {
-	struct mdl_profile *profile = (struct mdl_profile *) pArg;
+	mdl_profile_t *profile = (mdl_profile_t *) pArg;
 
 	char *sub_from = argv[0];
 	char *sub_to = argv[1];
@@ -274,23 +394,23 @@
 		}
 	}
 
-	ldl_handle_send_presence(profile->handle, sub_to, sub_from, NULL, show, status);
+	ldl_handle_send_presence(profile->handle, sub_to, sub_from, NULL, show, status, profile->avatar);
 
 	return 0;
 }
 
 static void pres_event_handler(switch_event_t *event)
 {
-	struct mdl_profile *profile = NULL;
+	mdl_profile_t *profile = NULL;
 	switch_hash_index_t *hi;
-    void *val;
+	void *val;
 	char *proto = switch_event_get_header(event, "proto");
 	char *from = switch_event_get_header(event, "from");
-	char *status= switch_event_get_header(event, "status");
+	char *status = switch_event_get_header(event, "status");
 	char *rpid = switch_event_get_header(event, "rpid");
 	char *type = switch_event_get_header(event, "event_subtype");
 	char *sql;
-	switch_core_db_t *db;
+
 
 	if (!proto) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Missing 'proto' header\n");
@@ -306,35 +426,26 @@
 		status = NULL;
 	}
 
-	switch(event->event_id) {
-	case SWITCH_EVENT_PRESENCE_PROBE: 
-        if (proto) {
-        	char *sql;
-            switch_core_db_t *db;
-            char *errmsg;
-            char *to = switch_event_get_header(event, "to");
-            char *f_host = NULL;
-            if (to) {
-                if ((f_host = strchr(to, '@'))) {
-                    f_host++;
-                }
-            }
-
-            if (f_host && (profile = switch_core_hash_find(globals.profile_hash, f_host))) {
-                if (to && (sql = switch_mprintf("select * from subscriptions where sub_to='%q'", to))) {
-                    if (!(db = switch_core_db_open_file(profile->dbname))) {
-                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-                        return;
-                    }
-                    switch_mutex_lock(profile->mutex);
-                    switch_core_db_exec(db, sql, sin_callback, profile, &errmsg);
-                    switch_mutex_unlock(profile->mutex);
-                    switch_core_db_close(db);
-                    switch_safe_free(sql);
-                }
-            }
-        }
-        return;
+	switch (event->event_id) {
+	case SWITCH_EVENT_PRESENCE_PROBE:
+		if (proto) {
+			char *sql;
+			char *to = switch_event_get_header(event, "to");
+			char *f_host = NULL;
+			if (to) {
+				if ((f_host = strchr(to, '@'))) {
+					f_host++;
+				}
+			}
+
+			if (f_host && (profile = switch_core_hash_find(globals.profile_hash, f_host))) {
+				if (to && (sql = switch_mprintf("select * from jabber_subscriptions where sub_to='%q'", to))) {
+					mdl_execute_sql_callback(profile, profile->mutex, sql, sin_callback, profile);
+					switch_safe_free(sql);
+				}
+			}
+		}
+		return;
 	case SWITCH_EVENT_PRESENCE_IN:
 		if (!status) {
 			status = "Available";
@@ -346,7 +457,7 @@
 	default:
 		break;
 	}
-	
+
 
 	if (!type) {
 		type = "";
@@ -357,33 +468,28 @@
 	if (!status) {
 		status = "Away";
 	}
-	
 
-	sql = switch_mprintf("select sub_from, sub_to,'%q','%q','%q','%q' from subscriptions where sub_to like '%%%q'", 
-						 type, rpid, status, proto, from);
-	
-	
-	for (hi = switch_hash_first(apr_hash_pool_get(globals.profile_hash), globals.profile_hash); hi; hi = switch_hash_next(hi)) {
-		char *errmsg;
-        switch_hash_this(hi, NULL, NULL, &val);
-        profile = (struct mdl_profile *) val;
 
-        if (!(profile->user_flags & LDL_FLAG_COMPONENT)) {
+	sql = switch_mprintf("select sub_from, sub_to,'%q','%q','%q','%q' from jabber_subscriptions where sub_to like '%%%q'", type, rpid, status, proto, from);
+
+
+	for (hi = switch_hash_first(switch_hash_pool_get(globals.profile_hash), globals.profile_hash); hi; hi = switch_hash_next(hi)) {
+		switch_hash_this(hi, NULL, NULL, &val);
+		profile = (mdl_profile_t *) val;
+
+		if (!(profile->user_flags & LDL_FLAG_COMPONENT)) {
 			continue;
-        }
+		}
 
 
 		if (sql) {
-			if (!(db = switch_core_db_open_file(profile->dbname))) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
+			switch_bool_t worked = mdl_execute_sql_callback(profile, profile->mutex, sql, sub_callback, profile);
+			
+			if (!worked) {
 				continue;
 			}
-			switch_mutex_lock(profile->mutex);
-			switch_core_db_exec(db, sql, sub_callback, profile, &errmsg);
-			switch_mutex_unlock(profile->mutex);
-			switch_core_db_close(db);
 		}
-		
+
 
 	}
 
@@ -393,16 +499,16 @@
 static switch_status_t chat_send(char *proto, char *from, char *to, char *subject, char *body, char *hint)
 {
 	char *user, *host, *f_user = NULL, *ffrom = NULL, *f_host = NULL, *f_resource = NULL;
-	struct mdl_profile *profile = NULL;
+	mdl_profile_t *profile = NULL;
 
 	assert(proto != NULL);
 
 	if (from && (f_user = strdup(from))) {
 		if ((f_host = strchr(f_user, '@'))) {
 			*f_host++ = '\0';
-            if ((f_resource = strchr(f_host, '/'))) {
-                *f_resource++ = '\0';
-            }
+			if ((f_resource = strchr(f_host, '/'))) {
+				*f_resource++ = '\0';
+			}
 		}
 	}
 
@@ -412,7 +518,7 @@
 		}
 
 		if (f_host && (profile = switch_core_hash_find(globals.profile_hash, f_host))) {
-			
+
 			if (!strcmp(proto, MDL_CHAT_PROTO)) {
 				from = hint;
 			} else {
@@ -439,50 +545,45 @@
 
 static void roster_event_handler(switch_event_t *event)
 {
-	char *status= switch_event_get_header(event, "status");
-	char *from= switch_event_get_header(event, "from");
+	char *status = switch_event_get_header(event, "status");
+	char *from = switch_event_get_header(event, "from");
 	char *event_type = switch_event_get_header(event, "event_type");
-	struct mdl_profile *profile = NULL;
+	mdl_profile_t *profile = NULL;
 	switch_hash_index_t *hi;
-    void *val;
+	void *val;
 	char *sql;
-	switch_core_db_t *db;
+
 
 	if (status && !strcasecmp(status, "n/a")) {
 		status = NULL;
 	}
 
 	if (switch_strlen_zero(event_type)) {
-		event_type="presence";
+		event_type = "presence";
 	}
 
 	if (from) {
-		sql = switch_mprintf("select *,'%q' from subscriptions where sub_from='%q'", status ? status : "", from);
+		sql = switch_mprintf("select *,'%q' from jabber_subscriptions where sub_from='%q'", status ? status : "", from);
 	} else {
-		sql = switch_mprintf("select *,'%q' from subscriptions", status ? status : "");
+		sql = switch_mprintf("select *,'%q' from jabber_subscriptions", status ? status : "");
 	}
 
-	for (hi = switch_hash_first(apr_hash_pool_get(globals.profile_hash), globals.profile_hash); hi; hi = switch_hash_next(hi)) {
-		char *errmsg;
-        switch_hash_this(hi, NULL, NULL, &val);
-        profile = (struct mdl_profile *) val;
+	for (hi = switch_hash_first(switch_hash_pool_get(globals.profile_hash), globals.profile_hash); hi; hi = switch_hash_next(hi)) {
+		switch_hash_this(hi, NULL, NULL, &val);
+		profile = (mdl_profile_t *) val;
 
-        if (!(profile->user_flags & LDL_FLAG_COMPONENT)) {
+		if (!(profile->user_flags & LDL_FLAG_COMPONENT)) {
 			continue;
-        }
+		}
 
 
 		if (sql) {
-			if (!(db = switch_core_db_open_file(profile->dbname))) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
+			switch_bool_t worked = mdl_execute_sql_callback(profile, profile->mutex, sql, rost_callback, profile);
+			if (!worked) {
 				continue;
 			}
-			switch_mutex_lock(profile->mutex);
-			switch_core_db_exec(db, sql, rost_callback, profile, &errmsg);
-			switch_mutex_unlock(profile->mutex);
-			switch_core_db_close(db);
 		}
-		
+
 	}
 
 	switch_safe_free(sql);
@@ -491,31 +592,31 @@
 
 static int so_callback(void *pArg, int argc, char **argv, char **columnNames)
 {
-	struct mdl_profile *profile = (struct mdl_profile *) pArg;
+	mdl_profile_t *profile = (mdl_profile_t *) pArg;
 
 	char *sub_from = argv[0];
 	char *sub_to = argv[1];
 
 
-	ldl_handle_send_presence(profile->handle, sub_to, sub_from, "unavailable", "dnd", "Bub-Bye");
-	
+	ldl_handle_send_presence(profile->handle, sub_to, sub_from, "unavailable", "dnd", "Bub-Bye", profile->avatar);
+
 	return 0;
 }
 
 
 static int sin_callback(void *pArg, int argc, char **argv, char **columnNames)
 {
-	struct mdl_profile *profile = (struct mdl_profile *) pArg;
+	mdl_profile_t *profile = (mdl_profile_t *) pArg;
 	switch_event_t *event;
 
 	//char *sub_from = argv[0];
 	char *sub_to = argv[1];
-	
+
 	if (is_special(sub_to)) {
 		if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
 			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", MDL_CHAT_PROTO);
 			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->login);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s",  sub_to);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", sub_to);
 			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "available");
 			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Online");
 			switch_event_fire(&event);
@@ -527,59 +628,46 @@
 
 static void sign_off(void)
 {
-	struct mdl_profile *profile = NULL;
+	mdl_profile_t *profile = NULL;
 	switch_hash_index_t *hi;
-    void *val;
+	void *val;
 	char *sql;
-	switch_core_db_t *db;
 
 
-	sql = switch_mprintf("select * from subscriptions");
-	
 
-	for (hi = switch_hash_first(apr_hash_pool_get(globals.profile_hash), globals.profile_hash); hi; hi = switch_hash_next(hi)) {
-		char *errmsg;
-        switch_hash_this(hi, NULL, NULL, &val);
-        profile = (struct mdl_profile *) val;
+	sql = switch_mprintf("select * from jabber_subscriptions");
+
 
-        if (!(profile->user_flags & LDL_FLAG_COMPONENT)) {
+	for (hi = switch_hash_first(switch_hash_pool_get(globals.profile_hash), globals.profile_hash); hi; hi = switch_hash_next(hi)) {
+		switch_hash_this(hi, NULL, NULL, &val);
+		profile = (mdl_profile_t *) val;
+
+		if (!(profile->user_flags & LDL_FLAG_COMPONENT)) {
 			continue;
-        }
+		}
 
 
 		if (sql) {
-			if (!(db = switch_core_db_open_file(profile->dbname))) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
+			switch_bool_t worked = mdl_execute_sql_callback(profile, profile->mutex, sql, so_callback, profile);
+			if (!worked) {
 				continue;
 			}
-			switch_mutex_lock(profile->mutex);
-			switch_core_db_exec(db, sql, so_callback, profile, &errmsg);
-			switch_mutex_unlock(profile->mutex);
-			switch_core_db_close(db);
 		}
-		
+
 	}
-	
+
 	switch_yield(1000000);
 	switch_safe_free(sql);
 
 }
 
-static void sign_on(struct mdl_profile *profile)
+static void sign_on(mdl_profile_t *profile)
 {
 	char *sql;
-	switch_core_db_t *db;
-	char *errmsg;
 
-	if ((sql = switch_mprintf("select * from subscriptions where sub_to like 'ext+%%' or sub_to like 'user+%%' or sub_to like 'conf+%%'"))) {
-		if (!(db = switch_core_db_open_file(profile->dbname))) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-			return;
-		}
-		switch_mutex_lock(profile->mutex);
-		switch_core_db_exec(db, sql, sin_callback, profile, &errmsg);
-		switch_mutex_unlock(profile->mutex);
-		switch_core_db_close(db);
+
+	if ((sql = switch_mprintf("select * from jabber_subscriptions where sub_to like 'ext+%%' or sub_to like 'user+%%' or sub_to like 'conf+%%'"))) {
+		mdl_execute_sql_callback(profile, profile->mutex, sql, sin_callback, profile);
 		switch_safe_free(sql);
 	}
 }
@@ -590,9 +678,9 @@
 		switch_channel_t *channel = switch_core_session_get_channel(*session);
 		switch_channel_state_t state = switch_channel_get_state(channel);
 		struct private_object *tech_pvt = NULL;
-		
+
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Terminate called from line %d state=%s\n", line, switch_channel_state_name(state));
- 
+
 		tech_pvt = switch_core_session_get_private(*session);
 
 		if (!tech_pvt || !switch_test_flag(tech_pvt, TFLAG_READY)) {
@@ -601,14 +689,14 @@
 		}
 
 		if (switch_test_flag(tech_pvt, TFLAG_TERM)) {
-			/*once is enough*/
+			/*once is enough */
 			return;
 		}
 
 		if (state < CS_HANGUP) {
 			switch_channel_hangup(channel, cause);
 		}
-		
+
 		switch_mutex_lock(tech_pvt->flag_mutex);
 		switch_set_flag(tech_pvt, TFLAG_TERM);
 		switch_set_flag(tech_pvt, TFLAG_BYE);
@@ -623,13 +711,35 @@
 static void dl_logger(char *file, const char *func, int line, int level, char *fmt, ...)
 {
 	va_list ap;
-	char data[1024];
+	char *data = NULL;
+	int ret;
 
 	va_start(ap, fmt);
-	
-	vsnprintf(data, sizeof(data), fmt, ap);
-	switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_DEBUG, "%s", data);
-
+	if ((ret = switch_vasprintf(&data, fmt, ap)) != -1) {
+		if (!strncasecmp(data, "+xml:", 5)) {
+			switch_xml_t xml;
+			char *form;
+			char *ll = data + 5;
+			char *xmltxt;
+
+			if (ll) {
+				if ((xmltxt = strchr(ll, ':'))) {
+					*xmltxt++ = '\0';
+					if (strlen(xmltxt) > 2) {
+						xml = switch_xml_parse_str(xmltxt, strlen(xmltxt));
+						form = switch_xml_toxml(xml);
+						switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, level, 
+										  "%s:\n-------------------------------------------------------------------------------\n"
+										  "%s\n", ll, form);
+						switch_xml_free(xml);
+						free(data);
+					}
+				}
+			}
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, level, "%s\n", data);
+		}
+	}
 	va_end(ap);
 }
 
@@ -641,9 +751,7 @@
 	if (!tech_pvt->num_codecs) {
 		if (globals.codec_string) {
 			if ((tech_pvt->num_codecs = switch_loadable_module_get_codecs_sorted(tech_pvt->codecs,
-																				 SWITCH_MAX_CODECS,
-																				 globals.codec_order,
-																				 globals.codec_order_last)) <= 0) {
+																				 SWITCH_MAX_CODECS, globals.codec_order, globals.codec_order_last)) <= 0) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "NO codecs?\n");
 				return 0;
 			}
@@ -659,10 +767,10 @@
 
 
 
-static void *SWITCH_THREAD_FUNC handle_thread_run(switch_thread_t *thread, void *obj)
+static void *SWITCH_THREAD_FUNC handle_thread_run(switch_thread_t * thread, void *obj)
 {
 	ldl_handle_t *handle = obj;
-	struct mdl_profile *profile = NULL;
+	mdl_profile_t *profile = NULL;
 
 
 
@@ -674,15 +782,15 @@
 	globals.handles--;
 	ldl_handle_destroy(&handle);
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Handle %s [%s] Destroyed\n", profile->name, profile->login);
-	
+
 	return NULL;
 }
 
-static void handle_thread_launch(ldl_handle_t *handle)
+static void handle_thread_launch(ldl_handle_t * handle)
 {
 	switch_thread_t *thread;
 	switch_threadattr_t *thd_attr = NULL;
-	
+
 	switch_threadattr_create(&thd_attr, module_pool);
 	switch_threadattr_detach_set(thd_attr, 1);
 	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
@@ -702,10 +810,10 @@
 		return 1;
 	}
 
-    if (!(tech_pvt->remote_ip && tech_pvt->remote_port)) {
+	if (!(tech_pvt->remote_ip && tech_pvt->remote_port)) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "No valid candidates received!\n");
-        return 0;
-    }
+		return 0;
+	}
 
 	if (switch_core_codec_init(&tech_pvt->read_codec,
 							   tech_pvt->codec_name,
@@ -722,9 +830,9 @@
 	tech_pvt->read_frame.rate = tech_pvt->read_codec.implementation->samples_per_second;
 	tech_pvt->read_frame.codec = &tech_pvt->read_codec;
 
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Set Read Codec to %s@%d\n", 
-					  tech_pvt->codec_name, (int)tech_pvt->read_codec.implementation->samples_per_second);
-	
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Set Read Codec to %s@%d\n",
+					  tech_pvt->codec_name, (int) tech_pvt->read_codec.implementation->samples_per_second);
+
 	if (switch_core_codec_init(&tech_pvt->write_codec,
 							   tech_pvt->codec_name,
 							   NULL,
@@ -737,20 +845,20 @@
 		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 		return 0;
 	}
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Set Write Codec to %s@%d\n",  
-					  tech_pvt->codec_name,(int)tech_pvt->write_codec.implementation->samples_per_second);
-							
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Set Write Codec to %s@%d\n",
+					  tech_pvt->codec_name, (int) tech_pvt->write_codec.implementation->samples_per_second);
+
 	switch_core_session_set_read_codec(tech_pvt->session, &tech_pvt->read_codec);
 	switch_core_session_set_write_codec(tech_pvt->session, &tech_pvt->write_codec);
-	
 
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SETUP RTP %s:%d -> %s:%d\n", tech_pvt->profile->ip, tech_pvt->local_port, tech_pvt->remote_ip, tech_pvt->remote_port);
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SETUP RTP %s:%d -> %s:%d\n", tech_pvt->profile->ip,
+					  tech_pvt->local_port, tech_pvt->remote_ip, tech_pvt->remote_port);
 	
-	flags = SWITCH_RTP_FLAG_GOOGLEHACK | SWITCH_RTP_FLAG_AUTOADJ;
-	//flags = SWITCH_RTP_FLAG_AUTOADJ;
+	flags = SWITCH_RTP_FLAG_GOOGLEHACK | SWITCH_RTP_FLAG_AUTOADJ | SWITCH_RTP_FLAG_RAW_WRITE | SWITCH_RTP_FLAG_AUTO_CNG;
 
 	if (switch_test_flag(tech_pvt->profile, TFLAG_TIMER)) {
-	  flags |= SWITCH_RTP_FLAG_USE_TIMER;
+		flags |= SWITCH_RTP_FLAG_USE_TIMER;
 	}
 
 	if (!(tech_pvt->rtp_session = switch_rtp_new(tech_pvt->profile->ip,
@@ -758,12 +866,9 @@
 												 tech_pvt->remote_ip,
 												 tech_pvt->remote_port,
 												 tech_pvt->codec_num,
-                                                 tech_pvt->read_codec.implementation->encoded_bytes_per_frame,
+												 tech_pvt->read_codec.implementation->encoded_bytes_per_frame,
 												 tech_pvt->read_codec.implementation->microseconds_per_frame,
-												 flags,
-												 NULL,
-												 tech_pvt->profile->timer_name,
-												 &err, switch_core_session_get_pool(tech_pvt->session)))) {
+												 flags, NULL, tech_pvt->profile->timer_name, &err, switch_core_session_get_pool(tech_pvt->session)))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "RTP ERROR %s\n", err);
 		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 		return 0;
@@ -773,9 +878,15 @@
 		uint8_t inb = switch_test_flag(tech_pvt, TFLAG_OUTBOUND) ? 0 : 1;
 		switch_rtp_activate_ice(tech_pvt->rtp_session, tech_pvt->remote_user, tech_pvt->local_user);
 		if ((vad_in && inb) || (vad_out && !inb)) {
-			switch_rtp_enable_vad(tech_pvt->rtp_session, tech_pvt->session, &tech_pvt->read_codec, SWITCH_VAD_FLAG_TALKING);
+			if (switch_rtp_enable_vad(tech_pvt->rtp_session, tech_pvt->session, &tech_pvt->read_codec, SWITCH_VAD_FLAG_TALKING) != SWITCH_STATUS_SUCCESS) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "VAD ERROR %s\n", err);
+				switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+				return 0;
+			}
 			switch_set_flag_locked(tech_pvt, TFLAG_VAD);
 		}
+		switch_rtp_set_cng_pt(tech_pvt->rtp_session, 13);
+		switch_rtp_set_telephony_event(tech_pvt->rtp_session, 101);
 	}
 
 	return 1;
@@ -814,10 +925,10 @@
 
 		cand[0].port = tech_pvt->local_port;
 		cand[0].address = advip;
-				
+
 		if (!strncasecmp(advip, "stun:", 5)) {
 			char *stun_ip = advip + 5;
-					
+
 			if (tech_pvt->stun_ip) {
 				cand[0].address = tech_pvt->stun_ip;
 				cand[0].port = tech_pvt->stun_port;
@@ -830,12 +941,9 @@
 
 				cand[0].address = tech_pvt->profile->ip;
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Stun Lookup Local %s:%d\n", cand[0].address, cand[0].port);
-				if (switch_stun_lookup(&cand[0].address,
-									   &cand[0].port,
-									   stun_ip,
-									   SWITCH_STUN_DEFAULT_PORT,
-									   &err,
-									   switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
+				if (switch_stun_lookup
+					(&cand[0].address, &cand[0].port, stun_ip, SWITCH_STUN_DEFAULT_PORT, &err,
+					 switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Stun Failed! %s:%d [%s]\n", stun_ip, SWITCH_STUN_DEFAULT_PORT, err);
 					switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 					return 0;
@@ -908,12 +1016,12 @@
 			tech_pvt->codec_rate = tech_pvt->codecs[0]->samples_per_second;
 			tech_pvt->r_codec_num = tech_pvt->codecs[0]->ianacode;
 			tech_pvt->codec_index = 0;
-					
+
 			payloads[0].name = lame(tech_pvt->codecs[0]->iananame);
 			payloads[0].id = tech_pvt->codecs[0]->ianacode;
 			payloads[0].rate = tech_pvt->codecs[0]->samples_per_second;
 			payloads[0].bps = tech_pvt->codecs[0]->bits_per_second;
-			
+
 		} else {
 			payloads[0].name = lame(tech_pvt->codecs[tech_pvt->codec_index]->iananame);
 			payloads[0].id = tech_pvt->codecs[tech_pvt->codec_index]->ianacode;
@@ -921,12 +1029,13 @@
 			payloads[0].bps = tech_pvt->codecs[tech_pvt->codec_index]->bits_per_second;
 		}
 
-				
+
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Send Describe [%s@%d]\n", payloads[0].name, payloads[0].rate);
-		tech_pvt->desc_id = ldl_session_describe(tech_pvt->dlsession, payloads, 1,
-												 switch_test_flag(tech_pvt, TFLAG_OUTBOUND) ? LDL_DESCRIPTION_INITIATE : LDL_DESCRIPTION_ACCEPT);
+		tech_pvt->desc_id =
+			ldl_session_describe(tech_pvt->dlsession, payloads, 1,
+								 switch_test_flag(tech_pvt, TFLAG_OUTBOUND) ? LDL_DESCRIPTION_INITIATE : LDL_DESCRIPTION_ACCEPT);
 		switch_set_flag_locked(tech_pvt, TFLAG_CODEC_READY);
-	} 
+	}
 	switch_clear_flag_locked(tech_pvt, TFLAG_DO_CAND);
 	return 1;
 }
@@ -953,7 +1062,7 @@
 	/* jingle has no ringing indication so we will just pretend that we got one */
 	switch_core_session_queue_indication(session, SWITCH_MESSAGE_INDICATE_RINGING);
 	switch_channel_mark_ring_ready(channel);
-	
+
 	if (switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
 		tech_pvt->next_cand = switch_time_now() + DL_CAND_WAIT;
 		tech_pvt->next_desc = switch_time_now();
@@ -962,62 +1071,62 @@
 		tech_pvt->next_desc = switch_time_now() + DL_CAND_WAIT;
 	}
 
-	while(! (switch_test_flag(tech_pvt, TFLAG_CODEC_READY) && 
-			 switch_test_flag(tech_pvt, TFLAG_RTP_READY) && 
-			 switch_test_flag(tech_pvt, TFLAG_ANSWER) && 
-			 switch_test_flag(tech_pvt, TFLAG_TRANSPORT_ACCEPT) &&
-			 switch_test_flag(tech_pvt, TFLAG_TRANSPORT))) {
+	while (!(switch_test_flag(tech_pvt, TFLAG_CODEC_READY) &&
+			 switch_test_flag(tech_pvt, TFLAG_RTP_READY) &&
+			 switch_test_flag(tech_pvt, TFLAG_ANSWER) && switch_test_flag(tech_pvt, TFLAG_TRANSPORT_ACCEPT) &&
+			 tech_pvt->remote_ip && tech_pvt->remote_port
+			 && switch_test_flag(tech_pvt, TFLAG_TRANSPORT))) {
 		now = switch_time_now();
-		elapsed = (unsigned int)((now - started) / 1000);
+		elapsed = (unsigned int) ((now - started) / 1000);
 
 		if (switch_channel_get_state(channel) >= CS_HANGUP || switch_test_flag(tech_pvt, TFLAG_BYE)) {
 			goto out;
 		}
 
-		
+
 		if (now >= tech_pvt->next_desc) {
 			if (!do_describe(tech_pvt, 0)) {
 				goto out;
 			}
 		}
-		
+
 		if (tech_pvt->next_cand && now >= tech_pvt->next_cand) {
 			if (!do_candidates(tech_pvt, 0)) {
 				goto out;
 			}
 		}
 		if (elapsed > 60000) {
-			terminate_session(&tech_pvt->session,  __LINE__, SWITCH_CAUSE_NORMAL_CLEARING);
+			terminate_session(&tech_pvt->session, __LINE__, SWITCH_CAUSE_NORMAL_CLEARING);
 			switch_set_flag_locked(tech_pvt, TFLAG_BYE);
 			switch_clear_flag_locked(tech_pvt, TFLAG_IO);
 			goto done;
 		}
-		if (switch_test_flag(tech_pvt, TFLAG_BYE) || ! switch_test_flag(tech_pvt, TFLAG_IO)) {
+		if (switch_test_flag(tech_pvt, TFLAG_BYE) || !switch_test_flag(tech_pvt, TFLAG_IO)) {
 			goto done;
 		}
 		switch_yield(1000);
 	}
-	
+
 	if (switch_channel_get_state(channel) >= CS_HANGUP || switch_test_flag(tech_pvt, TFLAG_BYE)) {
 		goto out;
-	}	
+	}
 
 	if (!activate_rtp(tech_pvt)) {
 		goto out;
 	}
-	
+
 	if (switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
 		if (!do_candidates(tech_pvt, 0)) {
 			goto out;
 		}
 		switch_channel_answer(channel);
-	} 
+	}
 	ret = SWITCH_STATUS_SUCCESS;
 
 	goto done;
-	
+
  out:
-	terminate_session(&session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+	terminate_session(&session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
  done:
 
 	return ret;
@@ -1061,7 +1170,7 @@
 
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
-	
+
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s CHANNEL RING\n", switch_channel_get_name(channel));
 
 	return SWITCH_STATUS_SUCCESS;
@@ -1089,7 +1198,7 @@
 {
 	switch_channel_t *channel = NULL;
 	struct private_object *tech_pvt = NULL;
-	
+
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
 
@@ -1101,12 +1210,11 @@
 	switch_set_flag_locked(tech_pvt, TFLAG_BYE);
 
 	/* Dunno why, but if googletalk calls us for the first time, as soon as the call ends
-	 they think we are offline for no reason so we send this presence packet to stop it from happening
-	 We should find out why.....
+	   they think we are offline for no reason so we send this presence packet to stop it from happening
+	   We should find out why.....
 	*/
-	if ((tech_pvt->profile->user_flags & LDL_FLAG_COMPONENT) && is_special(tech_pvt->them)) {	
-		ldl_handle_send_presence(tech_pvt->profile->handle,
-								 tech_pvt->them, tech_pvt->us, NULL, NULL, "Click To Call");
+	if ((tech_pvt->profile->user_flags & LDL_FLAG_COMPONENT) && is_special(tech_pvt->them)) {
+		ldl_handle_send_presence(tech_pvt->profile->handle, tech_pvt->them, tech_pvt->us, NULL, NULL, "Click To Call", tech_pvt->profile->avatar);
 	}
 	if (tech_pvt->dlsession) {
 		if (!switch_test_flag(tech_pvt, TFLAG_TERM)) {
@@ -1140,42 +1248,42 @@
 	switch_channel_t *channel = NULL;
 	struct private_object *tech_pvt = NULL;
 
-    if (!(channel = switch_core_session_get_channel(session))) {
-        return SWITCH_STATUS_SUCCESS;
-    }
+	if (!(channel = switch_core_session_get_channel(session))) {
+		return SWITCH_STATUS_SUCCESS;
+	}
 
-    if (!(tech_pvt = switch_core_session_get_private(session))) {
-        return SWITCH_STATUS_SUCCESS;
-    }
-    
+	if (!(tech_pvt = switch_core_session_get_private(session))) {
+		return SWITCH_STATUS_SUCCESS;
+	}
+
+
+	switch (sig) {
+	case SWITCH_SIG_KILL:
+		switch_clear_flag_locked(tech_pvt, TFLAG_IO);
+		switch_clear_flag_locked(tech_pvt, TFLAG_VOICE);
+		switch_set_flag_locked(tech_pvt, TFLAG_BYE);
+
+		if (tech_pvt->dlsession) {
+			if (!switch_test_flag(tech_pvt, TFLAG_TERM)) {
+				ldl_session_terminate(tech_pvt->dlsession);
+				switch_set_flag_locked(tech_pvt, TFLAG_TERM);
+			}
+			ldl_session_destroy(&tech_pvt->dlsession);
+
+		}
 
-    switch (sig) {
-    case SWITCH_SIG_KILL:
-        switch_clear_flag_locked(tech_pvt, TFLAG_IO);
-        switch_clear_flag_locked(tech_pvt, TFLAG_VOICE);
-        switch_set_flag_locked(tech_pvt, TFLAG_BYE);
-
-        if (tech_pvt->dlsession) {
-            if (!switch_test_flag(tech_pvt, TFLAG_TERM)) {
-                ldl_session_terminate(tech_pvt->dlsession);
-                switch_set_flag_locked(tech_pvt, TFLAG_TERM);
-            }
-            ldl_session_destroy(&tech_pvt->dlsession);
-            
-        }
-
-        if (switch_rtp_ready(tech_pvt->rtp_session)) {
-            switch_rtp_kill_socket(tech_pvt->rtp_session);
-        }
-        break;
+		if (switch_rtp_ready(tech_pvt->rtp_session)) {
+			switch_rtp_kill_socket(tech_pvt->rtp_session);
+		}
+		break;
 	case SWITCH_SIG_BREAK:
-        if (switch_rtp_ready(tech_pvt->rtp_session)) {
+		if (switch_rtp_ready(tech_pvt->rtp_session)) {
 			switch_rtp_set_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_BREAK);
 		}
 		break;
-    }
+	}
 
-    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s CHANNEL KILL\n", switch_channel_get_name(channel));
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s CHANNEL KILL\n", switch_channel_get_name(channel));
 
 
 	return SWITCH_STATUS_SUCCESS;
@@ -1223,148 +1331,158 @@
 
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "DTMF [%s]\n", dtmf);
 
-	return switch_rtp_queue_rfc2833(tech_pvt->rtp_session,
-									dtmf,
-									100 * (tech_pvt->read_codec.implementation->samples_per_second / 1000));
+	return switch_rtp_queue_rfc2833(tech_pvt->rtp_session, dtmf, 100 * (tech_pvt->read_codec.implementation->samples_per_second / 1000));
 
 }
 
-static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-										  switch_io_flag_t flags, int stream_id)
+static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
 	struct private_object *tech_pvt = NULL;
-	uint32_t bytes = 0;
-	switch_size_t samples = 0, frames = 0, ms = 0;
 	switch_channel_t *channel = NULL;
-	switch_payload_t payload = 0;
-	switch_status_t status;
+	int payload = 0;
 
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
 
-	tech_pvt = switch_core_session_get_private(session);
+	tech_pvt = (struct private_object *) switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
-
-	if (!tech_pvt->rtp_session) {
-		return SWITCH_STATUS_FALSE;
-	}
-
-	if (switch_test_flag(tech_pvt, TFLAG_BYE)) {
-		//terminate_session(&session,  __LINE__, SWITCH_CAUSE_NORMAL_CLEARING);
-		return SWITCH_STATUS_FALSE;
+	while (!(tech_pvt->read_codec.implementation && switch_rtp_ready(tech_pvt->rtp_session))) {
+		if (switch_channel_ready(channel)) {
+			switch_yield(10000);
+		} else {
+			return SWITCH_STATUS_GENERR;
+		}
 	}
 
 
 	tech_pvt->read_frame.datalen = 0;
 	switch_set_flag_locked(tech_pvt, TFLAG_READING);
 
-	bytes = tech_pvt->read_codec.implementation->encoded_bytes_per_frame;
-	samples = tech_pvt->read_codec.implementation->samples_per_frame;
-	ms = tech_pvt->read_codec.implementation->microseconds_per_frame;
-	tech_pvt->read_frame.datalen = 0;
-
-	
-	while (!switch_test_flag(tech_pvt, TFLAG_BYE) && switch_test_flag(tech_pvt, TFLAG_IO) && tech_pvt->read_frame.datalen == 0) {
-		tech_pvt->read_frame.flags = 0;
-		status = switch_rtp_zerocopy_read_frame(tech_pvt->rtp_session, &tech_pvt->read_frame);
-		
-		if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
-			return SWITCH_STATUS_FALSE;
+#if 0
+	if (tech_pvt->last_read) {
+		elapsed = (unsigned int) ((switch_time_now() - tech_pvt->last_read) / 1000);
+		if (elapsed > 60000) {
+			return SWITCH_STATUS_TIMEOUT;
 		}
-		payload = tech_pvt->read_frame.payload;
+	}
+#endif
 
-		if (switch_rtp_has_dtmf(tech_pvt->rtp_session)) {
-			char dtmf[128];
-			switch_rtp_dequeue_dtmf(tech_pvt->rtp_session, dtmf, sizeof(dtmf));
-			switch_channel_queue_dtmf(channel, dtmf);
-			switch_set_flag_locked(tech_pvt, TFLAG_DTMF);
-		}
-
-		if (switch_test_flag(tech_pvt, TFLAG_DTMF)) {
-			switch_clear_flag_locked(tech_pvt, TFLAG_DTMF);
-			return SWITCH_STATUS_BREAK;
-		}
-
-		if (switch_test_flag(&tech_pvt->read_frame, SFF_CNG)) {
-			tech_pvt->read_frame.datalen = tech_pvt->last_read ? tech_pvt->last_read : tech_pvt->read_codec.implementation->encoded_bytes_per_frame;
-		}
-
-		if (tech_pvt->read_frame.datalen > 0) {
-            if (!switch_test_flag((&tech_pvt->read_frame), SFF_CNG)) {
-                if (tech_pvt->read_codec.implementation->encoded_bytes_per_frame && bytes) {
-                    bytes = tech_pvt->read_codec.implementation->encoded_bytes_per_frame;
-                    frames = (tech_pvt->read_frame.datalen / bytes);
-                } else {
-                    frames = 1;
-                }
-                samples = frames * tech_pvt->read_codec.implementation->samples_per_frame;
-                ms = frames * tech_pvt->read_codec.implementation->microseconds_per_frame;
-                tech_pvt->timestamp_recv += (int32_t) samples;
-                tech_pvt->read_frame.samples = (int) samples;
-                tech_pvt->last_read = tech_pvt->read_frame.datalen;
-            }
-			break;
-		}
 
-		switch_yield(1000);
-	}
+	if (switch_test_flag(tech_pvt, TFLAG_IO)) {
+		switch_status_t status;
 
+		assert(tech_pvt->rtp_session != NULL);
+		tech_pvt->read_frame.datalen = 0;
+
+
+		while (switch_test_flag(tech_pvt, TFLAG_IO) && tech_pvt->read_frame.datalen == 0) {
+			tech_pvt->read_frame.flags = SFF_NONE;
+
+			status = switch_rtp_zerocopy_read_frame(tech_pvt->rtp_session, &tech_pvt->read_frame);
+			if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
+				return SWITCH_STATUS_FALSE;
+			}
+
+
+
+			payload = tech_pvt->read_frame.payload;
+
+#if 0
+			elapsed = (unsigned int) ((switch_time_now() - started) / 1000);
+
+			if (timeout > -1) {
+				if (elapsed >= (unsigned int) timeout) {
+					return SWITCH_STATUS_BREAK;
+				}
+			}
+
+			elapsed = (unsigned int) ((switch_time_now() - last_act) / 1000);
+			if (elapsed >= hard_timeout) {
+				return SWITCH_STATUS_BREAK;
+			}
+#endif
+			if (switch_rtp_has_dtmf(tech_pvt->rtp_session)) {
+				char dtmf[128];
+				switch_rtp_dequeue_dtmf(tech_pvt->rtp_session, dtmf, sizeof(dtmf));
+				switch_channel_queue_dtmf(channel, dtmf);
+			}
+
+
+			if (tech_pvt->read_frame.datalen > 0) {
+				size_t bytes = 0;
+				int frames = 1;
+
+				if (!switch_test_flag((&tech_pvt->read_frame), SFF_CNG)) {
+					if ((bytes = tech_pvt->read_codec.implementation->encoded_bytes_per_frame)) {
+						frames = (tech_pvt->read_frame.datalen / bytes);
+					}
+					tech_pvt->read_frame.samples = (int) (frames * tech_pvt->read_codec.implementation->samples_per_frame);
+				}
+				break;
+			}
+		}
+	}
 
 	switch_clear_flag_locked(tech_pvt, TFLAG_READING);
 
+	if (tech_pvt->read_frame.datalen == 0) {
+		*frame = NULL;
+		return SWITCH_STATUS_GENERR;
+	}
 
 	*frame = &tech_pvt->read_frame;
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-										   switch_io_flag_t flags, int stream_id)
+static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
 	struct private_object *tech_pvt;
 	switch_channel_t *channel = NULL;
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
 	int bytes = 0, samples = 0, frames = 0;
 
-
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
 
-	tech_pvt = switch_core_session_get_private(session);
+	tech_pvt = (struct private_object *) switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
-	if (!tech_pvt->rtp_session) {
-		return SWITCH_STATUS_FALSE;
+	while (!(tech_pvt->read_codec.implementation && switch_rtp_ready(tech_pvt->rtp_session))) {
+		if (switch_channel_ready(channel)) {
+			switch_yield(10000);
+		} else {
+			return SWITCH_STATUS_GENERR;
+		}
 	}
 
-	if (!switch_test_flag(tech_pvt, TFLAG_RTP_READY)) {
+	if (!switch_test_flag(tech_pvt, TFLAG_IO)) {
 		return SWITCH_STATUS_SUCCESS;
 	}
 
-
-	if (switch_test_flag(tech_pvt, TFLAG_BYE)) {
-		return SWITCH_STATUS_FALSE;
-	}
-
 	switch_set_flag_locked(tech_pvt, TFLAG_WRITING);
 
-	if (tech_pvt->read_codec.implementation->encoded_bytes_per_frame) {
-		bytes = tech_pvt->read_codec.implementation->encoded_bytes_per_frame;
-		frames = ((int) frame->datalen / bytes);
-	} else {
-		frames = 1;
-	}
-
-	samples = frames * tech_pvt->read_codec.implementation->samples_per_frame;
+	if (!switch_test_flag(frame, SFF_CNG)) {
+		if (tech_pvt->read_codec.implementation->encoded_bytes_per_frame) {
+			bytes = tech_pvt->read_codec.implementation->encoded_bytes_per_frame;
+			frames = ((int) frame->datalen / bytes);
+		} else
+			frames = 1;
 
-	if (switch_rtp_write_frame(tech_pvt->rtp_session, frame, samples) < 0) {
-		terminate_session(&session,  __LINE__, SWITCH_CAUSE_NORMAL_CLEARING);
-		return SWITCH_STATUS_FALSE;
+		samples = frames * tech_pvt->read_codec.implementation->samples_per_frame;
 	}
-	tech_pvt->timestamp_send += (int) samples;
+#if 0
+	printf("%s %s->%s send %d bytes %d samples in %d frames ts=%d\n",
+		   switch_channel_get_name(channel),
+		   tech_pvt->local_sdp_audio_ip, tech_pvt->remote_sdp_audio_ip, frame->datalen, samples, frames, tech_pvt->timestamp_send);
+#endif
 
-	switch_clear_flag_locked(tech_pvt, TFLAG_WRITING);
+	tech_pvt->timestamp_send += samples;
+	//switch_rtp_write_frame(tech_pvt->rtp_session, frame, tech_pvt->timestamp_send);
+	switch_rtp_write_frame(tech_pvt->rtp_session, frame, 0);
 
+	switch_clear_flag_locked(tech_pvt, TFLAG_WRITING);
 	return status;
 }
 
@@ -1387,16 +1505,19 @@
 {
 	switch_channel_t *channel;
 	struct private_object *tech_pvt;
-			
+
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
-			
+
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
 	switch (msg->message_id) {
+	case SWITCH_MESSAGE_INDICATE_ANSWER:
+		channel_answer_channel(session);
+		break;
 	case SWITCH_MESSAGE_INDICATE_BRIDGE:
-	  if (tech_pvt->rtp_session && switch_test_flag(tech_pvt->profile, TFLAG_TIMER)) {
+		if (tech_pvt->rtp_session && switch_test_flag(tech_pvt->profile, TFLAG_TIMER)) {
 			switch_rtp_clear_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_USE_TIMER);
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "De-activate timed RTP!\n");
 			//switch_rtp_set_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_TIMER_RECLOCK);
@@ -1419,14 +1540,14 @@
 static switch_status_t channel_receive_event(switch_core_session_t *session, switch_event_t *event)
 {
 	switch_channel_t *channel;
-    struct private_object *tech_pvt;
+	struct private_object *tech_pvt;
 	char *subject, *body;
 
-    channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-    tech_pvt = switch_core_session_get_private(session);
-    assert(tech_pvt != NULL);
+	tech_pvt = switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
 
 	if (!(body = switch_event_get_body(event))) {
@@ -1453,15 +1574,14 @@
 
 static const switch_io_routines_t channel_io_routines = {
 	/*.outgoing_channel */ channel_outgoing_channel,
-	/*.answer_channel */ channel_answer_channel,
 	/*.read_frame */ channel_read_frame,
 	/*.write_frame */ channel_write_frame,
 	/*.kill_channel */ channel_kill_channel,
 	/*.waitfor_read */ channel_waitfor_read,
 	/*.waitfor_write */ channel_waitfor_write,
 	/*.send_dtmf */ channel_send_dtmf,
-	/*.receive_message*/ channel_receive_message,
-	/*.receive_event*/ channel_receive_event
+	/*.receive_message */ channel_receive_message,
+	/*.receive_event */ channel_receive_event
 };
 
 static const switch_endpoint_interface_t channel_endpoint_interface = {
@@ -1473,13 +1593,28 @@
 };
 
 
+static switch_api_interface_t debug_api_interface = {
+	/*.interface_name */ "dl_debug",
+	/*.desc */ "DingaLing Presence",
+	/*.function */ dl_debug,
+	/*.syntax */ "dl_debug [true|false]",
+	/*.next */ NULL
+};
+
+static switch_api_interface_t pres_api_interface = {
+	/*.interface_name */ "dl_pres",
+	/*.desc */ "DingaLing Presence",
+	/*.function */ dl_pres,
+	/*.syntax */ "dl_pres <profile_name>",
+	/*.next */ &debug_api_interface
+};
 
 static switch_api_interface_t logout_api_interface = {
 	/*.interface_name */ "dl_logout",
 	/*.desc */ "DingaLing Logout",
 	/*.function */ dl_logout,
 	/*.syntax */ "dl_logout <profile_name>",
-	/*.next */ NULL
+	/*.next */ &pres_api_interface
 };
 
 static switch_api_interface_t login_api_interface = {
@@ -1504,24 +1639,24 @@
 	/*.application_interface */ NULL,
 	/*.api_interface */ &login_api_interface,
 	/*.file_interface */ NULL,
-    /*.speech_interface */ NULL,
-    /*.directory_interface */ NULL,
-    /*.chat_interface */ &channel_chat_interface
-
+	/*.speech_interface */ NULL,
+	/*.directory_interface */ NULL,
+	/*.chat_interface */ &channel_chat_interface
 };
 
 
 /* Make sure when you have 2 sessions in the same scope that you pass the appropriate one to the routines
    that allocate memory or you will have 1 channel with memory allocated from another channel's pool!
 */
-static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-													switch_core_session_t **new_session, switch_memory_pool_t *pool)
+static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session,
+													switch_caller_profile_t *outbound_profile,
+													switch_core_session_t **new_session, switch_memory_pool_t **pool)
 {
 	if ((*new_session = switch_core_session_request(&channel_endpoint_interface, pool)) != 0) {
 		struct private_object *tech_pvt;
 		switch_channel_t *channel;
 		switch_caller_profile_t *caller_profile = NULL;
-		struct mdl_profile *mdl_profile = NULL;
+		mdl_profile_t *mdl_profile = NULL;
 		ldl_session_t *dlsession = NULL;
 		char *profile_name;
 		char *callto;
@@ -1540,7 +1675,7 @@
 			*callto++ = '\0';
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Invalid URL!\n");
-			terminate_session(new_session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+			terminate_session(new_session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 			return SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
 		}
 
@@ -1548,9 +1683,9 @@
 			*dnis++ = '\0';
 		}
 
-        for (p = callto; p && *p; p++) {
-            *p = (char) tolower(*p);
-        }
+		for (p = callto; p && *p; p++) {
+			*p = (char) tolower(*p);
+		}
 
 		if ((p = strchr(profile_name, '@'))) {
 			*p++ = '\0';
@@ -1565,33 +1700,41 @@
 				user = ldl_handle_get_login(mdl_profile->handle);
 			} else {
 				if (!user) {
-					if (strchr(outbound_profile->caller_id_number, '@')) {
-						snprintf(ubuf, sizeof(ubuf), "%s/talk", outbound_profile->caller_id_number);
+					char *id_num;
+					
+					if (!(id_num = outbound_profile->caller_id_number)) {
+						if (!(id_num = outbound_profile->caller_id_name)) {
+							id_num = "nobody";
+						}
+					}
+
+					if (strchr(id_num, '@')) {
+						snprintf(ubuf, sizeof(ubuf), "%s/talk", id_num);
 						user = ubuf;
 					} else {
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Invalid User!\n");
-						terminate_session(new_session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+						snprintf(ubuf, sizeof(ubuf), "%s@%s/talk", id_num, profile_name);
+						user = ubuf;
 					}
 				}
 			}
 
 			if (!ldl_handle_ready(mdl_profile->handle)) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Doh! we are not logged in yet!\n");
-				terminate_session(new_session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+				terminate_session(new_session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 				return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
 			}
 			if (!(full_id = ldl_handle_probe(mdl_profile->handle, callto, user, idbuf, sizeof(idbuf)))) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Unknown Recipient!\n");
-				terminate_session(new_session,  __LINE__, SWITCH_CAUSE_NO_USER_RESPONSE);
+				terminate_session(new_session, __LINE__, SWITCH_CAUSE_NO_USER_RESPONSE);
 				return SWITCH_CAUSE_NO_USER_RESPONSE;
 			}
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Unknown Profile!\n");
-			terminate_session(new_session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+			terminate_session(new_session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 			return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
 		}
-		
-		
+
+
 		switch_core_session_add_stream(*new_session, NULL);
 		if ((tech_pvt = (struct private_object *) switch_core_session_alloc(*new_session, sizeof(struct private_object))) != 0) {
 			memset(tech_pvt, 0, sizeof(*tech_pvt));
@@ -1607,13 +1750,13 @@
 			tech_pvt->dnis = switch_core_session_strdup(*new_session, dnis);
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Hey where is my memory pool?\n");
-			terminate_session(new_session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+			terminate_session(new_session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 			return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
 		}
 
 		if (outbound_profile) {
 			char name[128];
-			
+
 			snprintf(name, sizeof(name), "DingaLing/%s", outbound_profile->destination_number);
 			switch_channel_set_name(channel, name);
 
@@ -1622,7 +1765,7 @@
 			tech_pvt->caller_profile = caller_profile;
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Doh! no caller profile\n");
-			terminate_session(new_session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+			terminate_session(new_session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 			return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
 		}
 
@@ -1633,7 +1776,7 @@
 		tech_pvt->us = switch_core_session_strdup(*new_session, user);
 		tech_pvt->them = switch_core_session_strdup(*new_session, full_id);
 		ldl_session_create(&dlsession, mdl_profile->handle, sess_id, full_id, user, LDL_FLAG_OUTBOUND);
-		
+
 		if (session) {
 			switch_channel_t *calling_channel = switch_core_session_get_channel(session);
 			cid_msg = switch_channel_get_variable(calling_channel, "dl_cid_msg");
@@ -1665,8 +1808,8 @@
 		ldl_session_set_value(dlsession, "caller_id_number", outbound_profile->caller_id_number);
 		tech_pvt->dlsession = dlsession;
 		if (!get_codecs(tech_pvt)) {
-			terminate_session(new_session,  __LINE__, SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL);
-            return SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL;
+			terminate_session(new_session, __LINE__, SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL);
+			return SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL;
 		}
 		switch_channel_set_state(channel, CS_INIT);
 		return SWITCH_CAUSE_SUCCESS;
@@ -1701,7 +1844,7 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass %s!", DL_EVENT_CONNECTED);
 		return SWITCH_STATUS_GENERR;
 	}
-	
+
 	if (switch_event_bind((char *) modname, SWITCH_EVENT_PRESENCE_IN, SWITCH_EVENT_SUBCLASS_ANY, pres_event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 		return SWITCH_STATUS_GENERR;
@@ -1717,7 +1860,8 @@
 		return SWITCH_STATUS_GENERR;
 	}
 
-	if (switch_event_bind((char *) modname, SWITCH_EVENT_ROSTER, SWITCH_EVENT_SUBCLASS_ANY, roster_event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_ROSTER, SWITCH_EVENT_SUBCLASS_ANY, roster_event_handler, NULL)
+		!= SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 		return SWITCH_STATUS_GENERR;
 	}
@@ -1729,7 +1873,7 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static ldl_status handle_loop(ldl_handle_t *handle)
+static ldl_status handle_loop(ldl_handle_t * handle)
 {
 	if (!globals.running) {
 		return LDL_STATUS_FALSE;
@@ -1737,20 +1881,13 @@
 	return LDL_STATUS_SUCCESS;
 }
 
-static switch_status_t init_profile(struct mdl_profile *profile, uint8_t login)
+static switch_status_t init_profile(mdl_profile_t *profile, uint8_t login)
 {
-	if (profile &&
-		profile->login &&
-		profile->password &&
-		profile->dialplan &&
-		profile->message &&
-		profile->ip &&
-		profile->name &&
-		profile->exten) {
+	if (profile && profile->login && profile->password && profile->dialplan && profile->message && profile->ip && profile->name && profile->exten) {
 		ldl_handle_t *handle;
 
 		if (switch_test_flag(profile, TFLAG_TIMER) && !profile->timer_name) {
-			profile->timer_name = switch_core_strdup(module_pool, "soft");			
+			profile->timer_name = switch_core_strdup(module_pool, "soft");
 		}
 
 		if (login) {
@@ -1758,12 +1895,7 @@
 								profile->login,
 								profile->password,
 								profile->server,
-								profile->user_flags,
-								profile->message,
-								handle_loop,
-								handle_signalling,
-								handle_response,
-								profile) == LDL_STATUS_SUCCESS) {
+								profile->user_flags, profile->message, handle_loop, handle_signalling, handle_response, profile) == LDL_STATUS_SUCCESS) {
 				profile->handle = handle;
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Started Thread for %s@%s\n", profile->login, profile->dialplan);
 				switch_core_hash_insert(globals.profile_hash, profile->name, profile);
@@ -1774,7 +1906,7 @@
 			switch_core_hash_insert(globals.profile_hash, profile->name, profile);
 		}
 	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, 
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
 						  "Invalid Profile\n"
 						  "login[%s]\n"
 						  "pass[%s]\n"
@@ -1782,13 +1914,7 @@
 						  "message[%s]\n"
 						  "rtp-ip[%s]\n"
 						  "name[%s]\n"
-						  "exten[%s]\n",
-						  profile->login,
-						  profile->password,
-						  profile->dialplan,
-						  profile->message,
-						  profile->ip,
-						  profile->name,
+						  "exten[%s]\n", profile->login, profile->password, profile->dialplan, profile->message, profile->ip, profile->name,
 						  profile->exten);
 
 		return SWITCH_STATUS_FALSE;
@@ -1808,10 +1934,11 @@
 		while (globals.handles > 0) {
 			switch_yield(100000);
 			x++;
-			if(x > 10) {
+			if (x > 10) {
 				break;
 			}
 		}
+
 		if (globals.init) {
 			ldl_global_destroy();
 		}
@@ -1820,19 +1947,37 @@
 }
 
 
-static void set_profile_val(struct mdl_profile *profile, char *var, char *val)
+static void set_profile_val(mdl_profile_t *profile, char *var, char *val)
 {
-	
+
 	if (!strcasecmp(var, "login")) {
 		profile->login = switch_core_strdup(module_pool, val);
 	} else if (!strcasecmp(var, "password")) {
 		profile->password = switch_core_strdup(module_pool, val);
+	} else if (!strcasecmp(var, "avatar")) {
+		profile->avatar = switch_core_strdup(module_pool, val);
+	} else if (!strcasecmp(var, "odbc-dsn")) {
+#ifdef SWITCH_HAVE_ODBC
+		profile->odbc_dsn = switch_core_strdup(module_pool, val);
+		if ((profile->odbc_user = strchr(profile->odbc_dsn, ':'))) {
+			*profile->odbc_user++ = '\0';
+		}
+		if ((profile->odbc_pass = strchr(profile->odbc_user, ':'))) {
+			*profile->odbc_pass++ = '\0';
+		}
+		
+		
+#else
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "ODBC IS NOT AVAILABLE!\n");
+#endif
 	} else if (!strcasecmp(var, "use-rtp-timer") && switch_true(val)) {
-	  	switch_set_flag(profile, TFLAG_TIMER);
+		switch_set_flag(profile, TFLAG_TIMER);
 	} else if (!strcasecmp(var, "dialplan")) {
 		profile->dialplan = switch_core_strdup(module_pool, val);
+#ifdef AUTO_REPLY // gotta fix looping on this
 	} else if (!strcasecmp(var, "auto-reply")) {
 		profile->auto_reply = switch_core_strdup(module_pool, val);
+#endif
 	} else if (!strcasecmp(var, "name")) {
 		profile->name = switch_core_strdup(module_pool, val);
 	} else if (!strcasecmp(var, "message")) {
@@ -1879,9 +2024,57 @@
 	}
 }
 
+static switch_status_t dl_debug(char *tf, switch_core_session_t *session, switch_stream_handle_t *stream)
+{
+	int on, cur;
+
+	if (session) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	if (tf) {
+		on = switch_true(tf);
+		cur = ldl_global_debug(on);
+	} else {
+		cur = ldl_global_debug(-1);
+	}
+
+
+	stream->write_function(stream, "DEBUG IS NOW %s\n", cur ? "ON" : "OFF");
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+static switch_status_t dl_pres(char *profile_name, switch_core_session_t *session, switch_stream_handle_t *stream)
+{
+	mdl_profile_t *profile;
+
+	if (session) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	if (!profile_name) {
+		stream->write_function(stream, "USAGE: %s\n", pres_api_interface.syntax);
+		return SWITCH_STATUS_SUCCESS;
+	}
+
+	if ((profile = switch_core_hash_find(globals.profile_hash, profile_name))) {
+		if (profile->user_flags & LDL_FLAG_COMPONENT) {
+			sign_on(profile);
+			stream->write_function(stream, "OK\n");
+		} else {
+			stream->write_function(stream, "NO PROFILE %s NOT A COMPONENT\n", profile_name);
+		}
+	} else {
+		stream->write_function(stream, "NO SUCH PROFILE %s\n", profile_name);
+	}
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
 static switch_status_t dl_logout(char *profile_name, switch_core_session_t *session, switch_stream_handle_t *stream)
 {
-	struct mdl_profile *profile;
+	mdl_profile_t *profile;
 
 	if (session) {
 		return SWITCH_STATUS_FALSE;
@@ -1904,20 +2097,20 @@
 
 static switch_status_t dl_login(char *arg, switch_core_session_t *session, switch_stream_handle_t *stream)
 {
-	char *argv[10] = {0};
+	char *argv[10] = { 0 };
 	int argc = 0;
 	char *var, *val, *myarg;
-	struct mdl_profile *profile = NULL;
+	mdl_profile_t *profile = NULL;
 	int x;
 
 	if (session) {
 		return SWITCH_STATUS_FALSE;
 	}
 
-    if (switch_strlen_zero(arg)) {
-        stream->write_function(stream, "USAGE: %s\n", login_api_interface.syntax);
-        return SWITCH_STATUS_SUCCESS;
-    }
+	if (switch_strlen_zero(arg)) {
+		stream->write_function(stream, "USAGE: %s\n", login_api_interface.syntax);
+		return SWITCH_STATUS_SUCCESS;
+	}
 
 	myarg = strdup(arg);
 
@@ -1943,7 +2136,7 @@
 	} else {
 		profile = switch_core_alloc(module_pool, sizeof(*profile));
 
-		for(x = 0; x < argc; x++) {
+		for (x = 0; x < argc; x++) {
 			var = argv[x];
 			if ((val = strchr(var, '='))) {
 				*val++ = '\0';
@@ -1951,7 +2144,7 @@
 			}
 		}
 	}
-	
+
 
 	if (profile && init_profile(profile, 1) == SWITCH_STATUS_SUCCESS) {
 		stream->write_function(stream, "OK\n");
@@ -1966,15 +2159,15 @@
 static switch_status_t load_config(void)
 {
 	char *cf = "dingaling.conf";
-	struct mdl_profile *profile = NULL;
+	mdl_profile_t *profile = NULL;
 	switch_xml_t cfg, xml, settings, param, xmlint;
 
 	memset(&globals, 0, sizeof(globals));
 	globals.running = 1;
-    
-    switch_find_local_ip(globals.guess_ip, sizeof(globals.guess_ip), AF_INET);
 
-	switch_core_hash_init(&globals.profile_hash, module_pool);	
+	switch_find_local_ip(globals.guess_ip, sizeof(globals.guess_ip), AF_INET);
+
+	switch_core_hash_init(&globals.profile_hash, module_pool);
 
 	if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", cf);
@@ -1990,16 +2183,14 @@
 				globals.debug = atoi(val);
 			} else if (!strcasecmp(var, "codec-prefs")) {
 				set_global_codec_string(val);
-				globals.codec_order_last =
-					switch_separate_string(globals.codec_string, ',', globals.codec_order, SWITCH_MAX_CODECS);
+				globals.codec_order_last = switch_separate_string(globals.codec_string, ',', globals.codec_order, SWITCH_MAX_CODECS);
 			} else if (!strcasecmp(var, "codec-rates")) {
 				set_global_codec_rates_string(val);
-				globals.codec_rates_last =
-					switch_separate_string(globals.codec_rates_string, ',', globals.codec_rates, SWITCH_MAX_CODECS);
+				globals.codec_rates_last = switch_separate_string(globals.codec_rates_string, ',', globals.codec_rates, SWITCH_MAX_CODECS);
 			}
 		}
 	}
-	
+
 	if (!(xmlint = switch_xml_child(cfg, "profile"))) {
 		if ((xmlint = switch_xml_child(cfg, "interface"))) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "!!!!!!! DEPRICATION WARNING 'interface' is now 'profile' !!!!!!!\n");
@@ -2018,7 +2209,7 @@
 				globals.init = 1;
 			}
 
-			if(!profile) {
+			if (!profile) {
 				profile = switch_core_alloc(module_pool, sizeof(*profile));
 			}
 			set_profile_val(profile, var, val);
@@ -2040,13 +2231,34 @@
 			snprintf(dbname, sizeof(dbname), "dingaling_%s", profile->name);
 			profile->dbname = switch_core_strdup(module_pool, dbname);
 
-			if ((db = switch_core_db_open_file(profile->dbname))) {
-				switch_core_db_test_reactive(db, "select * from subscriptions", sub_sql);
+
+#ifdef SWITCH_HAVE_ODBC
+			if (profile->odbc_dsn) {
+				if (!(profile->master_odbc = switch_odbc_handle_new(profile->odbc_dsn, profile->odbc_user, profile->odbc_pass))) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Cannot Open ODBC Database!\n");
+					continue;
+					
+				}
+				if (switch_odbc_handle_connect(profile->master_odbc) != SWITCH_ODBC_SUCCESS) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Cannot Open ODBC Database!\n");
+					continue;
+				}
+
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Connected ODBC DSN: %s\n", profile->odbc_dsn);
+				switch_odbc_handle_exec(profile->master_odbc, sub_sql, NULL);
+				//mdl_execute_sql(profile, sub_sql, NULL);
 			} else {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Cannot Open SQL Database!\n");
-				continue;
+#endif
+				if ((db = switch_core_db_open_file(profile->dbname))) {
+					switch_core_db_test_reactive(db, "select * from jabber_subscriptions", sub_sql);
+				} else {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Cannot Open SQL Database!\n");
+					continue;
+				}
+				switch_core_db_close(db);
+#ifdef SWITCH_HAVE_ODBC
 			}
-			switch_core_db_close(db);
+#endif
 		}
 
 		if (profile) {
@@ -2077,32 +2289,11 @@
 }
 
 
-static void execute_sql(char *dbname, char *sql, switch_mutex_t *mutex)
-{
-	switch_core_db_t *db;
-
-	if (mutex) {
-		switch_mutex_lock(mutex);
-	}
-
-	if (!(db = switch_core_db_open_file(dbname))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", dbname);
-		goto end;
-	}
-	
-	switch_core_db_persistant_execute(db, sql, 25);
-	switch_core_db_close(db);
-
- end:
-	if (mutex) {
-		switch_mutex_unlock(mutex);
-	}
-}
-
 static void do_vcard(ldl_handle_t *handle, char *to, char *from, char *id)
 {
 	char *params = NULL, *real_to, *to_user, *xmlstr = NULL, *to_host = NULL;
 	switch_xml_t domain, xml = NULL, user, vcard;
+	int sent = 0;
 
 	if (!strncasecmp(to, "user+", 5)) {
 		real_to = to + 5;
@@ -2119,34 +2310,30 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
 		goto end;
 	}
-	
+
 	if (!to_host) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Missing Host!\n");
 		goto end;
 	}
 
-	if (!(params = switch_mprintf("to=%s@%s&from=%s&object=vcard",
-								  to_user,
-								  to_host,
-								  from
-								  ))) {
+	if (!(params = switch_mprintf("to=%s@%s&from=%s&object=vcard", to_user, to_host, from))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
 		goto end;
 	}
 
-	
+
 	if (switch_xml_locate("directory", "domain", "name", to_host, &xml, &domain, params) != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "can't find domain for [%s@%s]\n", to_user, to_host);
+		//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "can't find domain for [%s@%s]\n", to_user, to_host);
 		goto end;
 	}
 
 	if (!(user = switch_xml_find_child(domain, "user", "id", to_user))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "can't find user [%s@%s]\n", to_user, to_host);
+		//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "can't find user [%s@%s]\n", to_user, to_host);
 		goto end;
 	}
 
 	if (!(vcard = switch_xml_child(user, "vcard"))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "can't find <vcard> tag for user [%s@%s]\n", to_user, to_host);
+		//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "can't find <vcard> tag for user [%s@%s]\n", to_user, to_host);
 		goto end;
 	}
 
@@ -2154,23 +2341,31 @@
 
 	if ((xmlstr = switch_xml_toxml(vcard))) {
 		ldl_handle_send_vcard(handle, to, from, id, xmlstr);
+		sent = 1;
 	} else {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
 	}
 
  end:
-	if (xml) switch_xml_free(xml);
+
+	if (!sent) {
+		ldl_handle_send_vcard(handle, to, from, id, NULL);
+	}
+
+	if (xml)
+		switch_xml_free(xml);
 	switch_safe_free(to_user);
 	switch_safe_free(params);
 	switch_safe_free(xmlstr);
 }
 
-static ldl_status handle_signalling(ldl_handle_t *handle, ldl_session_t *dlsession, ldl_signal_t dl_signal, char *to, char *from, char *subject, char *msg)
+static ldl_status handle_signalling(ldl_handle_t * handle, ldl_session_t * dlsession, ldl_signal_t dl_signal, char *to, char *from, char *subject,
+									char *msg)
 {
-	struct mdl_profile *profile = NULL;
+	mdl_profile_t *profile = NULL;
 	switch_core_session_t *session = NULL;
 	switch_channel_t *channel = NULL;
-    struct private_object *tech_pvt = NULL;
+	struct private_object *tech_pvt = NULL;
 	switch_event_t *event;
 	ldl_status status = LDL_STATUS_SUCCESS;
 	char *sql;
@@ -2185,43 +2380,55 @@
 
 	if (!dlsession) {
 		if (profile->user_flags & LDL_FLAG_COMPONENT) {
-			switch(dl_signal) {
+			switch (dl_signal) {
 			case LDL_SIGNAL_VCARD:
 				do_vcard(handle, to, from, subject);
 				break;
 			case LDL_SIGNAL_UNSUBSCRIBE:
 
-				if ((sql = switch_mprintf("delete from subscriptions where sub_from='%q' and sub_to='%q';", from, to))) {
-					execute_sql(profile->dbname, sql, profile->mutex);
+				if ((sql = switch_mprintf("delete from jabber_subscriptions where sub_from='%q' and sub_to='%q';", from, to))) {
+					mdl_execute_sql(profile, sql, profile->mutex);
 					switch_core_db_free(sql);
 				}
 
 				break;
 
 			case LDL_SIGNAL_SUBSCRIBE:
-				
-				if ((sql = switch_mprintf("delete from subscriptions where sub_from='%q' and sub_to='%q';\n"
-										  "insert into subscriptions values('%q','%q','%q','%q');\n", from, to, from, to, msg, subject))) {
-					execute_sql(profile->dbname, sql, profile->mutex);
-					switch_core_db_free(sql);
-				}
-
-				if (is_special(to)) {
-					ldl_handle_send_presence(profile->handle, to, from, NULL, NULL, "Click To Call");
-				}
-
+				if (profile->user_flags & LDL_FLAG_COMPONENT && ldl_jid_domcmp(from, to)) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Attempt to add presence from/to our own domain [%s][%s]\n", from, to);
+				} else {
+					switch_mutex_lock(profile->mutex);
+					if ((sql = switch_mprintf("delete from jabber_subscriptions where sub_from='%q' and sub_to='%q'", from, to))) {
+						mdl_execute_sql(profile, sql, NULL);
+						switch_core_db_free(sql);
+					}
+					if ((sql = switch_mprintf("insert into jabber_subscriptions values('%q','%q','%q','%q');\n", 
+											  switch_str_nil(from),
+											  switch_str_nil(to),
+											  switch_str_nil(msg),
+											  switch_str_nil(subject)))) {
+						mdl_execute_sql(profile, sql, NULL);
+						switch_core_db_free(sql);
+					}
+					switch_mutex_unlock(profile->mutex);
+					if (is_special(to)) {
+						ldl_handle_send_presence(profile->handle, to, from, NULL, NULL, "Click To Call", profile->avatar);
+					} else {
+						ldl_handle_send_presence(profile->handle, to, from, NULL, NULL, "Authenticated.\nCome to ClueCon!\nhttp://www.cluecon.com", profile->avatar);
+					}
 #if 0
-				if (is_special(to)) {
-					if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", MDL_CHAT_PROTO);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->login);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s",  to);
-						//switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "unknown");
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Click To Call");
-						switch_event_fire(&event);
+					if (is_special(to)) {
+						if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
+							switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", MDL_CHAT_PROTO);
+							switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->login);
+							switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", to);
+							//switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "unknown");
+							switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Click To Call");
+							switch_event_fire(&event);
+						}
 					}
-				}
 #endif
+				}
 				break;
 			case LDL_SIGNAL_ROSTER:
 				if (switch_event_create(&event, SWITCH_EVENT_ROSTER) == SWITCH_STATUS_SUCCESS) {
@@ -2232,43 +2439,44 @@
 				break;
 			case LDL_SIGNAL_PRESENCE_PROBE:
 				if (is_special(to)) {
-                    ldl_handle_send_presence(profile->handle, to, from, NULL, NULL, "Click To Call");
-                } else {
+					ldl_handle_send_presence(profile->handle, to, from, NULL, NULL, "Click To Call", profile->avatar);
+				} else {
 					if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_PROBE) == SWITCH_STATUS_SUCCESS) {
 						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", MDL_CHAT_PROTO);
 						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->login);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s",  from);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "to", "%s",  to);
+						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", from);
+						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "to", "%s", to);
 						switch_event_fire(&event);
 					}
-                }
-                break;
+				}
+				break;
 			case LDL_SIGNAL_PRESENCE_IN:
-				
-				if ((sql = switch_mprintf("update subscriptions set show='%q', status='%q' where sub_from='%q'", msg, subject, from))) {
-					execute_sql(profile->dbname, sql, profile->mutex);
+
+				if ((sql = switch_mprintf("update jabber_subscriptions set show_pres='%q', status='%q' where sub_from='%q'", 
+										  switch_str_nil(msg), switch_str_nil(subject), switch_str_nil(from)))) {
+					mdl_execute_sql(profile, sql, profile->mutex);
 					switch_core_db_free(sql);
 				}
-				
+
 				if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
 					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", MDL_CHAT_PROTO);
 					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->login);
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s",  from);
+					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", from);
 					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "%s", msg);
 					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "%s", subject);
 					switch_event_fire(&event);
 				}
 
-				
+
 				if (is_special(to)) {
-					ldl_handle_send_presence(profile->handle, to, from, NULL, NULL, "Click To Call");
+					ldl_handle_send_presence(profile->handle, to, from, NULL, NULL, "Click To Call", profile->avatar);
 				}
 #if 0
 				if (is_special(to)) {
 					if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
 						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", MDL_CHAT_PROTO);
 						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->login);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s",  to);
+						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", to);
 						//switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "unknown");
 						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Click To Call");
 						switch_event_fire(&event);
@@ -2278,9 +2486,10 @@
 				break;
 
 			case LDL_SIGNAL_PRESENCE_OUT:
-				
-				if ((sql = switch_mprintf("update subscriptions set show='%q', status='%q' where sub_from='%q'", msg, subject, from))) {
-					execute_sql(profile->dbname, sql, profile->mutex);
+
+				if ((sql = switch_mprintf("update jabber_subscriptions set show_pres='%q', status='%q' where sub_from='%q'", 
+										  switch_str_nil(msg), switch_str_nil(subject), switch_str_nil(from)))) {
+					mdl_execute_sql(profile, sql, profile->mutex);
 					switch_core_db_free(sql);
 				}
 				if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_OUT) == SWITCH_STATUS_SUCCESS) {
@@ -2293,20 +2502,21 @@
 			default:
 				break;
 			}
-		} 
+		}
 
-		switch(dl_signal) {
-		case LDL_SIGNAL_MSG: {
+		switch (dl_signal) {
+		case LDL_SIGNAL_MSG:{
 			switch_chat_interface_t *ci;
 			char *proto = MDL_CHAT_PROTO;
 			char *pproto = NULL, *ffrom = NULL;
 			char *hint;
-
+#ifdef AUTO_REPLY
 			if (profile->auto_reply) {
 				ldl_handle_send_msg(handle,
-									(profile->user_flags & LDL_FLAG_COMPONENT) ? to : ldl_handle_get_login(profile->handle),
-									from, "", profile->auto_reply);
+									(profile->user_flags & LDL_FLAG_COMPONENT) ? to : ldl_handle_get_login(profile->handle), from, "",
+									profile->auto_reply);
 			}
+#endif
 
 			if (strchr(to, '+')) {
 				pproto = strdup(to);
@@ -2360,12 +2570,12 @@
 			break;
 		default:
 			break;
-			
+
 		}
 		status = LDL_STATUS_SUCCESS;
 		goto done;
 	}
-	
+
 
 	if ((session = ldl_session_get_private(dlsession))) {
 		tech_pvt = switch_core_session_get_private(session);
@@ -2373,7 +2583,7 @@
 
 		channel = switch_core_session_get_channel(session);
 		assert(channel != NULL);
-		
+
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "using Existing session for %s\n", ldl_session_get_id(dlsession));
 
 		if (switch_channel_get_state(channel) >= CS_HANGUP) {
@@ -2383,15 +2593,22 @@
 		}
 
 	} else {
-		if (dl_signal != LDL_SIGNAL_INITIATE) {
+		if (dl_signal != LDL_SIGNAL_INITIATE && !msg) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Session is already dead\n");
 			status = LDL_STATUS_FALSE;
 			goto done;
 		}
 		if ((session = switch_core_session_request(&channel_endpoint_interface, NULL)) != 0) {
 			switch_core_session_add_stream(session, NULL);
+
 			
 			if ((tech_pvt = (struct private_object *) switch_core_session_alloc(session, sizeof(struct private_object))) != 0) {
+				char *exten;
+				char *context;
+				char *cid_name;
+				char *cid_num;
+				char *tmp, *t, *them = NULL;
+
 				memset(tech_pvt, 0, sizeof(*tech_pvt));
 				switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
 				tech_pvt->flags |= globals.flags;
@@ -2404,10 +2621,93 @@
 				tech_pvt->local_port = switch_rtp_request_port();
 				switch_set_flag_locked(tech_pvt, TFLAG_ANSWER);
 				tech_pvt->recip = switch_core_session_strdup(session, from);
+				if (!(exten = ldl_session_get_value(dlsession, "dnis"))) {
+					exten = profile->exten;
+					/* if it's _auto_ set the extension to match the username portion of the called address */
+					if (!strcmp(exten, "_auto_")) {
+						if ((t = ldl_session_get_callee(dlsession))) {
+							if ((them = strdup(t))) {
+								char *a, *b, *p;
+								if ((p = strchr(them, '/'))) {
+									*p = '\0';
+								}
+
+								if ((a = strchr(them, '+')) && (b = strrchr(them, '+')) && a != b) {
+									*b++ = '\0';
+									switch_channel_set_variable(channel, "dl_user", them);
+									switch_channel_set_variable(channel, "dl_host", b);
+								}
+								exten = them;
+							}
+						}
+					}
+				}
+
+				if (!(context = ldl_session_get_value(dlsession, "context"))) {
+					context = profile->context;
+				}
+
+				if (!(cid_name = ldl_session_get_value(dlsession, "caller_id_name"))) {
+					cid_name = tech_pvt->recip;
+				}
+
+				if (!(cid_num = ldl_session_get_value(dlsession, "caller_id_number"))) {
+					cid_num = tech_pvt->recip;
+				}
+
+				/* context of "_auto_" means set it to the domain */
+				if (profile->context && !strcmp(profile->context, "_auto_")) {
+					context = profile->name;
+				}
+
+				tech_pvt->them = switch_core_session_strdup(session, ldl_session_get_callee(dlsession));
+				tech_pvt->us = switch_core_session_strdup(session, ldl_session_get_caller(dlsession));
+
+				if ((tmp = strdup(tech_pvt->us))) {
+					char *p, *q;
+
+					if ((p = strchr(tmp, '@'))) {
+						*p++ = '\0';
+						if ((q = strchr(p, '/'))) {
+							*q = '\0';
+						}
+						switch_channel_set_variable(channel, "dl_from_user", tmp);
+						switch_channel_set_variable(channel, "dl_from_host", p);
+					}
+
+					switch_safe_free(tmp);
+				}
+
+				if (!tech_pvt->caller_profile) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
+									  "Creating an identity for %s %s <%s> %s\n", ldl_session_get_id(dlsession), cid_name, cid_num, exten);
+
+					if ((tech_pvt->caller_profile = switch_caller_profile_new(switch_core_session_get_pool(session),
+																			  ldl_handle_get_login(profile->handle),
+																			  profile->dialplan,
+																			  cid_name,
+																			  cid_num,
+																			  ldl_session_get_ip(dlsession),
+																			  ldl_session_get_value(dlsession,
+																									"ani"),
+																			  ldl_session_get_value(dlsession,
+																									"aniii"),
+																			  ldl_session_get_value(dlsession,
+																									"rdnis"), (char *) modname, context,
+																			  exten)) != 0) {
+						char name[128];
+						snprintf(name, sizeof(name), "DingaLing/%s", tech_pvt->caller_profile->destination_number);
+						switch_channel_set_name(channel, name);
+						switch_channel_set_caller_profile(channel, tech_pvt->caller_profile);
+					}
+				}
+
+				switch_safe_free(them);
+
 				switch_set_flag_locked(tech_pvt, TFLAG_TRANSPORT_ACCEPT);
 			} else {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Hey where is my memory pool?\n");
-				terminate_session(&session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+				terminate_session(&session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 				status = LDL_STATUS_FALSE;
 				goto done;
 			}
@@ -2424,9 +2724,9 @@
 
 	}
 
-	switch(dl_signal) {
+	switch (dl_signal) {
 	case LDL_SIGNAL_MSG:
-		if (msg) { 
+		if (msg) {
 			if (*msg == '+') {
 				switch_channel_queue_dtmf(channel, msg + 1);
 				switch_set_flag_locked(tech_pvt, TFLAG_DTMF);
@@ -2440,12 +2740,12 @@
 		if (switch_event_create(&event, SWITCH_EVENT_MESSAGE) == SWITCH_STATUS_SUCCESS) {
 			char *hint = NULL, *p, *freeme = NULL;
 
-			hint = from;			
+			hint = from;
 			if (strchr(from, '/')) {
 				freeme = strdup(from);
 				p = strchr(freeme, '/');
 				*p = '\0';
-				from = freeme;				
+				from = freeme;
 			}
 
 			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", MDL_CHAT_PROTO);
@@ -2478,7 +2778,7 @@
 				if (!strcasecmp(msg, "accept")) {
 					switch_set_flag_locked(tech_pvt, TFLAG_ANSWER);
 					if (!do_candidates(tech_pvt, 0)) {
-						terminate_session(&session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+						terminate_session(&session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 						status = LDL_STATUS_FALSE;
 						goto done;
 					}
@@ -2492,42 +2792,43 @@
 
 
 			if (!get_codecs(tech_pvt)) {
-				terminate_session(&session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+				terminate_session(&session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 				status = LDL_STATUS_FALSE;
 				goto done;
 			}
 
-			
+
 			if (ldl_session_get_payloads(dlsession, &payloads, &len) == LDL_STATUS_SUCCESS) {
-                unsigned int x, y;
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%u payloads\n", len);
-				for(x = 0; x < len; x++) {
+				unsigned int x, y;
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%u payloads\n", len);
+				for (x = 0; x < len; x++) {
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Available Payload %s %u\n", payloads[x].name, payloads[x].id);
-					for(y = 0; y < tech_pvt->num_codecs; y++) {
+					for (y = 0; y < tech_pvt->num_codecs; y++) {
 						char *name = tech_pvt->codecs[y]->iananame;
 
 						if (!strncasecmp(name, "ilbc", 4)) {
 							name = "ilbc";
 						}
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "compare %s %d/%d to %s %d/%d\n", 
-                                          payloads[x].name, payloads[x].id, payloads[x].rate,
-                                          name, tech_pvt->codecs[y]->ianacode, tech_pvt->codecs[y]->samples_per_second);
+						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "compare %s %d/%d to %s %d/%d\n",
+										  payloads[x].name, payloads[x].id, payloads[x].rate,
+										  name, tech_pvt->codecs[y]->ianacode, tech_pvt->codecs[y]->samples_per_second);
 						if (tech_pvt->codecs[y]->ianacode > 95) {
 							match = strcasecmp(name, payloads[x].name) ? 0 : 1;
 						} else {
 							match = (payloads[x].id == tech_pvt->codecs[y]->ianacode) ? 1 : 0;
 						}
-						
+
 						if (match && payloads[x].rate == tech_pvt->codecs[y]->samples_per_second) {
 							tech_pvt->codec_index = y;
-							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Choosing Payload index %u %s %u\n", y, payloads[x].name, payloads[x].id);
+							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Choosing Payload index %u %s %u\n", y, payloads[x].name,
+											  payloads[x].id);
 							tech_pvt->codec_name = tech_pvt->codecs[y]->iananame;
 							tech_pvt->codec_num = tech_pvt->codecs[y]->ianacode;
-							tech_pvt->r_codec_num = (switch_payload_t)(payloads[x].id);
+							tech_pvt->r_codec_num = (switch_payload_t) (payloads[x].id);
 							tech_pvt->codec_rate = payloads[x].rate;
 							if (!switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
 								if (!do_describe(tech_pvt, 0)) {
-									terminate_session(&session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+									terminate_session(&session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 									status = LDL_STATUS_FALSE;
 									goto done;
 								}
@@ -2539,14 +2840,14 @@
 				}
 				if (!match && !switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
 					if (!do_describe(tech_pvt, 0)) {
-						terminate_session(&session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+						terminate_session(&session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 						status = LDL_STATUS_FALSE;
 						goto done;
 					}
 				}
 			}
 		}
-		
+
 		break;
 	case LDL_SIGNAL_CANDIDATES:
 		if (dl_signal) {
@@ -2562,47 +2863,44 @@
 				goto done;
 			}
 
-				
+
 			if (tech_pvt->remote_ip) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Already picked an IP [%s]\n", tech_pvt->remote_ip);
 				break;
 			}
 
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%u candidates\n", len);
-			for(x = 0; x < len; x++) {
+			for (x = 0; x < len; x++) {
 				uint8_t lanaddr = 0;
 
 				if (profile->lanaddr) {
 					lanaddr = strncasecmp(candidates[x].address, profile->lanaddr, strlen(profile->lanaddr)) ? 0 : 1;
-				} 
+				}
 
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "candidates %s:%d\n", candidates[x].address, candidates[x].port);
-					
-				if (!strcasecmp(candidates[x].protocol, "udp") && (!strcasecmp(candidates[x].type, "local") || !strcasecmp(candidates[x].type, "stun")) && 
-					((profile->lanaddr && lanaddr) ||
-					 (strncasecmp(candidates[x].address, "10.", 3) && 
-					  strncasecmp(candidates[x].address, "192.168.", 8) &&
-					  strncasecmp(candidates[x].address, "127.", 4) &&
-					  strncasecmp(candidates[x].address, "255.", 4) &&
-					  strncasecmp(candidates[x].address, "0.", 2) &&
-					  strncasecmp(candidates[x].address, "1.", 2) &&
-					  strncasecmp(candidates[x].address, "2.", 2) &&
-					  strncasecmp(candidates[x].address, "172.16.", 7) &&
-					  strncasecmp(candidates[x].address, "172.17.", 7) &&
-					  strncasecmp(candidates[x].address, "172.18.", 7) &&
-					  strncasecmp(candidates[x].address, "172.19.", 7) &&
-					  strncasecmp(candidates[x].address, "172.2", 5) &&
-					  strncasecmp(candidates[x].address, "172.30.", 7) &&
-					  strncasecmp(candidates[x].address, "172.31.", 7)  &&
-					  strncasecmp(candidates[x].address, "192.0.2.", 8)  && // 192.0.0.0 - 192.0.127.255 is marked as reserved, should we filter all of them?
-					  strncasecmp(candidates[x].address, "169.254.", 8)
-					  ))) {
+
+				// 192.0.0.0 - 192.0.127.255 is marked as reserved, should we filter all of them?
+				if (!strcasecmp(candidates[x].protocol, "udp") &&
+					(!strcasecmp(candidates[x].type, "local") || !strcasecmp(candidates[x].type, "stun")) &&
+					((profile->lanaddr &&
+					  lanaddr) || (strncasecmp(candidates[x].address, "10.", 3) &&
+								   strncasecmp(candidates[x].address, "192.168.", 8) &&
+								   strncasecmp(candidates[x].address, "127.", 4) &&
+								   strncasecmp(candidates[x].address, "255.", 4) &&
+								   strncasecmp(candidates[x].address, "0.", 2) &&
+								   strncasecmp(candidates[x].address, "1.", 2) &&
+								   strncasecmp(candidates[x].address, "2.", 2) &&
+								   strncasecmp(candidates[x].address, "172.16.", 7) &&
+								   strncasecmp(candidates[x].address, "172.17.", 7) &&
+								   strncasecmp(candidates[x].address, "172.18.", 7) &&
+								   strncasecmp(candidates[x].address, "172.19.", 7) &&
+								   strncasecmp(candidates[x].address, "172.2", 5) &&
+								   strncasecmp(candidates[x].address, "172.30.", 7) &&
+								   strncasecmp(candidates[x].address, "172.31.", 7) &&
+								   strncasecmp(candidates[x].address, "192.0.2.", 8) &&
+								   strncasecmp(candidates[x].address, "169.254.", 8)
+								   ))) {
 					ldl_payload_t payloads[5];
-					char *exten;
-					char *context;
-					char *cid_name;
-					char *cid_num;
-					char *tmp, *t, *them = NULL;
 
 					memset(payloads, 0, sizeof(payloads));
 
@@ -2613,113 +2911,36 @@
 						ldl_session_accept_candidate(dlsession, &candidates[x]);
 					}
 
-					if (!(exten = ldl_session_get_value(dlsession, "dnis"))) {
-						exten = profile->exten;
-						/* if it's _auto_ set the extension to match the username portion of the called address */
-						if (!strcmp(exten, "_auto_")) {
-							if ((t = ldl_session_get_callee(dlsession))) {
-								if ((them = strdup(t))) {
-									char *a, *b, *p;
-									if ((p = strchr(them, '/'))) {
-										*p = '\0';
-									}
-
-									if ((a = strchr(them, '+')) && (b = strrchr(them, '+')) && a != b) {
-										*b++ = '\0';
-										switch_channel_set_variable(channel, "dl_user", them);
-										switch_channel_set_variable(channel, "dl_host", b);
-									}
-									exten = them;
-								}
-							}
-						}
-					}
-						
-					if (!(context = ldl_session_get_value(dlsession, "context"))) {
-						context = profile->context;
-					}
-
-					if (!(cid_name = ldl_session_get_value(dlsession, "caller_id_name"))) {
-						cid_name = tech_pvt->recip;
-					}
-
-					if (!(cid_num = ldl_session_get_value(dlsession, "caller_id_number"))) {
-						cid_num = tech_pvt->recip;
-					}
-
-					/* context of "_auto_" means set it to the domain */
-					if (profile->context && !strcmp(profile->context, "_auto_")) {
-						context = profile->name;
-					}
-			
-					tech_pvt->them = switch_core_session_strdup(session, ldl_session_get_callee(dlsession));
-					tech_pvt->us = switch_core_session_strdup(session, ldl_session_get_caller(dlsession));
-
-					if ((tmp = strdup(tech_pvt->us))) {
-						char *p, *q;
-
-						if ((p = strchr(tmp, '@'))) {
-							*p++ = '\0';
-							if ((q = strchr(p, '/'))) {
-								*q = '\0';
-							}
-							switch_channel_set_variable(channel, "dl_from_user", tmp);
-							switch_channel_set_variable(channel, "dl_from_host", p);
-						}
-
-						switch_safe_free(tmp);
-					}
-						
-					if (!tech_pvt->caller_profile) {
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Creating an identity for %s %s <%s> %s\n", 
-										  ldl_session_get_id(dlsession), cid_name, cid_num, exten);
-			
-						if ((tech_pvt->caller_profile = switch_caller_profile_new(switch_core_session_get_pool(session),
-																				  ldl_handle_get_login(profile->handle),
-																				  profile->dialplan,
-																				  cid_name,
-																				  cid_num,
-																				  ldl_session_get_ip(dlsession),
-																				  ldl_session_get_value(dlsession, "ani"),
-																				  ldl_session_get_value(dlsession, "aniii"),
-																				  ldl_session_get_value(dlsession, "rdnis"),
-																				  (char *)modname,
-																				  context,
-																				  exten)) != 0) {
-							char name[128];
-							snprintf(name, sizeof(name), "DingaLing/%s", tech_pvt->caller_profile->destination_number);
-							switch_channel_set_name(channel, name);
-							switch_channel_set_caller_profile(channel, tech_pvt->caller_profile);
-						}
+					if (!strcasecmp(subject, "candidates")) {
+						switch_set_flag_locked(tech_pvt, TFLAG_TRANSPORT_ACCEPT);
+						switch_set_flag_locked(tech_pvt, TFLAG_ANSWER);
 					}
 
-					switch_safe_free(them);
-						
 					if (lanaddr) {
 						switch_set_flag_locked(tech_pvt, TFLAG_LANADDR);
 					}
 
 					if (!get_codecs(tech_pvt)) {
-						terminate_session(&session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+						terminate_session(&session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 						status = LDL_STATUS_FALSE;
 						goto done;
 					}
 
-						
+
 					tech_pvt->remote_ip = switch_core_session_strdup(session, candidates[x].address);
 					ldl_session_set_ip(dlsession, tech_pvt->remote_ip);
 					tech_pvt->remote_port = candidates[x].port;
 					tech_pvt->remote_user = switch_core_session_strdup(session, candidates[x].username);
 
-						
+
 					if (!switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
 						if (!do_candidates(tech_pvt, 0)) {
-							terminate_session(&session,  __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+							terminate_session(&session, __LINE__, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 							status = LDL_STATUS_FALSE;
 							goto done;
 						}
 					}
-						
+
 					status = LDL_STATUS_SUCCESS;
 					goto done;
 				}
@@ -2727,18 +2948,18 @@
 		}
 		break;
 	case LDL_SIGNAL_REJECT:
-        if (channel) {
+		if (channel) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "reject %s\n", switch_channel_get_name(channel));
-			terminate_session(&session,  __LINE__, SWITCH_CAUSE_CALL_REJECTED);
+			terminate_session(&session, __LINE__, SWITCH_CAUSE_CALL_REJECTED);
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "End Call (Rejected)\n");
 			goto done;
 		}
-        break;
+		break;
 	case LDL_SIGNAL_ERROR:
 	case LDL_SIGNAL_TERMINATE:
 		if (channel) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "hungup %s %u %d\n", switch_channel_get_name(channel));
-			terminate_session(&session,  __LINE__, SWITCH_CAUSE_NORMAL_CLEARING);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "hungup %s\n", switch_channel_get_name(channel));
+			terminate_session(&session, __LINE__, SWITCH_CAUSE_NORMAL_CLEARING);
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "End Call\n");
 			goto done;
 		}
@@ -2750,11 +2971,11 @@
 	}
 
  done:
-	
+
 	return status;
 }
 
-static ldl_status handle_response(ldl_handle_t *handle, char *id)
+static ldl_status handle_response(ldl_handle_t * handle, char *id)
 {
 	return LDL_STATUS_SUCCESS;
 }

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_iax/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_iax/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_iax/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,17 +1,11 @@
-LDFLAGS += -liax -L/usr/local/lib
+BASE=../../../..
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+IAX_DIR=$(BASE)/libs/iax
+IAXLA=$(IAX_DIR)/src/libiax.la
+LOCAL_CFLAGS=-I$(IAX_DIR)/src
+LOCAL_LIBADD=$(IAXLA)
+include $(BASE)/build/modmake.rules
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install iax --enable-newjb --prefix=$(PREFIX)
+$(IAXLA): $(IAX_DIR) $(IAX_DIR)/.update
+	cd $(IAX_DIR) && $(MAKE)
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
-
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_iax/mod_iax.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_iax/mod_iax.c	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_iax/mod_iax.c	Tue Apr 24 10:14:28 2007
@@ -31,15 +31,11 @@
  */
 #include <switch.h>
 
-#ifdef WIN32
 #include <iax2.h>
 #include <iax-client.h>
 #include <iax2-parser.h>
+#ifdef WIN32
 #include <sys/timeb.h>
-#else
-#include <iax/iax2.h>
-#include <iax/iax-client.h>
-#include <iax/iax2-parser.h>
 #endif
 
 static const char modname[] = "mod_iax";
@@ -86,7 +82,7 @@
 	switch_codec_t read_codec;
 	switch_codec_t write_codec;
 	switch_frame_t read_frame;
-	unsigned char databuf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
+	unsigned char databuf[SWITCH_RECOMMENDED_BUFFER_SIZE];
 	switch_core_session_t *session;
 	struct iax_session *iax_session;
 	switch_caller_profile_t *caller_profile;
@@ -102,13 +98,12 @@
 
 
 SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_dialplan, globals.dialplan)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_codec_string, globals.codec_string)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_codec_rates_string, globals.codec_rates_string)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_ip, globals.ip)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_codec_string, globals.codec_string)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_codec_rates_string, globals.codec_rates_string)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_ip, globals.ip)
 
 
-	 static char *IAXNAMES[] =
-		 { "IAX_EVENT_CONNECT", "IAX_EVENT_ACCEPT", "IAX_EVENT_HANGUP", "IAX_EVENT_REJECT", "IAX_EVENT_VOICE",
+	 static char *IAXNAMES[] = { "IAX_EVENT_CONNECT", "IAX_EVENT_ACCEPT", "IAX_EVENT_HANGUP", "IAX_EVENT_REJECT", "IAX_EVENT_VOICE",
 		 "IAX_EVENT_DTMF", "IAX_EVENT_TIMEOUT", "IAX_EVENT_LAGRQ", "IAX_EVENT_LAGRP", "IAX_EVENT_RINGA",
 		 "IAX_EVENT_PING", "IAX_EVENT_PONG", "IAX_EVENT_BUSY", "IAX_EVENT_ANSWER", "IAX_EVENT_IMAGE",
 		 "IAX_EVENT_AUTHRQ", "IAX_EVENT_AUTHRP", "IAX_EVENT_REGREQ", "IAX_EVENT_REGACK",
@@ -213,9 +208,8 @@
 	IAX_QUERY = 2
 } iax_io_t;
 
-static switch_status_t iax_set_codec(private_t *tech_pvt, struct iax_session *iax_session,
-								   unsigned int *format, unsigned int *cababilities, unsigned short *samprate,
-								   iax_io_t io)
+static switch_status_t iax_set_codec(private_t * tech_pvt, struct iax_session *iax_session,
+									 unsigned int *format, unsigned int *cababilities, unsigned short *samprate, iax_io_t io)
 {
 	char *dname = NULL;
 	//int rate = 8000;
@@ -228,16 +222,11 @@
 	uint32_t interval = 0;
 
 	if (globals.codec_string) {
-		if ((num_codecs = switch_loadable_module_get_codecs_sorted(codecs,
-																	SWITCH_MAX_CODECS,
-																	globals.codec_order,
-																	globals.codec_order_last)) <= 0) {
+		if ((num_codecs = switch_loadable_module_get_codecs_sorted(codecs, SWITCH_MAX_CODECS, globals.codec_order, globals.codec_order_last)) <= 0) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "NO codecs?\n");
 			return SWITCH_STATUS_GENERR;
 		}
-	} else
-		if (((num_codecs =
-			 switch_loadable_module_get_codecs(switch_core_session_get_pool(tech_pvt->session), codecs, SWITCH_MAX_CODECS))) <= 0) {
+	} else if (((num_codecs = switch_loadable_module_get_codecs(switch_core_session_get_pool(tech_pvt->session), codecs, SWITCH_MAX_CODECS))) <= 0) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "NO codecs?\n");
 		return SWITCH_STATUS_GENERR;
 	}
@@ -248,7 +237,7 @@
 			unsigned int codec = iana2ast(imp->ianacode);
 			if (io == IAX_QUERY && !(codec & local_cap)) {
 				iax_pref_codec_add(iax_session, codec);
-			}	
+			}
 			local_cap |= codec;
 		}
 	}
@@ -426,12 +415,11 @@
 static switch_status_t channel_on_ring(switch_core_session_t *session);
 static switch_status_t channel_on_loopback(switch_core_session_t *session);
 static switch_status_t channel_on_transmit(switch_core_session_t *session);
-static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-													switch_core_session_t **new_session, switch_memory_pool_t *pool);
-static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-										switch_io_flag_t flags, int stream_id);
-static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-										 switch_io_flag_t flags, int stream_id);
+static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session,
+													switch_caller_profile_t *outbound_profile,
+													switch_core_session_t **new_session, switch_memory_pool_t **pool);
+static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id);
+static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id);
 static switch_status_t channel_kill_channel(switch_core_session_t *session, int sig);
 
 
@@ -447,14 +435,14 @@
 	}
 }
 
-static void tech_init(private_t *tech_pvt, switch_core_session_t *session)
+static void tech_init(private_t * tech_pvt, switch_core_session_t *session)
 {
 	tech_pvt->read_frame.data = tech_pvt->databuf;
 	tech_pvt->read_frame.buflen = sizeof(tech_pvt->databuf);
 	switch_mutex_init(&tech_pvt->mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
-    switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
-    switch_core_session_set_private(session, tech_pvt);
-    tech_pvt->session = session;
+	switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
+	switch_core_session_set_private(session, tech_pvt);
+	tech_pvt->session = session;
 }
 
 /* 
@@ -563,7 +551,7 @@
 		globals.calls = 0;
 	}
 	switch_mutex_unlock(globals.mutex);
-		
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -578,21 +566,19 @@
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
-    switch(sig) {
-    case SWITCH_SIG_KILL:
-        switch_clear_flag_locked(tech_pvt, TFLAG_IO);
-        switch_clear_flag_locked(tech_pvt, TFLAG_VOICE);
-        switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
-        //switch_thread_cond_signal(tech_pvt->cond);
-        break;
-    case SWITCH_SIG_BREAK:
-        switch_set_flag_locked(tech_pvt, TFLAG_BREAK);
-        break;
-    default:
-        break;
-    }
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s CHANNEL KILL\n", switch_channel_get_name(channel));
-
+	switch (sig) {
+	case SWITCH_SIG_KILL:
+		switch_clear_flag_locked(tech_pvt, TFLAG_IO);
+		switch_clear_flag_locked(tech_pvt, TFLAG_VOICE);
+		switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
+		//switch_thread_cond_signal(tech_pvt->cond);
+		break;
+	case SWITCH_SIG_BREAK:
+		switch_set_flag_locked(tech_pvt, TFLAG_BREAK);
+		break;
+	default:
+		break;
+	}
 
 	return SWITCH_STATUS_SUCCESS;
 }
@@ -646,33 +632,33 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-										switch_io_flag_t flags, int stream_id)
+static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
 	switch_channel_t *channel = NULL;
 	private_t *tech_pvt = NULL;
 	switch_time_t started = switch_time_now();
 	unsigned int elapsed;
+	switch_byte_t *data;
 
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
 
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
-    tech_pvt->read_frame.flags = SFF_NONE;
-    *frame = NULL;
+	tech_pvt->read_frame.flags = SFF_NONE;
+	*frame = NULL;
 
 	while (switch_test_flag(tech_pvt, TFLAG_IO)) {
-        
-        if (!switch_test_flag(tech_pvt, TFLAG_CODEC)) {
-            switch_yield(1000);
-            continue;
-        }
+
+		if (!switch_test_flag(tech_pvt, TFLAG_CODEC)) {
+			switch_yield(1000);
+			continue;
+		}
 		//switch_thread_cond_wait(tech_pvt->cond, tech_pvt->mutex);
 		if (switch_test_flag(tech_pvt, TFLAG_BREAK)) {
-            switch_clear_flag(tech_pvt, TFLAG_BREAK);
-            goto cng;
-        }
+			switch_clear_flag(tech_pvt, TFLAG_BREAK);
+			goto cng;
+		}
 
 		if (!switch_test_flag(tech_pvt, TFLAG_IO)) {
 			return SWITCH_STATUS_FALSE;
@@ -693,12 +679,12 @@
 		}
 
 		if (timeout > -1) {
-			elapsed = (unsigned int)((switch_time_now() - started) / 1000);
-			if (elapsed >= (unsigned int)timeout) {
+			elapsed = (unsigned int) ((switch_time_now() - started) / 1000);
+			if (elapsed >= (unsigned int) timeout) {
 				return SWITCH_STATUS_SUCCESS;
 			}
 		}
-		
+
 
 		switch_yield(1000);
 	}
@@ -706,17 +692,18 @@
 
 	return SWITCH_STATUS_FALSE;
 
- cng:
-    tech_pvt->read_frame.datalen = 13;
-    memset(tech_pvt->read_frame.data, 0, 13);
-    tech_pvt->read_frame.flags = SFF_CNG; 
-    *frame = &tech_pvt->read_frame;
-    return SWITCH_STATUS_SUCCESS;
+  cng:
+	data = (switch_byte_t *) tech_pvt->read_frame.data;
+	data[0] = 65;
+	data[1] = 0;
+	tech_pvt->read_frame.datalen = 2;
+	tech_pvt->read_frame.flags = SFF_CNG;
+	*frame = &tech_pvt->read_frame;
+	return SWITCH_STATUS_SUCCESS;
 
 }
 
-static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-										 switch_io_flag_t flags, int stream_id)
+static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
 	switch_channel_t *channel = NULL;
 	private_t *tech_pvt = NULL;
@@ -737,8 +724,7 @@
 	}
 #endif
 	//printf("Send %ld %d\n", time(NULL), (int) frame->datalen);
-	iax_send_voice(tech_pvt->iax_session, tech_pvt->codec, frame->data, (int) frame->datalen,
-				   tech_pvt->write_codec.implementation->samples_per_frame);
+	iax_send_voice(tech_pvt->iax_session, tech_pvt->codec, frame->data, (int) frame->datalen, tech_pvt->write_codec.implementation->samples_per_frame);
 
 	return SWITCH_STATUS_SUCCESS;
 
@@ -761,6 +747,29 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
+
+static switch_status_t channel_receive_message(switch_core_session_t *session, switch_core_session_message_t *msg)
+{
+	switch_channel_t *channel;
+	private_t *tech_pvt;
+
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
+			
+	tech_pvt = (private_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
+
+	switch (msg->message_id) {
+	case SWITCH_MESSAGE_INDICATE_ANSWER:
+		channel_answer_channel(session);
+		break;
+	default:
+		break;
+	}
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
 static const switch_state_handler_table_t channel_event_handlers = {
 	/*.on_init */ channel_on_init,
 	/*.on_ring */ channel_on_ring,
@@ -772,13 +781,13 @@
 
 static const switch_io_routines_t channel_io_routines = {
 	/*.outgoing_channel */ channel_outgoing_channel,
-	/*.answer_channel */ channel_answer_channel,
 	/*.read_frame */ channel_read_frame,
 	/*.write_frame */ channel_write_frame,
 	/*.kill_channel */ channel_kill_channel,
 	/*.waitfor_read */ channel_waitfor_read,
 	/*.waitfor_write */ channel_waitfor_write,
-	/*.send_dtmf */ channel_send_dtmf
+	/*.send_dtmf */ channel_send_dtmf,
+	/*.receive_message*/ channel_receive_message
 };
 
 static const switch_endpoint_interface_t channel_endpoint_interface = {
@@ -802,8 +811,9 @@
 /* Make sure when you have 2 sessions in the same scope that you pass the appropriate one to the routines
 that allocate memory or you will have 1 channel with memory allocated from another channel's pool!
 */
-static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-													switch_core_session_t **new_session, switch_memory_pool_t *pool)
+static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session,
+													switch_caller_profile_t *outbound_profile,
+													switch_core_session_t **new_session, switch_memory_pool_t **pool)
 {
 	if ((*new_session = switch_core_session_request(&channel_endpoint_interface, pool)) != 0) {
 		private_t *tech_pvt;
@@ -815,7 +825,7 @@
 		switch_core_session_add_stream(*new_session, NULL);
 		if ((tech_pvt = (private_t *) switch_core_session_alloc(*new_session, sizeof(private_t))) != 0) {
 			channel = switch_core_session_get_channel(*new_session);
-            tech_init(tech_pvt, *new_session);
+			tech_init(tech_pvt, *new_session);
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Hey where is my memory pool?\n");
 			switch_core_session_destroy(new_session);
@@ -853,8 +863,7 @@
 		}
 
 		iax_call(tech_pvt->iax_session,
-				 caller_profile->caller_id_number,
-				 caller_profile->caller_id_name, caller_profile->destination_number, NULL, 0, req, cap);
+				 caller_profile->caller_id_number, caller_profile->caller_id_name, caller_profile->destination_number, NULL, 0, req, cap);
 
 		switch_channel_set_flag(channel, CF_OUTBOUND);
 		switch_set_flag_locked(tech_pvt, TFLAG_OUTBOUND);
@@ -874,7 +883,7 @@
 		return SWITCH_STATUS_TERM;
 	}
 
-	
+
 	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &channel_module_interface;
 
@@ -923,12 +932,10 @@
 				set_global_dialplan(val);
 			} else if (!strcmp(var, "codec-prefs")) {
 				set_global_codec_string(val);
-				globals.codec_order_last =
-					switch_separate_string(globals.codec_string, ',', globals.codec_order, SWITCH_MAX_CODECS);
+				globals.codec_order_last = switch_separate_string(globals.codec_string, ',', globals.codec_order, SWITCH_MAX_CODECS);
 			} else if (!strcmp(var, "codec-rates")) {
 				set_global_codec_rates_string(val);
-				globals.codec_rates_last =
-					switch_separate_string(globals.codec_rates_string, ',', globals.codec_rates, SWITCH_MAX_CODECS);
+				globals.codec_rates_last = switch_separate_string(globals.codec_rates_string, ',', globals.codec_rates, SWITCH_MAX_CODECS);
 			}
 		}
 	}
@@ -946,18 +953,18 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t tech_media(private_t *tech_pvt, struct iax_event *iaxevent)
+static switch_status_t tech_media(private_t * tech_pvt, struct iax_event *iaxevent)
 {
-    unsigned int cap = iax_session_get_capability(iaxevent->session);
-    unsigned int format = iaxevent->ies.format;
+	unsigned int cap = iax_session_get_capability(iaxevent->session);
+	unsigned int format = iaxevent->ies.format;
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
-    
-    if (!switch_test_flag(tech_pvt, TFLAG_CODEC) && 
-        (status = iax_set_codec(tech_pvt, iaxevent->session, &format, &cap, &iaxevent->ies.samprate, IAX_SET)) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec Error %u %u\n", iaxevent->ies.format, iaxevent->ies.capability);
-    }
-    
-    return status;
+
+	if (!switch_test_flag(tech_pvt, TFLAG_CODEC) &&
+		(status = iax_set_codec(tech_pvt, iaxevent->session, &format, &cap, &iaxevent->ies.samprate, IAX_SET)) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec Error %u %u\n", iaxevent->ies.format, iaxevent->ies.capability);
+	}
+
+	return status;
 }
 
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_runtime(void)
@@ -997,7 +1004,7 @@
 		/* Wait for an event. */
 		if ((iaxevent = iax_get_event(0)) == NULL) {
 			int waitlen = 0;
-			
+
 			if (globals.calls == 0) {
 				waitlen = 10000;
 			} else if (globals.calls < 10) {
@@ -1010,15 +1017,14 @@
 			continue;
 		} else {
 			private_t *tech_pvt = NULL;
-            switch_channel_t *channel = NULL;
+			switch_channel_t *channel = NULL;
+
+			if ((tech_pvt = iax_get_private(iaxevent->session))) {
+				channel = switch_core_session_get_channel(tech_pvt->session);
+			}
 
-            if ((tech_pvt = iax_get_private(iaxevent->session))) {
-                channel = switch_core_session_get_channel(tech_pvt->session);
-            }
-            
 			if (globals.debug && iaxevent->etype != IAX_EVENT_VOICE) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Event %d [%s]!\n",
-								  iaxevent->etype, IAXNAMES[iaxevent->etype]);
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Event %d [%s]!\n", iaxevent->etype, IAXNAMES[iaxevent->etype]);
 			}
 
 			switch (iaxevent->etype) {
@@ -1034,11 +1040,11 @@
 				break;
 			case IAX_EVENT_ACCEPT:
 				if (channel && !switch_channel_test_flag(channel, CF_ANSWERED)) {
-                    if (tech_media(tech_pvt, iaxevent) == SWITCH_STATUS_SUCCESS) {
-                        switch_channel_mark_pre_answered(channel);
-                    } else {
-                        switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-                    }
+					if (tech_media(tech_pvt, iaxevent) == SWITCH_STATUS_SUCCESS) {
+						switch_channel_mark_pre_answered(channel);
+					} else {
+						switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					}
 				}
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Call accepted.\n");
 				break;
@@ -1055,32 +1061,30 @@
 			case IAX_EVENT_ANSWER:
 				// the other side answered our call
 				if (channel) {
-                    if (tech_media(tech_pvt, iaxevent) == SWITCH_STATUS_SUCCESS) {
-                        if (switch_channel_test_flag(channel, CF_ANSWERED)) {
-                            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "WTF Mutiple Answer %s?\n", switch_channel_get_name(channel));
-						
-                        } else {
-                            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Answer %s\n", switch_channel_get_name(channel));
-                            switch_channel_mark_answered(channel);
-                        }
-                    } else {
-                        switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-                    }
-                }
+					if (tech_media(tech_pvt, iaxevent) == SWITCH_STATUS_SUCCESS) {
+						if (switch_channel_test_flag(channel, CF_ANSWERED)) {
+							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "WTF Mutiple Answer %s?\n", switch_channel_get_name(channel));
+
+						} else {
+							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Answer %s\n", switch_channel_get_name(channel));
+							switch_channel_mark_answered(channel);
+						}
+					} else {
+						switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					}
+				}
 				break;
 			case IAX_EVENT_CONNECT:
 				// incoming call detected
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
-									  "Incoming call connected %s, %s, %s %u/%u\n",
-									  iaxevent->ies.called_number,
-									  iaxevent->ies.calling_number,
-									  iaxevent->ies.calling_name, iaxevent->ies.format, iaxevent->ies.capability);
+								  "Incoming call connected %s, %s, %s %u/%u\n",
+								  iaxevent->ies.called_number,
+								  iaxevent->ies.calling_number, iaxevent->ies.calling_name, iaxevent->ies.format, iaxevent->ies.capability);
 
 				if (iaxevent) {
 					switch_core_session_t *session;
 
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "New Inbound Channel %s!\n",
-										  iaxevent->ies.calling_name);
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "New Inbound Channel %s!\n", iaxevent->ies.calling_name);
 					if ((session = switch_core_session_request(&channel_endpoint_interface, NULL)) != 0) {
 						private_t *tech_pvt;
 						switch_channel_t *channel;
@@ -1088,7 +1092,7 @@
 						switch_core_session_add_stream(session, NULL);
 						if ((tech_pvt = (private_t *) switch_core_session_alloc(session, sizeof(private_t))) != 0) {
 							channel = switch_core_session_get_channel(session);
-                            tech_init(tech_pvt, session);
+							tech_init(tech_pvt, session);
 						} else {
 							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Hey where is my memory pool?\n");
 							switch_core_session_destroy(&session);
@@ -1103,23 +1107,19 @@
 																				  iaxevent->ies.calling_number,
 																				  iax_get_peer_ip(iaxevent->session),
 																				  iaxevent->ies.calling_ani,
-																				  NULL, 
 																				  NULL,
-																				  (char *)modname,
-																				  iaxevent->ies.called_context,
-																				  iaxevent->ies.called_number)) != 0) {
+																				  NULL,
+																				  (char *) modname,
+																				  iaxevent->ies.called_context, iaxevent->ies.called_number)) != 0) {
 							char name[128];
-							snprintf(name, sizeof(name), "IAX/%s-%04x", tech_pvt->caller_profile->destination_number,
-									 rand() & 0xffff);
+							snprintf(name, sizeof(name), "IAX/%s-%04x", tech_pvt->caller_profile->destination_number, rand() & 0xffff);
 							switch_channel_set_name(channel, name);
 							switch_channel_set_caller_profile(channel, tech_pvt->caller_profile);
 
 						}
 
 						if (iax_set_codec(tech_pvt, iaxevent->session,
-										  &iaxevent->ies.format,
-										  &iaxevent->ies.capability,
-										  &iaxevent->ies.samprate, IAX_SET) != SWITCH_STATUS_SUCCESS) {
+										  &iaxevent->ies.format, &iaxevent->ies.capability, &iaxevent->ies.samprate, IAX_SET) != SWITCH_STATUS_SUCCESS) {
 							iax_reject(iaxevent->session, "Codec Error!");
 							switch_core_session_destroy(&session);
 						} else {
@@ -1144,11 +1144,11 @@
 					switch_mutex_unlock(tech_pvt->flag_mutex);
 
 
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Hangup %s\n", switch_channel_get_name(channel));
-                    switch_set_flag_locked(tech_pvt, TFLAG_HANGUP);
-                    switch_channel_hangup(channel, iaxevent->etype == IAX_EVENT_HANGUP ? SWITCH_CAUSE_NORMAL_CLEARING : SWITCH_CAUSE_FACILITY_REJECTED);
-                    //switch_thread_cond_signal(tech_pvt->cond);
-                    iaxevent->session = NULL;
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Hangup %s\n", switch_channel_get_name(channel));
+					switch_set_flag_locked(tech_pvt, TFLAG_HANGUP);
+					switch_channel_hangup(channel, iaxevent->etype == IAX_EVENT_HANGUP ? SWITCH_CAUSE_NORMAL_CLEARING : SWITCH_CAUSE_FACILITY_REJECTED);
+					//switch_thread_cond_signal(tech_pvt->cond);
+					iaxevent->session = NULL;
 				}
 				break;
 			case IAX_EVENT_CNG:
@@ -1159,7 +1159,7 @@
 				if (tech_pvt && (tech_pvt->read_frame.datalen = iaxevent->datalen) != 0) {
 					if (channel && switch_channel_get_state(channel) <= CS_HANGUP) {
 						int bytes, frames;
-						
+
 						if (!switch_test_flag(tech_pvt, TFLAG_CODEC)) {
 							//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "audio with no codec yet!\n");
 							break;
@@ -1186,18 +1186,16 @@
 				break;
 			case IAX_EVENT_DTMF:
 				if (channel) {
-                    char str[2] = { (char)iaxevent->subclass };
-                    if (globals.debug) {
-                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "%s DTMF %s\n", str,
-                                          switch_channel_get_name(channel));
-                    }
-                    switch_channel_queue_dtmf(channel, str);
+					char str[2] = { (char) iaxevent->subclass };
+					if (globals.debug) {
+						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "%s DTMF %s\n", str, switch_channel_get_name(channel));
+					}
+					switch_channel_queue_dtmf(channel, str);
 				}
 
 				break;
 			default:
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Don't know what to do with IAX event %d.\n",
-									  iaxevent->etype);
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Don't know what to do with IAX event %d.\n", iaxevent->etype);
 				break;
 			}
 
@@ -1219,7 +1217,7 @@
 	running = -1;
 
 	if (globals.fd) {
-		/* Die Mutha $%#$@% Die Mutha $#%#$^ Die*/
+		/* Die Mutha $%#$@% Die Mutha $#%#$^ Die */
 		shutdown(globals.fd, 2);
 	}
 	iax_shutdown();

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,22 +1,20 @@
-CFLAGS += -I.
-LDFLAGS += -lportaudio -L$(PREFIX) 
-MYOBJS = pablio.o pa_ringbuffer.o
+BASE=../../../..
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+PA_DIR=$(BASE)/libs/portaudio
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install portaudio --prefix=$(PREFIX) --with-pic
-%.o:  %.c
-	$(CC) -fPIC $(CFLAGS) -c -o $@ $<
+PALA=$(PA_DIR)/lib/libportaudio.la
+LOCAL_CFLAGS=-I. -I$(PA_DIR)/include -D__EXTENSION__=1
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c $(MYOBJS)
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(MODNAME).o $(MYOBJS) $(LDFLAGS)
+LOCAL_INSERT_LDFLAGS=if test $$osarch = "Darwin" ; then echo "-framework CoreAudio -framework AudioToolbox -framework AudioUnit -framework Carbon" ; fi ;
 
+LOCAL_LIBADD=$(PALA)
+LOCAL_OBJS=pablio.o pa_ringbuffer.o
+LOCAL_SOURCES=pablio.c pa_ringbuffer.c
 
+include $(BASE)/build/modmake.rules
 
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+$(PALA): $(PA_DIR) $(PA_DIR)/.update
+	cd $(PA_DIR) && $(MAKE)
+	$(TOUCH_TARGET)
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(LOCAL_OBJS): $(LOCAL_SOURCES)

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/mod_portaudio.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/mod_portaudio.c	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/mod_portaudio.c	Tue Apr 24 10:14:28 2007
@@ -48,13 +48,13 @@
 //#define SAMPLE_TYPE  paFloat32
 typedef short SAMPLE;
 
-typedef switch_status_t (*pa_command_t)(char **argv, int argc, switch_stream_handle_t *stream);
+typedef switch_status_t (*pa_command_t) (char **argv, int argc, switch_stream_handle_t *stream);
 
 typedef enum {
-    GFLAG_NONE = 0,
-    GFLAG_EAR = (1 << 0),
-    GFLAG_MOUTH = (1 << 1),
-    GFLAG_RING = (1 << 2)
+	GFLAG_NONE = 0,
+	GFLAG_EAR = (1 << 0),
+	GFLAG_MOUTH = (1 << 1),
+	GFLAG_RING = (1 << 2)
 } GFLAGS;
 
 typedef enum {
@@ -75,17 +75,17 @@
 	switch_core_session_t *session;
 	switch_caller_profile_t *caller_profile;
 	char call_id[50];
-    int sample_rate;
-    int codec_ms;
+	int sample_rate;
+	int codec_ms;
 	switch_mutex_t *flag_mutex;
-    char *hold_file;
-    switch_file_handle_t fh;
-    switch_file_handle_t *hfh;
+	char *hold_file;
+	switch_file_handle_t fh;
+	switch_file_handle_t *hfh;
 	switch_frame_t hold_frame;
-    unsigned char holdbuf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
+	unsigned char holdbuf[SWITCH_RECOMMENDED_BUFFER_SIZE];
 	switch_codec_t write_codec;
-    switch_timer_t timer;
-    struct private_object *next;
+	switch_timer_t timer;
+	struct private_object *next;
 };
 
 typedef struct private_object private_t;
@@ -96,9 +96,9 @@
 	char *cid_name;
 	char *cid_num;
 	char *dialplan;
-    char *ring_file;
-    char *hold_file;
-    char *timer_name;
+	char *ring_file;
+	char *hold_file;
+	char *timer_name;
 	int ringdev;
 	int indev;
 	int outdev;
@@ -114,12 +114,13 @@
 	switch_codec_t read_codec;
 	switch_codec_t write_codec;
 	switch_frame_t read_frame;
-    switch_frame_t cng_frame;
-	unsigned char databuf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-	unsigned char cngbuf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-    private_t *call_list;
-    int ring_interval;
-    GFLAGS flags;
+	switch_frame_t cng_frame;
+	unsigned char databuf[SWITCH_RECOMMENDED_BUFFER_SIZE];
+	unsigned char cngbuf[SWITCH_RECOMMENDED_BUFFER_SIZE];
+	private_t *call_list;
+	int ring_interval;
+	GFLAGS flags;
+	switch_timer_t timer;
 } globals;
 
 
@@ -128,37 +129,34 @@
 
 
 SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_dialplan, globals.dialplan)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_cid_name, globals.cid_name)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_cid_num, globals.cid_num)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_ring_file, globals.ring_file)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_hold_file, globals.hold_file)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_timer_name, globals.timer_name)
-
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_cid_name, globals.cid_name)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_cid_num, globals.cid_num)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_ring_file, globals.ring_file)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_hold_file, globals.hold_file)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_timer_name, globals.timer_name)
 #define is_master(t) switch_test_flag(t, TFLAG_MASTER)
-static void add_pvt(private_t *tech_pvt, int master);
-static void remove_pvt(private_t *tech_pvt);
-static switch_status_t channel_on_init(switch_core_session_t *session);
-static switch_status_t channel_on_hangup(switch_core_session_t *session);
-static switch_status_t channel_on_ring(switch_core_session_t *session);
-static switch_status_t channel_on_loopback(switch_core_session_t *session);
-static switch_status_t channel_on_transmit(switch_core_session_t *session);
-static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session,
-													switch_caller_profile_t *outbound_profile,
-													switch_core_session_t **new_session, switch_memory_pool_t *pool);
-static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-                                          switch_io_flag_t flags, int stream_id);
-static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-                                           switch_io_flag_t flags, int stream_id);
-static switch_status_t channel_kill_channel(switch_core_session_t *session, int sig);
-static switch_status_t engage_device(int samplerate, int codec_ms);
-static switch_status_t engage_ring_device(int sample_rate, int channels);
-static void deactivate_ring_device(void);
-static int dump_info(void);
-static switch_status_t load_config(void);
-static int get_dev_by_name(char *name, int in);
-static int get_dev_by_number(int number, int in);
-static switch_status_t pa_cmd(char *dest, switch_core_session_t *session, switch_stream_handle_t *stream);
-static switch_status_t padep(char *dest, switch_core_session_t *session, switch_stream_handle_t *stream);
+	 static void add_pvt(private_t * tech_pvt, int master);
+	 static void remove_pvt(private_t * tech_pvt);
+	 static switch_status_t channel_on_init(switch_core_session_t *session);
+	 static switch_status_t channel_on_hangup(switch_core_session_t *session);
+	 static switch_status_t channel_on_ring(switch_core_session_t *session);
+	 static switch_status_t channel_on_loopback(switch_core_session_t *session);
+	 static switch_status_t channel_on_transmit(switch_core_session_t *session);
+	 static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session,
+														 switch_caller_profile_t *outbound_profile,
+														 switch_core_session_t **new_session, switch_memory_pool_t **pool);
+	 static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id);
+	 static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id);
+	 static switch_status_t channel_kill_channel(switch_core_session_t *session, int sig);
+	 static switch_status_t engage_device(int samplerate, int codec_ms);
+	 static switch_status_t engage_ring_device(int sample_rate, int channels);
+	 static void deactivate_ring_device(void);
+	 static int dump_info(void);
+	 static switch_status_t load_config(void);
+	 static int get_dev_by_name(char *name, int in);
+	 static int get_dev_by_number(int number, int in);
+	 static switch_status_t pa_cmd(char *dest, switch_core_session_t *session, switch_stream_handle_t *stream);
+	 static switch_status_t padep(char *dest, switch_core_session_t *session, switch_stream_handle_t *stream);
 
 
 /* 
@@ -166,88 +164,90 @@
    returning SWITCH_STATUS_SUCCESS tells the core to execute the standard state method next
    so if you fully implement the state you can return SWITCH_STATUS_FALSE to skip it.
 */
-static switch_status_t channel_on_init(switch_core_session_t *session)
+	 static switch_status_t channel_on_init(switch_core_session_t *session)
 {
 	switch_channel_t *channel;
 	private_t *tech_pvt = NULL;
 	switch_time_t last;
 	int waitsec = globals.ring_interval * 1000000;
-    switch_file_handle_t fh = {0};
-    char *val, *ring_file = NULL, *hold_file = NULL;
-    int16_t abuf[2048];
+	switch_file_handle_t fh = { 0 };
+	char *val, *ring_file = NULL, *hold_file = NULL;
+	int16_t abuf[2048];
 
-    tech_pvt = switch_core_session_get_private(session);
+	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
 
-    
+
 	last = switch_time_now() - waitsec;
 
 
-    if ((val = switch_channel_get_variable(channel, "pa_hold_file"))) {
-        hold_file = val;
-    } else {
-        hold_file = globals.hold_file;
-    }
-
-    if (hold_file) {
-        tech_pvt->hold_file = switch_core_session_strdup(session, hold_file);
-    }
+
+	if ((val = switch_channel_get_variable(channel, "pa_hold_file"))) {
+		hold_file = val;
+	} else {
+		hold_file = globals.hold_file;
+	}
+
+	if (hold_file) {
+		tech_pvt->hold_file = switch_core_session_strdup(session, hold_file);
+	}
 
 	if (switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
 
-        
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s CHANNEL INIT %d %d\n", switch_channel_get_name(channel),
-                          switch_channel_get_state(channel), switch_test_flag(tech_pvt, TFLAG_ANSWER));
-        
-
-
-        if (engage_device(tech_pvt->sample_rate, tech_pvt->codec_ms) != SWITCH_STATUS_SUCCESS) {
-            switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-            return SWITCH_STATUS_FALSE;
-        }
-
-        if (switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
-            add_pvt(tech_pvt, PA_SLAVE);
-
-            ring_file = globals.ring_file;
-            if ((val = switch_channel_get_variable(channel, "pa_ring_file"))) {
-                ring_file = val;
-            }
-
-            if (switch_test_flag((&globals), GFLAG_RING)) {
-                ring_file = NULL;
-            }
-            switch_set_flag_locked((&globals), GFLAG_RING);
-            if (ring_file) {
-                if (switch_core_file_open(&fh,
-                                          ring_file,
-                                          SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT,
-                                          NULL) == SWITCH_STATUS_SUCCESS) {
-            
-                    if (engage_ring_device(fh.samplerate, fh.channels) != SWITCH_STATUS_SUCCESS) {
-                        switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Ring Error!\n");
-                        switch_core_file_close(&fh);
-                        return SWITCH_STATUS_GENERR;
-                    }
-                } else {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot open %s, disabling ring file!\n", ring_file);
-                    ring_file = NULL;
-                }
-            }
-        }
+
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s CHANNEL INIT %d %d\n",
+						  switch_channel_get_name(channel), switch_channel_get_state(channel), switch_test_flag(tech_pvt, TFLAG_ANSWER));
+
+
+
+		if (engage_device(tech_pvt->sample_rate, tech_pvt->codec_ms) != SWITCH_STATUS_SUCCESS) {
+			switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+			return SWITCH_STATUS_FALSE;
+		}
+
+		if (switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
+			add_pvt(tech_pvt, PA_SLAVE);
+
+			ring_file = globals.ring_file;
+			if ((val = switch_channel_get_variable(channel, "pa_ring_file"))) {
+				ring_file = val;
+			}
+
+			if (switch_test_flag((&globals), GFLAG_RING)) {
+				ring_file = NULL;
+			}
+			switch_set_flag_locked((&globals), GFLAG_RING);
+			if (ring_file) {
+				if (switch_core_file_open(&fh,
+										  ring_file,
+										  globals.read_codec.implementation->number_of_channels,
+										  globals.read_codec.implementation->samples_per_second,
+										  SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT, NULL) == SWITCH_STATUS_SUCCESS) {
+
+					if (engage_ring_device(fh.samplerate, fh.channels) != SWITCH_STATUS_SUCCESS) {
+						switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Ring Error!\n");
+						switch_core_file_close(&fh);
+						return SWITCH_STATUS_GENERR;
+					}
+				} else {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot open %s, disabling ring file!\n", ring_file);
+					ring_file = NULL;
+				}
+			}
+		}
 
 		switch_core_session_queue_indication(session, SWITCH_MESSAGE_INDICATE_RINGING);
 		switch_channel_mark_ring_ready(channel);
-		
+
 		while (switch_channel_get_state(channel) == CS_INIT && !switch_test_flag(tech_pvt, TFLAG_ANSWER)) {
 			if (switch_time_now() - last >= waitsec) {
 				char buf[512];
 				switch_event_t *event;
-                
+
 				snprintf(buf, sizeof(buf), "BRRRRING! BRRRRING! call %s\n", tech_pvt->call_id);
 
 				if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, MY_EVENT_RINGING) == SWITCH_STATUS_SUCCESS) {
@@ -259,46 +259,46 @@
 
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s\n", buf);
 				last = switch_time_now();
-                if (ring_file) {
-                    unsigned int pos = 0;
-                    switch_core_file_seek(&fh, &pos, 0, SEEK_SET);				 
-                    for (;;) {
-                        switch_size_t olen = 1024;
-                        switch_core_file_read(&fh, abuf, &olen);
-                        if (olen == 0) {
-                            break;
-                        }
-                        WriteAudioStream(globals.ring_stream, abuf, (long)olen);
-                    }
-                }
-            }
-
-            switch_yield(globals.read_codec.implementation->microseconds_per_frame);
-
-        }
-        switch_clear_flag_locked((&globals), GFLAG_RING);
-    }
-
-    if (ring_file) {
-        deactivate_ring_device();
-        switch_core_file_close(&fh);
-        switch_core_codec_destroy(&tech_pvt->write_codec);
+				if (ring_file) {
+					unsigned int pos = 0;
+					switch_core_file_seek(&fh, &pos, 0, SEEK_SET);
+					for (;;) {
+						switch_size_t olen = 1024;
+						switch_core_file_read(&fh, abuf, &olen);
+						if (olen == 0) {
+							break;
+						}
+						WriteAudioStream(globals.ring_stream, abuf, (long) olen);
+					}
+				}
+			}
+
+			switch_yield(globals.read_codec.implementation->microseconds_per_frame);
+
+		}
+		switch_clear_flag_locked((&globals), GFLAG_RING);
+	}
+
+	if (ring_file) {
+		deactivate_ring_device();
+		switch_core_file_close(&fh);
+		switch_core_codec_destroy(&tech_pvt->write_codec);
 		switch_core_timer_destroy(&tech_pvt->timer);
-    }
+	}
 
 	if (switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
-        if (!switch_test_flag(tech_pvt, TFLAG_ANSWER)) {
-            switch_channel_hangup(channel, SWITCH_CAUSE_NO_ANSWER);
-            return SWITCH_STATUS_SUCCESS;
-        }
+		if (!switch_test_flag(tech_pvt, TFLAG_ANSWER)) {
+			switch_channel_hangup(channel, SWITCH_CAUSE_NO_ANSWER);
+			return SWITCH_STATUS_SUCCESS;
+		}
 	}
 
-    switch_set_flag_locked(tech_pvt, TFLAG_IO);
-
-    /* Move Channel's State Machine to RING */
-    switch_channel_set_state(channel, CS_RING);
-	
-    return SWITCH_STATUS_SUCCESS;
+	switch_set_flag_locked(tech_pvt, TFLAG_IO);
+
+	/* Move Channel's State Machine to RING */
+	switch_channel_set_state(channel, CS_RING);
+
+	return SWITCH_STATUS_SUCCESS;
 
 }
 
@@ -359,72 +359,72 @@
 
 
 
-static void add_pvt(private_t *tech_pvt, int master) 
+static void add_pvt(private_t * tech_pvt, int master)
 {
-    private_t *tp;
-    uint8_t in_list = 0;
+	private_t *tp;
+	uint8_t in_list = 0;
+
+	switch_mutex_lock(globals.pvt_lock);
+
+	if (switch_strlen_zero(tech_pvt->call_id)) {
+		snprintf(tech_pvt->call_id, sizeof(tech_pvt->call_id), "%d", ++globals.call_id);
+		switch_core_hash_insert(globals.call_hash, tech_pvt->call_id, tech_pvt);
+		switch_core_session_set_read_codec(tech_pvt->session, &globals.read_codec);
+		switch_core_session_set_write_codec(tech_pvt->session, &globals.write_codec);
+	}
+
+	for (tp = globals.call_list; tp; tp = tp->next) {
+		if (tp == tech_pvt) {
+			in_list = 1;
+		}
+		if (master) {
+			switch_clear_flag_locked(tp, TFLAG_MASTER);
+		}
+	}
 
-    switch_mutex_lock(globals.pvt_lock);
 
-    if (switch_strlen_zero(tech_pvt->call_id)) {
-        snprintf(tech_pvt->call_id, sizeof(tech_pvt->call_id), "%d", ++globals.call_id);
-        switch_core_hash_insert(globals.call_hash, tech_pvt->call_id, tech_pvt);
-        switch_core_session_set_read_codec(tech_pvt->session, &globals.read_codec);
-        switch_core_session_set_write_codec(tech_pvt->session, &globals.write_codec);
-    }
-
-    for (tp = globals.call_list; tp; tp = tp->next) {
-        if (tp == tech_pvt) {
-            in_list = 1;
-        }
-        if (master) {
-            switch_clear_flag_locked(tp, TFLAG_MASTER);
-        }
-    }
-
-
-    if (master) {
-        if (!in_list) {
-            tech_pvt->next = globals.call_list;
-            globals.call_list = tech_pvt;
-        }
-        switch_set_flag_locked(tech_pvt, TFLAG_MASTER);
-
-    } else if (!in_list) {
-        for (tp = globals.call_list; tp && tp->next; tp = tp->next);
-        if (tp) {
-            tp->next = tech_pvt;
-        } else {
-            globals.call_list = tech_pvt;
-        }
-    }
+	if (master) {
+		if (!in_list) {
+			tech_pvt->next = globals.call_list;
+			globals.call_list = tech_pvt;
+		}
+		switch_set_flag_locked(tech_pvt, TFLAG_MASTER);
+
+	} else if (!in_list) {
+		for (tp = globals.call_list; tp && tp->next; tp = tp->next);
+		if (tp) {
+			tp->next = tech_pvt;
+		} else {
+			globals.call_list = tech_pvt;
+		}
+	}
 
 	switch_mutex_unlock(globals.pvt_lock);
 }
 
-static void remove_pvt(private_t *tech_pvt) 
+static void remove_pvt(private_t * tech_pvt)
 {
-    private_t *tp, *last = NULL;
+	private_t *tp, *last = NULL;
 
 	switch_mutex_lock(globals.pvt_lock);
-    for (tp = globals.call_list; tp; tp = tp->next) {
-        switch_clear_flag_locked(tp, TFLAG_MASTER);
-        if (tp == tech_pvt) {
-            if (last) {
-                last->next = tp->next;
-            } else {
-                globals.call_list = tp->next;
-            }
-        }
-        last = tp;
-    }
-
-    if (globals.call_list) {
-        switch_set_flag_locked(globals.call_list, TFLAG_MASTER);
-    } else {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "No more channels, deactivating audio\n");
-        deactivate_audio_device();
-    }
+	for (tp = globals.call_list; tp; tp = tp->next) {
+		switch_clear_flag_locked(tp, TFLAG_MASTER);
+		if (tp == tech_pvt) {
+			if (last) {
+				last->next = tp->next;
+			} else {
+				globals.call_list = tp->next;
+			}
+		}
+		last = tp;
+	}
+
+	if (globals.call_list) {
+		switch_set_flag_locked(globals.call_list, TFLAG_MASTER);
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "No more channels, deactivating audio\n");
+		deactivate_audio_device();
+	}
 
 	switch_mutex_unlock(globals.pvt_lock);
 }
@@ -440,17 +440,17 @@
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
-    remove_pvt(tech_pvt);
+	remove_pvt(tech_pvt);
 
 	switch_clear_flag_locked(tech_pvt, TFLAG_IO);
 	switch_set_flag_locked(tech_pvt, TFLAG_HUP);
 
 	switch_core_hash_delete(globals.call_hash, tech_pvt->call_id);
 
-    if (tech_pvt->hfh) {
-        tech_pvt->hfh = NULL;
-        switch_core_file_close(&tech_pvt->fh);
-    }
+	if (tech_pvt->hfh) {
+		tech_pvt->hfh = NULL;
+		switch_core_file_close(&tech_pvt->fh);
+	}
 
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s CHANNEL HANGUP\n", switch_channel_get_name(channel));
 
@@ -468,14 +468,14 @@
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
-    switch (sig) {
-    case SWITCH_SIG_KILL:
-        switch_set_flag_locked(tech_pvt, TFLAG_HUP);
-        switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
-        break;
-    default:
-        break;
-    }
+	switch (sig) {
+	case SWITCH_SIG_KILL:
+		switch_set_flag_locked(tech_pvt, TFLAG_HUP);
+		switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
+		break;
+	default:
+		break;
+	}
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s CHANNEL KILL\n", switch_channel_get_name(channel));
 
 
@@ -538,8 +538,7 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-                                          switch_io_flag_t flags, int stream_id)
+static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
 	switch_channel_t *channel = NULL;
 	private_t *tech_pvt = NULL;
@@ -553,109 +552,103 @@
 	assert(tech_pvt != NULL);
 
 	if (!globals.audio_stream) {
-        return SWITCH_STATUS_FALSE;
-    }
+		return SWITCH_STATUS_FALSE;
+	}
+
+	if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	if (!switch_test_flag(tech_pvt, TFLAG_IO)) {
+		goto cng;
+	}
+
+	if (!is_master(tech_pvt)) {
+		if (tech_pvt->hold_file) {
+			if (!tech_pvt->hfh) {
+				int codec_ms = tech_pvt->codec_ms ? tech_pvt->codec_ms : globals.codec_ms;
+				int sample_rate = tech_pvt->sample_rate ? tech_pvt->sample_rate : globals.sample_rate;
+
+				if (switch_core_codec_init(&tech_pvt->write_codec,
+										   "L16",
+										   NULL,
+										   sample_rate,
+										   codec_ms,
+										   1,
+										   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
+										   NULL, switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
+					switch_core_codec_destroy(&globals.read_codec);
+					tech_pvt->hold_file = NULL;
+					goto cng;
+				}
 
-    if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
-        return SWITCH_STATUS_FALSE;
-    }
-    
-    if (!switch_test_flag(tech_pvt, TFLAG_IO)) {
-        goto cng;
-    }
-
-    if (!is_master(tech_pvt)) {
-        if (tech_pvt->hold_file) {
-            if (!tech_pvt->hfh) {
-                int codec_ms = tech_pvt->codec_ms ? tech_pvt->codec_ms : globals.codec_ms;
-                int sample_rate = tech_pvt->sample_rate ? tech_pvt->sample_rate : globals.sample_rate;
-
-                if (switch_core_codec_init(&tech_pvt->write_codec,
-                                           "L16",
-                                           NULL,
-                                           sample_rate,
-                                           codec_ms,
-                                           1,
-                                           SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-                                           NULL,
-                                           switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
-                    switch_core_codec_destroy(&globals.read_codec);
-                    tech_pvt->hold_file = NULL;
-                    goto cng;
-                }
-
-                if (switch_core_file_open(&tech_pvt->fh,
-                                          tech_pvt->hold_file,
-                                          SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT,
-                                          switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
-                    switch_core_codec_destroy(&tech_pvt->write_codec);
-                    tech_pvt->hold_file = NULL;
-                    goto cng;
-                }
-
-                if (switch_core_timer_init(&tech_pvt->timer,
-                                           globals.timer_name,
-                                           codec_ms,
-                                           globals.read_codec.implementation->samples_per_frame,
-                                           switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "setup timer failed!\n");
-                    switch_core_file_close(&tech_pvt->fh);
-                    switch_core_codec_destroy(&tech_pvt->write_codec);
-                    goto cng;
-                }
-                
-                tech_pvt->hfh = &tech_pvt->fh;
-                tech_pvt->hold_frame.data = tech_pvt->holdbuf;
-                tech_pvt->hold_frame.buflen = sizeof(tech_pvt->holdbuf);
-                tech_pvt->hold_frame.rate = sample_rate;
-                tech_pvt->hold_frame.codec = &tech_pvt->write_codec;
-            }
-            
-            goto hold;
-        }
-    cng:
-        switch_yield(globals.read_codec.implementation->microseconds_per_frame);
-        *frame = &globals.cng_frame;
+				if (switch_core_file_open(&tech_pvt->fh,
+										  tech_pvt->hold_file,
+										  globals.read_codec.implementation->number_of_channels,
+										  globals.read_codec.implementation->samples_per_second,
+										  SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT,
+										  switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
+					switch_core_codec_destroy(&tech_pvt->write_codec);
+					tech_pvt->hold_file = NULL;
+					goto cng;
+				}
+
+				tech_pvt->hfh = &tech_pvt->fh;
+				tech_pvt->hold_frame.data = tech_pvt->holdbuf;
+				tech_pvt->hold_frame.buflen = sizeof(tech_pvt->holdbuf);
+				tech_pvt->hold_frame.rate = sample_rate;
+				tech_pvt->hold_frame.codec = &tech_pvt->write_codec;
+			}
+
+			goto hold;
+		}
+	  cng:
+		switch_yield(globals.read_codec.implementation->microseconds_per_frame);
+		*frame = &globals.cng_frame;
 		return SWITCH_STATUS_SUCCESS;
 
-    hold:
+	  hold:
 
-        {
-            switch_size_t olen = globals.read_codec.implementation->samples_per_frame;
-			if (switch_core_timer_next(&tech_pvt->timer) < 0) {
-                switch_core_file_close(&tech_pvt->fh);
-                switch_core_codec_destroy(&tech_pvt->write_codec);
-                goto cng;
+		{
+			switch_size_t olen = globals.read_codec.implementation->samples_per_frame;
+			if (switch_core_timer_next(&tech_pvt->timer) != SWITCH_STATUS_SUCCESS) {
+				switch_core_file_close(&tech_pvt->fh);
+				switch_core_codec_destroy(&tech_pvt->write_codec);
+				goto cng;
 			}
-            switch_core_file_read(tech_pvt->hfh, tech_pvt->hold_frame.data, &olen);
-            
-            if (olen == 0) {
-                unsigned int pos = 0;
-                switch_core_file_seek(tech_pvt->hfh, &pos, 0, SEEK_SET);				 
-                goto cng;
-            }
-            
-            
-            tech_pvt->hold_frame.datalen = (uint32_t)(olen * sizeof(int16_t));
-            tech_pvt->hold_frame.samples = (uint32_t)olen;
-            *frame = &tech_pvt->hold_frame;
-            
-        }
+			switch_core_file_read(tech_pvt->hfh, tech_pvt->hold_frame.data, &olen);
+
+			if (olen == 0) {
+				unsigned int pos = 0;
+				switch_core_file_seek(tech_pvt->hfh, &pos, 0, SEEK_SET);
+				goto cng;
+			}
+
+
+			tech_pvt->hold_frame.datalen = (uint32_t) (olen * sizeof(int16_t));
+			tech_pvt->hold_frame.samples = (uint32_t) olen;
+			tech_pvt->hold_frame.timestamp = tech_pvt->timer.samplecount;
+			*frame = &tech_pvt->hold_frame;
 
-		return SWITCH_STATUS_SUCCESS;        
-    }
+		}
+
+		return SWITCH_STATUS_SUCCESS;
+	}
 
 	switch_mutex_lock(globals.device_lock);
 
-    if ((samples = ReadAudioStream(globals.audio_stream, globals.read_frame.data, globals.read_codec.implementation->samples_per_frame)) != 0) {
+	if ((samples = ReadAudioStream(globals.audio_stream, globals.read_frame.data, globals.read_codec.implementation->samples_per_frame)) != 0) {
 		globals.read_frame.datalen = samples * 2;
 		globals.read_frame.samples = samples;
+
+		switch_core_timer_check(&globals.timer);
+		globals.read_frame.timestamp = globals.timer.samplecount;
 		*frame = &globals.read_frame;
 
-        if (!switch_test_flag((&globals), GFLAG_MOUTH)) {
-            memset(globals.read_frame.data, 255, globals.read_frame.datalen);
-        }
+		if (!switch_test_flag((&globals), GFLAG_MOUTH)) {
+			memset(globals.read_frame.data, 255, globals.read_frame.datalen);
+		}
 
 		status = SWITCH_STATUS_SUCCESS;
 	}
@@ -664,8 +657,7 @@
 	return status;
 }
 
-static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-                                           switch_io_flag_t flags, int stream_id)
+static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
 	switch_channel_t *channel = NULL;
 	private_t *tech_pvt = NULL;
@@ -677,21 +669,21 @@
 	assert(tech_pvt != NULL);
 
 	if (!globals.audio_stream) {
-        return SWITCH_STATUS_FALSE;
-    }
+		return SWITCH_STATUS_FALSE;
+	}
 
-    if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
-        return SWITCH_STATUS_FALSE;
-    }
-
-    if (!is_master(tech_pvt) || !switch_test_flag(tech_pvt, TFLAG_IO)) {
-		return SWITCH_STATUS_SUCCESS;        
-    }
+	if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	if (!is_master(tech_pvt) || !switch_test_flag(tech_pvt, TFLAG_IO)) {
+		return SWITCH_STATUS_SUCCESS;
+	}
 
 	if (globals.audio_stream) {
-        if (switch_test_flag((&globals), GFLAG_EAR)) {
-            WriteAudioStream(globals.audio_stream, (short *) frame->data, (int) (frame->datalen / sizeof(SAMPLE)));
-        }
+		if (switch_test_flag((&globals), GFLAG_EAR)) {
+			WriteAudioStream(globals.audio_stream, (short *) frame->data, (int) (frame->datalen / sizeof(SAMPLE)));
+		}
 		status = SWITCH_STATUS_SUCCESS;
 	}
 
@@ -717,16 +709,19 @@
 {
 	switch_channel_t *channel;
 	private_t *tech_pvt;
-			
+
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
-			
+
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
 
 	switch (msg->message_id) {
-	case SWITCH_MESSAGE_INDICATE_PROGRESS: 
+	case SWITCH_MESSAGE_INDICATE_ANSWER:
+		channel_answer_channel(session);
+		break;
+	case SWITCH_MESSAGE_INDICATE_PROGRESS:
 		{
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Engage Early Media\n");
 			switch_set_flag_locked(tech_pvt, TFLAG_IO);
@@ -738,43 +733,43 @@
 }
 
 static switch_api_interface_t send_dtmf_interface = {
-    /*.interface_name */ "padtmf",
-    /*.desc */ "DEPRICATED (see 'pa')",
-    /*.function */ padep,
-    /*.syntax */ "DEPRICATED (see 'pa')",
-    /*.next */ NULL
+	/*.interface_name */ "padtmf",
+	/*.desc */ "DEPRICATED (see 'pa')",
+	/*.function */ padep,
+	/*.syntax */ "DEPRICATED (see 'pa')",
+	/*.next */ NULL
 };
 
 static switch_api_interface_t answer_call_interface = {
-    /*.interface_name */ "paoffhook",
-    /*.desc */ "DEPRICATED (see 'pa')",
-    /*.function */ padep,
-    /*.syntax */ "DEPRICATED (see 'pa')",
-    /*.next */ &send_dtmf_interface
+	/*.interface_name */ "paoffhook",
+	/*.desc */ "DEPRICATED (see 'pa')",
+	/*.function */ padep,
+	/*.syntax */ "DEPRICATED (see 'pa')",
+	/*.next */ &send_dtmf_interface
 };
 
 static switch_api_interface_t channel_info_interface = {
-    /*.interface_name */ "painfo",
-    /*.desc */ "DEPRICATED (see 'pa')",
-    /*.function */ padep,
-    /*.syntax */ "DEPRICATED (see 'pa')",
-    /*.next */ &answer_call_interface
+	/*.interface_name */ "painfo",
+	/*.desc */ "DEPRICATED (see 'pa')",
+	/*.function */ padep,
+	/*.syntax */ "DEPRICATED (see 'pa')",
+	/*.next */ &answer_call_interface
 };
 
 static switch_api_interface_t channel_hup_interface = {
-    /*.interface_name */ "pahup",
-    /*.desc */ "DEPRICATED (see 'pa')",
-    /*.function */ padep,
-    /*.syntax */ "DEPRICATED (see 'pa')",
-    /*.next */ &channel_info_interface
+	/*.interface_name */ "pahup",
+	/*.desc */ "DEPRICATED (see 'pa')",
+	/*.function */ padep,
+	/*.syntax */ "DEPRICATED (see 'pa')",
+	/*.next */ &channel_info_interface
 };
 
 static switch_api_interface_t channel_call_interface = {
-    /*.interface_name */ "pacall",
-    /*.desc */ "DEPRICATED (see 'pa')",
-    /*.function */ padep,
-    /*.syntax */ "DEPRICATED (see 'pa')",
-    /*.next */ &channel_hup_interface
+	/*.interface_name */ "pacall",
+	/*.desc */ "DEPRICATED (see 'pa')",
+	/*.function */ padep,
+	/*.syntax */ "DEPRICATED (see 'pa')",
+	/*.next */ &channel_hup_interface
 };
 
 static switch_api_interface_t channel_api_interface = {
@@ -796,14 +791,13 @@
 
 static const switch_io_routines_t channel_io_routines = {
 	/*.outgoing_channel */ channel_outgoing_channel,
-	/*.answer_channel */ channel_answer_channel,
 	/*.read_frame */ channel_read_frame,
 	/*.write_frame */ channel_write_frame,
 	/*.kill_channel */ channel_kill_channel,
 	/*.waitfor_read */ channel_waitfor_read,
 	/*.waitfor_write */ channel_waitfor_write,
 	/*.send_dtmf */ channel_send_dtmf,
-	/*.receive_message*/ channel_receive_message
+	/*.receive_message */ channel_receive_message
 };
 
 static const switch_endpoint_interface_t channel_endpoint_interface = {
@@ -827,8 +821,9 @@
 /* Make sure when you have 2 sessions in the same scope that you pass the appropriate one to the routines
    that allocate memory or you will have 1 channel with memory allocated from another channel's pool!
 */
-static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-													switch_core_session_t **new_session, switch_memory_pool_t *pool)
+static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session,
+													switch_caller_profile_t *outbound_profile,
+													switch_core_session_t **new_session, switch_memory_pool_t **pool)
 {
 
 	if ((*new_session = switch_core_session_request(&channel_endpoint_interface, pool)) != 0) {
@@ -838,12 +833,12 @@
 
 		switch_core_session_add_stream(*new_session, NULL);
 		if ((tech_pvt = (private_t *) switch_core_session_alloc(*new_session, sizeof(private_t))) != 0) {
-			memset(tech_pvt, 0, sizeof(*tech_pvt));            
+			memset(tech_pvt, 0, sizeof(*tech_pvt));
 			switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(*new_session));
 			channel = switch_core_session_get_channel(*new_session);
 			switch_core_session_set_private(*new_session, tech_pvt);
 			tech_pvt->session = *new_session;
-            globals.flags = GFLAG_EAR | GFLAG_MOUTH;
+			globals.flags = GFLAG_EAR | GFLAG_MOUTH;
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Hey where is my memory pool?\n");
 			switch_core_session_destroy(new_session);
@@ -852,9 +847,9 @@
 
 		if (outbound_profile) {
 			char name[128];
-            char *id = !switch_strlen_zero(outbound_profile->caller_id_number) ? outbound_profile->caller_id_number : "na";
+			char *id = !switch_strlen_zero(outbound_profile->caller_id_number) ? outbound_profile->caller_id_number : "na";
 			snprintf(name, sizeof(name), "PortAudio/%s", id);
-					 
+
 			switch_channel_set_name(channel, name);
 
 			caller_profile = switch_caller_profile_clone(*new_session, outbound_profile);
@@ -880,7 +875,7 @@
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
 
-    switch_status_t status;
+	switch_status_t status;
 
 	if (switch_core_new_memory_pool(&module_pool) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "OH OH no pool\n");
@@ -890,17 +885,18 @@
 	Pa_Initialize();
 
 	if (dump_info()) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't find any audio devices!\n");
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't find any audio devices!\n");
 		return SWITCH_STATUS_TERM;
-    }
+	}
 
 	if ((status = load_config()) != SWITCH_STATUS_SUCCESS) {
-        return status;
-    }
+		return status;
+	}
 
 
-    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Input Device: %d, Output Device: %d, Ring Device: %d Sample Rate: %d MS: %d\n", 
-                      globals.indev, globals.outdev, globals.ringdev, globals.sample_rate, globals.codec_ms);
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
+					  "Input Device: %d, Output Device: %d, Ring Device: %d Sample Rate: %d MS: %d\n", globals.indev,
+					  globals.outdev, globals.ringdev, globals.sample_rate, globals.codec_ms);
 
 
 	switch_core_hash_init(&globals.call_hash, module_pool);
@@ -920,7 +916,7 @@
 	globals.cng_frame.data = globals.cngbuf;
 	globals.cng_frame.buflen = sizeof(globals.cngbuf);
 	globals.cng_frame.datalen = sizeof(globals.cngbuf);
-    switch_set_flag((&globals.cng_frame), SFF_CNG);
+	switch_set_flag((&globals.cng_frame), SFF_CNG);
 
 	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &channel_module_interface;
@@ -934,7 +930,7 @@
 {
 	char *cf = "portaudio.conf";
 	switch_xml_t cfg, xml, settings, param;
-    switch_status_t status = SWITCH_STATUS_SUCCESS;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
 
 	if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", cf);
@@ -942,7 +938,7 @@
 	}
 
 	memset(&globals, 0, sizeof(globals));
-    globals.indev = globals.outdev = globals.ringdev = -1;
+	globals.indev = globals.outdev = globals.ringdev = -1;
 
 	if ((settings = switch_xml_child(cfg, "settings"))) {
 		for (param = switch_xml_child(settings, "param"); param; param = param->next) {
@@ -952,7 +948,7 @@
 			if (!strcmp(var, "debug")) {
 				globals.debug = atoi(val);
 			} else if (!strcmp(var, "ring-interval")) {
-                globals.ring_interval = atoi(val);
+				globals.ring_interval = atoi(val);
 			} else if (!strcmp(var, "ring-file")) {
 				set_global_ring_file(val);
 			} else if (!strcmp(var, "hold-file")) {
@@ -987,7 +983,7 @@
 				} else {
 					globals.ringdev = get_dev_by_name(val, 0);
 				}
-            }
+			}
 		}
 	}
 
@@ -1006,37 +1002,37 @@
 	if (!globals.ring_interval) {
 		globals.ring_interval = 5;
 	}
-    
-    if (!globals.timer_name) {
-        set_global_timer_name("soft");
-    }
-
-    if (globals.indev < 0) {
-        globals.indev = get_dev_by_name(NULL, 1);
-        if (globals.indev > -1) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Switching to default input device!\n");
-        } else {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find an input device!\n");
-            status = SWITCH_STATUS_GENERR;            
-        }
-    }
-
-    if (globals.outdev < 0) {
-        globals.outdev = get_dev_by_name(NULL, 0);
-        if (globals.outdev > -1) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Switching to default output device!\n");
-        } else {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find an input device!\n");
-            status = SWITCH_STATUS_GENERR;            
-        }
-    }
-
-    if (globals.ringdev < 0) {
-        if (globals.outdev > -1) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid ring device configured using output device!\n");
-            globals.ringdev = globals.outdev;
-        } 
-    }
+
+	if (!globals.timer_name) {
+		set_global_timer_name("soft");
+	}
+
+	if (globals.indev < 0) {
+		globals.indev = get_dev_by_name(NULL, 1);
+		if (globals.indev > -1) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Switching to default input device!\n");
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find an input device!\n");
+			status = SWITCH_STATUS_GENERR;
+		}
+	}
+
+	if (globals.outdev < 0) {
+		globals.outdev = get_dev_by_name(NULL, 0);
+		if (globals.outdev > -1) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Switching to default output device!\n");
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find an input device!\n");
+			status = SWITCH_STATUS_GENERR;
+		}
+	}
+
+	if (globals.ringdev < 0) {
+		if (globals.outdev > -1) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid ring device configured using output device!\n");
+			globals.ringdev = globals.outdev;
+		}
+	}
 
 	switch_xml_free(xml);
 
@@ -1061,18 +1057,18 @@
 
 static int get_dev_by_number(int number, int in)
 {
-    int numDevices = Pa_GetDeviceCount();
+	int numDevices = Pa_GetDeviceCount();
 	const PaDeviceInfo *pdi;
 
-    if (number > -1 && number < numDevices && (pdi = Pa_GetDeviceInfo(number))) {
-        if (in && pdi->maxInputChannels) {
-            return number;
-        } else if (!in && pdi->maxOutputChannels) {
-            return number;
-        }
-    }
-    
-    return -1;
+	if (number > -1 && number < numDevices && (pdi = Pa_GetDeviceInfo(number))) {
+		if (in && pdi->maxInputChannels) {
+			return number;
+		} else if (!in && pdi->maxOutputChannels) {
+			return number;
+		}
+	}
+
+	return -1;
 }
 
 static int get_dev_by_name(char *name, int in)
@@ -1088,15 +1084,15 @@
 	}
 
 	for (i = 0; i < numDevices; i++) {
-        int match = 0;
+		int match = 0;
 		pdi = Pa_GetDeviceInfo(i);
-        
+
 		if (switch_strlen_zero(name)) {
-            match = 1;
-        } else if (strstr(pdi->name, name)) {
-            match = 1;
-        }
-        
+			match = 1;
+		} else if (strstr(pdi->name, name)) {
+			match = 1;
+		}
+
 		if (match) {
 			if (in && pdi->maxInputChannels) {
 				return i;
@@ -1106,248 +1102,252 @@
 		}
 	}
 
-    if (switch_strlen_zero(name)) {
-        return -1;
-    }
+	if (switch_strlen_zero(name)) {
+		return -1;
+	}
 
 	return get_dev_by_name(NULL, in);
 }
 
 
 /*******************************************************************/
-static void PrintSupportedStandardSampleRates(const PaStreamParameters *inputParameters,
-                                              const PaStreamParameters *outputParameters)
+static void PrintSupportedStandardSampleRates(const PaStreamParameters * inputParameters, const PaStreamParameters * outputParameters)
 {
-    int i, printCount, cr = 7;
-    PaError err;
-    static double standardSampleRates[] = { 8000.0, 9600.0, 11025.0, 12000.0, 16000.0, 22050.0, 24000.0, 32000.0,
-                                            44100.0, 48000.0, 88200.0, 96000.0, 192000.0, -1};
-
-    printCount = cr;
-    for(i=0; standardSampleRates[i] > 0; i++) {
-        err = Pa_IsFormatSupported(inputParameters, outputParameters, standardSampleRates[i]);
-        if (err == paFormatIsSupported) {
-            if (printCount == cr) {
-                printCount = 0;
-                switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "\n\t%0.2f", standardSampleRates[i]);
-            } else {
-                switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  ", %0.2f", standardSampleRates[i]);
-            }
-            printCount++;
-        }
-    }
-    if (!printCount) {
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  " None\n");
-    } else {
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "\n");
-    }
+	int i, printCount, cr = 7;
+	PaError err;
+	static double standardSampleRates[] = { 8000.0, 9600.0, 11025.0, 12000.0, 16000.0, 22050.0, 24000.0, 32000.0,
+		44100.0, 48000.0, 88200.0, 96000.0, 192000.0, -1
+	};
+
+	printCount = cr;
+	for (i = 0; standardSampleRates[i] > 0; i++) {
+		err = Pa_IsFormatSupported(inputParameters, outputParameters, standardSampleRates[i]);
+		if (err == paFormatIsSupported) {
+			if (printCount == cr) {
+				printCount = 0;
+				switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "\n\t%0.2f", standardSampleRates[i]);
+			} else {
+				switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, ", %0.2f", standardSampleRates[i]);
+			}
+			printCount++;
+		}
+	}
+	if (!printCount) {
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, " None\n");
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "\n");
+	}
 }
+
 /*******************************************************************/
 
 static switch_status_t devlist(char **argv, int argc, switch_stream_handle_t *stream)
 {
-	int     i, numDevices;
-    const   PaDeviceInfo *deviceInfo;
-            
-    numDevices = Pa_GetDeviceCount();
-    if (numDevices < 0) {
+	int i, numDevices;
+	const PaDeviceInfo *deviceInfo;
+
+	numDevices = Pa_GetDeviceCount();
+	if (numDevices < 0) {
 		return SWITCH_STATUS_SUCCESS;
-    }
-	for(i=0; i<numDevices; i++) {
-        deviceInfo = Pa_GetDeviceInfo(i);
-        stream->write_function(stream, "%d;%s;%d;%d\n", i, deviceInfo->name, deviceInfo->maxInputChannels, deviceInfo->maxOutputChannels);
+	}
+	for (i = 0; i < numDevices; i++) {
+		deviceInfo = Pa_GetDeviceInfo(i);
+		stream->write_function(stream, "%d;%s;%d;%d\n", i, deviceInfo->name, deviceInfo->maxInputChannels, deviceInfo->maxOutputChannels);
 	}
 
-    return SWITCH_STATUS_SUCCESS;
+	return SWITCH_STATUS_SUCCESS;
 }
 
 static int dump_info(void)
 {
-    int     i, numDevices, defaultDisplayed;
-    const   PaDeviceInfo *deviceInfo;
-    PaStreamParameters inputParameters, outputParameters;
-    PaError err;
-    const char *line = "--------------------------------------------------------------------------------\n";
-    
+	int i, numDevices, defaultDisplayed;
+	const PaDeviceInfo *deviceInfo;
+	PaStreamParameters inputParameters, outputParameters;
+	PaError err;
+	const char *line = "--------------------------------------------------------------------------------\n";
 
 
-    switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "PortAudio version number = %d\nPortAudio version text = '%s'\n",
-                      Pa_GetVersion(), Pa_GetVersionText());
+
+	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,
+					  "PortAudio version number = %d\nPortAudio version text = '%s'\n", Pa_GetVersion(), Pa_GetVersionText());
 	if (globals.audio_stream) {
-		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "ERROR: Cannot use this command this while a call is in progress\n");
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "ERROR: Cannot use this command this while a call is in progress\n");
 		return 0;
 	}
-            
-    numDevices = Pa_GetDeviceCount();
-    if (numDevices < 0) {
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "ERROR: Pa_CountDevices returned 0x%x\n", numDevices);
-        err = numDevices;
-        goto error;
-    }
-    
-    switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "Number of devices = %d\n", numDevices);
-    for(i=0; i<numDevices; i++) {
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "%s", line);
-        deviceInfo = Pa_GetDeviceInfo(i);
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "Device #%d ", i);
-                
-        /* Mark global and API specific default devices */
-        defaultDisplayed = 0;
-        if (i == Pa_GetDefaultInputDevice()) {
-            switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "**Default Input");
-            defaultDisplayed = 1;
-            
-        } else if (i == Pa_GetHostApiInfo(deviceInfo->hostApi)->defaultInputDevice) {
-            
-            const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo(deviceInfo->hostApi);
-            switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "**Default %s Input", hostInfo->name);
-            defaultDisplayed = 1;
-        }
-        
-        if (i == Pa_GetDefaultOutputDevice()) {
-            switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "**Default Output");
-            defaultDisplayed = 1;
-
-        } else if (i == Pa_GetHostApiInfo(deviceInfo->hostApi)->defaultOutputDevice) {
-
-            const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo(deviceInfo->hostApi);
-            switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "**Default %s Output", hostInfo->name);
-            defaultDisplayed = 1;
-        }
-
-        if (defaultDisplayed) {
-            switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "** | ");
-        }
-        /* print device info fields */
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "Name: %s\n", deviceInfo->name);
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "Host: %s | ",  Pa_GetHostApiInfo(deviceInfo->hostApi)->name);
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "inputs: %d | ", deviceInfo->maxInputChannels );
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "outputs: %d | ", deviceInfo->maxOutputChannels );
-
-        switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,  "Default rate: %8.2f\n", deviceInfo->defaultSampleRate);
-
-        /* poll for standard sample rates */
-        inputParameters.device = i;
-        inputParameters.channelCount = deviceInfo->maxInputChannels;
-        inputParameters.sampleFormat = paInt16;
-        inputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
-        inputParameters.hostApiSpecificStreamInfo = NULL;
-        
-        outputParameters.device = i;
-        outputParameters.channelCount = deviceInfo->maxOutputChannels;
-        outputParameters.sampleFormat = paInt16;
-        outputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */
-        outputParameters.hostApiSpecificStreamInfo = NULL;
-
-        if (inputParameters.channelCount > 0) {
-
-            switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "half-duplex 16 bit %d channel input rates:",
-                              inputParameters.channelCount);
-            PrintSupportedStandardSampleRates(&inputParameters, NULL);
-        }
-
-        if (outputParameters.channelCount > 0) {
-            switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "half-duplex 16 bit %d channel output rates:",
-                              outputParameters.channelCount);
-            PrintSupportedStandardSampleRates(NULL, &outputParameters);
-        }
-
-        if (inputParameters.channelCount > 0 && outputParameters.channelCount > 0) {
-
-            switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "full-duplex 16 bit %d channel input, %d channel output rates:",
-                              inputParameters.channelCount, outputParameters.channelCount);
-            PrintSupportedStandardSampleRates(&inputParameters, &outputParameters);
-        }
-    }
-
-    switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "%s", line);
-    
-    return 0;
-
- error:
-    switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_ERROR,  "An error occured while using the portaudio stream\n");
-    switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_ERROR,  "Error number: %d\n", err);
-    switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_ERROR,  "Error message: %s\n", Pa_GetErrorText(err));
-    return err;
+
+	numDevices = Pa_GetDeviceCount();
+	if (numDevices < 0) {
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "ERROR: Pa_CountDevices returned 0x%x\n", numDevices);
+		err = numDevices;
+		goto error;
+	}
+
+	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "Number of devices = %d\n", numDevices);
+	for (i = 0; i < numDevices; i++) {
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "%s", line);
+		deviceInfo = Pa_GetDeviceInfo(i);
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "Device #%d ", i);
+
+		/* Mark global and API specific default devices */
+		defaultDisplayed = 0;
+		if (i == Pa_GetDefaultInputDevice()) {
+			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "**Default Input");
+			defaultDisplayed = 1;
+
+		} else if (i == Pa_GetHostApiInfo(deviceInfo->hostApi)->defaultInputDevice) {
+
+			const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo(deviceInfo->hostApi);
+			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "**Default %s Input", hostInfo->name);
+			defaultDisplayed = 1;
+		}
+
+		if (i == Pa_GetDefaultOutputDevice()) {
+			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "**Default Output");
+			defaultDisplayed = 1;
+
+		} else if (i == Pa_GetHostApiInfo(deviceInfo->hostApi)->defaultOutputDevice) {
+
+			const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo(deviceInfo->hostApi);
+			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "**Default %s Output", hostInfo->name);
+			defaultDisplayed = 1;
+		}
+
+		if (defaultDisplayed) {
+			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "** | ");
+		}
+		/* print device info fields */
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "Name: %s\n", deviceInfo->name);
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "Host: %s | ", Pa_GetHostApiInfo(deviceInfo->hostApi)->name);
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "inputs: %d | ", deviceInfo->maxInputChannels);
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "outputs: %d | ", deviceInfo->maxOutputChannels);
+
+		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "Default rate: %8.2f\n", deviceInfo->defaultSampleRate);
+
+		/* poll for standard sample rates */
+		inputParameters.device = i;
+		inputParameters.channelCount = deviceInfo->maxInputChannels;
+		inputParameters.sampleFormat = paInt16;
+		inputParameters.suggestedLatency = 0;	/* ignored by Pa_IsFormatSupported() */
+		inputParameters.hostApiSpecificStreamInfo = NULL;
+
+		outputParameters.device = i;
+		outputParameters.channelCount = deviceInfo->maxOutputChannels;
+		outputParameters.sampleFormat = paInt16;
+		outputParameters.suggestedLatency = 0;	/* ignored by Pa_IsFormatSupported() */
+		outputParameters.hostApiSpecificStreamInfo = NULL;
+
+		if (inputParameters.channelCount > 0) {
+
+			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "half-duplex 16 bit %d channel input rates:", inputParameters.channelCount);
+			PrintSupportedStandardSampleRates(&inputParameters, NULL);
+		}
+
+		if (outputParameters.channelCount > 0) {
+			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "half-duplex 16 bit %d channel output rates:", outputParameters.channelCount);
+			PrintSupportedStandardSampleRates(NULL, &outputParameters);
+		}
+
+		if (inputParameters.channelCount > 0 && outputParameters.channelCount > 0) {
+
+			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,
+							  "full-duplex 16 bit %d channel input, %d channel output rates:", inputParameters.channelCount,
+							  outputParameters.channelCount);
+			PrintSupportedStandardSampleRates(&inputParameters, &outputParameters);
+		}
+	}
+
+	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "%s", line);
+
+	return 0;
+
+  error:
+	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_ERROR, "An error occured while using the portaudio stream\n");
+	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_ERROR, "Error number: %d\n", err);
+	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_ERROR, "Error message: %s\n", Pa_GetErrorText(err));
+	return err;
 }
 
 
 
 static switch_status_t engage_device(int sample_rate, int codec_ms)
 {
-    PaStreamParameters inputParameters, outputParameters;
+	PaStreamParameters inputParameters, outputParameters;
 	PaError err;
 
-    if (!globals.audio_stream) {
-        if (!sample_rate) {
-            sample_rate = globals.sample_rate;
-        }
-        if (!codec_ms) {
-            codec_ms = globals.codec_ms;
-        }
-
-        if (switch_core_codec_init(&globals.read_codec,
-                                   "L16",
-                                   NULL,
-                                   sample_rate,
-                                   codec_ms,
-                                   1,
-                                   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-                                   NULL, 
-                                   NULL) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
-            return SWITCH_STATUS_FALSE;
-        } else {
-            if (switch_core_codec_init(&globals.write_codec,
-                                       "L16",
-                                       NULL,
-                                       sample_rate,
-                                       codec_ms,
-                                       1,
-                                       SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-                                       NULL,
-                                       NULL) != SWITCH_STATUS_SUCCESS) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
-                switch_core_codec_destroy(&globals.read_codec);
-                return SWITCH_STATUS_FALSE;
-            }
-        }
-
-        globals.read_frame.rate = sample_rate;
-        globals.read_frame.codec = &globals.read_codec;
-
-
-
-        switch_mutex_lock(globals.device_lock);
-        /* LOCKED ***************************************************************************************************/
-        inputParameters.device = globals.indev;
-        inputParameters.channelCount = 1;
-        inputParameters.sampleFormat = SAMPLE_TYPE;
-        inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
-        inputParameters.hostApiSpecificStreamInfo = NULL;
-
-        outputParameters.device = globals.outdev;
-        outputParameters.channelCount = 1;
-        outputParameters.sampleFormat =  SAMPLE_TYPE;
-        outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency;
-        outputParameters.hostApiSpecificStreamInfo = NULL;
-        err = OpenAudioStream(&globals.audio_stream, &inputParameters, &outputParameters, sample_rate, paClipOff);
-        /* UNLOCKED **************************************************************************************************/
-        switch_mutex_unlock(globals.device_lock);
-
-
-        if (err != paNoError) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open audio device!\n");
-            switch_core_codec_destroy(&globals.read_codec);
-            switch_core_codec_destroy(&globals.write_codec);
-
-            return SWITCH_STATUS_FALSE;
-        }
-    }
+	if (!globals.audio_stream) {
+		if (!sample_rate) {
+			sample_rate = globals.sample_rate;
+		}
+		if (!codec_ms) {
+			codec_ms = globals.codec_ms;
+		}
+
+		if (switch_core_codec_init(&globals.read_codec,
+								   "L16",
+								   NULL, sample_rate, codec_ms, 1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL,
+								   NULL) != SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
+			return SWITCH_STATUS_FALSE;
+		} else {
+			if (switch_core_codec_init(&globals.write_codec,
+									   "L16",
+									   NULL,
+									   sample_rate, codec_ms, 1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL,
+									   NULL) != SWITCH_STATUS_SUCCESS) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
+				switch_core_codec_destroy(&globals.read_codec);
+				return SWITCH_STATUS_FALSE;
+			}
+		}
+
+		if (switch_core_timer_init(&globals.timer,
+								   globals.timer_name, codec_ms, globals.read_codec.implementation->samples_per_frame,
+								   module_pool) != SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "setup timer failed!\n");
+			switch_core_codec_destroy(&globals.read_codec);
+			switch_core_codec_destroy(&globals.write_codec);
+			return SWITCH_STATUS_FALSE;
+		}
+
+
+
+
 
+		globals.read_frame.rate = sample_rate;
+		globals.read_frame.codec = &globals.read_codec;
 
 
-    return SWITCH_STATUS_SUCCESS;
+
+		switch_mutex_lock(globals.device_lock);
+		/* LOCKED ************************************************************************************************** */
+		inputParameters.device = globals.indev;
+		inputParameters.channelCount = 1;
+		inputParameters.sampleFormat = SAMPLE_TYPE;
+		inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
+		inputParameters.hostApiSpecificStreamInfo = NULL;
+
+		outputParameters.device = globals.outdev;
+		outputParameters.channelCount = 1;
+		outputParameters.sampleFormat = SAMPLE_TYPE;
+		outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency;
+		outputParameters.hostApiSpecificStreamInfo = NULL;
+		err = OpenAudioStream(&globals.audio_stream, &inputParameters, &outputParameters, sample_rate, paClipOff);
+		/* UNLOCKED ************************************************************************************************* */
+		switch_mutex_unlock(globals.device_lock);
+
+
+		if (err != paNoError) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open audio device!\n");
+			switch_core_codec_destroy(&globals.read_codec);
+			switch_core_codec_destroy(&globals.write_codec);
+
+			return SWITCH_STATUS_FALSE;
+		}
+	}
+
+
+
+	return SWITCH_STATUS_SUCCESS;
 
 
 }
@@ -1356,34 +1356,34 @@
 static switch_status_t engage_ring_device(int sample_rate, int channels)
 {
 	//int codec_ms = 20;
-    PaStreamParameters outputParameters;
+	PaStreamParameters outputParameters;
 	PaError err;
 
-    if (!globals.ring_stream) {
-        if (!sample_rate) {
-            sample_rate = globals.sample_rate;
-        }
-
-        switch_mutex_lock(globals.device_lock);
-        /* LOCKED ***************************************************************************************************/
-        outputParameters.device = globals.ringdev;
-        outputParameters.channelCount = channels;
-        outputParameters.sampleFormat =  SAMPLE_TYPE;
-        outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency;
-        outputParameters.hostApiSpecificStreamInfo = NULL;
-        err = OpenAudioStream(&globals.ring_stream, NULL, &outputParameters, sample_rate, paClipOff);
-        /* UNLOCKED **************************************************************************************************/
-        switch_mutex_unlock(globals.device_lock);
-
-
-        if (err != paNoError) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open ring device!\n");
-            return SWITCH_STATUS_FALSE;
-        }
-    }
+	if (!globals.ring_stream) {
+		if (!sample_rate) {
+			sample_rate = globals.sample_rate;
+		}
+
+		switch_mutex_lock(globals.device_lock);
+		/* LOCKED ************************************************************************************************** */
+		outputParameters.device = globals.ringdev;
+		outputParameters.channelCount = channels;
+		outputParameters.sampleFormat = SAMPLE_TYPE;
+		outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency;
+		outputParameters.hostApiSpecificStreamInfo = NULL;
+		err = OpenAudioStream(&globals.ring_stream, NULL, &outputParameters, sample_rate, paClipOff);
+		/* UNLOCKED ************************************************************************************************* */
+		switch_mutex_unlock(globals.device_lock);
+
+
+		if (err != paNoError) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open ring device!\n");
+			return SWITCH_STATUS_FALSE;
+		}
+	}
 
-    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Engage ring device! rate: %d channels %d\n", sample_rate, channels);
-    return SWITCH_STATUS_SUCCESS;
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Engage ring device! rate: %d channels %d\n", sample_rate, channels);
+	return SWITCH_STATUS_SUCCESS;
 }
 
 
@@ -1391,64 +1391,64 @@
 
 static switch_status_t dtmf_call(char **argv, int argc, switch_stream_handle_t *stream)
 {
-    char *dtmf = argv[0];
+	char *dtmf = argv[0];
 
-    if (switch_strlen_zero(dtmf)) {
-        stream->write_function(stream, "No DTMF Supplied!\n");
-    } else {
-        switch_mutex_lock(globals.pvt_lock);
-        if (globals.call_list) {
-            switch_channel_t *channel = switch_core_session_get_channel(globals.call_list->session);
-            switch_channel_queue_dtmf(channel, dtmf);
-        }
-        switch_mutex_unlock(globals.pvt_lock);
-    }
+	if (switch_strlen_zero(dtmf)) {
+		stream->write_function(stream, "No DTMF Supplied!\n");
+	} else {
+		switch_mutex_lock(globals.pvt_lock);
+		if (globals.call_list) {
+			switch_channel_t *channel = switch_core_session_get_channel(globals.call_list->session);
+			switch_channel_queue_dtmf(channel, dtmf);
+		}
+		switch_mutex_unlock(globals.pvt_lock);
+	}
 
-    return SWITCH_STATUS_SUCCESS;
+	return SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t switch_call(char **argv, int argc, switch_stream_handle_t *stream)
 {
-    private_t *tp,*tech_pvt = NULL;
-    char *callid = argv[0];
-    uint8_t one_call = 0;
-
-    switch_mutex_lock(globals.pvt_lock);
-    if (switch_strlen_zero(callid)) {
-        if (globals.call_list) {
-            if (globals.call_list->next) {
-                tech_pvt = globals.call_list->next;
-            } else {
-                tech_pvt = globals.call_list;
-                one_call = 1;
-            }
-        }
-    } else if (!strcasecmp(callid, "none")) {
-        for (tp = globals.call_list; tp; tp = tp->next) {
-            switch_clear_flag_locked(tp, TFLAG_MASTER);
-        }
-        stream->write_function(stream, "OK\n");
-        goto done;
-    } else {
-        tech_pvt = switch_core_hash_find(globals.call_hash, callid);
-    }
+	private_t *tp, *tech_pvt = NULL;
+	char *callid = argv[0];
+	uint8_t one_call = 0;
+
+	switch_mutex_lock(globals.pvt_lock);
+	if (switch_strlen_zero(callid)) {
+		if (globals.call_list) {
+			if (globals.call_list->next) {
+				tech_pvt = globals.call_list->next;
+			} else {
+				tech_pvt = globals.call_list;
+				one_call = 1;
+			}
+		}
+	} else if (!strcasecmp(callid, "none")) {
+		for (tp = globals.call_list; tp; tp = tp->next) {
+			switch_clear_flag_locked(tp, TFLAG_MASTER);
+		}
+		stream->write_function(stream, "OK\n");
+		goto done;
+	} else {
+		tech_pvt = switch_core_hash_find(globals.call_hash, callid);
+	}
 
 	if (tech_pvt) {
-        if (tech_pvt == globals.call_list && !tech_pvt->next) {
-            one_call = 1;
-        }
-
-        if (!one_call) {
-            remove_pvt(tech_pvt);
-        }
-        add_pvt(tech_pvt, PA_MASTER);
-        stream->write_function(stream, "OK\n");
+		if (tech_pvt == globals.call_list && !tech_pvt->next) {
+			one_call = 1;
+		}
+
+		if (!one_call) {
+			remove_pvt(tech_pvt);
+		}
+		add_pvt(tech_pvt, PA_MASTER);
+		stream->write_function(stream, "OK\n");
 	} else {
 		stream->write_function(stream, "NO SUCH CALL\n");
 	}
 
- done:
-    switch_mutex_unlock(globals.pvt_lock);
+  done:
+	switch_mutex_unlock(globals.pvt_lock);
 
 	return SWITCH_STATUS_SUCCESS;
 
@@ -1456,23 +1456,24 @@
 
 static switch_status_t hangup_call(char **argv, int argc, switch_stream_handle_t *stream)
 {
-    private_t *tech_pvt;
-    char *callid = argv[0];
-    
-    switch_mutex_lock(globals.pvt_lock);
-    if (switch_strlen_zero(callid)) {
-        tech_pvt = globals.call_list;
-    } else {
-        tech_pvt = switch_core_hash_find(globals.call_hash, callid);
-    }
+	private_t *tech_pvt;
+	char *callid = argv[0];
+
+	switch_mutex_lock(globals.pvt_lock);
+	if (switch_strlen_zero(callid)) {
+		tech_pvt = globals.call_list;
+	} else {
+		tech_pvt = switch_core_hash_find(globals.call_hash, callid);
+	}
 
 	if (tech_pvt) {
-        switch_set_flag_locked(tech_pvt, TFLAG_HUP);
+		switch_channel_hangup(switch_core_session_get_channel(tech_pvt->session), SWITCH_CAUSE_NORMAL_CLEARING);
+		//switch_set_flag_locked(tech_pvt, TFLAG_HUP);
 		stream->write_function(stream, "OK\n");
 	} else {
 		stream->write_function(stream, "NO SUCH CALL\n");
 	}
-    switch_mutex_unlock(globals.pvt_lock);
+	switch_mutex_unlock(globals.pvt_lock);
 
 	return SWITCH_STATUS_SUCCESS;
 
@@ -1480,43 +1481,43 @@
 
 static switch_status_t answer_call(char **argv, int argc, switch_stream_handle_t *stream)
 {
-    private_t *tp;
-    int x = 0;
-    char *callid = argv[0];
-    
-    switch_mutex_lock(globals.pvt_lock);
-
-    if (!switch_strlen_zero(callid)) {
-        if ((tp = switch_core_hash_find(globals.call_hash, callid))) {
-            if (switch_test_flag(tp, TFLAG_ANSWER)) {
-                stream->write_function(stream, "CALL ALREADY ANSWERED\n");
-            } else {
-                switch_channel_t *channel = switch_core_session_get_channel(tp->session);
-                switch_set_flag_locked(tp, TFLAG_ANSWER);
-                switch_channel_answer(channel);
-                add_pvt(tp, PA_MASTER);
-            }
-        } else {
-            stream->write_function(stream, "NO SUCH CALL\n");
-        }
-
-        goto done;
-    }
-
-    for (tp = globals.call_list; tp; tp = tp->next) {
-        if (!switch_test_flag(tp, TFLAG_ANSWER)) {
-            switch_channel_t *channel = switch_core_session_get_channel(tp->session);
-            switch_set_flag_locked(tp, TFLAG_ANSWER);
-            switch_channel_answer(channel);
-            add_pvt(tp, PA_MASTER);
-            x++;
-            break;
-        }
-	} 
- done:
-    switch_mutex_unlock(globals.pvt_lock);
+	private_t *tp;
+	int x = 0;
+	char *callid = argv[0];
+
+	switch_mutex_lock(globals.pvt_lock);
+
+	if (!switch_strlen_zero(callid)) {
+		if ((tp = switch_core_hash_find(globals.call_hash, callid))) {
+			if (switch_test_flag(tp, TFLAG_ANSWER)) {
+				stream->write_function(stream, "CALL ALREADY ANSWERED\n");
+			} else {
+				switch_channel_t *channel = switch_core_session_get_channel(tp->session);
+				switch_set_flag_locked(tp, TFLAG_ANSWER);
+				switch_channel_answer(channel);
+				add_pvt(tp, PA_MASTER);
+			}
+		} else {
+			stream->write_function(stream, "NO SUCH CALL\n");
+		}
 
-    stream->write_function(stream, "Answered %d channels.\n", x);    
+		goto done;
+	}
+
+	for (tp = globals.call_list; tp; tp = tp->next) {
+		if (!switch_test_flag(tp, TFLAG_ANSWER)) {
+			switch_channel_t *channel = switch_core_session_get_channel(tp->session);
+			switch_set_flag_locked(tp, TFLAG_ANSWER);
+			switch_channel_answer(channel);
+			add_pvt(tp, PA_MASTER);
+			x++;
+			break;
+		}
+	}
+  done:
+	switch_mutex_unlock(globals.pvt_lock);
+
+	stream->write_function(stream, "Answered %d channels.\n", x);
 
 
 	return SWITCH_STATUS_SUCCESS;
@@ -1525,113 +1526,110 @@
 
 static switch_status_t do_flags(char **argv, int argc, switch_stream_handle_t *stream)
 {
-    char *action = argv[0];
-    char *flag_str = argv[1];
-    GFLAGS flags = GFLAG_NONE;
-    char *p;
-    int x = 0;
-
-    if (argc < 2) {
-        goto desc;
-    }
-
-    for (x = 1; x < argc; x++) {
-        flag_str = argv[x];
-        for(p = flag_str; *p; p++) {
-            *p = (char)tolower(*p);
-        }
-    
-        if (strstr(flag_str, "ear")) {
-            flags |= GFLAG_EAR;
-        } 
-        if (strstr(flag_str, "mouth")) {
-            flags |= GFLAG_MOUTH;
-        }
-    }
-
-    if (!strcasecmp(action, "on")) {
-        if (flags & GFLAG_EAR) {
-            switch_set_flag((&globals), GFLAG_EAR);
-        }
-        if (flags & GFLAG_MOUTH) {
-            switch_set_flag((&globals), GFLAG_MOUTH);
-        }
-    } else if (!strcasecmp(action, "off")) {
-        if (flags & GFLAG_EAR) {
-            switch_clear_flag((&globals), GFLAG_EAR);
-        }
-        if (flags & GFLAG_MOUTH) {
-            switch_clear_flag((&globals), GFLAG_MOUTH);
-        }
-    } else {
-        goto bad;
-    }
-
- desc:
-    x = 0;
-    stream->write_function(stream, "FLAGS: ");
-    if (switch_test_flag((&globals), GFLAG_EAR)) {
-        stream->write_function(stream, "ear");
-        x++;
-    }
-    if (switch_test_flag((&globals), GFLAG_MOUTH)) {
-        stream->write_function(stream, "%smouth", x ? "|" : "");
-        x++;
-    }
-    if (!x) {
-        stream->write_function(stream, "none");
-    }
-
-    goto done;
-
- bad:
-    stream->write_function(stream, "Usage: flags [on|off] <flags>\n");    
- done:
-    return SWITCH_STATUS_SUCCESS;
+	char *action = argv[0];
+	char *flag_str = argv[1];
+	GFLAGS flags = GFLAG_NONE;
+	char *p;
+	int x = 0;
+
+	if (argc < 2) {
+		goto desc;
+	}
+
+	for (x = 1; x < argc; x++) {
+		flag_str = argv[x];
+		for (p = flag_str; *p; p++) {
+			*p = (char) tolower(*p);
+		}
+
+		if (strstr(flag_str, "ear")) {
+			flags |= GFLAG_EAR;
+		}
+		if (strstr(flag_str, "mouth")) {
+			flags |= GFLAG_MOUTH;
+		}
+	}
+
+	if (!strcasecmp(action, "on")) {
+		if (flags & GFLAG_EAR) {
+			switch_set_flag((&globals), GFLAG_EAR);
+		}
+		if (flags & GFLAG_MOUTH) {
+			switch_set_flag((&globals), GFLAG_MOUTH);
+		}
+	} else if (!strcasecmp(action, "off")) {
+		if (flags & GFLAG_EAR) {
+			switch_clear_flag((&globals), GFLAG_EAR);
+		}
+		if (flags & GFLAG_MOUTH) {
+			switch_clear_flag((&globals), GFLAG_MOUTH);
+		}
+	} else {
+		goto bad;
+	}
+
+  desc:
+	x = 0;
+	stream->write_function(stream, "FLAGS: ");
+	if (switch_test_flag((&globals), GFLAG_EAR)) {
+		stream->write_function(stream, "ear");
+		x++;
+	}
+	if (switch_test_flag((&globals), GFLAG_MOUTH)) {
+		stream->write_function(stream, "%smouth", x ? "|" : "");
+		x++;
+	}
+	if (!x) {
+		stream->write_function(stream, "none");
+	}
+
+	goto done;
+
+  bad:
+	stream->write_function(stream, "Usage: flags [on|off] <flags>\n");
+  done:
+	return SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t list_calls(char **argv, int argc, switch_stream_handle_t *stream)
 {
-    private_t *tp;
-    int x = 0;
-    char *cid_name = "n/a";
-    char *cid_num = "n/a";
-    
-    switch_mutex_lock(globals.pvt_lock);
-    for (tp = globals.call_list; tp; tp = tp->next) {
+	private_t *tp;
+	int x = 0;
+	char *cid_name = "n/a";
+	char *cid_num = "n/a";
+
+	switch_mutex_lock(globals.pvt_lock);
+	for (tp = globals.call_list; tp; tp = tp->next) {
 		switch_channel_t *channel;
-        switch_caller_profile_t *profile;
-        x++;
-        channel = switch_core_session_get_channel(tp->session);        
-        
-        if ((profile = switch_channel_get_caller_profile(channel))) {
-            if (profile->originatee_caller_profile) {
-                cid_name = "Outbound Call";
-                cid_num = profile->originatee_caller_profile->destination_number;
-            } else {
-                cid_name = profile->caller_id_name;
-                cid_num = profile->caller_id_number;
-            }
-        }
-
-        stream->write_function(stream, "%s %s [%s (%s)] %s\n", tp->call_id, switch_channel_get_name(channel),
-                               cid_name,
-                               cid_num,
-                               switch_test_flag(tp, TFLAG_MASTER) ? "active" : "hold"
-                               );
-    }
-    switch_mutex_unlock(globals.pvt_lock);
+		switch_caller_profile_t *profile;
+		x++;
+		channel = switch_core_session_get_channel(tp->session);
+
+		if ((profile = switch_channel_get_caller_profile(channel))) {
+			if (profile->originatee_caller_profile) {
+				cid_name = "Outbound Call";
+				cid_num = profile->originatee_caller_profile->destination_number;
+			} else {
+				cid_name = profile->caller_id_name;
+				cid_num = profile->caller_id_number;
+			}
+		}
+
+		stream->write_function(stream, "%s %s [%s (%s)] %s\n", tp->call_id, switch_channel_get_name(channel),
+							   cid_name, cid_num, switch_test_flag(tp, TFLAG_MASTER) ? "active" : "hold");
+	}
+	switch_mutex_unlock(globals.pvt_lock);
 
-    stream->write_function(stream, "\n%d call%s\n", x, x == 1 ? "" : "s");
+	stream->write_function(stream, "\n%d call%s\n", x, x == 1 ? "" : "s");
 
-    return SWITCH_STATUS_SUCCESS;
+	return SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t place_call(char **argv, int argc, switch_stream_handle_t *stream)
 {
 	switch_core_session_t *session;
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
-    char *dest = NULL;
+	char *dest = NULL;
 
 	if (!argv[0]) {
 		stream->write_function(stream, "FAIL:Usage: call <dest>\n");
@@ -1642,9 +1640,9 @@
 	if ((session = switch_core_session_request(&channel_endpoint_interface, NULL)) != 0) {
 		private_t *tech_pvt;
 		switch_channel_t *channel;
-        char *dialplan = globals.dialplan;
-        char *cid_name = globals.cid_name;
-        char *cid_num = globals.cid_num;        
+		char *dialplan = globals.dialplan;
+		char *cid_name = globals.cid_name;
+		char *cid_num = globals.cid_num;
 
 		switch_core_session_add_stream(session, NULL);
 		if ((tech_pvt = (private_t *) switch_core_session_alloc(session, sizeof(private_t))) != 0) {
@@ -1653,7 +1651,7 @@
 			channel = switch_core_session_get_channel(session);
 			switch_core_session_set_private(session, tech_pvt);
 			tech_pvt->session = session;
-            globals.flags = GFLAG_EAR | GFLAG_MOUTH;
+			globals.flags = GFLAG_EAR | GFLAG_MOUTH;
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Hey where is my memory pool?\n");
 			switch_core_session_destroy(&session);
@@ -1661,31 +1659,29 @@
 		}
 
 		if (!switch_strlen_zero(argv[1])) {
-            dialplan = argv[1];
-        }
+			dialplan = argv[1];
+		}
 
-        if (!switch_strlen_zero(argv[2])) {
-            cid_num = argv[2];
-        }
-
-        if (!switch_strlen_zero(argv[3])) {
-            cid_name = argv[3];
-        }
-
-        if (!switch_strlen_zero(argv[4])) {
-            tech_pvt->sample_rate = atoi(argv[4]);
-        }
-
-        if (!switch_strlen_zero(argv[4])) {
-            tech_pvt->codec_ms = atoi(argv[5]);
-        }
+		if (!switch_strlen_zero(argv[2])) {
+			cid_num = argv[2];
+		}
+
+		if (!switch_strlen_zero(argv[3])) {
+			cid_name = argv[3];
+		}
+
+		if (!switch_strlen_zero(argv[4])) {
+			tech_pvt->sample_rate = atoi(argv[4]);
+		}
+
+		if (!switch_strlen_zero(argv[4])) {
+			tech_pvt->codec_ms = atoi(argv[5]);
+		}
 
 		if ((tech_pvt->caller_profile = switch_caller_profile_new(switch_core_session_get_pool(session),
 																  NULL,
-																  dialplan,
-                                                                  cid_name,
-																  cid_num,
-                                                                  NULL, NULL, NULL, NULL, (char *)modname, NULL, dest)) != 0) {
+																  dialplan, cid_name, cid_num, NULL, NULL, NULL, NULL, (char *) modname, NULL,
+																  dest)) != 0) {
 			char name[128];
 			snprintf(name, sizeof(name), "PortAudio/%s",
 					 tech_pvt->caller_profile->destination_number ? tech_pvt->caller_profile->destination_number : modname);
@@ -1695,14 +1691,14 @@
 		}
 		tech_pvt->session = session;
 		if ((status = engage_device(tech_pvt->sample_rate, tech_pvt->codec_ms)) == SWITCH_STATUS_SUCCESS) {
-            switch_set_flag_locked(tech_pvt, TFLAG_ANSWER);
-            switch_channel_mark_answered(channel);
+			switch_set_flag_locked(tech_pvt, TFLAG_ANSWER);
+			switch_channel_mark_answered(channel);
 			switch_channel_set_state(channel, CS_INIT);
 			switch_core_session_thread_launch(tech_pvt->session);
-            add_pvt(tech_pvt, PA_MASTER);
+			add_pvt(tech_pvt, PA_MASTER);
 			stream->write_function(stream, "SUCCESS:%s:%s\n", tech_pvt->call_id, switch_core_session_get_uuid(tech_pvt->session));
 		} else {
-            switch_core_session_destroy(&session);
+			switch_core_session_destroy(&session);
 			stream->write_function(stream, "FAIL:Device Error!\n");
 		}
 	}
@@ -1712,72 +1708,71 @@
 
 static switch_status_t padep(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
-    stream->write_function(stream, "This command no longer exists (try 'pa help')\n");
-    return SWITCH_STATUS_SUCCESS;
+	stream->write_function(stream, "This command no longer exists (try 'pa help')\n");
+	return SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t pa_cmd(char *cmd, switch_core_session_t *isession, switch_stream_handle_t *stream)
 {
-    char *argv[1024] = {0};
-    int argc = 0;
-    char *mycmd = NULL, *devname = NULL;
-    switch_status_t status = SWITCH_STATUS_SUCCESS;
-    pa_command_t func = NULL;
-    int lead = 1, devval = 0;
-    const char *usage_string = "USAGE:\n"
-        "--------------------------------------------------------------------------------\n"
-        "pa help\n"
-        "pa dump\n"
-        "pa call <dest> [<dialplan> <cid_name> <cid_num> <rate>]\n"
-        "pa answer [<call_id>]\n"
-        "pa hangup [<call_id>]\n"
-        "pa list\n"
-        "pa switch [<call_id>|none]\n"
-        "pa dtmf <digit string>\n"
-        "pa flags [on|off] [ear] [mouth]\n"
+	char *argv[1024] = { 0 };
+	int argc = 0;
+	char *mycmd = NULL, *devname = NULL;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
+	pa_command_t func = NULL;
+	int lead = 1, devval = 0;
+	const char *usage_string = "USAGE:\n"
+		"--------------------------------------------------------------------------------\n"
+		"pa help\n"
+		"pa dump\n"
+		"pa call <dest> [<dialplan> <cid_name> <cid_num> <rate>]\n"
+		"pa answer [<call_id>]\n"
+		"pa hangup [<call_id>]\n"
+		"pa list\n"
+		"pa switch [<call_id>|none]\n"
+		"pa dtmf <digit string>\n"
+		"pa flags [on|off] [ear] [mouth]\n"
 		"pa devlist\n"
 		"pa indev [#<num>|<partial name>\n"
 		"pa outdev [#<num>|<partial name>\n"
-		"pa ringdev [#<num>|<partial name>\n"
-        "--------------------------------------------------------------------------------\n";
+		"pa ringdev [#<num>|<partial name>\n" "--------------------------------------------------------------------------------\n";
+
+	if (switch_strlen_zero(cmd)) {
+		stream->write_function(stream, "%s", usage_string);
+		goto done;
+	}
+
+	if (!(mycmd = strdup(cmd))) {
+		status = SWITCH_STATUS_MEMERR;
+		goto done;
+	}
 
-    if (switch_strlen_zero(cmd)) {
-        stream->write_function(stream, "%s", usage_string);
-        goto done;
-    }
-
-    if (!(mycmd = strdup(cmd))) {
-        status = SWITCH_STATUS_MEMERR;
-        goto done;
-    }
-    
-    if (!(argc = switch_separate_string(mycmd, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
-        stream->write_function(stream, "%s", usage_string);
-        goto done;
-    }
-    
-    if (!strcasecmp(argv[0], "call")) {
-        func = place_call;
-    } else if (!strcasecmp(argv[0], "help")) {
-        stream->write_function(stream, "%s", usage_string);
-        goto done;
-    } else if (!strcasecmp(argv[0], "devlist")) {
+	if (!(argc = switch_separate_string(mycmd, ' ', argv, (sizeof(argv) / sizeof(argv[0]))))) {
+		stream->write_function(stream, "%s", usage_string);
+		goto done;
+	}
+
+	if (!strcasecmp(argv[0], "call")) {
+		func = place_call;
+	} else if (!strcasecmp(argv[0], "help")) {
+		stream->write_function(stream, "%s", usage_string);
+		goto done;
+	} else if (!strcasecmp(argv[0], "devlist")) {
 		func = devlist;
-    } else if (!strcasecmp(argv[0], "dump")) {
-        dump_info();
-        goto done;
-    } else if (!strcasecmp(argv[0], "list")) {
-        func = list_calls;
-    } else if (!strcasecmp(argv[0], "flags")) {
-        func = do_flags;
-    } else if (!strcasecmp(argv[0], "hangup")) {
-        func = hangup_call;
-    } else if (!strcasecmp(argv[0], "answer")) {
-        func = answer_call;
-    } else if (!strcasecmp(argv[0], "switch")) {
-        func = switch_call;
-    } else if (!strcasecmp(argv[0], "dtmf")) {
-        func = dtmf_call;
+	} else if (!strcasecmp(argv[0], "dump")) {
+		dump_info();
+		goto done;
+	} else if (!strcasecmp(argv[0], "list")) {
+		func = list_calls;
+	} else if (!strcasecmp(argv[0], "flags")) {
+		func = do_flags;
+	} else if (!strcasecmp(argv[0], "hangup")) {
+		func = hangup_call;
+	} else if (!strcasecmp(argv[0], "answer")) {
+		func = answer_call;
+	} else if (!strcasecmp(argv[0], "switch")) {
+		func = switch_call;
+	} else if (!strcasecmp(argv[0], "dtmf")) {
+		func = dtmf_call;
 	} else if (argv[1] && !strcmp(argv[0], "indev")) {
 		if (*argv[1] == '#') {
 			devval = get_dev_by_number(atoi(argv[1] + 1), 1);
@@ -1795,7 +1790,7 @@
 			devval = get_dev_by_name(argv[1], 0);
 		}
 		devname = "outdev";
-		if (devval > 0)  {
+		if (devval > 0) {
 			globals.outdev = devval;
 		}
 	} else if (argv[1] && !strcmp(argv[0], "ringdev")) {
@@ -1808,11 +1803,11 @@
 		if (devval > 0) {
 			globals.ringdev = devval;
 		}
-    }
-    
-    if (func) {
-        status = func(&argv[lead], argc - lead, stream);
-    } else {
+	}
+
+	if (func) {
+		status = func(&argv[lead], argc - lead, stream);
+	} else {
 		if (devname) {
 			if (devval > 0) {
 				stream->write_function(stream, "%s set to %d\n", devname, devval);
@@ -1822,13 +1817,13 @@
 		} else {
 			stream->write_function(stream, "Unknown Command [%s]\n", argv[0]);
 		}
-    }
+	}
 
- done:
+  done:
 
-    switch_safe_free(mycmd);
+	switch_safe_free(mycmd);
 
-    return status;
+	return status;
 }
 
 

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pa_ringbuffer.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pa_ringbuffer.c	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pa_ringbuffer.c	Tue Apr 24 10:14:28 2007
@@ -81,24 +81,25 @@
 #   define PaUtil_WriteMemoryBarrier()
 #else
 
-#if defined(__APPLE__) //|| defined(__FreeBSD__)
+#if defined(__APPLE__)			//|| defined(__FreeBSD__)
 #   include <libkern/OSAtomic.h>
-    /* Here are the memory barrier functions. Mac OS X and FreeBSD only provide
-       full memory barriers, so the three types of barriers are the same. */
+	/* Here are the memory barrier functions. Mac OS X and FreeBSD only provide
+	   full memory barriers, so the three types of barriers are the same. */
 #   define PaUtil_FullMemoryBarrier()  OSMemoryBarrier()
 #   define PaUtil_ReadMemoryBarrier()  OSMemoryBarrier()
 #   define PaUtil_WriteMemoryBarrier() OSMemoryBarrier()
 #elif defined(__GNUC__)
-    /* GCC understands volatile asm and "memory" to mean it
-     * should not reorder memory read/writes */
+
+	/* GCC understands volatile asm and "memory" to mean it
+	 * should not reorder memory read/writes */
 #   if defined( __PPC__ )
-#      define PaUtil_FullMemoryBarrier()  asm volatile("sync":::"memory")
-#      define PaUtil_ReadMemoryBarrier()  asm volatile("sync":::"memory")
-#      define PaUtil_WriteMemoryBarrier() asm volatile("sync":::"memory")
+#      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")
+#      define PaUtil_FullMemoryBarrier()  __asm__ volatile("mfence":::"memory")
+#      define PaUtil_ReadMemoryBarrier()  __asm__ volatile("lfence":::"memory")
+#      define PaUtil_WriteMemoryBarrier() __asm__ volatile("sfence":::"memory")
 #   else
 #      define PaUtil_FullMemoryBarrier()
 #      define PaUtil_ReadMemoryBarrier()
@@ -122,37 +123,39 @@
  * Initialize FIFO.
  * numBytes must be power of 2, returns -1 if not.
  */
-long PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, long numBytes, void *dataPtr )
+long PaUtil_InitializeRingBuffer(PaUtilRingBuffer * rbuf, long numBytes, void *dataPtr)
 {
-    if( ((numBytes-1) & numBytes) != 0) return -1; /* Not Power of two. */
-    rbuf->bufferSize = numBytes;
-    rbuf->buffer = (char *)dataPtr;
-    PaUtil_FlushRingBuffer( rbuf );
-    rbuf->bigMask = (numBytes*2)-1;
-    rbuf->smallMask = (numBytes)-1;
-    return 0;
+	if (((numBytes - 1) & numBytes) != 0)
+		return -1;				/* Not Power of two. */
+	rbuf->bufferSize = numBytes;
+	rbuf->buffer = (char *) dataPtr;
+	PaUtil_FlushRingBuffer(rbuf);
+	rbuf->bigMask = (numBytes * 2) - 1;
+	rbuf->smallMask = (numBytes) - 1;
+	return 0;
 }
 
 /***************************************************************************
 ** Return number of bytes available for reading. */
-long PaUtil_GetRingBufferReadAvailable( PaUtilRingBuffer *rbuf )
+long PaUtil_GetRingBufferReadAvailable(PaUtilRingBuffer * rbuf)
 {
-    PaUtil_ReadMemoryBarrier();
-    return ( (rbuf->writeIndex - rbuf->readIndex) & rbuf->bigMask );
+	PaUtil_ReadMemoryBarrier();
+	return ((rbuf->writeIndex - rbuf->readIndex) & rbuf->bigMask);
 }
+
 /***************************************************************************
 ** Return number of bytes available for writing. */
-long PaUtil_GetRingBufferWriteAvailable( PaUtilRingBuffer *rbuf )
+long PaUtil_GetRingBufferWriteAvailable(PaUtilRingBuffer * rbuf)
 {
-    /* Since we are calling PaUtil_GetRingBufferReadAvailable, we don't need an aditional MB */
-    return ( rbuf->bufferSize - PaUtil_GetRingBufferReadAvailable(rbuf));
+	/* Since we are calling PaUtil_GetRingBufferReadAvailable, we don't need an aditional MB */
+	return (rbuf->bufferSize - PaUtil_GetRingBufferReadAvailable(rbuf));
 }
 
 /***************************************************************************
 ** Clear buffer. Should only be called when buffer is NOT being read. */
-void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf )
+void PaUtil_FlushRingBuffer(PaUtilRingBuffer * rbuf)
 {
-    rbuf->writeIndex = rbuf->readIndex = 0;
+	rbuf->writeIndex = rbuf->readIndex = 0;
 }
 
 /***************************************************************************
@@ -161,42 +164,38 @@
 ** If non-contiguous, size2 will be the size of second region.
 ** Returns room available to be written or numBytes, whichever is smaller.
 */
-long PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, long numBytes,
-                                       void **dataPtr1, long *sizePtr1,
-                                       void **dataPtr2, long *sizePtr2 )
-{
-    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 + numBytes) > rbuf->bufferSize )
-    {
-        /* Write data in two blocks that wrap the buffer. */
-        long   firstHalf = rbuf->bufferSize - index;
-        *dataPtr1 = &rbuf->buffer[index];
-        *sizePtr1 = firstHalf;
-        *dataPtr2 = &rbuf->buffer[0];
-        *sizePtr2 = numBytes - firstHalf;
-    }
-    else
-    {
-        *dataPtr1 = &rbuf->buffer[index];
-        *sizePtr1 = numBytes;
-        *dataPtr2 = NULL;
-        *sizePtr2 = 0;
-    }
-    return numBytes;
+long PaUtil_GetRingBufferWriteRegions(PaUtilRingBuffer * rbuf, long numBytes, void **dataPtr1, long *sizePtr1, void **dataPtr2, long *sizePtr2)
+{
+	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 + numBytes) > rbuf->bufferSize) {
+		/* Write data in two blocks that wrap the buffer. */
+		long firstHalf = rbuf->bufferSize - index;
+		*dataPtr1 = &rbuf->buffer[index];
+		*sizePtr1 = firstHalf;
+		*dataPtr2 = &rbuf->buffer[0];
+		*sizePtr2 = numBytes - firstHalf;
+	} else {
+		*dataPtr1 = &rbuf->buffer[index];
+		*sizePtr1 = numBytes;
+		*dataPtr2 = NULL;
+		*sizePtr2 = 0;
+	}
+	return numBytes;
 }
 
 
 /***************************************************************************
 */
-long PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, long numBytes )
+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 + numBytes) & rbuf->bigMask;
+	/* we need to ensure that previous writes are seen before we update the write index */
+	PaUtil_WriteMemoryBarrier();
+	return rbuf->writeIndex = (rbuf->writeIndex + numBytes) & rbuf->bigMask;
 }
 
 /***************************************************************************
@@ -205,81 +204,72 @@
 ** If non-contiguous, size2 will be the size of second region.
 ** Returns room available to be written or numBytes, whichever is smaller.
 */
-long PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, long numBytes,
-                                void **dataPtr1, long *sizePtr1,
-                                void **dataPtr2, long *sizePtr2 )
-{
-    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 + numBytes) > rbuf->bufferSize )
-    {
-        /* Write data in two blocks that wrap the buffer. */
-        long firstHalf = rbuf->bufferSize - index;
-        *dataPtr1 = &rbuf->buffer[index];
-        *sizePtr1 = firstHalf;
-        *dataPtr2 = &rbuf->buffer[0];
-        *sizePtr2 = numBytes - firstHalf;
-    }
-    else
-    {
-        *dataPtr1 = &rbuf->buffer[index];
-        *sizePtr1 = numBytes;
-        *dataPtr2 = NULL;
-        *sizePtr2 = 0;
-    }
-    return numBytes;
+long PaUtil_GetRingBufferReadRegions(PaUtilRingBuffer * rbuf, long numBytes, void **dataPtr1, long *sizePtr1, void **dataPtr2, long *sizePtr2)
+{
+	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 + numBytes) > rbuf->bufferSize) {
+		/* Write data in two blocks that wrap the buffer. */
+		long firstHalf = rbuf->bufferSize - index;
+		*dataPtr1 = &rbuf->buffer[index];
+		*sizePtr1 = firstHalf;
+		*dataPtr2 = &rbuf->buffer[0];
+		*sizePtr2 = numBytes - firstHalf;
+	} else {
+		*dataPtr1 = &rbuf->buffer[index];
+		*sizePtr1 = numBytes;
+		*dataPtr2 = NULL;
+		*sizePtr2 = 0;
+	}
+	return numBytes;
 }
+
 /***************************************************************************
 */
-long PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, long numBytes )
+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 + numBytes) & rbuf->bigMask;
+	/* we need to ensure that previous writes are always seen before updating the index. */
+	PaUtil_WriteMemoryBarrier();
+	return rbuf->readIndex = (rbuf->readIndex + numBytes) & rbuf->bigMask;
 }
 
 /***************************************************************************
 ** Return bytes written. */
-long PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, long numBytes )
+long PaUtil_WriteRingBuffer(PaUtilRingBuffer * rbuf, const void *data, long numBytes)
 {
-    long size1, size2, numWritten;
-    void *data1, *data2;
-    numWritten = PaUtil_GetRingBufferWriteRegions( rbuf, numBytes, &data1, &size1, &data2, &size2 );
-    if( size2 > 0 )
-    {
-
-        memcpy( data1, data, size1 );
-        data = ((char *)data) + size1;
-        memcpy( data2, data, size2 );
-    }
-    else
-    {
-        memcpy( data1, data, size1 );
-    }
-    PaUtil_AdvanceRingBufferWriteIndex( rbuf, numWritten );
-    return numWritten;
+	long size1, size2, numWritten;
+	void *data1, *data2;
+	numWritten = PaUtil_GetRingBufferWriteRegions(rbuf, numBytes, &data1, &size1, &data2, &size2);
+	if (size2 > 0) {
+
+		memcpy(data1, data, size1);
+		data = ((char *) data) + size1;
+		memcpy(data2, data, size2);
+	} else {
+		memcpy(data1, data, size1);
+	}
+	PaUtil_AdvanceRingBufferWriteIndex(rbuf, numWritten);
+	return numWritten;
 }
 
 /***************************************************************************
 ** Return bytes read. */
-long PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, long numBytes )
+long PaUtil_ReadRingBuffer(PaUtilRingBuffer * rbuf, void *data, long numBytes)
 {
-    long size1, size2, numRead;
-    void *data1, *data2;
-    numRead = PaUtil_GetRingBufferReadRegions( rbuf, numBytes, &data1, &size1, &data2, &size2 );
-    if( size2 > 0 )
-    {
-        memcpy( data, data1, size1 );
-        data = ((char *)data) + size1;
-        memcpy( data, data2, size2 );
-    }
-    else
-    {
-        memcpy( data, data1, size1 );
-    }
-    PaUtil_AdvanceRingBufferReadIndex( rbuf, numRead );
-    return numRead;
+	long size1, size2, numRead;
+	void *data1, *data2;
+	numRead = PaUtil_GetRingBufferReadRegions(rbuf, numBytes, &data1, &size1, &data2, &size2);
+	if (size2 > 0) {
+		memcpy(data, data1, size1);
+		data = ((char *) data) + size1;
+		memcpy(data, data2, size2);
+	} else {
+		memcpy(data, data1, size1);
+	}
+	PaUtil_AdvanceRingBufferReadIndex(rbuf, numRead);
+	return numRead;
 }

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pa_ringbuffer.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pa_ringbuffer.h	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pa_ringbuffer.h	Tue Apr 24 10:14:28 2007
@@ -51,19 +51,17 @@
 */
 
 #ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-typedef struct PaUtilRingBuffer
-{
-    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;
+extern "C" {
+#endif							/* __cplusplus */
+
+	typedef struct PaUtilRingBuffer {
+		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.
 
@@ -76,13 +74,13 @@
 
  @return -1 if numBytes is not a power of 2, otherwise 0.
 */
-long PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, long numBytes, void *dataPtr );
+	long PaUtil_InitializeRingBuffer(PaUtilRingBuffer * rbuf, long numBytes, void *dataPtr);
 
 /** Clear buffer. Should only be called when buffer is NOT being read.
 
  @param rbuf The ring buffer.
 */
-void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf );
+	void PaUtil_FlushRingBuffer(PaUtilRingBuffer * rbuf);
 
 /** Retrieve the number of bytes available in the ring buffer for writing.
 
@@ -90,7 +88,7 @@
 
  @return The number of bytes available for writing.
 */
-long PaUtil_GetRingBufferWriteAvailable( PaUtilRingBuffer *rbuf );
+	long PaUtil_GetRingBufferWriteAvailable(PaUtilRingBuffer * rbuf);
 
 /** Retrieve the number of bytes available in the ring buffer for reading.
 
@@ -98,7 +96,7 @@
 
  @return The number of bytes available for reading.
 */
-long PaUtil_GetRingBufferReadAvailable( PaUtilRingBuffer *rbuf );
+	long PaUtil_GetRingBufferReadAvailable(PaUtilRingBuffer * rbuf);
 
 /** Write data to the ring buffer.
 
@@ -110,7 +108,7 @@
 
  @return The number of bytes written.
 */
-long PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, long numBytes );
+	long PaUtil_WriteRingBuffer(PaUtilRingBuffer * rbuf, const void *data, long numBytes);
 
 /** Read data from the ring buffer.
 
@@ -122,7 +120,7 @@
 
  @return The number of bytes read.
 */
-long PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, long numBytes );
+	long PaUtil_ReadRingBuffer(PaUtilRingBuffer * rbuf, void *data, long numBytes);
 
 /** Get address of region(s) to which we can write data.
 
@@ -144,9 +142,7 @@
 
  @return The room available to be written or numBytes, whichever is smaller.
 */
-long PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, long numBytes,
-                                       void **dataPtr1, long *sizePtr1,
-                                       void **dataPtr2, long *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.
 
@@ -156,7 +152,7 @@
 
  @return The new position.
 */
-long PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, long numBytes );
+	long PaUtil_AdvanceRingBufferWriteIndex(PaUtilRingBuffer * rbuf, long numBytes);
 
 /** Get address of region(s) from which we can write data.
 
@@ -178,9 +174,7 @@
 
  @return The number of bytes available for reading.
 */
-long PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, long numBytes,
-                                      void **dataPtr1, long *sizePtr1,
-                                      void **dataPtr2, long *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.
 
@@ -190,9 +184,9 @@
 
  @return The new position.
 */
-long PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, long numBytes );
+	long PaUtil_AdvanceRingBufferReadIndex(PaUtilRingBuffer * rbuf, long numBytes);
 
 #ifdef __cplusplus
 }
-#endif /* __cplusplus */
-#endif /* PA_RINGBUFFER_H */
+#endif							/* __cplusplus */
+#endif							/* PA_RINGBUFFER_H */

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pablio.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pablio.c	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pablio.c	Tue Apr 24 10:14:28 2007
@@ -59,13 +59,10 @@
 /******** Prototypes ****************************************************/
 /************************************************************************/
 
-static int blockingIOCallback( const void *inputBuffer, void *outputBuffer,
-                               unsigned long framesPerBuffer,
-							   const PaStreamCallbackTimeInfo* timeInfo,
-							   PaStreamCallbackFlags statusFlags,
-							   void *userData );
-static PaError PABLIO_InitFIFO( PaUtilRingBuffer *rbuf, long numFrames, long bytesPerFrame );
-static PaError PABLIO_TermFIFO( PaUtilRingBuffer *rbuf );
+static int blockingIOCallback(const void *inputBuffer, void *outputBuffer,
+							  unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo * timeInfo, PaStreamCallbackFlags statusFlags, void *userData);
+static PaError PABLIO_InitFIFO(PaUtilRingBuffer * rbuf, long numFrames, long bytesPerFrame);
+static PaError PABLIO_TermFIFO(PaUtilRingBuffer * rbuf);
 
 /************************************************************************/
 /******** Functions *****************************************************/
@@ -74,122 +71,118 @@
 /* Called from PortAudio.
  * Read and write data only if there is room in FIFOs.
  */
-static int blockingIOCallback( const void *inputBuffer, void *outputBuffer,
-                               unsigned long framesPerBuffer,
-                               const PaStreamCallbackTimeInfo* timeInfo,
-							   PaStreamCallbackFlags statusFlags,
-							   void *userData )
-{
-    PABLIO_Stream *data = (PABLIO_Stream*)userData;
-    long numBytes = data->bytesPerFrame * framesPerBuffer;
-
-    /* This may get called with NULL inputBuffer during initial setup. */
-    if( inputBuffer != NULL )
-    {
-        PaUtil_WriteRingBuffer( &data->inFIFO, inputBuffer, numBytes );
-    }
-    if( outputBuffer != NULL )
-    {
-        int i;
-        int numRead = PaUtil_ReadRingBuffer( &data->outFIFO, outputBuffer, numBytes );
-        /* Zero out remainder of buffer if we run out of data. */
-        for( i=numRead; i<numBytes; i++ )
-        {
-            ((char *)outputBuffer)[i] = 0;
-        }
-    }
+static int blockingIOCallback(const void *inputBuffer, void *outputBuffer,
+							  unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo * timeInfo, PaStreamCallbackFlags statusFlags, void *userData)
+{
+	PABLIO_Stream *data = (PABLIO_Stream *) userData;
+	long numBytes = data->bytesPerFrame * framesPerBuffer;
+
+	/* This may get called with NULL inputBuffer during initial setup. */
+	if (inputBuffer != NULL) {
+		PaUtil_WriteRingBuffer(&data->inFIFO, inputBuffer, numBytes);
+	}
+	if (outputBuffer != NULL) {
+		int i;
+		int numRead = PaUtil_ReadRingBuffer(&data->outFIFO, outputBuffer, numBytes);
+		/* Zero out remainder of buffer if we run out of data. */
+		for (i = numRead; i < numBytes; i++) {
+			((char *) outputBuffer)[i] = 0;
+		}
+	}
 
-    return 0;
+	return 0;
 }
 
 /* Allocate buffer. */
-static PaError PABLIO_InitFIFO( PaUtilRingBuffer *rbuf, long numFrames, long bytesPerFrame )
+static PaError PABLIO_InitFIFO(PaUtilRingBuffer * rbuf, long numFrames, long bytesPerFrame)
 {
-    long numBytes = numFrames * bytesPerFrame;
-    char *buffer = (char *) malloc( numBytes );
-    if( buffer == NULL ) return paInsufficientMemory;
-    memset( buffer, 0, numBytes );
-    return (PaError) PaUtil_InitializeRingBuffer( rbuf, numBytes, buffer );
+	long numBytes = numFrames * bytesPerFrame;
+	char *buffer = (char *) malloc(numBytes);
+	if (buffer == NULL)
+		return paInsufficientMemory;
+	memset(buffer, 0, numBytes);
+	return (PaError) PaUtil_InitializeRingBuffer(rbuf, numBytes, buffer);
 }
 
 /* Free buffer. */
-static PaError PABLIO_TermFIFO( PaUtilRingBuffer *rbuf )
+static PaError PABLIO_TermFIFO(PaUtilRingBuffer * rbuf)
 {
-    if( rbuf->buffer ) free( rbuf->buffer );
-    rbuf->buffer = NULL;
-    return paNoError;
+	if (rbuf->buffer)
+		free(rbuf->buffer);
+	rbuf->buffer = NULL;
+	return paNoError;
 }
 
 /************************************************************
  * Write data to ring buffer.
  * Will not return until all the data has been written.
  */
-long WriteAudioStream( PABLIO_Stream *aStream, void *data, long numFrames )
+long WriteAudioStream(PABLIO_Stream * aStream, void *data, long numFrames)
 {
-    long bytesWritten;
-    char *p = (char *) data;
-    long numBytes = aStream->bytesPerFrame * numFrames;
-    while( numBytes > 0)
-    {
-        bytesWritten = PaUtil_WriteRingBuffer( &aStream->outFIFO, p, numBytes );
-        numBytes -= bytesWritten;
-        p += bytesWritten;
-        if( numBytes > 0) Pa_Sleep(10);
-    }
-    return numFrames;
+	long bytesWritten;
+	char *p = (char *) data;
+	long numBytes = aStream->bytesPerFrame * numFrames;
+	while (numBytes > 0) {
+		bytesWritten = PaUtil_WriteRingBuffer(&aStream->outFIFO, p, numBytes);
+		numBytes -= bytesWritten;
+		p += bytesWritten;
+		if (numBytes > 0)
+			Pa_Sleep(10);
+	}
+	return numFrames;
 }
 
 /************************************************************
  * Read data from ring buffer.
  * Will not return until all the data has been read.
  */
-long ReadAudioStream( PABLIO_Stream *aStream, void *data, long numFrames )
+long ReadAudioStream(PABLIO_Stream * aStream, void *data, long numFrames)
 {
-    long bytesRead;
-    char *p = (char *) data;
-    long numBytes = aStream->bytesPerFrame * numFrames;
-
-    while( numBytes > 0)
-    {
-        bytesRead = PaUtil_ReadRingBuffer( &aStream->inFIFO, p, numBytes );
-        numBytes -= bytesRead;
-        p += bytesRead;
-        if( numBytes > 0) Pa_Sleep(10);
-    }
-    return numFrames;
+	long bytesRead;
+	char *p = (char *) data;
+	long numBytes = aStream->bytesPerFrame * numFrames;
+
+	while (numBytes > 0) {
+		bytesRead = PaUtil_ReadRingBuffer(&aStream->inFIFO, p, numBytes);
+		numBytes -= bytesRead;
+		p += bytesRead;
+		if (numBytes > 0)
+			Pa_Sleep(10);
+	}
+	return numFrames;
 }
 
 /************************************************************
  * Return the number of frames that could be written to the stream without
  * having to wait.
  */
-long GetAudioStreamWriteable( PABLIO_Stream *aStream )
+long GetAudioStreamWriteable(PABLIO_Stream * aStream)
 {
-    int bytesEmpty = PaUtil_GetRingBufferWriteAvailable( &aStream->outFIFO );
-    return bytesEmpty / aStream->bytesPerFrame;
+	int bytesEmpty = PaUtil_GetRingBufferWriteAvailable(&aStream->outFIFO);
+	return bytesEmpty / aStream->bytesPerFrame;
 }
 
 /************************************************************
  * Return the number of frames that are available to be read from the
  * stream without having to wait.
  */
-long GetAudioStreamReadable( PABLIO_Stream *aStream )
+long GetAudioStreamReadable(PABLIO_Stream * aStream)
 {
-    int bytesFull = PaUtil_GetRingBufferReadAvailable( &aStream->inFIFO );
-    return bytesFull / aStream->bytesPerFrame;
+	int bytesFull = PaUtil_GetRingBufferReadAvailable(&aStream->inFIFO);
+	return bytesFull / aStream->bytesPerFrame;
 }
 
 /************************************************************/
-static unsigned long RoundUpToNextPowerOf2( unsigned long n )
+static unsigned long RoundUpToNextPowerOf2(unsigned long n)
 {
-    long numBits = 0;
-    if( ((n-1) & n) == 0) return n; /* Already Power of two. */
-    while( n > 0 )
-    {
-        n= n>>1;
-        numBits++;
-    }
-    return (1<<numBits);
+	long numBits = 0;
+	if (((n - 1) & n) == 0)
+		return n;				/* Already Power of two. */
+	while (n > 0) {
+		n = n >> 1;
+		numBits++;
+	}
+	return (1 << numBits);
 }
 
 /************************************************************
@@ -197,28 +190,27 @@
  * Allocates PABLIO_Stream structure.
  *
  */
-PaError OpenAudioStream( PABLIO_Stream **rwblPtr, 
-						 const PaStreamParameters *inputParameters,
-						 const PaStreamParameters *outputParameters,
-						 double sampleRate,
-						 PaStreamFlags streamFlags)
-{
-    long   bytesPerSample;
-    PaError err;
-    PABLIO_Stream *aStream;
-    long   minNumBuffers;
-    long   numFrames;
+PaError OpenAudioStream(PABLIO_Stream ** rwblPtr,
+						const PaStreamParameters * inputParameters, const PaStreamParameters * outputParameters, double sampleRate,
+						PaStreamFlags streamFlags)
+{
+	long bytesPerSample;
+	PaError err;
+	PABLIO_Stream *aStream;
+	long numFrames;
 	long numBytes;
 	int channels = 1;
 
-    /* Allocate PABLIO_Stream structure for caller. */
-    aStream = (PABLIO_Stream *) malloc( sizeof(PABLIO_Stream) );
-    if( aStream == NULL ) return paInsufficientMemory;
-    memset( aStream, 0, sizeof(PABLIO_Stream) );
-
-    /* Initialize PortAudio  */
-    err = Pa_Initialize();
-    if( err != paNoError ) goto error;
+	/* Allocate PABLIO_Stream structure for caller. */
+	aStream = (PABLIO_Stream *) malloc(sizeof(PABLIO_Stream));
+	if (aStream == NULL)
+		return paInsufficientMemory;
+	memset(aStream, 0, sizeof(PABLIO_Stream));
+
+	/* Initialize PortAudio  */
+	err = Pa_Initialize();
+	if (err != paNoError)
+		goto error;
 
 	if (inputParameters) {
 		channels = inputParameters->channelCount;
@@ -226,81 +218,77 @@
 		channels = outputParameters->channelCount;
 	}
 
-    numFrames = 4 * FRAMES_PER_BUFFER;
-    numFrames = RoundUpToNextPowerOf2( numFrames );
+	numFrames = 4 * FRAMES_PER_BUFFER;
+	numFrames = RoundUpToNextPowerOf2(numFrames);
 
 	bytesPerSample = 2;
 	aStream->samplesPerFrame = channels;
-    aStream->bytesPerFrame = bytesPerSample * aStream->samplesPerFrame;
+	aStream->bytesPerFrame = bytesPerSample * aStream->samplesPerFrame;
 
-    /* Initialize Ring Buffers */
+	/* Initialize Ring Buffers */
 
 	if (inputParameters) {
-		err = PABLIO_InitFIFO( &aStream->inFIFO, numFrames, aStream->bytesPerFrame );
-		if( err != paNoError ) goto error;
+		err = PABLIO_InitFIFO(&aStream->inFIFO, numFrames, aStream->bytesPerFrame);
+		if (err != paNoError)
+			goto error;
 	}
 
 	if (outputParameters) {
-		err = PABLIO_InitFIFO( &aStream->outFIFO, numFrames, aStream->bytesPerFrame );
-		if( err != paNoError ) goto error;
+		err = PABLIO_InitFIFO(&aStream->outFIFO, numFrames, aStream->bytesPerFrame);
+		if (err != paNoError)
+			goto error;
 	}
 
 	/* Make Write FIFO appear full initially. */
-	numBytes = PaUtil_GetRingBufferWriteAvailable( &aStream->outFIFO );
-	PaUtil_AdvanceRingBufferWriteIndex( &aStream->outFIFO, numBytes );
-	
-
-    /* Open a PortAudio stream that we will use to communicate with the underlying
-     * audio drivers. */
-    err = Pa_OpenStream(
-              &aStream->stream,
-			  inputParameters,
-              outputParameters,
-			  sampleRate,
-              FRAMES_PER_BUFFER,
-			  streamFlags,
-              blockingIOCallback,
-              aStream );
-    if( err != paNoError ) goto error;
-
-    err = Pa_StartStream( aStream->stream );
-    if( err != paNoError ) goto error;
-    *rwblPtr = aStream;
-    return paNoError;
-
-error:
-    CloseAudioStream( aStream );
-    *rwblPtr = NULL;
-    return err;
+	numBytes = PaUtil_GetRingBufferWriteAvailable(&aStream->outFIFO);
+	PaUtil_AdvanceRingBufferWriteIndex(&aStream->outFIFO, numBytes);
+
+
+	/* Open a PortAudio stream that we will use to communicate with the underlying
+	 * audio drivers. */
+	err = Pa_OpenStream(&aStream->stream, inputParameters, outputParameters, sampleRate, FRAMES_PER_BUFFER, streamFlags, blockingIOCallback, aStream);
+	if (err != paNoError)
+		goto error;
+
+	err = Pa_StartStream(aStream->stream);
+	if (err != paNoError)
+		goto error;
+	*rwblPtr = aStream;
+	return paNoError;
+
+  error:
+	CloseAudioStream(aStream);
+	*rwblPtr = NULL;
+	return err;
 }
 
 /************************************************************/
-PaError CloseAudioStream( PABLIO_Stream *aStream )
+PaError CloseAudioStream(PABLIO_Stream * aStream)
 {
-    PaError err;
-    int bytesEmpty;
-    int byteSize = aStream->outFIFO.bufferSize;
-
-    /* If we are writing data, make sure we play everything written. */
-    if( byteSize > 0 )
-    {
-        bytesEmpty = PaUtil_GetRingBufferWriteAvailable( &aStream->outFIFO );
-        while( bytesEmpty < byteSize )
-        {
-            Pa_Sleep( 10 );
-            bytesEmpty = PaUtil_GetRingBufferWriteAvailable( &aStream->outFIFO );
-        }
-    }
-
-    err = Pa_StopStream( aStream->stream );
-    if( err != paNoError ) goto error;
-    err = Pa_CloseStream( aStream->stream );
-    if( err != paNoError ) goto error;
-    Pa_Terminate();
-
-error:
-    PABLIO_TermFIFO( &aStream->inFIFO );
-    PABLIO_TermFIFO( &aStream->outFIFO );
-    free( aStream );
-    return err;
+	PaError err;
+	int bytesEmpty;
+	int byteSize = aStream->outFIFO.bufferSize;
+
+	/* If we are writing data, make sure we play everything written. */
+	if (byteSize > 0) {
+		bytesEmpty = PaUtil_GetRingBufferWriteAvailable(&aStream->outFIFO);
+		while (bytesEmpty < byteSize) {
+			Pa_Sleep(10);
+			bytesEmpty = PaUtil_GetRingBufferWriteAvailable(&aStream->outFIFO);
+		}
+	}
+
+	err = Pa_StopStream(aStream->stream);
+	if (err != paNoError)
+		goto error;
+	err = Pa_CloseStream(aStream->stream);
+	if (err != paNoError)
+		goto error;
+	Pa_Terminate();
+
+  error:
+	PABLIO_TermFIFO(&aStream->inFIFO);
+	PABLIO_TermFIFO(&aStream->outFIFO);
+	free(aStream);
+	return err;
 }

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pablio.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pablio.h	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_portaudio/pablio.h	Tue Apr 24 10:14:28 2007
@@ -2,9 +2,8 @@
 #define _PABLIO_H
 
 #ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
+extern "C" {
+#endif							/* __cplusplus */
 
 /*
  * $Id: pablio.h 1083 2006-08-23 07:30:49Z rossb $
@@ -57,15 +56,13 @@
 
 #include <string.h>
 
-typedef struct
-{
-    PaUtilRingBuffer   inFIFO;
-    PaUtilRingBuffer   outFIFO;
-    PaStream *stream;
-    int          bytesPerFrame;
-    int          samplesPerFrame;
-}
-PABLIO_Stream;
+	typedef struct {
+		PaUtilRingBuffer inFIFO;
+		PaUtilRingBuffer outFIFO;
+		PaStream *stream;
+		int bytesPerFrame;
+		int samplesPerFrame;
+	} PABLIO_Stream;
 
 /* Values for flags for OpenAudioStream(). */
 #define PABLIO_READ     (1<<0)
@@ -78,25 +75,25 @@
  * Write data to ring buffer.
  * Will not return until all the data has been written.
  */
-long WriteAudioStream( PABLIO_Stream *aStream, void *data, long numFrames );
+	long WriteAudioStream(PABLIO_Stream * aStream, void *data, long numFrames);
 
 /************************************************************
  * Read data from ring buffer.
  * Will not return until all the data has been read.
  */
-long ReadAudioStream( PABLIO_Stream *aStream, void *data, long numFrames );
+	long ReadAudioStream(PABLIO_Stream * aStream, void *data, long numFrames);
 
 /************************************************************
  * Return the number of frames that could be written to the stream without
  * having to wait.
  */
-long GetAudioStreamWriteable( PABLIO_Stream *aStream );
+	long GetAudioStreamWriteable(PABLIO_Stream * aStream);
 
 /************************************************************
  * Return the number of frames that are available to be read from the
  * stream without having to wait.
  */
-long GetAudioStreamReadable( PABLIO_Stream *aStream );
+	long GetAudioStreamReadable(PABLIO_Stream * aStream);
 
 /************************************************************
  * Opens a PortAudio stream with default characteristics.
@@ -106,15 +103,13 @@
  *    PABLIO_READ, PABLIO_WRITE, or PABLIO_READ_WRITE,
  *    and either PABLIO_MONO or PABLIO_STEREO
  */
-PaError OpenAudioStream( PABLIO_Stream **rwblPtr, 
-						 const PaStreamParameters *inputParameters,
-						 const PaStreamParameters *outputParameters,
-						 double sampleRate,
-						 PaStreamCallbackFlags statusFlags);
+	PaError OpenAudioStream(PABLIO_Stream ** rwblPtr,
+							const PaStreamParameters * inputParameters,
+							const PaStreamParameters * outputParameters, double sampleRate, PaStreamCallbackFlags statusFlags);
 
-PaError CloseAudioStream( PABLIO_Stream *aStream );
+	PaError CloseAudioStream(PABLIO_Stream * aStream);
 
 #ifdef __cplusplus
 }
-#endif /* __cplusplus */
-#endif /* _PABLIO_H */
+#endif							/* __cplusplus */
+#endif							/* _PABLIO_H */

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,25 +1,36 @@
-OS_ARCH         := $(subst /,_,$(shell uname -s | sed /\ /s//_/))
-VERSION = sofia-sip-1.12
-CFLAGS += -I. -I$(PREFIX)/include/$(VERSION)
-LDFLAGS += -lsofia-sip-ua
-LINKER=$(CC)
-ifeq ($(OS_ARCH),Darwin)
-	LDFLAGS +=-framework CoreFoundation -framework SystemConfiguration
-endif
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install sofia-sip --prefix=$(PREFIX) --with-pic --with-glib=no
-
-%.o:  %.c
-	$(CC) -fPIC $(CFLAGS) -c -o $@ $<
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(LINKER) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(MODNAME).o $(LDFLAGS)
+BASE=../../../..
 
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+SOFIA_DIR=$(BASE)/libs/sofia-sip
+SOFIAUA_DIR=$(SOFIA_DIR)/libsofia-sip-ua
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+LOCAL_CFLAGS  = -I. -I$(SOFIAUA_DIR)/bnf  -I$(SOFIAUA_DIR)/features
+LOCAL_CFLAGS += -I$(SOFIAUA_DIR)/http -I$(SOFIAUA_DIR)/ipt
+LOCAL_CFLAGS += -I$(SOFIAUA_DIR)/iptsec -I$(SOFIAUA_DIR)/msg
+LOCAL_CFLAGS += -I$(SOFIAUA_DIR)/nea -I$(SOFIAUA_DIR)/nta
+LOCAL_CFLAGS += -I$(SOFIAUA_DIR)/nth -I$(SOFIAUA_DIR)/nua
+LOCAL_CFLAGS += -I$(SOFIAUA_DIR)/sdp -I$(SOFIAUA_DIR)/sip
+LOCAL_CFLAGS += -I$(SOFIAUA_DIR)/soa -I$(SOFIAUA_DIR)/sresolv
+LOCAL_CFLAGS += -I$(SOFIAUA_DIR)/stun -I$(SOFIAUA_DIR)/su
+LOCAL_CFLAGS += -I$(SOFIAUA_DIR)/tport -I$(SOFIAUA_DIR)/url
+LOCAL_CFLAGS += `if test -f $(BASE)/.libs/libfreeswitch_la-switch_odbc.o ; then echo -DSWITCH_HAVE_ODBC; fi ;`
+
+LOCAL_OBJS=sofia.o sofia_glue.o sofia_presence.o sofia_reg.o
+LOCAL_SOURCES=sofia.c sofia_glue.c sofia_presense.c sofia_reg.c mod_sofia.c
+
+SOFIALA=$(SOFIAUA_DIR)/libsofia-sip-ua.la
+
+LOCAL_LIBADD=$(SOFIALA)
+
+LOCAL_INSERT_LDFLAGS=if test $$osarch = "Darwin" ; then echo "-framework CoreFoundation -framework SystemConfiguration" ; fi ;
+
+include $(BASE)/build/modmake.rules
+
+$(SOFIALA): $(SOFIA_DIR) $(SOFIA_DIR)/.update
+	cd $(SOFIA_DIR) && $(MAKE)
+	$(TOUCH_TARGET)
+
+local_depend: $(SOFIALA)
+
+../../../../libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua_tag.h: $(SOFIALA)
+
+$(LOCAL_OBJS) $(LOCAL_SOURCES): ../../../../libs/sofia-sip/libsofia-sip-ua/nua/sofia-sip/nua_tag.h

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/mod_sofia.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/mod_sofia.c	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/mod_sofia.c	Tue Apr 24 10:14:28 2007
@@ -36,5744 +36,1075 @@
 /* Best viewed in a 160 x 60 VT100 Terminal or so the line below at least fits across your screen*/
 /*************************************************************************************************************************************************************/
 
+#include "mod_sofia.h"
 
-/*Defines etc..*/
-/*************************************************************************************************************************************************************/
-#define HAVE_APR
-#include <switch.h>
-static const switch_state_handler_table_t noop_state_handler = {0};
-struct outbound_reg;
-typedef struct outbound_reg outbound_reg_t;
-
-struct sofia_profile;
-typedef struct sofia_profile sofia_profile_t;
-#define NUA_MAGIC_T sofia_profile_t
-
-struct sofia_private {
-    char uuid[SWITCH_UUID_FORMATTED_LENGTH + 1];
-	outbound_reg_t *oreg;
-};
-
-typedef struct sofia_private sofia_private_t;
-
-struct private_object;
-typedef struct private_object private_object_t;
-#define NUA_HMAGIC_T sofia_private_t
-
-#define MY_EVENT_REGISTER "sofia::register"
-#define MY_EVENT_EXPIRE "sofia::expire"
-#define MULTICAST_EVENT "multicast::event"
-#define SOFIA_REPLACES_HEADER "_sofia_replaces_"
-#define SOFIA_USER_AGENT "FreeSWITCH(mod_sofia)"
-#define SOFIA_CHAT_PROTO "sip"
-#define SOFIA_SIP_HEADER_PREFIX "sip_h_"
-#define SOFIA_SIP_HEADER_PREFIX_T "~sip_h_"
-
-#include <sofia-sip/nua.h>
-#include <sofia-sip/sip_status.h>
-#include <sofia-sip/sdp.h>
-#include <sofia-sip/sip_protos.h>
-#include <sofia-sip/auth_module.h>
-#include <sofia-sip/su_md5.h>
-#include <sofia-sip/su_log.h>
-#include <sofia-sip/nea.h>
-#include <sofia-sip/msg_addr.h>
-
-extern su_log_t tport_log[];
+struct mod_sofia_globals mod_sofia_globals;
 
 static switch_frame_t silence_frame = { 0 };
 static char silence_data[13] = "";
 
 
-static char reg_sql[] =
-"CREATE TABLE sip_registrations (\n"
-"   user            VARCHAR(255),\n"
-"   host            VARCHAR(255),\n"
-"   contact         VARCHAR(1024),\n"
-"   status          VARCHAR(255),\n"
-"   rpid            VARCHAR(255),\n"
-"   expires         INTEGER(8)"
-");\n";
-
-
-static char sub_sql[] =
-"CREATE TABLE sip_subscriptions (\n"
-"   proto           VARCHAR(255),\n"
-"   user            VARCHAR(255),\n"
-"   host            VARCHAR(255),\n"
-"   sub_to_user     VARCHAR(255),\n"
-"   sub_to_host     VARCHAR(255),\n"
-"   event           VARCHAR(255),\n"
-"   contact         VARCHAR(1024),\n"
-"   call_id         VARCHAR(255),\n"
-"   full_from       VARCHAR(255),\n"
-"   full_via        VARCHAR(255),\n"
-"   expires         INTEGER(8)"
-");\n";
-
-
-static char auth_sql[] =
-"CREATE TABLE sip_authentication (\n"
-"   user            VARCHAR(255),\n"
-"   host            VARCHAR(255),\n"
-"   passwd            VARCHAR(255),\n"
-"   nonce           VARCHAR(255),\n"
-"   expires         INTEGER(8)"
-");\n";
-
-static const char modname[] = "mod_sofia";
 #define STRLEN 15
 
 static switch_memory_pool_t *module_pool = NULL;
 
-#define set_param(ptr,val) if (ptr) {free(ptr) ; ptr = NULL;} if (val) {ptr = strdup(val);}
-#define set_anchor(t,m) if (t->Anchor) {delete t->Anchor;} t->Anchor = new SipMessage(m);
-
-
-/* Local Structures */
-/*************************************************************************************************************************************************************/
-struct sip_alias_node {
-	char *url;
-	nua_t *nua;
-	struct sip_alias_node *next;
-};
-
-typedef struct sip_alias_node sip_alias_node_t;
-
-typedef enum {
-	PFLAG_AUTH_CALLS = (1 << 0),
-	PFLAG_BLIND_REG = (1 << 1),
-	PFLAG_AUTH_ALL = (1 << 2),
-	PFLAG_FULL_ID = (1 << 3),
-	PFLAG_PRESENCE = (1 << 4),
-	PFLAG_PASS_RFC2833 = (1 << 5),
-    PFLAG_DISABLE_TRANSCODING = (1 << 6)
-} PFLAGS;
-
-typedef enum {
-	TFLAG_IO = (1 << 0),
-	TFLAG_CHANGE_MEDIA = (1 << 1),
-	TFLAG_OUTBOUND = (1 << 2),
-	TFLAG_READING = (1 << 3),
-	TFLAG_WRITING = (1 << 4),
-	TFLAG_HUP = (1 << 5),
-	TFLAG_RTP = (1 << 6),
-	TFLAG_BYE = (1 << 7),
-	TFLAG_ANS = (1 << 8),
-	TFLAG_EARLY_MEDIA = (1 << 9),
-	TFLAG_SECURE = (1 << 10),
-	TFLAG_VAD_IN = ( 1 << 11),
-	TFLAG_VAD_OUT = ( 1 << 12),
-	TFLAG_VAD = ( 1 << 13),
-	TFLAG_TIMER = (1 << 14),
-	TFLAG_READY = (1 << 15),
-	TFLAG_REINVITE = (1 << 16),
-	TFLAG_REFER = (1 << 17),
-	TFLAG_NOHUP = (1 << 18),
-	TFLAG_XFER = (1 << 19),
-	TFLAG_NOMEDIA = (1 << 20),
-	TFLAG_BUGGY_2833 = (1 << 21),
-	TFLAG_SIP_HOLD = (1 << 22),
-	TFLAG_INB_NOMEDIA = (1 << 23),
-	TFLAG_LATE_NEGOTIATION = (1 << 24)
-} TFLAGS;
-
-static struct {
-	switch_hash_t *profile_hash;
-	switch_mutex_t *hash_mutex;
-	uint32_t callid;
-	int32_t running;
-	switch_mutex_t *mutex;
-    char guess_ip[80];
-} globals;
-
-typedef enum {
-	REG_FLAG_AUTHED = (1 << 0),
-} reg_flags_t;
-
-typedef enum {
-	REG_STATE_UNREGED,
-	REG_STATE_TRYING,
-	REG_STATE_REGISTER,
-	REG_STATE_REGED,
-	REG_STATE_FAILED,
-	REG_STATE_EXPIRED
-} reg_state_t;
-
-struct outbound_reg {
-	sofia_private_t *sofia_private;
-	nua_handle_t *nh;
-	sofia_profile_t *profile;
-	char *name;
-	char *register_scheme;
-	char *register_realm;
-	char *register_username;
-	char *register_password;
-	char *register_from;
-	char *register_to;
-	char *register_proxy;
-	char *expires_str;
-	uint32_t freq;
-	time_t expires;
-	time_t retry;
-	uint32_t flags;
-	reg_state_t state;
-	switch_memory_pool_t *pool;
-	struct outbound_reg *next;
-};
-
-
-struct sofia_profile {
-	int debug;
-	char *name;
-	char *dbname;
-	char *dialplan;
-	char *context;
-	char *extrtpip;
-	char *rtpip;
-	char *sipip;
-	char *extsipip;
-	char *username;
-	char *url;
-	char *bindurl;
-	char *sipdomain;
-	char *timer_name;
-	int sip_port;
-	char *codec_string;
-	int running;
-	int codec_ms;
-	int dtmf_duration;
-	unsigned int flags;
-	unsigned int pflags;
-	uint32_t max_calls;
-    uint32_t nonce_ttl;
-	nua_t *nua;
-	switch_memory_pool_t *pool;
-	su_root_t *s_root;
-	sip_alias_node_t *aliases;
-	switch_payload_t te;
-	uint32_t codec_flags;
-	switch_mutex_t *ireg_mutex;
-	switch_mutex_t *oreg_mutex;
-	outbound_reg_t *registrations;
-	su_home_t *home;
-	switch_hash_t *profile_hash;
-	switch_hash_t *chat_hash;
-};
-
-
-struct private_object {
-	sofia_private_t *sofia_private;
-	uint32_t flags;
-	switch_payload_t agreed_pt;
-	switch_core_session_t *session;
-	switch_frame_t read_frame;
-	char *codec_order[SWITCH_MAX_CODECS];
-	int codec_order_last;
-	const switch_codec_implementation_t *codecs[SWITCH_MAX_CODECS];
-	int num_codecs;
-	switch_codec_t read_codec;
-	switch_codec_t write_codec;
-	uint32_t codec_ms;
-	switch_caller_profile_t *caller_profile;
-	int32_t timestamp_send;
-	//int32_t timestamp_recv;
-	switch_rtp_t *rtp_session;
-	int ssrc;
-	//switch_time_t last_read;
-	sofia_profile_t *profile;
-	char *local_sdp_audio_ip;
-	switch_port_t local_sdp_audio_port;
-	char *remote_sdp_audio_ip;
-	switch_port_t remote_sdp_audio_port;
-	char *adv_sdp_audio_ip;
-	switch_port_t adv_sdp_audio_port;
-	char *proxy_sdp_audio_ip;
-	switch_port_t proxy_sdp_audio_port;
-	char *from_uri;
-	char *to_uri;
-	char *from_address;
-	char *to_address;
-	char *callid;
-	char *far_end_contact;
-	char *contact_url;
-	char *from_str;
-	char *rm_encoding;
-	char *rm_fmtp;
-	char *fmtp_out;
-	char *remote_sdp_str;
-	char *local_sdp_str;
-	char *dest;
-	char *dest_to;
-	char *key;
-	char *xferto;
-	char *kick;
-	char *origin;
-	char *hash_key;
-	char *chat_from;
-	char *chat_to;
-	char *e_dest;
-    char *call_id;
-	unsigned long rm_rate;
-	switch_payload_t pt;
-	switch_mutex_t *flag_mutex;
-	switch_payload_t te;
-	switch_payload_t bte;
-	nua_handle_t *nh;
-	nua_handle_t *nh2;
-	su_home_t *home;
-	sip_contact_t *contact;
-};
-
-/* Function Prototypes */
-/*************************************************************************************************************************************************************/
 static switch_status_t sofia_on_init(switch_core_session_t *session);
 
-static switch_status_t sofia_on_hangup(switch_core_session_t *session);
 
 static switch_status_t sofia_on_loopback(switch_core_session_t *session);
-
 static switch_status_t sofia_on_transmit(switch_core_session_t *session);
-
-static switch_call_cause_t sofia_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-												  switch_core_session_t **new_session, switch_memory_pool_t *pool);
-
-static switch_status_t sofia_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-										switch_io_flag_t flags, int stream_id);
-
-static switch_status_t sofia_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-										 switch_io_flag_t flags, int stream_id);
-
-static switch_status_t config_sofia(int reload);
-
+static switch_call_cause_t sofia_outgoing_channel(switch_core_session_t *session,
+												  switch_caller_profile_t *outbound_profile, switch_core_session_t **new_session,
+												  switch_memory_pool_t **pool);
+static switch_status_t sofia_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id);
+static switch_status_t sofia_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id);
+static switch_status_t sofia_read_video_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id);
+static switch_status_t sofia_write_video_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id);
 static switch_status_t sofia_kill_channel(switch_core_session_t *session, int sig);
 
-static switch_status_t activate_rtp(private_object_t *tech_pvt);
-
-static void deactivate_rtp(private_object_t *tech_pvt);
-
-static void set_local_sdp(private_object_t *tech_pvt, char *ip, uint32_t port, char *sr, int force);
-
-static void tech_set_codecs(private_object_t *tech_pvt);
-
-static void attach_private(switch_core_session_t *session,
-                           sofia_profile_t *profile,
-                           private_object_t *tech_pvt,
-                           const char *channame);
-
-static void terminate_session(switch_core_session_t **session, switch_call_cause_t cause, int line);
-
-static switch_status_t tech_choose_port(private_object_t *tech_pvt);
-
-static switch_status_t do_invite(switch_core_session_t *session);
-
-static uint8_t negotiate_sdp(switch_core_session_t *session, sdp_session_t *sdp);
-
-static char *get_auth_data(char *dbname, char *nonce, char *npassword, size_t len, switch_mutex_t *mutex);
-
-static void establish_presence(sofia_profile_t *profile);
-
-static void sip_i_state(int status,
-                        char const *phrase,
-                        nua_t *nua,
-                        sofia_profile_t *profile,
-                        nua_handle_t *nh,
-						sofia_private_t *sofia_private,
-                        sip_t const *sip,
-                        tagi_t tags[]);
-
-
-static void sip_i_refer(nua_t *nua,
-						sofia_profile_t *profile,
-						nua_handle_t *nh,
-                        switch_core_session_t *session,
-						sip_t const *sip,
-						tagi_t tags[]);
-
-static void sip_i_info(nua_t *nua,
-                       sofia_profile_t *profile,
-                       nua_handle_t *nh,
-                       switch_core_session_t *session,
-                       sip_t const *sip,
-                       tagi_t tags[]);
-
-static void sip_i_invite(nua_t *nua,
-                         sofia_profile_t *profile,
-                         nua_handle_t *nh,
-						 sofia_private_t *sofia_private,
-                         sip_t const *sip,
-                         tagi_t tags[]);
-
-static void sip_i_register(nua_t *nua,
-						   sofia_profile_t *profile,
-						   nua_handle_t *nh,
-						   sofia_private_t *sofia_private,
-						   sip_t const *sip,
-						   tagi_t tags[]);
-
-static void event_callback(nua_event_t   event,
-                           int           status,
-                           char const   *phrase,
-                           nua_t        *nua,
-                           sofia_profile_t  *profile,
-                           nua_handle_t *nh,
-						   sofia_private_t *sofia_private,
-                           sip_t const  *sip,
-                           tagi_t        tags[]);
-
-
-static void *SWITCH_THREAD_FUNC profile_thread_run(switch_thread_t *thread, void *obj);
-
-static void launch_profile_thread(sofia_profile_t *profile);
-
-static switch_status_t chat_send(char *proto, char *from, char *to, char *subject, char *body, char *hint);
 
 /* BODY OF THE MODULE */
 /*************************************************************************************************************************************************************/
 
-typedef enum {
-	AUTH_OK,
-	AUTH_FORBIDDEN,
-	AUTH_STALE,
-} auth_res_t;
-
-
-static char *get_url_from_contact(char *buf, uint8_t to_dup)
-{
-	char *url = NULL, *e;
-
-	if ((url = strchr(buf, '<')) && (e = strchr(url, '>'))) {
-		url++;
-		if (to_dup) {
-			url = strdup(url);
-			e = strchr(url, '>');
-		}
-
-		*e = '\0';
-	}
-	
-	return url;
-}
-
 
-static auth_res_t parse_auth(sofia_profile_t *profile, sip_authorization_t const *authorization, char *regstr, char *np, size_t nplen)
+/* 
+   State methods they get called when the state changes to the specific state 
+   returning SWITCH_STATUS_SUCCESS tells the core to execute the standard state method next
+   so if you fully implement the state you can return SWITCH_STATUS_FALSE to skip it.
+*/
+static switch_status_t sofia_on_init(switch_core_session_t *session)
 {
-	int indexnum;
-	const char *cur;
-	su_md5_t ctx;
-	char uridigest[2 * SU_MD5_DIGEST_SIZE + 1];
-	char bigdigest[2 * SU_MD5_DIGEST_SIZE + 1];
-	char *nonce, *uri, *qop, *cnonce, *nc, *response, *input = NULL, *input2 = NULL;
-	auth_res_t ret = AUTH_FORBIDDEN;
-	char *npassword = NULL;
-	int cnt = 0;
-	nonce = uri = qop = cnonce = nc = response = NULL;
-
-	if (authorization->au_params) {
-		for(indexnum = 0; (cur=authorization->au_params[indexnum]); indexnum++) {
-			char *var, *val, *p, *work; 
-			var = val = work = NULL;
-			if ((work = strdup(cur))) {
-				var = work;
-				if ((val = strchr(var, '='))) {
-					*val++ = '\0';
-					while(*val == '"') {
-						*val++ = '\0';
-					}
-					if ((p = strchr(val, '"'))) {
-						*p = '\0';
-					}
-
-					if (!strcasecmp(var, "nonce")) {
-						nonce = strdup(val);
-						cnt++;
-					} else if (!strcasecmp(var, "uri")) {
-						uri = strdup(val);
-						cnt++;
-					} else if (!strcasecmp(var, "qop")) {
-						qop = strdup(val);
-						cnt++;
-					} else if (!strcasecmp(var, "cnonce")) {
-						cnonce = strdup(val);
-						cnt++;
-					} else if (!strcasecmp(var, "response")) {
-						response = strdup(val);
-						cnt++;
-					} else if (!strcasecmp(var, "nc")) {
-						nc = strdup(val);
-						cnt++;
-					}
-				}
-				
-				free(work);
-			}
-		}
-	}
-
-	if (cnt != 6) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Authorization header!\n");
-		goto end;
-	}
-
-	if (switch_strlen_zero(np)) {
-		if (!get_auth_data(profile->dbname, nonce, np, nplen, profile->ireg_mutex)) {
-			ret = AUTH_STALE;
-			goto end;
-		} 
-	}
-
-	npassword = np;
-
-	if ((input = switch_mprintf("%s:%q", regstr, uri))) {
-		su_md5_init(&ctx);
-		su_md5_strupdate(&ctx, input);
-		su_md5_hexdigest(&ctx, uridigest);
-		su_md5_deinit(&ctx);
-	}
-
-	if ((input2 = switch_mprintf("%q:%q:%q:%q:%q:%q", npassword, nonce, nc, cnonce, qop, uridigest))) {
-		memset(&ctx, 0, sizeof(ctx));
-		su_md5_init(&ctx);
-		su_md5_strupdate(&ctx, input2);
-		su_md5_hexdigest(&ctx, bigdigest);
-		su_md5_deinit(&ctx);
-
-		if (!strcasecmp(bigdigest, response)) {
-			ret = AUTH_OK;
-		} else {
-			ret = AUTH_FORBIDDEN;
-		}
-	}
-
- end:
-    switch_safe_free(input);
-    switch_safe_free(input2);
-	switch_safe_free(nonce);
-	switch_safe_free(uri);
-	switch_safe_free(qop);
-	switch_safe_free(cnonce);
-	switch_safe_free(nc);
-	switch_safe_free(response);
-
-	return ret;
-
-}
-
+	private_object_t *tech_pvt;
+	switch_channel_t *channel = NULL;
 
-static void execute_sql(char *dbname, char *sql, switch_mutex_t *mutex)
-{
-	switch_core_db_t *db;
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-	if (mutex) {
-		switch_mutex_lock(mutex);
-	}
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-	if (!(db = switch_core_db_open_file(dbname))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", dbname);
-		goto end;
-	}
-	switch_core_db_persistant_execute(db, sql, 25);
-	switch_core_db_close(db);
+	tech_pvt->read_frame.buflen = SWITCH_RTP_MAX_BUF_LEN;
 
- end:
-	if (mutex) {
-		switch_mutex_unlock(mutex);
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA INIT\n");
+	if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
+		switch_set_flag_locked(tech_pvt, TFLAG_NOMEDIA);
+		sofia_glue_tech_absorb_sdp(tech_pvt);
 	}
-}
-
-
-struct callback_t {
-	char *val;
-	switch_size_t len;
-	int matches;
-};
-
-static int find_callback(void *pArg, int argc, char **argv, char **columnNames){
-	struct callback_t *cbt = (struct callback_t *) pArg;
-
-	switch_copy_string(cbt->val, argv[0], cbt->len);
-	cbt->matches++;
-	return 0;
-}
 
-static int del_callback(void *pArg, int argc, char **argv, char **columnNames){
-	switch_event_t *s_event;
-
-	if (argc >=3 ) {
-		if (switch_event_create_subclass(&s_event, SWITCH_EVENT_CUSTOM, MY_EVENT_EXPIRE) == SWITCH_STATUS_SUCCESS) {
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "profile-name", "%s", argv[0]);
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "user", "%s", argv[1]);
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "host", "%s", argv[2]);
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "contact", "%s", argv[3]);
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "expires", "%d", argv[4]);
-			switch_event_fire(&s_event);
+	if (switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
+		if (sofia_glue_do_invite(session) != SWITCH_STATUS_SUCCESS) {
+			switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+			return SWITCH_STATUS_FALSE;
 		}
 	}
-	return 0;
-}
-
-static void check_expire(switch_core_db_t *db, sofia_profile_t *profile, time_t now)
-{
-	char sql[1024];
-	char *errmsg;
-
-	if (!db) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-		return;
-	}
-
-	switch_mutex_lock(profile->ireg_mutex);
-	snprintf(sql, sizeof(sql), "select '%s',* from sip_registrations where expires > 0 and expires < %ld", profile->name, (long) now);	
-	switch_core_db_exec(db, sql, del_callback, NULL, &errmsg);
-
-	if (errmsg) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "SQL ERR [%s][%s]\n", sql, errmsg);
-		switch_safe_free(errmsg);
-		errmsg = NULL;
-	}
-	
-	snprintf(sql, sizeof(sql), "delete from sip_registrations where expires > 0 and expires < %ld", (long) now);
-	switch_core_db_persistant_execute(db, sql, 1000);
-	snprintf(sql, sizeof(sql), "delete from sip_authentication where expires > 0 and expires < %ld", (long) now);
-	switch_core_db_persistant_execute(db, sql, 1000);
-	snprintf(sql, sizeof(sql), "delete from sip_subscriptions where expires > 0 and expires < %ld", (long) now);
-	switch_core_db_persistant_execute(db, sql, 1000);
-
-	switch_mutex_unlock(profile->ireg_mutex);
 
+	/* Move Channel's State Machine to RING */
+	switch_channel_set_state(channel, CS_RING);
+	return SWITCH_STATUS_SUCCESS;
 }
 
-static char *find_reg_url(sofia_profile_t *profile, char *user, char *host, char *val, switch_size_t len)
+static switch_status_t sofia_on_ring(switch_core_session_t *session)
 {
-	char *errmsg;
-	struct callback_t cbt = {0};
-	switch_core_db_t *db;
-
-	if (!(db = switch_core_db_open_file(profile->dbname))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-		return NULL;
-	}
-
-	cbt.val = val;
-	cbt.len = len;
-	switch_mutex_lock(profile->ireg_mutex);
-	if (host) {
-		snprintf(val, len, "select contact from sip_registrations where user='%s' and host='%s'", user, host);	
-	} else {
-		snprintf(val, len, "select contact from sip_registrations where user='%s'", user);	
-	}
+	switch_channel_t *channel = NULL;
+	private_object_t *tech_pvt = NULL;
 
-	switch_core_db_exec(db, val, find_callback, &cbt, &errmsg);
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-	if (errmsg) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "SQL ERR [%s][%s]\n", val, errmsg);
-		switch_safe_free(errmsg);
-		errmsg = NULL;
-	}
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-	switch_mutex_unlock(profile->ireg_mutex);
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA RING\n");
 
-	switch_core_db_close(db);
-    if (cbt.matches) {
-        return val;
-    } else {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Cannot locate registered user %s@%s\n", user, host);
-        return NULL;
-    }
+	return SWITCH_STATUS_SUCCESS;
 }
 
 
-static void set_local_sdp(private_object_t *tech_pvt, char *ip, uint32_t port, char *sr, int force)
+static switch_status_t sofia_on_execute(switch_core_session_t *session)
 {
-	char buf[2048];
-	switch_time_t now = switch_time_now();
-    int ptime = 0;
-
-	if (!force && !ip && !sr && switch_test_flag(tech_pvt, TFLAG_NOMEDIA)) {
-		return;
-	}
-
-	if (!ip) {
-		if (!(ip = tech_pvt->adv_sdp_audio_ip)) {
-			ip = tech_pvt->proxy_sdp_audio_ip;
-		}
-	}
-	if (!port) {
-		if (!(port = tech_pvt->adv_sdp_audio_port)) {
-			port = tech_pvt->proxy_sdp_audio_port;
-		}
-	}
-	if (!sr) {
-		sr = "sendrecv";
-	}
-
-	snprintf(buf, sizeof(buf), 
-			 "v=0\n"
-			 "o=FreeSWITCH %d%"APR_TIME_T_FMT" %d%"APR_TIME_T_FMT" IN IP4 %s\n"
-			 "s=FreeSWITCH\n"
-			 "c=IN IP4 %s\n"
-			 "t=0 0\n"
-			 "a=%s\n"
-			 "m=audio %d RTP/AVP",
-			 port,
-			 now,
-			 port,
-			 now,
-			 ip,
-			 ip,
-			 sr,
-			 port
-			 );
-
-	if (tech_pvt->rm_encoding) {
-		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %d", tech_pvt->pt);
-	} else if (tech_pvt->num_codecs) {
-		int i;
-		for (i = 0; i < tech_pvt->num_codecs; i++) {
-			const switch_codec_implementation_t *imp = tech_pvt->codecs[i];
-
-			snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %d", imp->ianacode);
-            if (!ptime) {
-                ptime = imp->microseconds_per_frame / 1000;
-            }
-		}
-	}
-
-	if (tech_pvt->te > 95) {
-		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %d", tech_pvt->te);
-	}
-
-	snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "\n");
+	switch_channel_t *channel = NULL;
+	private_object_t *tech_pvt = NULL;
 
-	if (tech_pvt->rm_encoding) {
-		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "a=rtpmap:%d %s/%ld\n", tech_pvt->pt, tech_pvt->rm_encoding, tech_pvt->rm_rate);
-		if (tech_pvt->fmtp_out) {
-			snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "a=fmtp:%d %s\n", tech_pvt->pt, tech_pvt->fmtp_out);
-		}
-		if (tech_pvt->read_codec.implementation && ! ptime) {
-            ptime = tech_pvt->read_codec.implementation->microseconds_per_frame / 1000;
-		}
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-	} else if (tech_pvt->num_codecs) {
-		int i;
-		for (i = 0; i < tech_pvt->num_codecs; i++) {
-			const switch_codec_implementation_t *imp = tech_pvt->codecs[i];
-            if (ptime && ptime != imp->microseconds_per_frame / 1000) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "ptime %u != advertised ptime %u\n", imp->microseconds_per_frame / 1000, ptime);
-            }
-			snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "a=rtpmap:%d %s/%d\n", imp->ianacode, imp->iananame, imp->samples_per_second);
-			if (imp->fmtp) {
-				snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "a=fmtp:%d %s\n", imp->ianacode, imp->fmtp);
-			}
-		}
-	}
-	
-	if (tech_pvt->te > 95) {
-		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "a=rtpmap:%d telephone-event/8000\na=fmtp:%d 0-16\n", tech_pvt->te, tech_pvt->te);
-	}
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-    if (ptime) {
-        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "a=ptime:%d\n", ptime);
-    }
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA EXECUTE\n");
 
-	tech_pvt->local_sdp_str = switch_core_session_strdup(tech_pvt->session, buf);
+	return SWITCH_STATUS_SUCCESS;
 }
 
-static void tech_set_codecs(private_object_t *tech_pvt)
-{
-    switch_channel_t *channel;
-    char *abs, *codec_string = NULL;
-    char *csdyn = NULL;
-    char *ocodec = NULL;
-
-	if (switch_test_flag(tech_pvt, TFLAG_NOMEDIA)) {
-		return;
-	}
-
-	if (tech_pvt->num_codecs) {
-		return;
-	}
-
-    assert(tech_pvt->session != NULL);
-
-    channel = switch_core_session_get_channel(tech_pvt->session);
-    assert (channel != NULL);
-
-
-    if ((abs = switch_channel_get_variable(channel, "absolute_codec_string"))) {
-        codec_string = abs;
-    } else {
-        if (!(codec_string = switch_channel_get_variable(channel, "codec_string"))) {
-			if (tech_pvt->profile->codec_string) {
-				codec_string = tech_pvt->profile->codec_string;
-			}
-        }
-        
-        if ((ocodec = switch_channel_get_variable(channel, SWITCH_ORIGINATOR_CODEC_VARIABLE))) {
-            if (!codec_string || (tech_pvt->profile->pflags & PFLAG_DISABLE_TRANSCODING)) {
-                codec_string = ocodec;
-            } else {
-                if ((csdyn = switch_mprintf("%s,%s", ocodec, codec_string))) {
-                    codec_string = csdyn;
-                } else {
-                    codec_string = ocodec;
-                }
-            }
-        }
-    }
-
-	if (codec_string) {
-		char *tmp_codec_string;
-		if ((tmp_codec_string = strdup(codec_string))) {
-			tech_pvt->codec_order_last = switch_separate_string(tmp_codec_string, ',', tech_pvt->codec_order, SWITCH_MAX_CODECS);
-			tech_pvt->num_codecs = switch_loadable_module_get_codecs_sorted(tech_pvt->codecs,
-																			SWITCH_MAX_CODECS,
-																			tech_pvt->codec_order,
-																			tech_pvt->codec_order_last);
-			free(tmp_codec_string);
-		}
-	} else {
-		tech_pvt->num_codecs = switch_loadable_module_get_codecs(switch_core_session_get_pool(tech_pvt->session), tech_pvt->codecs,
-																 sizeof(tech_pvt->codecs) / sizeof(tech_pvt->codecs[0]));
+// map QSIG cause codes to SIP from RFC4497 section 8.4.1
+static int hangup_cause_to_sip(switch_call_cause_t cause)
+{		
+	switch (cause) {
+	case SWITCH_CAUSE_NO_ROUTE_TRANSIT_NET:
+	case SWITCH_CAUSE_NO_ROUTE_DESTINATION:
+		return 404;
+	case SWITCH_CAUSE_USER_BUSY:
+		return 486;
+	case SWITCH_CAUSE_NO_USER_RESPONSE:
+		return 408;
+	case SWITCH_CAUSE_NO_ANSWER:
+		return 480;
+	case SWITCH_CAUSE_SUBSCRIBER_ABSENT:
+		return 480;
+	case SWITCH_CAUSE_CALL_REJECTED:
+		return 603;
+	case SWITCH_CAUSE_NUMBER_CHANGED:
+	case SWITCH_CAUSE_REDIRECTION_TO_NEW_DESTINATION:
+		return 410;
+	case SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER:
+		return 502;
+	case SWITCH_CAUSE_INVALID_NUMBER_FORMAT:
+		return 484;
+	case SWITCH_CAUSE_FACILITY_REJECTED:
+		return 501;
+	case SWITCH_CAUSE_NORMAL_UNSPECIFIED:
+		return 480;
+	case SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL:
+	case SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION:
+	case SWITCH_CAUSE_NETWORK_OUT_OF_ORDER:
+	case SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE:
+	case SWITCH_CAUSE_SWITCH_CONGESTION:
+		return 503;
+	case SWITCH_CAUSE_OUTGOING_CALL_BARRED:
+	case SWITCH_CAUSE_INCOMING_CALL_BARRED:
+	case SWITCH_CAUSE_BEARERCAPABILITY_NOTAUTH:
+		return 403;
+	case SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL:
+		return 503;
+	case SWITCH_CAUSE_BEARERCAPABILITY_NOTIMPL:
+	case SWITCH_CAUSE_INCOMPATIBLE_DESTINATION:
+		return 488;
+	case SWITCH_CAUSE_FACILITY_NOT_IMPLEMENTED:
+	case SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED:
+		return 501;
+	case SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE:
+		return 504;
+	case SWITCH_CAUSE_ORIGINATOR_CANCEL:
+		return 487;
+	default:
+		return 480;
 	}
 
-    switch_safe_free(csdyn);
 }
 
-
-static void attach_private(switch_core_session_t *session,
-						   sofia_profile_t *profile,
-						   private_object_t *tech_pvt,
-						   const char *channame)
+switch_status_t sofia_on_hangup(switch_core_session_t *session)
 {
-	switch_channel_t *channel;
-	char name[256];
-
-	assert(session != NULL);
-	assert(profile != NULL);
-	assert(tech_pvt != NULL);
+	switch_core_session_t *a_session;
+	private_object_t *tech_pvt;
+	switch_channel_t *channel = NULL;
+	switch_call_cause_t cause;
+	int sip_cause;
 
-	switch_core_session_add_stream(session, NULL);
 	channel = switch_core_session_get_channel(session);
-	
-	switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
-	switch_mutex_lock(tech_pvt->flag_mutex);
-	tech_pvt->flags = profile->flags;
-	switch_mutex_unlock(tech_pvt->flag_mutex);
-	tech_pvt->profile = profile;
-	if (tech_pvt->bte) {
-		tech_pvt->te = tech_pvt->bte;
-	} else {
-		tech_pvt->te = profile->te;
-	}
-	tech_pvt->session = session;
-	tech_pvt->home = su_home_new(sizeof(*tech_pvt->home));
-
-	switch_core_session_set_private(session, tech_pvt);
-
-
-	snprintf(name, sizeof(name), "sofia/%s/%s", profile->name, channame);
-    switch_channel_set_name(channel, name);
-	//tech_set_codecs(tech_pvt);
+	assert(channel != NULL);
 
-}
-
-static void terminate_session(switch_core_session_t **session, switch_call_cause_t cause, int line)
-{
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Term called from line: %d\n", line);
-	if (*session) {
-		switch_channel_t *channel = switch_core_session_get_channel(*session);
-		switch_channel_state_t state = switch_channel_get_state(channel);
-		struct private_object *tech_pvt = NULL;
-
-		tech_pvt = switch_core_session_get_private(*session);
-
-		if (tech_pvt) {
-			if (state < CS_HANGUP) {
-				switch_channel_hangup(channel, cause);
-			}
-			
-			if (!switch_test_flag(tech_pvt, TFLAG_READY)) {
-				if (state > CS_INIT && state < CS_HANGUP) {
-					sofia_on_hangup(*session);
-				}
-				switch_core_session_destroy(session);
-			} 
-		} else {
-			switch_core_session_destroy(session);
-		}
-	}
-}
-
-
-static switch_status_t tech_choose_port(private_object_t *tech_pvt)
-{
-	char *ip = tech_pvt->profile->rtpip;
-	switch_channel_t *channel;
-	switch_port_t sdp_port;
-	char *err;
-	char tmp[50];
-
-	channel = switch_core_session_get_channel(tech_pvt->session);
-	
-	if (switch_test_flag(tech_pvt, TFLAG_NOMEDIA) || tech_pvt->adv_sdp_audio_port) {
-		return SWITCH_STATUS_SUCCESS;
-	}
-	
-	tech_pvt->local_sdp_audio_ip = ip;
-	tech_pvt->local_sdp_audio_port = switch_rtp_request_port();
-	sdp_port = tech_pvt->local_sdp_audio_port;
-
-
-	if (tech_pvt->profile->extrtpip) {
-		if (!strncasecmp(tech_pvt->profile->extrtpip, "stun:", 5)) {
-			char *stun_ip = tech_pvt->profile->extrtpip + 5;
-			if (!stun_ip) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Stun Failed! NO STUN SERVER\n");
-				terminate_session(&tech_pvt->session, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER, __LINE__);
-				return SWITCH_STATUS_FALSE;
-			}
-			if (switch_stun_lookup(&ip,
-								   &sdp_port,
-								   stun_ip,
-								   SWITCH_STUN_DEFAULT_PORT,
-								   &err,
-								   switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Stun Failed! %s:%d [%s]\n", stun_ip, SWITCH_STUN_DEFAULT_PORT, err);
-				terminate_session(&tech_pvt->session, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER, __LINE__);
-				return SWITCH_STATUS_FALSE;
-			}
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Stun Success [%s]:[%d]\n", ip, sdp_port);
-		} else {
-			ip = tech_pvt->profile->extrtpip;
-		}
-	}
-
-	tech_pvt->adv_sdp_audio_ip = switch_core_session_strdup(tech_pvt->session, ip);
-	tech_pvt->adv_sdp_audio_port = sdp_port;
-
-	snprintf(tmp, sizeof(tmp), "%d", sdp_port);
-	switch_channel_set_variable(channel, SWITCH_LOCAL_MEDIA_IP_VARIABLE, tech_pvt->adv_sdp_audio_ip);
-	switch_channel_set_variable(channel, SWITCH_LOCAL_MEDIA_PORT_VARIABLE, tmp);
-	
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static switch_status_t do_invite(switch_core_session_t *session)
-{
-	char rpid[1024] = { 0 };
-	char alert_info[1024] = { 0 };
-	char max_forwards[8] = { 0 };
-	char *alertbuf;
-	char *forwardbuf;
-	int forwardval;
-	private_object_t *tech_pvt;
-    switch_channel_t *channel = NULL;
-	switch_caller_profile_t *caller_profile;
-	char *cid_name, *cid_num;
-	char *e_dest = NULL;
-	const char *holdstr = "";
-	switch_stream_handle_t stream = {0};
-	switch_hash_index_t *hi;
-	void *vval;
-	char *extra_headers = NULL;
-	const void *vvar;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-    channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
-
-    tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-    assert(tech_pvt != NULL);
-
-	caller_profile = switch_channel_get_caller_profile(channel);
-
-	cid_name = (char *) caller_profile->caller_id_name;
-	cid_num = (char *) caller_profile->caller_id_number;
-    tech_set_codecs(tech_pvt);
-
-	if ((tech_pvt->from_str = switch_mprintf("\"%s\" <sip:%s@%s>", 
-													 cid_name,
-													 cid_num,
-													 tech_pvt->profile->extsipip ? tech_pvt->profile->extsipip : tech_pvt->profile->sipip
-													 ))) {
-
-		char *rep = switch_channel_get_variable(channel, SOFIA_REPLACES_HEADER);
-
-		if ((alertbuf = switch_channel_get_variable(channel, "alert_info"))) {
-			snprintf(alert_info, sizeof(alert_info) - 1, "Alert-Info: %s", alertbuf);
-		}
-
-		if ((forwardbuf = switch_channel_get_variable(channel, SWITCH_MAX_FORWARDS_VARIABLE))) {
-			forwardval = atoi(forwardbuf) - 1;
-			snprintf(max_forwards, sizeof(max_forwards) - 1, "%d", forwardval);
-		}
-
-		if (tech_choose_port(tech_pvt) != SWITCH_STATUS_SUCCESS) {
-            return status;
-        }
-        
-		set_local_sdp(tech_pvt, NULL, 0, NULL, 0);
-
-		switch_set_flag_locked(tech_pvt, TFLAG_READY);
-
-		// forge a RPID for now KHR  -- Should wrap this in an if statement so it can be turned on and off
-		if (switch_test_flag(caller_profile, SWITCH_CPF_SCREEN)) {
-			const char *priv = "off";
-			const char *screen = "no";
-			if (switch_test_flag(caller_profile, SWITCH_CPF_HIDE_NAME)) {
-				priv = "name";
-				if (switch_test_flag(caller_profile, SWITCH_CPF_HIDE_NUMBER)) {
-					priv = "yes";
-				}
-			} else if (switch_test_flag(caller_profile, SWITCH_CPF_HIDE_NUMBER)) {
-				priv = "yes";
-			}
-			if (switch_test_flag(caller_profile, SWITCH_CPF_SCREEN)) {
-				screen = "yes";
-			}
-
-			snprintf(rpid, sizeof(rpid) - 1, "Remote-Party-ID: %s;party=calling;screen=%s;privacy=%s", tech_pvt->from_str, screen, priv);
-								
-		}
-
-		if (!tech_pvt->nh) {
-			char *url =  get_url_from_contact(tech_pvt->dest, 1);
-			tech_pvt->nh = nua_handle(tech_pvt->profile->nua, NULL,
-									  NUTAG_URL(url),
-									  SIPTAG_TO_STR(tech_pvt->dest_to),
-									  SIPTAG_FROM_STR(tech_pvt->from_str),
-									  SIPTAG_CONTACT_STR(tech_pvt->profile->url),
-									  TAG_END());
-			switch_safe_free(url);
-
-            if (!(tech_pvt->sofia_private = malloc(sizeof(*tech_pvt->sofia_private)))) {
-                abort();
-            }
-            memset(tech_pvt->sofia_private, 0, sizeof(*tech_pvt->sofia_private));
-			switch_copy_string(tech_pvt->sofia_private->uuid, switch_core_session_get_uuid(session), sizeof(tech_pvt->sofia_private->uuid));
-			nua_handle_bind(tech_pvt->nh, tech_pvt->sofia_private);
-
-		}
-
-
-		if (tech_pvt->e_dest && (e_dest = strdup(tech_pvt->e_dest))) {
-			char *user = e_dest, *host = NULL;
-			char hash_key[256] = "";
-
-			if ((host = strchr(user, '@'))) {
-				*host++ = '\0';
-			}
-			snprintf(hash_key, sizeof(hash_key), "%s%s%s", user, host, cid_num);
-
-			tech_pvt->chat_from = tech_pvt->from_str;
-			tech_pvt->chat_to = tech_pvt->dest;
-			tech_pvt->hash_key = switch_core_session_strdup(tech_pvt->session, hash_key);
-			switch_core_hash_insert(tech_pvt->profile->chat_hash, tech_pvt->hash_key, tech_pvt);
-			free(e_dest);			
-		}
-
-		holdstr = switch_test_flag(tech_pvt, TFLAG_SIP_HOLD) ? "*" : "";
-
-
-		SWITCH_STANDARD_STREAM(stream);
-		for (hi = switch_channel_variable_first(channel, switch_core_session_get_pool(tech_pvt->session)); hi; hi = switch_hash_next(hi)) {
-            switch_hash_this(hi, &vvar, NULL, &vval);
-            if (vvar && vval) {
-				const char *name = vvar;
-				char *value = (char *) vval;
-
-				if (!strncasecmp(name, SOFIA_SIP_HEADER_PREFIX, strlen(SOFIA_SIP_HEADER_PREFIX))) {
-					const char *hname = name + strlen(SOFIA_SIP_HEADER_PREFIX);
-					stream.write_function(&stream, "%s: %s\r\n", hname, value);
-				}
-			}
-		}
-		
-		if (stream.data) {
-			extra_headers = stream.data;
-		}
-
-		nua_invite(tech_pvt->nh,
-				   TAG_IF(!switch_strlen_zero(rpid), SIPTAG_HEADER_STR(rpid)),
-				   TAG_IF(!switch_strlen_zero(alert_info), SIPTAG_HEADER_STR(alert_info)),
-				   TAG_IF(!switch_strlen_zero(extra_headers), SIPTAG_HEADER_STR(extra_headers)),
-				   TAG_IF(!switch_strlen_zero(max_forwards),SIPTAG_MAX_FORWARDS_STR(max_forwards)),
-				   //SIPTAG_CONTACT_STR(tech_pvt->profile->url),
-				   SOATAG_USER_SDP_STR(tech_pvt->local_sdp_str),
-				   SOATAG_RTP_SORT(SOA_RTP_SORT_REMOTE),
-				   SOATAG_RTP_SELECT(SOA_RTP_SELECT_ALL),
-				   TAG_IF(rep, SIPTAG_REPLACES_STR(rep)),
-				   SOATAG_HOLD(holdstr),
-				   TAG_END());
-		
-		switch_safe_free(stream.data);
-		status = SWITCH_STATUS_SUCCESS;
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n");
-	}
-
-	return status;
-	
-}
-
-
-
-static void do_xfer_invite(switch_core_session_t *session)
-{
-	char rpid[1024];
-	private_object_t *tech_pvt;
-    switch_channel_t *channel = NULL;
-	switch_caller_profile_t *caller_profile;
-
-    channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
-
-    tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-    assert(tech_pvt != NULL);
-
-	caller_profile = switch_channel_get_caller_profile(channel);
-
-	
-
-	if ((tech_pvt->from_str = switch_mprintf("\"%s\" <sip:%s@%s>", 
-													 (char *) caller_profile->caller_id_name, 
-													 (char *) caller_profile->caller_id_number,
-													 tech_pvt->profile->extsipip ? tech_pvt->profile->extsipip : tech_pvt->profile->sipip
-													 ))) {
-
-		char *rep = switch_channel_get_variable(channel, SOFIA_REPLACES_HEADER);
-
-		tech_pvt->nh2 = nua_handle(tech_pvt->profile->nua, NULL,
-								  SIPTAG_TO_STR(tech_pvt->dest),
-								  SIPTAG_FROM_STR(tech_pvt->from_str),
-								  SIPTAG_CONTACT_STR(tech_pvt->profile->url),
-								  TAG_END());
-			
-        
-		nua_handle_bind(tech_pvt->nh2, tech_pvt->sofia_private);
-
-		nua_invite(tech_pvt->nh2,
-				   TAG_IF(rpid, SIPTAG_HEADER_STR(rpid)),
-				   SIPTAG_CONTACT_STR(tech_pvt->profile->url),
-				   SOATAG_USER_SDP_STR(tech_pvt->local_sdp_str),
-				   SOATAG_RTP_SORT(SOA_RTP_SORT_REMOTE),
-				   SOATAG_RTP_SELECT(SOA_RTP_SELECT_ALL),
-				   TAG_IF(rep, SIPTAG_REPLACES_STR(rep)),
-				   TAG_END());
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n");
-	}
-	
-}
-
-static void tech_absorb_sdp(private_object_t *tech_pvt)
-{
-	switch_channel_t *channel;
-	char *sdp_str;
-
-	channel = switch_core_session_get_channel(tech_pvt->session);
-	assert(channel != NULL);
-	
-	if ((sdp_str = switch_channel_get_variable(channel, SWITCH_B_SDP_VARIABLE))) {
-		sdp_parser_t *parser;
-		sdp_session_t *sdp;
-		sdp_media_t *m;
-		sdp_connection_t *connection;
-
-		if ((parser = sdp_parse(tech_pvt->home, sdp_str, (int)strlen(sdp_str), 0))) {
-			if ((sdp = sdp_session(parser))) {
-				for (m = sdp->sdp_media; m ; m = m->m_next) {
-					if (m->m_type != sdp_media_audio) {
-						continue;
-					}
-
-					connection = sdp->sdp_connection;
-					if (m->m_connections) {
-						connection = m->m_connections;
-					}
-
-					if (connection) {
-						tech_pvt->proxy_sdp_audio_ip = switch_core_session_strdup(tech_pvt->session, connection->c_address);
-					}
-					tech_pvt->proxy_sdp_audio_port = (switch_port_t)m->m_port;
-					if (tech_pvt->proxy_sdp_audio_ip && tech_pvt->proxy_sdp_audio_port) {
-						break;
-					}
-				}
-			}
-			sdp_parser_free(parser);
-		}	
-		tech_pvt->local_sdp_str = switch_core_session_strdup(tech_pvt->session, sdp_str);
-	}
-}
-
-/* 
-   State methods they get called when the state changes to the specific state 
-   returning SWITCH_STATUS_SUCCESS tells the core to execute the standard state method next
-   so if you fully implement the state you can return SWITCH_STATUS_FALSE to skip it.
-*/
-static switch_status_t sofia_on_init(switch_core_session_t *session)
-{
-	private_object_t *tech_pvt;
-	switch_channel_t *channel = NULL;
-	
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-	tech_pvt->read_frame.buflen = SWITCH_RTP_MAX_BUF_LEN;
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA INIT\n");
-	if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
-		switch_set_flag_locked(tech_pvt, TFLAG_NOMEDIA);
-		tech_absorb_sdp(tech_pvt);
-	}
-
-	if (switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
-		if (do_invite(session) != SWITCH_STATUS_SUCCESS) {
-			return SWITCH_STATUS_FALSE;
-		}
-	}
-	
-	/* Move Channel's State Machine to RING */
-	switch_channel_set_state(channel, CS_RING);
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static switch_status_t sofia_on_ring(switch_core_session_t *session)
-{
-	switch_channel_t *channel = NULL;
-	private_object_t *tech_pvt = NULL;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA RING\n");
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-
-static switch_status_t sofia_on_execute(switch_core_session_t *session)
-{
-	switch_channel_t *channel = NULL;
-	private_object_t *tech_pvt = NULL;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA EXECUTE\n");
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-// map QSIG cause codes to SIP from RFC4497 section 8.4.1
-static int hangup_cause_to_sip(switch_call_cause_t cause) {
-	switch (cause) {
-	case SWITCH_CAUSE_NO_ROUTE_TRANSIT_NET:
-	case SWITCH_CAUSE_NO_ROUTE_DESTINATION:
-		return 404;
-	case SWITCH_CAUSE_USER_BUSY:
-		return 486;
-	case SWITCH_CAUSE_NO_USER_RESPONSE:
-		return 408;
-	case SWITCH_CAUSE_NO_ANSWER:
-		return 480;
-	case SWITCH_CAUSE_SUBSCRIBER_ABSENT:
-		return 480;
-	case SWITCH_CAUSE_CALL_REJECTED:
-		return 603;
-	case SWITCH_CAUSE_NUMBER_CHANGED:
-	case SWITCH_CAUSE_REDIRECTION_TO_NEW_DESTINATION:
-		return 410;
-	case SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER:
-		return 502;
-	case SWITCH_CAUSE_INVALID_NUMBER_FORMAT:
-		return 484;
-	case SWITCH_CAUSE_FACILITY_REJECTED:
-		return 501;
-	case SWITCH_CAUSE_NORMAL_UNSPECIFIED:
-		return 480;
-	case SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL:
-	case SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION:
-	case SWITCH_CAUSE_NETWORK_OUT_OF_ORDER:
-	case SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE:
-	case SWITCH_CAUSE_SWITCH_CONGESTION:
-		return 503;
-	case SWITCH_CAUSE_OUTGOING_CALL_BARRED:
-	case SWITCH_CAUSE_INCOMING_CALL_BARRED:
-	case SWITCH_CAUSE_BEARERCAPABILITY_NOTAUTH: 
-		return 403;
-	case SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL:
-		return 503;
-	case SWITCH_CAUSE_BEARERCAPABILITY_NOTIMPL:
-		return 488;
-	case SWITCH_CAUSE_FACILITY_NOT_IMPLEMENTED:
-	case SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED:
-		return 501;
-	case SWITCH_CAUSE_INCOMPATIBLE_DESTINATION:
-		return 503;
-	case SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE:
-		return 504;
-	case SWITCH_CAUSE_ORIGINATOR_CANCEL:
-		return 487;
-	default:
-		return 480;
-	}
-
-}
-
-static switch_status_t sofia_on_hangup(switch_core_session_t *session)
-{
-	switch_core_session_t *a_session;
-	private_object_t *tech_pvt;
-	switch_channel_t *channel = NULL;
-	switch_call_cause_t cause;
-	int sip_cause;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
 	cause = switch_channel_get_cause(channel);
-	sip_cause = hangup_cause_to_sip(cause);
-
-	deactivate_rtp(tech_pvt);
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Channel %s hanging up, cause: %s\n", 
-					  switch_channel_get_name(channel), switch_channel_cause2str(cause));
-
-	if (tech_pvt->hash_key) {
-		switch_core_hash_delete(tech_pvt->profile->chat_hash, tech_pvt->hash_key);
-	}
-
-	if (tech_pvt->kick && (a_session = switch_core_session_locate(tech_pvt->kick))) {
-		switch_channel_t *a_channel = switch_core_session_get_channel(a_session);
-		switch_channel_hangup(a_channel, switch_channel_get_cause(channel));
-		switch_core_session_rwunlock(a_session);
-	}
-
-	if (tech_pvt->nh) {
-		if (!switch_test_flag(tech_pvt, TFLAG_BYE)) {
-			if (switch_test_flag(tech_pvt, TFLAG_ANS)) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Sending BYE to %s\n", switch_channel_get_name(channel));
-				nua_bye(tech_pvt->nh, TAG_END());
-			} else {
-				if (!switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Responding to INVITE with: %d\n", sip_cause);
-					nua_respond(tech_pvt->nh, sip_cause, NULL, TAG_END());
-				} else {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Sending CANCEL to %s\n", switch_channel_get_name(channel));
-					nua_cancel(tech_pvt->nh, TAG_END());
-				}
-			}
-			switch_set_flag_locked(tech_pvt, TFLAG_BYE);
-		}
-	}
-
-	if (tech_pvt->from_str) {
-		switch_safe_free(tech_pvt->from_str);
-	}
-
-	switch_clear_flag_locked(tech_pvt, TFLAG_IO);
-
-	if (tech_pvt->home) {
-		su_home_unref(tech_pvt->home);
-		tech_pvt->home = NULL;
-	}
-
-    if (tech_pvt->sofia_private) {
-        *tech_pvt->sofia_private->uuid = '\0';
-    }
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static switch_status_t sofia_on_loopback(switch_core_session_t *session)
-{
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA LOOPBACK\n");
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static switch_status_t sofia_on_transmit(switch_core_session_t *session)
-{
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA TRANSMIT\n");
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static void deactivate_rtp(private_object_t *tech_pvt)
-{
-	int loops = 0;//, sock = -1;
-	if (switch_rtp_ready(tech_pvt->rtp_session)) {
-		while (loops < 10 && (switch_test_flag(tech_pvt, TFLAG_READING) || switch_test_flag(tech_pvt, TFLAG_WRITING))) {
-			switch_yield(10000);
-			loops++;
-		}
-		switch_rtp_destroy(&tech_pvt->rtp_session);
-	}
-}
-
-static switch_status_t tech_set_codec(private_object_t *tech_pvt, int force)
-{
-	switch_channel_t *channel;
-
-	if (tech_pvt->read_codec.implementation) {
-		if (!force) {
-			return SWITCH_STATUS_SUCCESS;
-		}
-		if (strcasecmp(tech_pvt->read_codec.implementation->iananame, tech_pvt->rm_encoding) ||
-			tech_pvt->read_codec.implementation->samples_per_second != tech_pvt->rm_rate) {
-
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Changing Codec from %s to %s\n",
-							  tech_pvt->read_codec.implementation->iananame, tech_pvt->rm_encoding);
-		switch_core_codec_destroy(&tech_pvt->read_codec);
-		switch_core_codec_destroy(&tech_pvt->write_codec);
-		switch_core_session_reset(tech_pvt->session);
-		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Already using %s\n",
-							  tech_pvt->read_codec.implementation->iananame);
-			return SWITCH_STATUS_SUCCESS;
-		}
-	}
-
-	channel = switch_core_session_get_channel(tech_pvt->session);
-	assert(channel != NULL);
-
-	if (!tech_pvt->rm_encoding) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec with no name?\n");
-		terminate_session(&tech_pvt->session, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER, __LINE__);
-		return SWITCH_STATUS_FALSE;
-	}
-
-	if (switch_core_codec_init(&tech_pvt->read_codec,  
-							   tech_pvt->rm_encoding,
-							   tech_pvt->rm_fmtp,
-							   tech_pvt->rm_rate,
-							   tech_pvt->codec_ms,
-							   1,
-							   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE | tech_pvt->profile->codec_flags,
-							   NULL,
-							   switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
-		terminate_session(&tech_pvt->session, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER, __LINE__);
-		return SWITCH_STATUS_FALSE;
-	} else {
-		if (switch_core_codec_init(&tech_pvt->write_codec,
-								   tech_pvt->rm_encoding,
-								   tech_pvt->rm_fmtp,
-								   tech_pvt->rm_rate,
-								   tech_pvt->codec_ms,
-								   1,
-								   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE | tech_pvt->profile->codec_flags,
-								   NULL,
-								   switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
-			terminate_session(&tech_pvt->session, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER, __LINE__);
-			return SWITCH_STATUS_FALSE;
-		} else {
-			int ms;
-			tech_pvt->read_frame.rate = tech_pvt->rm_rate;
-			ms = tech_pvt->write_codec.implementation->microseconds_per_frame / 1000;
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Set Codec %s %s/%d %d ms\n",
-							  switch_channel_get_name(channel),
-							  tech_pvt->rm_encoding, tech_pvt->rm_rate, tech_pvt->codec_ms);
-			tech_pvt->read_frame.codec = &tech_pvt->read_codec;
-				
-			switch_core_session_set_read_codec(tech_pvt->session, &tech_pvt->read_codec);
-			switch_core_session_set_write_codec(tech_pvt->session, &tech_pvt->write_codec);
-			tech_pvt->fmtp_out = switch_core_session_strdup(tech_pvt->session, tech_pvt->write_codec.fmtp_out);
-		}
-	}
-	return SWITCH_STATUS_SUCCESS;
-}
-
-
-static switch_status_t activate_rtp(private_object_t *tech_pvt)
-{
-	int bw, ms;
-	switch_channel_t *channel;
-	const char *err = NULL;
-    char *val = NULL;
-	switch_rtp_flag_t flags;
-	switch_status_t status;
-	char tmp[50];
-	assert(tech_pvt != NULL);
-
-	channel = switch_core_session_get_channel(tech_pvt->session);
-	assert(channel != NULL);
-
-	if (switch_test_flag(tech_pvt, TFLAG_NOMEDIA)) {
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	if (switch_rtp_ready(tech_pvt->rtp_session) && !switch_test_flag(tech_pvt, TFLAG_REINVITE)) {
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	if ((status = tech_set_codec(tech_pvt, 0)) != SWITCH_STATUS_SUCCESS) {
-		return status;
-	}
-	
-	bw = tech_pvt->read_codec.implementation->bits_per_second;
-	ms = tech_pvt->read_codec.implementation->microseconds_per_frame;
-
-	flags = (switch_rtp_flag_t) (SWITCH_RTP_FLAG_RAW_WRITE | SWITCH_RTP_FLAG_AUTOADJ | SWITCH_RTP_FLAG_DATAWAIT);
-
-	if (switch_test_flag(tech_pvt, TFLAG_BUGGY_2833)) {
-		flags |= SWITCH_RTP_FLAG_BUGGY_2833;
-	}
-
-    if ((tech_pvt->profile->pflags & PFLAG_PASS_RFC2833) || ((val = switch_channel_get_variable(channel, "pass_rfc2833")) && switch_true(val))) {
-        flags |= SWITCH_RTP_FLAG_PASS_RFC2833;
-    }
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "RTP [%s] %s:%d->%s:%d codec: %u ms: %d\n",
-					  switch_channel_get_name(channel),
-					  tech_pvt->local_sdp_audio_ip,
-					  tech_pvt->local_sdp_audio_port,
-					  tech_pvt->remote_sdp_audio_ip,
-					  tech_pvt->remote_sdp_audio_port,
-					  tech_pvt->agreed_pt,
-					  tech_pvt->read_codec.implementation->microseconds_per_frame / 1000);
-
-	snprintf(tmp, sizeof(tmp), "%d", tech_pvt->remote_sdp_audio_port);
-	switch_channel_set_variable(channel, SWITCH_LOCAL_MEDIA_IP_VARIABLE, tech_pvt->adv_sdp_audio_ip);
-	switch_channel_set_variable(channel, SWITCH_LOCAL_MEDIA_PORT_VARIABLE, tmp);
-	
-	if (tech_pvt->rtp_session && switch_test_flag(tech_pvt, TFLAG_REINVITE)) {
-		switch_clear_flag_locked(tech_pvt, TFLAG_REINVITE);
-		
-		if (switch_rtp_set_remote_address(tech_pvt->rtp_session,
-										  tech_pvt->remote_sdp_audio_ip,
-										  tech_pvt->remote_sdp_audio_port,
-										  &err) != SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "RTP REPORTS ERROR: [%s]\n", err);
-		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "RTP CHANGING DEST TO: [%s:%d]\n", 
-							  tech_pvt->remote_sdp_audio_ip, tech_pvt->remote_sdp_audio_port);
-            /* Reactivate the NAT buster flag. */
-            switch_rtp_set_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_AUTOADJ);
-		}
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	tech_pvt->rtp_session = switch_rtp_new(tech_pvt->local_sdp_audio_ip,
-										   tech_pvt->local_sdp_audio_port,
-										   tech_pvt->remote_sdp_audio_ip,
-										   tech_pvt->remote_sdp_audio_port,
-										   tech_pvt->agreed_pt,
-										   tech_pvt->read_codec.implementation->encoded_bytes_per_frame,
-										   tech_pvt->codec_ms * 1000,
-										   (switch_rtp_flag_t) flags,
-										   NULL,
-										   tech_pvt->profile->timer_name,
-										   &err,
-										   switch_core_session_get_pool(tech_pvt->session));
-	
-	if (switch_rtp_ready(tech_pvt->rtp_session)) {
-		uint8_t vad_in = switch_test_flag(tech_pvt, TFLAG_VAD_IN) ? 1 : 0;
-		uint8_t vad_out = switch_test_flag(tech_pvt, TFLAG_VAD_OUT) ? 1 : 0;
-		uint8_t inb = switch_test_flag(tech_pvt, TFLAG_OUTBOUND) ? 0 : 1;
-
-		tech_pvt->ssrc = switch_rtp_get_ssrc(tech_pvt->rtp_session);
-		switch_set_flag_locked(tech_pvt, TFLAG_RTP);
-		switch_set_flag_locked(tech_pvt, TFLAG_IO);
-		
-		if ((vad_in && inb) || (vad_out && !inb)) {
-			switch_rtp_enable_vad(tech_pvt->rtp_session, tech_pvt->session, &tech_pvt->read_codec, SWITCH_VAD_FLAG_TALKING);
-			switch_set_flag_locked(tech_pvt, TFLAG_VAD);
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "RTP Engage VAD for %s ( %s %s )\n", 
-                              switch_channel_get_name(switch_core_session_get_channel(tech_pvt->session)),
-                              vad_in ? "in" : "", vad_out ? "out" : "");
-		}
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "RTP REPORTS ERROR: [%s]\n", err);
-		terminate_session(&tech_pvt->session, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER, __LINE__);
-		switch_clear_flag_locked(tech_pvt, TFLAG_IO);
-		return SWITCH_STATUS_FALSE;
-	}
-		
-	switch_set_flag_locked(tech_pvt, TFLAG_IO);
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static switch_status_t tech_media(private_object_t *tech_pvt, char *r_sdp)
-{
-    sdp_parser_t *parser = sdp_parse(tech_pvt->home, r_sdp, (int)strlen(r_sdp), 0);
-    sdp_session_t *sdp;
-    uint8_t match = 0;
-    switch_channel_t *channel = switch_core_session_get_channel(tech_pvt->session);
-
-    assert(tech_pvt != NULL);
-
-    if (switch_strlen_zero(r_sdp)) {
-        return SWITCH_STATUS_FALSE;
-    }
-
-    if (tech_pvt->num_codecs) {
-        if ((sdp = sdp_session(parser))) {
-            match = negotiate_sdp(tech_pvt->session, sdp);
-        }
-    }
-
-    if (parser) {
-        sdp_parser_free(parser);
-    }
-
-    if (match) {
-        if (tech_choose_port(tech_pvt) != SWITCH_STATUS_SUCCESS) {
-            return SWITCH_STATUS_FALSE;
-        }
-        activate_rtp(tech_pvt);
-        switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "EARLY MEDIA");
-        switch_set_flag_locked(tech_pvt, TFLAG_EARLY_MEDIA);
-        switch_channel_mark_pre_answered(channel);
-        return SWITCH_STATUS_SUCCESS;
-    }
-    
-    return SWITCH_STATUS_FALSE;
-}
-
-
-
-static switch_status_t sofia_answer_channel(switch_core_session_t *session)
-{
-	private_object_t *tech_pvt;
-	switch_channel_t *channel = NULL;
-	switch_status_t status;
-
-	assert(session != NULL);
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-    
-	if (!switch_test_flag(tech_pvt, TFLAG_ANS) && !switch_channel_test_flag(channel, CF_OUTBOUND)) {
-		switch_set_flag_locked(tech_pvt, TFLAG_ANS);
-
-		if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
-			char *sdp = NULL;
-			switch_set_flag_locked(tech_pvt, TFLAG_NOMEDIA);
-			if ((sdp = switch_channel_get_variable(channel, SWITCH_B_SDP_VARIABLE))) {
-				tech_pvt->local_sdp_str = switch_core_session_strdup(session, sdp);
-			}
-		} else {
-			if (switch_test_flag(tech_pvt, TFLAG_LATE_NEGOTIATION)) {
-				char *r_sdp = switch_channel_get_variable(channel, SWITCH_R_SDP_VARIABLE);
-				if (tech_media(tech_pvt, r_sdp) != SWITCH_STATUS_SUCCESS) {
-					switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "CODEC NEGOTIATION ERROR");
-					nua_respond(tech_pvt->nh, SIP_488_NOT_ACCEPTABLE, TAG_END());
-					return SWITCH_STATUS_FALSE;
-				}
-				switch_clear_flag_locked(tech_pvt, TFLAG_LATE_NEGOTIATION);
-			}
-
-			if ((status = tech_choose_port(tech_pvt)) != SWITCH_STATUS_SUCCESS) {
-				return status;
-			}
-
-			set_local_sdp(tech_pvt, NULL, 0, NULL, 0);
-			activate_rtp(tech_pvt);
-		
-			if (tech_pvt->nh) {
-				if (tech_pvt->local_sdp_str) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Local SDP %s:\n%s\n",
-									  switch_channel_get_name(channel),
-								  tech_pvt->local_sdp_str);
-				}
-			}
-		}
-		nua_respond(tech_pvt->nh, SIP_200_OK, 
-					SIPTAG_CONTACT_STR(tech_pvt->profile->url),
-					SOATAG_USER_SDP_STR(tech_pvt->local_sdp_str),
-					SOATAG_AUDIO_AUX("cn telephone-event"),
-					NUTAG_INCLUDE_EXTRA_SDP(1),
-					TAG_END());
-	} 
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-
-static switch_status_t sofia_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-										switch_io_flag_t flags, int stream_id)
-{
-	private_object_t *tech_pvt = NULL;
-	switch_channel_t *channel = NULL;
-	int payload = 0;
-	
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-	if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
-		return SWITCH_STATUS_FALSE;
-	}
-
-	while (!(tech_pvt->read_codec.implementation && switch_rtp_ready(tech_pvt->rtp_session))) {
-		if (switch_channel_ready(channel)) {
-			switch_yield(10000);
-		} else {
-			return SWITCH_STATUS_GENERR;
-		}
-	}
-
-
-	tech_pvt->read_frame.datalen = 0;
-	switch_set_flag_locked(tech_pvt, TFLAG_READING);
-
-#if 0	
-	if (tech_pvt->last_read) {
-		elapsed = (unsigned int)((switch_time_now() - tech_pvt->last_read) / 1000);
-		if (elapsed > 60000) {
-			return SWITCH_STATUS_TIMEOUT;
-		}
-	}
-#endif
-
-
-	if (switch_test_flag(tech_pvt, TFLAG_IO)) {
-		switch_status_t status;
-
-		if (!switch_test_flag(tech_pvt, TFLAG_RTP)) {
-			return SWITCH_STATUS_GENERR;
-		}
-
-		assert(tech_pvt->rtp_session != NULL);
-		tech_pvt->read_frame.datalen = 0;
-
-
-		while (switch_test_flag(tech_pvt, TFLAG_IO) && tech_pvt->read_frame.datalen == 0) {
-			tech_pvt->read_frame.flags = SFF_NONE;
-
-			status = switch_rtp_zerocopy_read_frame(tech_pvt->rtp_session, &tech_pvt->read_frame);
-			if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
-				return SWITCH_STATUS_FALSE;
-			}
-
-			
-			
-			payload = tech_pvt->read_frame.payload;
-
-#if 0
-			elapsed = (unsigned int)((switch_time_now() - started) / 1000);
-
-			if (timeout > -1) {
-				if (elapsed >= (unsigned int)timeout) {
-					return SWITCH_STATUS_BREAK;
-				}
-			}
-			
-			elapsed = (unsigned int)((switch_time_now() - last_act) / 1000);
-			if (elapsed >= hard_timeout) {
-				return SWITCH_STATUS_BREAK;
-			}
-#endif
-			if (switch_rtp_has_dtmf(tech_pvt->rtp_session)) {
-				char dtmf[128];
-				switch_rtp_dequeue_dtmf(tech_pvt->rtp_session, dtmf, sizeof(dtmf));
-				switch_channel_queue_dtmf(channel, dtmf);
-			}
-
-
-			if (tech_pvt->read_frame.datalen > 0) {
-                size_t bytes = 0;
-                int frames = 1;
-				//tech_pvt->last_read = switch_time_now();
-                if (!switch_test_flag((&tech_pvt->read_frame), SFF_CNG)) {
-                    if ((bytes = tech_pvt->read_codec.implementation->encoded_bytes_per_frame)) {
-                        frames = (tech_pvt->read_frame.datalen / bytes);
-                    }
-                    tech_pvt->read_frame.samples = (int) (frames * tech_pvt->read_codec.implementation->samples_per_frame);
-                }
-				break;
-			}
-		}
-	}
-	
-	switch_clear_flag_locked(tech_pvt, TFLAG_READING);
-
-	if (tech_pvt->read_frame.datalen == 0) {
-		*frame = NULL;
-		return SWITCH_STATUS_GENERR;
-	}
-
-	*frame = &tech_pvt->read_frame;
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-
-static switch_status_t sofia_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-										 switch_io_flag_t flags, int stream_id)
-{
-	private_object_t *tech_pvt;
-	switch_channel_t *channel = NULL;
-	switch_status_t status = SWITCH_STATUS_SUCCESS;
-	int bytes = 0, samples = 0, frames = 0;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-	while (!(tech_pvt->read_codec.implementation && switch_rtp_ready(tech_pvt->rtp_session))) {
-		if (switch_channel_ready(channel)) {
-			switch_yield(10000);
-		} else {
-			return SWITCH_STATUS_GENERR;
-		}
-	}
-
-	if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
-		return SWITCH_STATUS_FALSE;
-	}
-
-	if (!switch_test_flag(tech_pvt, TFLAG_RTP)) {
-		return SWITCH_STATUS_GENERR;
-	}
-
-	if (!switch_test_flag(tech_pvt, TFLAG_IO)) {
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	switch_set_flag_locked(tech_pvt, TFLAG_WRITING);
-
-
-	if (tech_pvt->read_codec.implementation->encoded_bytes_per_frame) {
-		bytes = tech_pvt->read_codec.implementation->encoded_bytes_per_frame;
-		frames = ((int) frame->datalen / bytes);
-	} else
-		frames = 1;
-
-	samples = frames * tech_pvt->read_codec.implementation->samples_per_frame;
-
-#if 0
-	printf("%s %s->%s send %d bytes %d samples in %d frames ts=%d\n",
-		   switch_channel_get_name(channel),
-		   tech_pvt->local_sdp_audio_ip,
-		   tech_pvt->remote_sdp_audio_ip,
-		   frame->datalen,
-		   samples,
-		   frames,
-		   tech_pvt->timestamp_send);
-#endif
-
-	switch_rtp_write_frame(tech_pvt->rtp_session, frame, samples);
-	
-	tech_pvt->timestamp_send += (int) samples;
-
-	switch_clear_flag_locked(tech_pvt, TFLAG_WRITING);
-	return status;
-}
-
-
-
-static switch_status_t sofia_kill_channel(switch_core_session_t *session, int sig)
-{
-	private_object_t *tech_pvt;
-	switch_channel_t *channel = NULL;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-
-    switch(sig) {
-    case SWITCH_SIG_BREAK:
-        if (switch_rtp_ready(tech_pvt->rtp_session)) {
-			switch_rtp_set_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_BREAK);
-		}
-        break;
-    case SWITCH_SIG_KILL:
-    default:
-        switch_clear_flag_locked(tech_pvt, TFLAG_IO);
-        switch_set_flag_locked(tech_pvt, TFLAG_HUP);
-
-        if (switch_rtp_ready(tech_pvt->rtp_session)) {
-            switch_rtp_kill_socket(tech_pvt->rtp_session);
-        }
-        break;
-    }
-
-	return SWITCH_STATUS_SUCCESS;
-
-}
-
-static switch_status_t sofia_waitfor_read(switch_core_session_t *session, int ms, int stream_id)
-{
-	private_object_t *tech_pvt;
-	switch_channel_t *channel = NULL;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-
-static switch_status_t sofia_waitfor_write(switch_core_session_t *session, int ms, int stream_id)
-{
-	private_object_t *tech_pvt;
-	switch_channel_t *channel = NULL;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-	return SWITCH_STATUS_SUCCESS;
-
-}
-
-static switch_status_t sofia_send_dtmf(switch_core_session_t *session, char *digits)
-{
-	private_object_t *tech_pvt;
-
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-    assert(tech_pvt != NULL);
-
-	return switch_rtp_queue_rfc2833(tech_pvt->rtp_session,
-									digits,
-									tech_pvt->profile->dtmf_duration * (tech_pvt->read_codec.implementation->samples_per_second / 1000));
-	
-}
-
-static switch_status_t sofia_receive_message(switch_core_session_t *session, switch_core_session_message_t *msg)
-{
-	switch_channel_t *channel;
-	private_object_t *tech_pvt;
-    switch_status_t status;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-			
-	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-
-	switch (msg->message_id) {
-	case SWITCH_MESSAGE_INDICATE_NOMEDIA: {
-		char *uuid;
-		switch_core_session_t *other_session;
-		switch_channel_t *other_channel;
-		char *ip = NULL, *port = NULL;
-
-		switch_set_flag_locked(tech_pvt, TFLAG_NOMEDIA);
-		tech_pvt->local_sdp_str = NULL;
-		if ((uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) && (other_session = switch_core_session_locate(uuid))) {
-			other_channel = switch_core_session_get_channel(other_session);
-			ip = switch_channel_get_variable(other_channel, SWITCH_REMOTE_MEDIA_IP_VARIABLE);
-			port = switch_channel_get_variable(other_channel, SWITCH_REMOTE_MEDIA_PORT_VARIABLE);
-			switch_core_session_rwunlock(other_session);
-			if (ip && port) {
-				set_local_sdp(tech_pvt, ip, atoi(port), NULL, 1);
-			}
-		}
-		if (!tech_pvt->local_sdp_str) {
-			tech_absorb_sdp(tech_pvt);
-		}
-		do_invite(session);
-	}
-		break;
-	case SWITCH_MESSAGE_INDICATE_MEDIA: {
-		switch_clear_flag_locked(tech_pvt, TFLAG_NOMEDIA);
-		tech_pvt->local_sdp_str = NULL;
-		if (!switch_rtp_ready(tech_pvt->rtp_session)) {
-			tech_set_codecs(tech_pvt);
-			if ((status=tech_choose_port(tech_pvt)) != SWITCH_STATUS_SUCCESS) {
-                return status;
-            }
-		}
-		set_local_sdp(tech_pvt, NULL, 0, NULL, 1);
-		do_invite(session);
-		while (!switch_rtp_ready(tech_pvt->rtp_session) && switch_channel_get_state(channel) < CS_HANGUP) {
-			switch_yield(1000);
-		}
-	}
-		break;
-
-	case SWITCH_MESSAGE_INDICATE_HOLD: {
-		switch_set_flag_locked(tech_pvt, TFLAG_SIP_HOLD);
-		do_invite(session);
-	}
-		break;
-
-	case SWITCH_MESSAGE_INDICATE_UNHOLD: {
-		switch_clear_flag_locked(tech_pvt, TFLAG_SIP_HOLD);
-		do_invite(session);
-	}
-		break;
-	case SWITCH_MESSAGE_INDICATE_BRIDGE:
-
-		if (switch_test_flag(tech_pvt, TFLAG_XFER)) {
-			switch_clear_flag_locked(tech_pvt, TFLAG_XFER);
-			if (msg->pointer_arg) {
-				switch_core_session_t *a_session, *b_session = msg->pointer_arg;
-
-				if ((a_session = switch_core_session_locate(tech_pvt->xferto))) {
-					private_object_t *a_tech_pvt = switch_core_session_get_private(a_session);
-					private_object_t *b_tech_pvt = switch_core_session_get_private(b_session);
-
-					switch_set_flag_locked(a_tech_pvt, TFLAG_REINVITE);
-					a_tech_pvt->remote_sdp_audio_ip = switch_core_session_strdup(a_session, b_tech_pvt->remote_sdp_audio_ip);
-					a_tech_pvt->remote_sdp_audio_port = b_tech_pvt->remote_sdp_audio_port;
-					a_tech_pvt->local_sdp_audio_ip = switch_core_session_strdup(a_session, b_tech_pvt->local_sdp_audio_ip);
-					a_tech_pvt->local_sdp_audio_port = b_tech_pvt->local_sdp_audio_port;
-					activate_rtp(a_tech_pvt);
-					
-					b_tech_pvt->kick = switch_core_session_strdup(b_session, tech_pvt->xferto);
-                    switch_core_session_rwunlock(a_session);
-				}
-
-				
-				msg->pointer_arg = NULL;
-				return SWITCH_STATUS_FALSE;
-			}
-		}
-		if (tech_pvt->rtp_session && switch_test_flag(tech_pvt, TFLAG_TIMER)) {
-			switch_rtp_clear_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_USE_TIMER);
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "De-activate timed RTP!\n");
-		}
-		break;
-	case SWITCH_MESSAGE_INDICATE_UNBRIDGE:
-		if (tech_pvt->rtp_session && switch_test_flag(tech_pvt, TFLAG_TIMER)) {
-			switch_rtp_set_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_USE_TIMER);
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Re-activate timed RTP!\n");
-		}
-		break;
-	case SWITCH_MESSAGE_INDICATE_REDIRECT:
-		if(msg->string_arg) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Re-directing to %s\n", msg->string_arg);
-			nua_respond(tech_pvt->nh, SIP_302_MOVED_TEMPORARILY, SIPTAG_CONTACT_STR(msg->string_arg), TAG_END());
-		}
-		break;
-	case SWITCH_MESSAGE_INDICATE_RINGING:
-		nua_respond(tech_pvt->nh, SIP_180_RINGING, SIPTAG_CONTACT_STR(tech_pvt->profile->url), TAG_END());
-		break;
-	case SWITCH_MESSAGE_INDICATE_PROGRESS: {
-		if (!switch_test_flag(tech_pvt, TFLAG_ANS)) {
-			switch_set_flag_locked(tech_pvt, TFLAG_EARLY_MEDIA);
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Asked to send early media by %s\n", msg->from);
-
-			/* Transmit 183 Progress with SDP */
-			if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
-				char *sdp = NULL;
-				switch_set_flag_locked(tech_pvt, TFLAG_NOMEDIA);
-				if ((sdp = switch_channel_get_variable(channel, SWITCH_B_SDP_VARIABLE))) {
-					tech_pvt->local_sdp_str = switch_core_session_strdup(session, sdp);
-				}
-			} else {
-				if (switch_test_flag(tech_pvt, TFLAG_LATE_NEGOTIATION)) {
-					char *r_sdp = switch_channel_get_variable(channel, SWITCH_R_SDP_VARIABLE);
-					if (tech_media(tech_pvt, r_sdp) != SWITCH_STATUS_SUCCESS) {
-						switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "CODEC NEGOTIATION ERROR");
-						nua_respond(tech_pvt->nh, SIP_488_NOT_ACCEPTABLE, TAG_END());
-						return SWITCH_STATUS_FALSE;
-					}
-					switch_clear_flag_locked(tech_pvt, TFLAG_LATE_NEGOTIATION);
-				}
-
-				if ((status=tech_choose_port(tech_pvt)) != SWITCH_STATUS_SUCCESS) {
-					return status;
-				}
-				set_local_sdp(tech_pvt, NULL, 0, NULL, 0);
-				activate_rtp(tech_pvt);
-				if (tech_pvt->local_sdp_str) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Ring SDP:\n%s\n", tech_pvt->local_sdp_str);
-				}
-			}
-			
-			nua_respond(tech_pvt->nh,
-						SIP_183_SESSION_PROGRESS,
-						SIPTAG_CONTACT_STR(tech_pvt->profile->url),
-						SOATAG_USER_SDP_STR(tech_pvt->local_sdp_str),
-						SOATAG_AUDIO_AUX("cn telephone-event"),
-						TAG_END());
-	    }
-	}
-		break;
-	default:
-		break;
-	}
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static switch_status_t sofia_receive_event(switch_core_session_t *session, switch_event_t *event)
-{
-	switch_channel_t *channel;
-    struct private_object *tech_pvt;
-	char *body;
-	nua_handle_t *msg_nh;
-
-    channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
-
-    tech_pvt = switch_core_session_get_private(session);
-    assert(tech_pvt != NULL);
-
-
-	if (!(body = switch_event_get_body(event))) {
-		body = "";
-	}
-
-	if (tech_pvt->hash_key) {
-		msg_nh = nua_handle(tech_pvt->profile->nua, NULL,
-							SIPTAG_FROM_STR(tech_pvt->chat_from),
-							NUTAG_URL(tech_pvt->chat_to),
-							SIPTAG_TO_STR(tech_pvt->chat_to),
-							SIPTAG_CONTACT_STR(tech_pvt->profile->url),
-							TAG_END());
-
-		nua_message(msg_nh,
-					SIPTAG_CONTENT_TYPE_STR("text/html"),
-					SIPTAG_PAYLOAD_STR(body),
-					TAG_END());
-	}
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static const switch_io_routines_t sofia_io_routines = {
-	/*.outgoing_channel */ sofia_outgoing_channel,
-	/*.answer_channel */ sofia_answer_channel,
-	/*.read_frame */ sofia_read_frame,
-	/*.write_frame */ sofia_write_frame,
-	/*.kill_channel */ sofia_kill_channel,
-	/*.waitfor_read */ sofia_waitfor_read,
-	/*.waitfor_read */ sofia_waitfor_write,
-	/*.send_dtmf*/ sofia_send_dtmf,
-	/*.receive_message*/ sofia_receive_message,
-	/*.receive_event*/ sofia_receive_event
-};
-
-static const switch_state_handler_table_t sofia_event_handlers = {
-	/*.on_init */ sofia_on_init,
-	/*.on_ring */ sofia_on_ring,
-	/*.on_execute */ sofia_on_execute,
-	/*.on_hangup */ sofia_on_hangup,
-	/*.on_loopback */ sofia_on_loopback,
-	/*.on_transmit */ sofia_on_transmit
-};
-
-static const switch_endpoint_interface_t sofia_endpoint_interface = {
-	/*.interface_name */ "sofia",
-	/*.io_routines */ &sofia_io_routines,
-	/*.event_handlers */ &sofia_event_handlers,
-	/*.private */ NULL,
-	/*.next */ NULL
-};
-
-static const switch_chat_interface_t sofia_chat_interface = {
-	/*.name */ SOFIA_CHAT_PROTO,
-	/*.chat_send */ chat_send,
-	
-};
-
-static const switch_loadable_module_interface_t sofia_module_interface = {
-	/*.module_name */ modname,
-	/*.endpoint_interface */ &sofia_endpoint_interface,
-	/*.timer_interface */ NULL,
-	/*.dialplan_interface */ NULL,
-	/*.codec_interface */ NULL,
-	/*.application_interface */ NULL,
-	/*.api_interface */ NULL,
-	/*.file_interface */ NULL,
-	/*.speech_interface */ NULL,
-	/*.directory_interface */ NULL,
-	/*.chat_interface */ &sofia_chat_interface
-};
-
-
-static void logger(void *logarg, char const *fmt, va_list ap)
-{
-	char *data = NULL;
-
-	if (fmt) {
-#ifdef HAVE_VASPRINTF
-		int ret;
-		ret = vasprintf(&data, fmt, ap);
-		if ((ret == -1) || !data) {
-			return;
-		}
-#else
-		data = (char *) malloc(2048);
-		if (data) {
-			vsnprintf(data, 2048, fmt, ap);
-		} else { 
-			return;
-		}
-#endif
-	}
-	if (data) {
-		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_CONSOLE, (char*) "%s", data);
-		free(data);
-	}
-}
-
-
-static switch_call_cause_t sofia_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-												  switch_core_session_t **new_session, switch_memory_pool_t *pool)
-{
-	switch_call_cause_t cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-	switch_core_session_t *nsession;
-	char *data, *profile_name, *dest;
-	sofia_profile_t *profile;
-	switch_caller_profile_t *caller_profile = NULL;
-	private_object_t *tech_pvt = NULL;
-	switch_channel_t *nchannel;
-	char *host, *dest_to;
-
-	*new_session = NULL;
-
-	if (!(nsession = switch_core_session_request(&sofia_endpoint_interface, pool))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Error Creating Session\n");
-		goto done;
-	}
-
-	if (!(tech_pvt = (struct private_object *) switch_core_session_alloc(nsession, sizeof(*tech_pvt)))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Error Creating Session\n");
-		terminate_session(&nsession, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER, __LINE__);
-		goto done;
-	}
-
-	data = switch_core_session_strdup(nsession, outbound_profile->destination_number);
-	profile_name = data;
-	
-	if (!(dest = strchr(profile_name, '/'))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid URL\n");
-        terminate_session(&nsession, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER, __LINE__);
-		cause = SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
-        goto done;
-	}
-
-	*dest++ = '\0';
-	
-	if (!(profile = (sofia_profile_t *) switch_core_hash_find(globals.profile_hash, profile_name))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Profile\n");
-        terminate_session(&nsession, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER, __LINE__);
-		cause =  SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-        goto done;
-	}
-
-	if ((dest_to = strchr(dest, '^'))) {
-		*dest_to++ = '\0';
-		tech_pvt->dest_to = switch_core_session_alloc(nsession, strlen(dest_to) + 5);
-		snprintf(tech_pvt->dest_to, strlen(dest_to) + 5, "sip:%s", dest_to);
-	}
-
-	if ((host = strchr(dest, '%'))) {
-		char buf[128];
-		*host = '@';
-		tech_pvt->e_dest = switch_core_session_strdup(nsession, dest);
-		*host++ = '\0';
-		if (find_reg_url(profile, dest, host, buf, sizeof(buf))) {
-			tech_pvt->dest = switch_core_session_strdup(nsession, buf);
-			
-		} else {
-			cause = SWITCH_CAUSE_NO_ROUTE_DESTINATION;
-			terminate_session(&nsession, cause, __LINE__);
-			goto done;
-		}
-	} else if (!strchr(dest, '@')) {
-		char buf[128];
-		tech_pvt->e_dest = switch_core_session_strdup(nsession, dest);
-		if (find_reg_url(profile, dest, profile_name, buf, sizeof(buf))) {
-            tech_pvt->dest = switch_core_session_strdup(nsession, buf);
-
-        } else {
-			cause = SWITCH_CAUSE_NO_ROUTE_DESTINATION;
-            terminate_session(&nsession, cause, __LINE__);
-            goto done;
-        }
-	} else {
-		tech_pvt->dest = switch_core_session_alloc(nsession, strlen(dest) + 5);
-		snprintf(tech_pvt->dest, strlen(dest) + 5, "sip:%s", dest);
-	}
-
-	if (!tech_pvt->dest_to) {
-		tech_pvt->dest_to = tech_pvt->dest;
-	}
-
-	attach_private(nsession, profile, tech_pvt, dest);
-
-	nchannel = switch_core_session_get_channel(nsession);
-	caller_profile = switch_caller_profile_clone(nsession, outbound_profile);
-	switch_channel_set_caller_profile(nchannel, caller_profile);
-	switch_channel_set_flag(nchannel, CF_OUTBOUND);
-	switch_set_flag_locked(tech_pvt, TFLAG_OUTBOUND);
-	switch_channel_set_state(nchannel, CS_INIT);
-	*new_session = nsession;
-	cause = SWITCH_CAUSE_SUCCESS;
-	if (session) {
-		//char *val;
-		//switch_channel_t *channel = switch_core_session_get_channel(session);
-		switch_ivr_transfer_variable(session, nsession, SOFIA_REPLACES_HEADER);
-		switch_ivr_transfer_variable(session, nsession, SOFIA_SIP_HEADER_PREFIX_T);
-		if (switch_core_session_compare(session, nsession)) {
-			/* It's another sofia channel! so lets cache what they use as a pt for telephone event so 
-			   we can keep it the same
-			*/
-			private_object_t *ctech_pvt;
-			ctech_pvt = switch_core_session_get_private(session);
-			assert(ctech_pvt != NULL);
-			tech_pvt->bte = ctech_pvt->te;
-		}
-	}
-
- done:
-	return cause;
-}
-
-
-static uint8_t negotiate_sdp(switch_core_session_t *session, sdp_session_t *sdp)
-{
-	uint8_t match = 0;
-	switch_payload_t te = 0;
-	private_object_t *tech_pvt;
-	sdp_media_t *m;
-	sdp_attribute_t *a;
-	switch_channel_t *channel;
-    int ptime = 0, dptime = 0;
-
-	tech_pvt = switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
-
-	channel = switch_core_session_get_channel(session);
-	
-	if ((tech_pvt->origin = switch_core_session_strdup(session, (char *) sdp->sdp_origin->o_username))) {
-		if (strstr(tech_pvt->origin, "CiscoSystemsSIP-GW-UserAgent")) {
-			switch_set_flag_locked(tech_pvt, TFLAG_BUGGY_2833);
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Activate Buggy RFC2833 Mode!\n");
-		}
-	}
-
-	for (a = sdp->sdp_attributes; a; a = a->a_next) {
-		if (!strcasecmp(a->a_name, "sendonly")) {
-			switch_set_flag_locked(tech_pvt, TFLAG_SIP_HOLD);
-		} else if (!strcasecmp(a->a_name, "sendrecv")) {
-			switch_clear_flag_locked(tech_pvt, TFLAG_SIP_HOLD);
-		} else if (!strcasecmp(a->a_name, "ptime")) {
-            dptime = atoi(a->a_value);
-		}
-	}
-
-	for (m = sdp->sdp_media; m ; m = m->m_next) {
-        sdp_connection_t *connection;
-
-        ptime = dptime;
-        for (a = m->m_attributes; a; a = a->a_next) {
-            if (!strcasecmp(a->a_name, "ptime") && a->a_value) {
-                ptime = atoi(a->a_value);
-            }
-        }
-
-		if (m->m_type == sdp_media_audio) {
-			sdp_rtpmap_t *map;
-
-			connection = sdp->sdp_connection;
-			if (m->m_connections) {
-				connection = m->m_connections;
-			}
-
-			if (!connection) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot find a c= line in the sdp at media or session level!\n");
-				match = 0;
-				break;
-			}
-
-			for (map = m->m_rtpmaps; map; map = map->rm_next) {
-				int32_t i;
-                const switch_codec_implementation_t *mimp = NULL, *near_match = NULL;
-
-				if (!te && !strcasecmp(map->rm_encoding, "telephone-event")) {
-					te = tech_pvt->te = (switch_payload_t)map->rm_pt;
-				}
-
-				if (match) {
-					if (te) {
-						break;
-					}
-					continue;
-				}
-
-				for (i = 0; i < tech_pvt->num_codecs; i++) {
-					const switch_codec_implementation_t *imp = tech_pvt->codecs[i];
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Codec Compare [%s:%d]/[%s:%d]\n", 
-									  map->rm_encoding, map->rm_pt, imp->iananame, imp->ianacode);
-					if (map->rm_pt < 96) {
-						match = (map->rm_pt == imp->ianacode) ? 1 : 0;
-					} else {
-						match = strcasecmp(map->rm_encoding, imp->iananame) ? 0 : 1;
-					}
-
-					if (match && (map->rm_rate == imp->samples_per_second)) {
-                        if (ptime && ptime * 1000 != imp->microseconds_per_frame) {
-                            near_match = imp;
-                            match = 0;
-                            continue;
-                        }
-                        mimp = imp;
-						break;
-					} else {
-						match = 0;
-					}
-                }
-                
-                if (!match && near_match) {
-                    const switch_codec_implementation_t *search[1];
-                    char *prefs[1];
-                    char tmp[80];
-                    int num;
-                    
-                    snprintf(tmp, sizeof(tmp), "%s@%uk@%ui",
-                             near_match->iananame,
-                             near_match->samples_per_second,
-                             ptime);
-
-                    prefs[0] = tmp;
-                    num = switch_loadable_module_get_codecs_sorted(search, 1, prefs, 1);
-
-                    if (num) {
-                        mimp = search[0];
-                    } else {
-                        mimp = near_match;
-                    }
-
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Substituting codec %s@%ums\n", 
-                                      mimp->iananame, mimp->microseconds_per_frame / 1000 );
-                    match = 1;
-                }
-
-                if (mimp) {
-                    if ((tech_pvt->rm_encoding = switch_core_session_strdup(session, (char *)map->rm_encoding))) {
-                        char tmp[50];
-                        tech_pvt->pt = (switch_payload_t)map->rm_pt;
-                        tech_pvt->rm_rate = map->rm_rate;
-                        tech_pvt->codec_ms = mimp->microseconds_per_frame / 1000;
-                        tech_pvt->remote_sdp_audio_ip = switch_core_session_strdup(session, (char *)connection->c_address);
-                        tech_pvt->rm_fmtp = switch_core_session_strdup(session, (char *)map->rm_fmtp);
-                        tech_pvt->remote_sdp_audio_port = (switch_port_t)m->m_port;
-                        tech_pvt->agreed_pt = (switch_payload_t)map->rm_pt;
-                        snprintf(tmp, sizeof(tmp), "%d", tech_pvt->remote_sdp_audio_port);
-                        switch_channel_set_variable(channel, SWITCH_REMOTE_MEDIA_IP_VARIABLE, tech_pvt->remote_sdp_audio_ip);
-                        switch_channel_set_variable(channel, SWITCH_REMOTE_MEDIA_PORT_VARIABLE, tmp);
-                    } else {
-                        match = 0;
-                    }
-                }
-                
-				if (match) {
-					if (tech_set_codec(tech_pvt, 1) != SWITCH_STATUS_SUCCESS) {
-						match = 0;
-					}
-				}
-			}
-		}
-	}
-
-	return match;
-}
-
-// map sip responses to QSIG cause codes ala RFC4497 section 8.4.4
-static switch_call_cause_t sip_cause_to_freeswitch(int status) {
-	switch (status) {
-	case 200:
-		return SWITCH_CAUSE_NORMAL_CLEARING;
-	case 401:
-	case 402: 
-	case 403:
-	case 407:
-	case 603:
-		return SWITCH_CAUSE_CALL_REJECTED;
-	case 404:
-	case 485:
-	case 604:	
-		return SWITCH_CAUSE_NO_ROUTE_DESTINATION;
-	case 408: 
-	case 504:
-		return SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
-	case 410: 
-		return SWITCH_CAUSE_NUMBER_CHANGED;
-	case 413: 
-	case 414:
-	case 416:
-	case 420:
-	case 421:
-	case 423:
-	case 505:
-	case 513:
-		return SWITCH_CAUSE_INTERWORKING;
-	case 480:
-		return SWITCH_CAUSE_NO_USER_RESPONSE;
-	case 400:
-	case 481:
-	case 500:
-	case 503:
-		return SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE;
-	case 486:
-	case 600:
-		return SWITCH_CAUSE_USER_BUSY;
-	case 484:
-		return SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
-	case 488:
-	case 606:
-		return SWITCH_CAUSE_BEARERCAPABILITY_NOTIMPL;
-	case 502:
-		return SWITCH_CAUSE_NETWORK_OUT_OF_ORDER;
-	case 405:
-		return SWITCH_CAUSE_SERVICE_UNAVAILABLE;
-	case 406:
-	case 415:
-	case 501:
-		return SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED;
-	case 482:
-	case 483:
-		return SWITCH_CAUSE_EXCHANGE_ROUTING_ERROR;
-	case 487:
-		return SWITCH_CAUSE_ORIGINATOR_CANCEL;
-
-	default: 
-		return SWITCH_CAUSE_NORMAL_UNSPECIFIED;
-
-	}
-}
-
-
-static void set_hash_key(char *hash_key, int32_t len, sip_t const *sip)
-{
-
-	snprintf(hash_key, len, "%s%s%s",
-			 (char *) sip->sip_from->a_url->url_user,
-			 (char *) sip->sip_from->a_url->url_host,
-			 (char *) sip->sip_to->a_url->url_user
-			 );	
-
-
-#if 0
-	/* nicer one we cant use in both directions >=0 */
-	snprintf(hash_key, len, "%s%s%s%s%s%s",
-			 (char *) sip->sip_to->a_url->url_user,
-			 (char *) sip->sip_to->a_url->url_host,
-			 (char *) sip->sip_to->a_url->url_params,
-			 
-			 (char *) sip->sip_from->a_url->url_user,
-			 (char *) sip->sip_from->a_url->url_host,
-			 (char *) sip->sip_from->a_url->url_params
-			 );	
-#endif
-
-}
-
-static void set_chat_hash(private_object_t *tech_pvt, sip_t const *sip)
-{
-	char hash_key[256] = "";
-	char buf[512];
-
-	if (!sip || tech_pvt->hash_key) {
-		return;
-	}
-
-	if (find_reg_url(tech_pvt->profile, (char *) sip->sip_from->a_url->url_user, (char *) sip->sip_from->a_url->url_host, buf, sizeof(buf))) {
-		tech_pvt->chat_from = sip_header_as_string(tech_pvt->home, (void *)sip->sip_to);
-		tech_pvt->chat_to = switch_core_session_strdup(tech_pvt->session, buf);
-		set_hash_key(hash_key, sizeof(hash_key), sip);
-	} else {
-		return;
-	}
-
-	
-
-	tech_pvt->hash_key = switch_core_session_strdup(tech_pvt->session, hash_key);
-	switch_core_hash_insert(tech_pvt->profile->chat_hash, tech_pvt->hash_key, tech_pvt);
-
-}
-
-
-static void sip_i_message(int status,
-						char const *phrase, 
-						nua_t *nua,
-						sofia_profile_t *profile,
-						nua_handle_t *nh,
-						sofia_private_t *sofia_private,
-						sip_t const *sip,
-						tagi_t tags[])
-{
-	if (sip) {
-		sip_from_t const *from = sip->sip_from;
-		char *from_user = NULL;
-		char *from_host = NULL;
-		sip_to_t const *to = sip->sip_to;
-		char *to_user = NULL;
-		char *to_host = NULL;
-		sip_subject_t const *sip_subject = sip->sip_subject;
-		sip_payload_t *payload = sip->sip_payload;
-		const char *subject = "n/a";
-		char *msg = NULL;
-
-		if (sip->sip_content_type) {
-			if (strstr((char*)sip->sip_content_type->c_subtype, "composing")) {
-				return;
-			}
-		}
-
-		if (from) {
-			from_user = (char *) from->a_url->url_user;
-			from_host = (char *) from->a_url->url_host;
-		}
-
-		if (to) {
-			to_user = (char *) to->a_url->url_user;
-			to_host = (char *) to->a_url->url_host;
-		}
-
-        
-		if (!to_user) {
-			return;
-		}
-
-		if (payload) {
-			msg = payload->pl_data;
-		}
-
-		if (sip_subject) {
-			subject = sip_subject->g_value;
-		}
-
-		if (nh) {			
-			char hash_key[512];
-			private_object_t *tech_pvt;
-			switch_channel_t *channel;
-			switch_event_t *event;
-			char *to_addr;
-			char *from_addr;
-			char *p;
-			char *full_from;
-			char proto[512] = SOFIA_CHAT_PROTO;
-			
-			full_from = sip_header_as_string(profile->home, (void *)sip->sip_from);
-
-			if ((p=strchr(to_user, '+'))) {
-				switch_copy_string(proto, to_user, sizeof(proto));
-				p = strchr(proto, '+');
-				*p++ = '\0';
-				
-				if ((to_addr = strdup(p))) {
-					if((p = strchr(to_addr, '+'))) {
-						*p = '@';
-					}
-				}
-				
-			} else {
-				to_addr = switch_mprintf("%s@%s", to_user, to_host);
-			}
-
-			from_addr = switch_mprintf("%s@%s", from_user, from_host);
-
-
-			set_hash_key(hash_key, sizeof(hash_key), sip);
-			if ((tech_pvt = (private_object_t *) switch_core_hash_find(profile->chat_hash, hash_key))) {
-				channel = switch_core_session_get_channel(tech_pvt->session);
-				if (switch_event_create(&event, SWITCH_EVENT_MESSAGE) == SWITCH_STATUS_SUCCESS) {
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", SOFIA_CHAT_PROTO);
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->url);
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s", tech_pvt->hash_key);
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "to", "%s", to_addr);
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "subject", "SIMPLE MESSAGE");
-					if (msg) {
-						switch_event_add_body(event, "%s", msg);
-					}
-					if (switch_core_session_queue_event(tech_pvt->session, &event) != SWITCH_STATUS_SUCCESS) {
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "delivery-failure", "true");
-						switch_event_fire(&event);
-					}
-				}
-			} else {
-				switch_chat_interface_t *ci;
-				
-				if ((ci = switch_loadable_module_get_chat_interface(proto))) {
-					ci->chat_send(SOFIA_CHAT_PROTO, from_addr, to_addr, "", msg, full_from);
-				} else {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Chat Interface [%s]!\n", proto ? proto : "(none)");
-				}
-				
-			}
-			switch_safe_free(to_addr);
-			switch_safe_free(from_addr);
-			if (full_from) {
-				su_free(profile->home, full_from);
-			}
-		}
-
-	}
-}
-
-static void pass_sdp(private_object_t *tech_pvt, char *sdp) 
-{
-	char *val;
-	switch_channel_t *channel;
-	switch_core_session_t *other_session;
-	switch_channel_t *other_channel;
-	
-	channel = switch_core_session_get_channel(tech_pvt->session);
-	assert(channel != NULL);
-	
-	if ((val = switch_channel_get_variable(channel, SWITCH_ORIGINATOR_VARIABLE)) && (other_session = switch_core_session_locate(val))) {
-		other_channel = switch_core_session_get_channel(other_session);
-		assert(other_channel != NULL);
-		if (!switch_channel_get_variable(other_channel, SWITCH_B_SDP_VARIABLE)) {
-			switch_channel_set_variable(other_channel, SWITCH_B_SDP_VARIABLE, sdp);
-		}
-
-		if (!switch_test_flag(tech_pvt, TFLAG_CHANGE_MEDIA) && (
-			switch_channel_test_flag(other_channel, CF_OUTBOUND) && 
-			//switch_channel_test_flag(other_channel, CF_NOMEDIA) && 
-			switch_channel_test_flag(channel, CF_OUTBOUND) && 
-			switch_channel_test_flag(channel, CF_NOMEDIA))) {
-			switch_ivr_nomedia(val, SMF_FORCE);
-			switch_set_flag_locked(tech_pvt, TFLAG_CHANGE_MEDIA);
-		}
-		
-		switch_core_session_rwunlock(other_session);
-	}
-}
-
-static void sip_i_state(int status,
-						char const *phrase, 
-						nua_t *nua,
-						sofia_profile_t *profile,
-						nua_handle_t *nh,
-						sofia_private_t *sofia_private,
-						sip_t const *sip,
-						tagi_t tags[])
-	 
-{
-	const char *l_sdp = NULL, *r_sdp = NULL;
-	int offer_recv = 0, answer_recv = 0, offer_sent = 0, answer_sent = 0;
-	int ss_state = nua_callstate_init;
-	switch_channel_t *channel = NULL;
-	private_object_t *tech_pvt = NULL;
-	switch_core_session_t *session = NULL;
-	const char *replaces_str = NULL;
-	char *uuid;
-	switch_core_session_t *other_session = NULL;
-	switch_channel_t *other_channel = NULL;
-	char st[80] = "";
-
-
-    if (sofia_private) {
-        if (!switch_strlen_zero(sofia_private->uuid)) {
-            if (!(session = switch_core_session_locate(sofia_private->uuid))) {
-                /* too late */
-                return;            
-            }
-        }
-    }
-
-	
-	tl_gets(tags, 
-			NUTAG_CALLSTATE_REF(ss_state),
-			NUTAG_OFFER_RECV_REF(offer_recv),
-			NUTAG_ANSWER_RECV_REF(answer_recv),
-			NUTAG_OFFER_SENT_REF(offer_sent),
-			NUTAG_ANSWER_SENT_REF(answer_sent),
-			SIPTAG_REPLACES_STR_REF(replaces_str),
-			SOATAG_LOCAL_SDP_STR_REF(l_sdp),
-			SOATAG_REMOTE_SDP_STR_REF(r_sdp),
-			TAG_END()); 
-
-	if (session) {
-		channel = switch_core_session_get_channel(session);
-		assert(channel != NULL);
-
-		tech_pvt = switch_core_session_get_private(session);
-		assert(tech_pvt != NULL);
-        assert(tech_pvt->nh != NULL);
-
-		if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
-            switch_set_flag(tech_pvt, TFLAG_NOMEDIA);
-        }
-
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Channel %s entering state [%s]\n", 
-						  switch_channel_get_name(channel),
-						  nua_callstate_name(ss_state));
-
-		if (r_sdp) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Remote SDP:\n%s\n", r_sdp);			
-			tech_pvt->remote_sdp_str = switch_core_session_strdup(session, r_sdp);
-			switch_channel_set_variable(channel, SWITCH_R_SDP_VARIABLE, r_sdp);
-			pass_sdp(tech_pvt, (char *)r_sdp);
-
-		}
-	}
-
-	if (status == 988) {
-		goto done;
-	}
-
-	switch ((enum nua_callstate)ss_state) {
-	case nua_callstate_init:
-		break;
-	case nua_callstate_authenticating:
-		break;
-	case nua_callstate_calling:
-		break;
-	case nua_callstate_proceeding:
-		if (channel) {
-			if (status == 180) {
-				switch_channel_mark_ring_ready(channel);
-				if (!switch_channel_test_flag(channel, CF_GEN_RINGBACK)) {
-					if (switch_test_flag(tech_pvt, TFLAG_NOMEDIA)) {
-						if ((uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) && (other_session = switch_core_session_locate(uuid))) {
-							switch_core_session_message_t msg;
-							msg.message_id = SWITCH_MESSAGE_INDICATE_RINGING;
-							msg.from = __FILE__;
-							switch_core_session_receive_message(other_session, &msg);
-							switch_core_session_rwunlock(other_session);
-						}
-						
-					} else {
-						switch_core_session_queue_indication(session, SWITCH_MESSAGE_INDICATE_RINGING);
-					}
-				}
-			}
-
-			if (r_sdp) {
-				if (switch_test_flag(tech_pvt, TFLAG_NOMEDIA)) {
-					switch_set_flag_locked(tech_pvt, TFLAG_EARLY_MEDIA);
-                    switch_channel_mark_pre_answered(channel);
-					if (!switch_channel_test_flag(channel, CF_GEN_RINGBACK) && 
-						(uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) && (other_session = switch_core_session_locate(uuid))) {
-						other_channel = switch_core_session_get_channel(other_session);
-						if (!switch_channel_get_variable(other_channel, SWITCH_B_SDP_VARIABLE)) {
-							switch_channel_set_variable(other_channel, SWITCH_B_SDP_VARIABLE, r_sdp);
-						}
-						
-						switch_channel_pre_answer(other_channel);
-						switch_core_session_rwunlock(other_session);
-					}
-                    goto done;
-				} else {
-					if (switch_test_flag(tech_pvt, TFLAG_LATE_NEGOTIATION)) {
-						switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "DELAYED NEGOTIATION");
-					} else {
-						if (tech_media(tech_pvt, (char *)r_sdp) != SWITCH_STATUS_SUCCESS) {
-							switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "CODEC NEGOTIATION ERROR");
-							nua_respond(nh, SIP_488_NOT_ACCEPTABLE, TAG_END());
-						}
-					}
-					goto done;
-                }
-			}
-		}
-		break;
-	case nua_callstate_completing:
-		nua_ack(nh, TAG_END());
-		break;
-	case nua_callstate_received: 
-		if (session && switch_core_session_running(session)) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Re-Entering Call State Received!\n");
-            goto done;
-		}
-
-		if (channel) {
-			if (r_sdp) {
-				if (switch_test_flag(tech_pvt, TFLAG_NOMEDIA)) {
-					switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "RECEIVED_NOMEDIA");
-					switch_channel_set_state(channel, CS_INIT);
-					switch_set_flag_locked(tech_pvt, TFLAG_READY);
-					switch_core_session_thread_launch(session);
-                    goto done;
-				} else {
-					sdp_parser_t *parser = sdp_parse(tech_pvt->home, r_sdp, (int)strlen(r_sdp), 0);
-					sdp_session_t *sdp;
-					uint8_t match = 0;
-				
-					if (tech_pvt->num_codecs) {
-						if ((sdp = sdp_session(parser))) {
-							match = negotiate_sdp(session, sdp);
-						}
-					}
-
-					if (parser) {
-						sdp_parser_free(parser);
-					}
-
-					if (match) {
-						nua_handle_t *bnh;
-						sip_replaces_t *replaces;
-						switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "RECEIVED");
-						switch_channel_set_state(channel, CS_INIT);
-						switch_set_flag_locked(tech_pvt, TFLAG_READY);
-
-						switch_core_session_thread_launch(session);
-						
-						if (replaces_str && (replaces = sip_replaces_make(tech_pvt->home, replaces_str)) && (bnh = nua_handle_by_replaces(nua, replaces))) {
-							sofia_private_t *b_private;
-
-							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Processing Replaces Attended Transfer\n");
-							while (switch_channel_get_state(channel) < CS_EXECUTE) {
-								switch_yield(10000);
-							}
-
-							if ((b_private = nua_handle_magic(bnh))) {
-								char *br_b = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE);
-								char *br_a = b_private->uuid;
-
-								if (br_b) {
-									switch_ivr_uuid_bridge(br_a, br_b);
-									switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "ATTENDED_TRANSFER");
-									switch_channel_hangup(channel, SWITCH_CAUSE_ATTENDED_TRANSFER);
-								} else {
-									switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "ATTENDED_TRANSFER_ERROR");
-									switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-								}
-							} else {
-								switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "ATTENDED_TRANSFER_ERROR");
-								switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-							}
-							nua_handle_unref(bnh);
-						}
-                        goto done;
-					}
-
-					switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "NO CODECS");
-					nua_respond(nh, SIP_488_NOT_ACCEPTABLE, 
-								TAG_END());
-				}
-			}
-		}
-
-		break;		
-	case nua_callstate_early:
-		break;
-	case nua_callstate_completed:
-		if (tech_pvt && r_sdp) {
-			if (r_sdp) {
-				if (switch_test_flag(tech_pvt, TFLAG_NOMEDIA)) {
-                    goto done;
-				} else {
-					sdp_parser_t *parser = sdp_parse(tech_pvt->home, r_sdp, (int)strlen(r_sdp), 0);
-					sdp_session_t *sdp;
-					uint8_t match = 0;
-
-					if (tech_pvt->num_codecs) {
-						if ((sdp = sdp_session(parser))) {
-							match = negotiate_sdp(session, sdp);
-						}
-					}
-					if (match) {
-						if (tech_choose_port(tech_pvt) != SWITCH_STATUS_SUCCESS) {
-                            goto done;
-                        }
-						set_local_sdp(tech_pvt, NULL, 0, NULL, 0);
-						switch_set_flag_locked(tech_pvt, TFLAG_REINVITE);
-						activate_rtp(tech_pvt);
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Processing Reinvite\n");
-						if (parser) {
-							sdp_parser_free(parser);
-						}
-					}
-				}
-			}
-		}
-		break;
-	case nua_callstate_ready:
-		if (tech_pvt && nh == tech_pvt->nh2) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Cheater Reinvite!\n");
-			switch_set_flag_locked(tech_pvt, TFLAG_REINVITE);
-			tech_pvt->nh = tech_pvt->nh2;
-			tech_pvt->nh2 = NULL;
-			if (tech_choose_port(tech_pvt) == SWITCH_STATUS_SUCCESS) {
-                activate_rtp(tech_pvt);
-            }
-			goto done;
-		}
-
-		if (channel) {
-			if (switch_test_flag(tech_pvt, TFLAG_EARLY_MEDIA)) {
-				switch_set_flag_locked(tech_pvt, TFLAG_ANS);
-                switch_channel_mark_answered(channel);
-                if ((uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) && (other_session = switch_core_session_locate(uuid))) {
-                    other_channel = switch_core_session_get_channel(other_session);
-                    switch_channel_answer(other_channel);
-                    switch_core_session_rwunlock(other_session);
-                }
-				goto done;
-			}
-
-			if (!r_sdp) {
-				r_sdp = (const char *) switch_channel_get_variable(channel, SWITCH_R_SDP_VARIABLE);
-			}
-			if (r_sdp) {
-				if (switch_test_flag(tech_pvt, TFLAG_NOMEDIA)) {
-					switch_set_flag_locked(tech_pvt, TFLAG_ANS);
-                    switch_channel_mark_answered(channel);
-					if ((uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) && (other_session = switch_core_session_locate(uuid))) {
-						other_channel = switch_core_session_get_channel(other_session);
-						if (!switch_channel_get_variable(other_channel, SWITCH_B_SDP_VARIABLE)) {
-							switch_channel_set_variable(other_channel, SWITCH_B_SDP_VARIABLE, r_sdp);
-						}
-						switch_channel_answer(other_channel);
-						switch_core_session_rwunlock(other_session);
-					}
-					goto done;
-				} else {
-					sdp_parser_t *parser = sdp_parse(tech_pvt->home, r_sdp, (int)strlen(r_sdp), 0);
-					sdp_session_t *sdp;
-					uint8_t match = 0;
-
-					if (tech_pvt->num_codecs) {
-						if ((sdp = sdp_session(parser))) {
-							match = negotiate_sdp(session, sdp);
-						}
-					}
-
-					if (parser) {
-						sdp_parser_free(parser);
-					}
-
-
-					if (match) {
-						switch_set_flag_locked(tech_pvt, TFLAG_ANS);
-						if (tech_choose_port(tech_pvt) == SWITCH_STATUS_SUCCESS) {
-                            activate_rtp(tech_pvt);
-                            switch_channel_mark_answered(channel);
-                            goto done;
-                        }
-					}
-					
-					switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "NO CODECS");
-					nua_respond(nh, SIP_488_NOT_ACCEPTABLE, TAG_END());
-				}
-			}
-			
-		}
-		
-		break;
-	case nua_callstate_terminating:
-		break;
-	case nua_callstate_terminated: 
-		if (session) {
-			if (!switch_test_flag(tech_pvt, TFLAG_BYE)) {
-                
-				switch_set_flag_locked(tech_pvt, TFLAG_BYE);
-				if (switch_test_flag(tech_pvt, TFLAG_NOHUP)) {
-					switch_clear_flag_locked(tech_pvt, TFLAG_NOHUP);
-				} else {
-					snprintf(st, sizeof(st), "%d", status);
-					switch_channel_set_variable(channel, "sip_term_status", st);
-					terminate_session(&session, sip_cause_to_freeswitch(status), __LINE__);
-				}
-			}
-
-            if (tech_pvt->sofia_private) {
-                free(tech_pvt->sofia_private);
-                tech_pvt->sofia_private = NULL;
-            }
-			tech_pvt->nh = NULL;
-		} else if (sofia_private) {
-            free(sofia_private);
-        }
-
-		if (nh) {
-            nua_handle_bind(nh, NULL);
-			nua_handle_destroy(nh);
-		}
-		break;
-	}
-
- done:
-
-    if (session) {
-        switch_core_session_rwunlock(session);
-    }
-}
-
-
-static char *get_auth_data(char *dbname, char *nonce, char *npassword, size_t len, switch_mutex_t *mutex)
-{
-	switch_core_db_t *db;
-	switch_core_db_stmt_t *stmt;
-	char *sql = NULL, *ret = NULL;
-
-	if (mutex) {
-		switch_mutex_lock(mutex);
-	}
-
-	if (!dbname) {
-		goto end;
-	}
-
-	if (!(db = switch_core_db_open_file(dbname))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", dbname);
-		goto end;
-	}
-
-	sql = switch_mprintf("select passwd from sip_authentication where nonce='%q'", nonce);
-	if (switch_core_db_prepare(db, sql, -1, &stmt, 0)) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Statement Error!\n");
-		goto fail;
-	} else {
-		int running = 1;
-		int colcount;
-
-		while (running < 5000) {
-			int result = switch_core_db_step(stmt);
-
-			if (result == SQLITE_ROW) {
-				if ((colcount = switch_core_db_column_count(stmt))) {
-					switch_copy_string(npassword, (char *)switch_core_db_column_text(stmt, 0), len);
-					ret = npassword;
-				}
-				break;
-			} else if (result == SQLITE_BUSY) {
-				running++;
-				switch_yield(1000);
-				continue;
-			}
-			break;
-		}
-			
-		switch_core_db_finalize(stmt);
-	}
-	
-
- fail:
-
-	switch_core_db_close(db);
-
- end:
-	if (mutex) {
-		switch_mutex_unlock(mutex);
-	}
-
-	if (sql) {
-		switch_safe_free(sql);
-	}
-	
-	return ret;
-}
-
-
-typedef enum {
-	REG_REGISTER,
-	REG_INVITE
-} sofia_regtype_t;
-
-static uint8_t handle_register(nua_t *nua,
-							   sofia_profile_t *profile,
-							   nua_handle_t *nh,
-							   sip_t const *sip,
-							   sofia_regtype_t regtype,
-							   char *key,
-							   uint32_t keylen)
-{
-	sip_from_t const *from = sip->sip_from;
-	sip_expires_t const *expires = sip->sip_expires;
-	sip_authorization_t const *authorization = sip->sip_authorization;
-	sip_contact_t const *contact = sip->sip_contact;
-	switch_xml_t domain, xml, user, param, xparams;
-	char params[1024] = "";
-	char *sql;
-	switch_event_t *s_event;
-	char *from_user = (char *) from->a_url->url_user;
-	char *from_host = (char *) from->a_url->url_host;
-	char contact_str[1024] = "";
-	char buf[512];
-	char *passwd = NULL;
-	char *a1_hash = NULL;
-	uint8_t stale = 0, ret = 0, forbidden = 0;
-	auth_res_t auth_res;
-	long exptime = 60;
-	switch_event_t *event;
-	const char *rpid = "unknown";
-	const char *display = "\"user\"";
-
-	if (contact && contact->m_url) {
-		char *port = (char *) contact->m_url->url_port;
-		display = contact->m_display;
-
-		if (switch_strlen_zero(display)) {
-			if (from) {
-				display = from->a_display;
-				if (switch_strlen_zero(display)) {
-					display = "\"user\"";
-				}
-			}
-		}
-		
-		if (!port) {
-			port = "5060";
-		}
-
-		if (contact->m_url->url_params) {
-			snprintf(contact_str, sizeof(contact_str), "%s <sip:%s@%s:%s;%s>", 
-					 display, contact->m_url->url_user, contact->m_url->url_host, port, contact->m_url->url_params);
-		} else {
-			snprintf(contact_str, sizeof(contact_str), "%s <sip:%s@%s:%s>", 
-					 display, contact->m_url->url_user, contact->m_url->url_host, port);
-		}
-	}
-	
-	if (expires) {
-		exptime = expires->ex_delta;
-	} else if (contact && contact->m_expires) {
-		exptime = atol(contact->m_expires);
-	} 
-
-	if (regtype == REG_REGISTER) {
-		authorization = sip->sip_authorization;
-	} else if (regtype == REG_INVITE) {
-		authorization = sip->sip_proxy_authorization;
-	}
-
-	if ((profile->pflags & PFLAG_BLIND_REG)) {
-		goto reg;
-	}
-
-	if (authorization) {
-		if ((auth_res = parse_auth(profile, authorization, (char *)sip->sip_request->rq_method_name, key, keylen)) == AUTH_STALE) {
-            stale = 1;
-        }
-
-		if (auth_res != AUTH_OK && !stale) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "send %s for [%s@%s]\n",
-							  forbidden ? "forbidden" : "challange",
-							  from_user, from_host);
-			if (auth_res == AUTH_FORBIDDEN) {
-				nua_respond(nh, SIP_403_FORBIDDEN, NUTAG_WITH_THIS(nua), TAG_END());
-			} else {
-				nua_respond(nh, SIP_401_UNAUTHORIZED, NUTAG_WITH_THIS(nua), TAG_END());
-			}
-			return 1;
-		}
-	} 
-
-	if (!authorization || stale) {
-		snprintf(params, sizeof(params), "from_user=%s&from_host=%s&contact=%s",
-				 from_user,
-				 from_host,
-				 contact_str
-				 );
-
-		
-		if (switch_xml_locate("directory", "domain", "name", from_host, &xml, &domain, params) != SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "can't find domain for [%s@%s]\n", from_user, from_host);
-			nua_respond(nh, SIP_401_UNAUTHORIZED, NUTAG_WITH_THIS(nua), SIPTAG_CONTACT(contact), TAG_END());
-			return 1;
-		}
-
-		if (!(user = switch_xml_find_child(domain, "user", "id", from_user))) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "can't find user [%s@%s]\n", from_user, from_host);
-			nua_respond(nh, SIP_401_UNAUTHORIZED, NUTAG_WITH_THIS(nua), SIPTAG_CONTACT(contact), TAG_END());
-			switch_xml_free(xml);
-			return 1;
-		}
-
-		if (!(xparams = switch_xml_child(user, "params"))) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "can't find params for user [%s@%s]\n", from_user, from_host);
-			nua_respond(nh, SIP_401_UNAUTHORIZED, NUTAG_WITH_THIS(nua), SIPTAG_CONTACT(contact), TAG_END());
-			switch_xml_free(xml);
-			return 1;
-		}
-	
-
-		for (param = switch_xml_child(xparams, "param"); param; param = param->next) {
-			char *var = (char *) switch_xml_attr_soft(param, "name");
-			char *val = (char *) switch_xml_attr_soft(param, "value");
-		
-			//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "param [%s]=[%s]\n", var, val);
-		
-			if (!strcasecmp(var, "password")) {
-				passwd = val;
-			}
-
-			if (!strcasecmp(var, "a1-hash")) {
-                a1_hash = val;
-			}
-		}
-	
-		if (passwd || a1_hash) {
-			switch_uuid_t uuid;
-			char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1];
-			char *sql, *auth_str;
-
-			su_md5_t ctx;
-			char hexdigest[2 * SU_MD5_DIGEST_SIZE + 1];
-			char *input;
-
-            if (!a1_hash) {
-                input = switch_mprintf("%s:%s:%s", from_user, from_host, passwd);
-                su_md5_init(&ctx);
-                su_md5_strupdate(&ctx, input);
-                su_md5_hexdigest(&ctx, hexdigest);
-                su_md5_deinit(&ctx);
-                switch_safe_free(input);
-
-                switch_uuid_get(&uuid);
-                switch_uuid_format(uuid_str, &uuid);
-                a1_hash = hexdigest;
-            }
-
-			sql = switch_mprintf("delete from sip_authentication where user='%q' and host='%q';\n"
-                                 "insert into sip_authentication values('%q','%q','%q','%q', %ld)",
-                                 from_user,
-                                 from_host,
-                                 from_user,
-                                 from_host,
-                                 a1_hash,
-                                 uuid_str,
-                                 time(NULL) + profile->nonce_ttl);
-			auth_str = switch_mprintf("Digest realm=\"%q\", nonce=\"%q\",%s algorithm=MD5, qop=\"auth\"", from_host, uuid_str, 
-											  stale ? " stale=\"true\"," : "");
-
-
-			if (regtype == REG_REGISTER) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Requesting Registration from: [%s@%s]\n", from_user, from_host);
-				nua_respond(nh, SIP_401_UNAUTHORIZED,
-							NUTAG_WITH_THIS(nua),
-							SIPTAG_WWW_AUTHENTICATE_STR(auth_str),
-							TAG_END());
-			} else if (regtype == REG_INVITE) {
-				nua_respond(nh, SIP_407_PROXY_AUTH_REQUIRED,
-							NUTAG_WITH_THIS(nua),
-							SIPTAG_PROXY_AUTHENTICATE_STR(auth_str),
-							TAG_END());
-
-			}
-
-			execute_sql(profile->dbname, sql, profile->ireg_mutex);
-			switch_safe_free(sql);
-			switch_safe_free(auth_str);
-			ret = 1;
-		} else {
-			ret = 0;
-		}
-		
-		switch_xml_free(xml);
-
-		if (ret) {
-			return ret;
-		}
-	}
- reg:
-
-	if (exptime) {
-		if (!find_reg_url(profile, from_user, from_host, buf, sizeof(buf))) {
-			sql = switch_mprintf("insert into sip_registrations values ('%q','%q','%q','Registered', '%q', %ld)", 
-								 from_user,
-								 from_host,
-								 contact_str,
-								 rpid,
-								 (long) time(NULL) + (long)exptime * 2);
-
-		} else {
-			sql = switch_mprintf("update sip_registrations set contact='%q', expires=%ld, rpid='%q' where user='%q' and host='%q'",
-								 contact_str,
-								 (long) time(NULL) + (long)exptime * 2,
-								 rpid,
-								 from_user,
-								 from_host);
-		
-		}
-
-		if (switch_event_create_subclass(&s_event, SWITCH_EVENT_CUSTOM, MY_EVENT_REGISTER) == SWITCH_STATUS_SUCCESS) {
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "profile-name", "%s", profile->name);
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "from-user", "%s", from_user);
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "from-host", "%s", from_host);
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "contact", "%s", contact_str);
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "rpid", "%s", rpid);
-			switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "expires", "%ld", (long)exptime);
-			switch_event_fire(&s_event);
-		}
-
-		if (sql) {
-			execute_sql(profile->dbname, sql, profile->ireg_mutex);
-			switch_safe_free(sql);
-			sql = NULL;
-		}
-	
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Register:\nFrom:    [%s@%s]\nContact: [%s]\nExpires: [%ld]\n", 
-						  from_user, 
-						  from_host,
-					  contact_str,
-					  (long)exptime
-					  );
-
-
-		if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", "sip");
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->url);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "%s", rpid);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", from_user, from_host);
-			
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "Registered");
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
-			switch_event_fire(&event);
-		}
-	} else {
-		if ((sql = switch_mprintf("delete from sip_subscriptions where user='%q' and host='%q'", from_user, from_host))) {
-			execute_sql(profile->dbname, sql, profile->ireg_mutex);
-			switch_safe_free(sql);
-			sql = NULL;
-		}
-		if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_OUT) == SWITCH_STATUS_SUCCESS) {
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", "sip");
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->url);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s+%s@%s", SOFIA_CHAT_PROTO, from_user, from_host);
-		
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "unavailable");
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "%s", rpid);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
-			switch_event_fire(&event);
-		}
-	}
+	sip_cause = hangup_cause_to_sip(cause);
+
+	sofia_glue_deactivate_rtp(tech_pvt);
 
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Channel %s hanging up, cause: %s\n",
+					  switch_channel_get_name(channel), switch_channel_cause2str(cause));
 
-	if (switch_event_create(&event, SWITCH_EVENT_ROSTER) == SWITCH_STATUS_SUCCESS) {
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", "sip");
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", from_user, from_host);
-		switch_event_fire(&event);
+	if (tech_pvt->hash_key) {
+		switch_core_hash_delete(tech_pvt->profile->chat_hash, tech_pvt->hash_key);
 	}
 
-	if (regtype == REG_REGISTER) {
-		nua_respond(nh, SIP_200_OK, SIPTAG_CONTACT(contact),
-					NUTAG_WITH_THIS(nua),
-					TAG_END());
-		return 1;
+	if (tech_pvt->kick && (a_session = switch_core_session_locate(tech_pvt->kick))) {
+		switch_channel_t *a_channel = switch_core_session_get_channel(a_session);
+		switch_channel_hangup(a_channel, switch_channel_get_cause(channel));
+		switch_core_session_rwunlock(a_session);
 	}
 
-	return 0;
-}
+	if (tech_pvt->nh) {
+		if (!switch_test_flag(tech_pvt, TFLAG_BYE)) {
+			if (switch_test_flag(tech_pvt, TFLAG_ANS)) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Sending BYE to %s\n", switch_channel_get_name(channel));
+				nua_bye(tech_pvt->nh, TAG_END());
+			} else {
+				if (!switch_test_flag(tech_pvt, TFLAG_OUTBOUND)) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Responding to INVITE with: %d\n", sip_cause);
+					nua_respond(tech_pvt->nh, sip_cause, NULL, TAG_END());
+				} else {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Sending CANCEL to %s\n", switch_channel_get_name(channel));
+					nua_cancel(tech_pvt->nh, TAG_END());
+				}
+			}
+			switch_set_flag_locked(tech_pvt, TFLAG_BYE);
+		}
+	}
 
+	switch_clear_flag_locked(tech_pvt, TFLAG_IO);
 
-static int sub_reg_callback(void *pArg, int argc, char **argv, char **columnNames)
-{
-	sofia_profile_t *profile = (sofia_profile_t *) pArg;
-	//char *proto = argv[0];
-	char *user = argv[1];
-	char *host = argv[2];
-	switch_event_t *event;
-	char *status = NULL;
-	if (switch_strlen_zero(status)) {
-		status = "Available";
-	}
-	if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", SOFIA_CHAT_PROTO);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->url);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", user, host);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "%s", status);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_subtype", "probe");
-		switch_event_fire(&event);
+	if (tech_pvt->sofia_private) {
+		*tech_pvt->sofia_private->uuid = '\0';
 	}
 
-	return 0;
+	return SWITCH_STATUS_SUCCESS;
 }
 
-static int resub_callback(void *pArg, int argc, char **argv, char **columnNames)
+static switch_status_t sofia_on_loopback(switch_core_session_t *session)
 {
-	sofia_profile_t *profile = (sofia_profile_t *) pArg;
-	char *user = argv[0];
-	char *host = argv[1];
-	char *status = argv[2];
-	char *rpid = argv[3];
-	char *proto = argv[4];
-	switch_event_t *event;
-
-	if (switch_strlen_zero(proto)) {
-		proto = NULL;
-	}
-
-	if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", "%s", proto ? proto : SOFIA_CHAT_PROTO);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->url);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", user, host);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "%s", status);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "%s", rpid);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "presence");
-		switch_event_fire(&event);
-	}
-
-	return 0;
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA LOOPBACK\n");
+	return SWITCH_STATUS_SUCCESS;
 }
 
-static int sub_callback(void *pArg, int argc, char **argv, char **columnNames)
+static switch_status_t sofia_on_transmit(switch_core_session_t *session)
 {
-	sofia_profile_t *profile = (sofia_profile_t *) pArg;
-	char *pl;
-	char *id, *note;
-	uint32_t in = atoi(argv[0]);
-	char *status = argv[1];
-	char *rpid = argv[2];
-	char *proto = argv[3];
-	char *user = argv[4];
-	char *host = argv[5];
-	char *sub_to_user = argv[6];
-	char *sub_to_host = argv[7];
-	char *event = argv[8];
-	char *contact = argv[9];
-	char *callid = argv[10];
-	char *full_from = argv[11];
-	char *full_via = argv[12];
-	nua_handle_t *nh;
-	char *to;
-	char *open;
-	char *tmp;
-
-	if (!rpid) {
-		rpid = "unknown";
-	}
-
-	if (in) {
-		note = switch_mprintf("<dm:note>%s</dm:note>", status);
-		open = "open";
-	} else {
-		note = NULL;
-		open = "closed";
-	}
-
-    if (!strcasecmp(sub_to_host, host)) {
-        /* same host */
-		id = switch_mprintf("sip:%s+%s@%s", proto, sub_to_user, sub_to_host);
-	} else if (strcasecmp(proto, SOFIA_CHAT_PROTO)) {
-		/*encapsulate*/
-		id = switch_mprintf("sip:%s+%s+%s@%s", proto, sub_to_user, sub_to_host, host);
-	} else {
-		id = switch_mprintf("sip:%s@%s", sub_to_user, sub_to_host);
-	}
-
-	to = switch_mprintf("sip:%s@%s", user, host);
-	pl = switch_mprintf("<?xml version='1.0' encoding='UTF-8'?>\r\n"
-								"<presence xmlns='urn:ietf:params:xml:ns:pidf'\r\n"
-								"xmlns:dm='urn:ietf:params:xml:ns:pidf:data-model'\r\n"
-								"xmlns:rpid='urn:ietf:params:xml:ns:pidf:rpid'\r\n"
-								"xmlns:c='urn:ietf:params:xml:ns:pidf:cipid'\r\n"
-								"entity='pres:%s'>\r\n"
-								"<tuple id='t6a5ed77e'>\r\n"
-								"<status>\r\n"
-								"<basic>%s</basic>\r\n"
-								"</status>\r\n"
-								"</tuple>\r\n"
-								"<dm:person id='p06360c4a'>\r\n"
-								"<rpid:activities>\r\n"
-								"<rpid:%s/>\r\n"
-								"</rpid:activities>%s</dm:person>\r\n"
-								"</presence>", id, open, rpid, note);
-
-	
-
-	nh = nua_handle(profile->nua, NULL,	TAG_END());
-	tmp = contact;
-	contact = get_url_from_contact(tmp, 0);
-
-	nua_notify(nh,
-			   NUTAG_URL(contact),
-			   SIPTAG_TO_STR(full_from),
-			   SIPTAG_FROM_STR(id),
-			   SIPTAG_CONTACT_STR(profile->url),
-			   SIPTAG_CALL_ID_STR(callid),
-			   SIPTAG_VIA_STR(full_via),
-			   SIPTAG_SUBSCRIPTION_STATE_STR("active;expires=3600"),
-			   SIPTAG_EVENT_STR(event),
-			   SIPTAG_CONTENT_TYPE_STR("application/pidf+xml"),
-			   SIPTAG_PAYLOAD_STR(pl),
-			   TAG_END());
-
-	switch_safe_free(id);
-	switch_safe_free(note);
-	switch_safe_free(pl);
-	switch_safe_free(to);
-
-	return 0;
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SOFIA TRANSMIT\n");
+	return SWITCH_STATUS_SUCCESS;
 }
 
-static void sip_i_subscribe(int status,
-						char const *phrase, 
-						nua_t *nua,
-						sofia_profile_t *profile,
-						nua_handle_t *nh,
-						sofia_private_t *sofia_private,
-						sip_t const *sip,
-						tagi_t tags[])
+static switch_status_t sofia_answer_channel(switch_core_session_t *session)
 {
-		if (sip) {
-			long exp, exp_raw;
-			sip_to_t const *to = sip->sip_to;
-			sip_from_t const *from = sip->sip_from;
-			sip_contact_t const *contact = sip->sip_contact;
-			char *from_user = NULL;
-			char *from_host = NULL;
-			char *to_user = NULL;
-			char *to_host = NULL;
-			char *sql, *event = NULL;
-			char *proto = "sip";
-			char *d_user = NULL;
-			char *contact_str = "";
-			char *call_id = NULL;
-			char *to_str = NULL;
-			char *full_from = NULL;
-			char *full_via = NULL;
-			switch_core_db_t *db;
-			char *errmsg;
-			char *sstr;
-			const char *display = "\"user\"";
-			switch_event_t *sevent;
+	private_object_t *tech_pvt;
+	switch_channel_t *channel = NULL;
+	switch_status_t status;
 
-			if (contact) {
-				char *port = (char *) contact->m_url->url_port;
+	assert(session != NULL);
 
-				display = contact->m_display;
-				
-				if (switch_strlen_zero(display)) {
-					if (from) {
-						display = from->a_display;
-						if (switch_strlen_zero(display)) {
-							display = "\"user\"";
-						}
-					}
-				} else {
-					display = "\"user\"";
-				}
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-				if (!port) {
-					port = "5060";
-				}
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-				if (contact->m_url->url_params) {
-					contact_str = switch_mprintf("%s <sip:%s@%s:%s;%s>", 
-												 display,
-												 contact->m_url->url_user,
-												 contact->m_url->url_host, port, contact->m_url->url_params);
-				} else {
-					contact_str = switch_mprintf("%s <sip:%s@%s:%s>", 
-												 display,
-												 contact->m_url->url_user,
-												 contact->m_url->url_host, port);
-				}
-			}
-			
-			if (to) {
-				to_str = switch_mprintf("sip:%s@%s", to->a_url->url_user, to->a_url->url_host);//, to->a_url->url_port);
-			}
+	if (!switch_test_flag(tech_pvt, TFLAG_ANS) && !switch_channel_test_flag(channel, CF_OUTBOUND)) {
+		switch_set_flag_locked(tech_pvt, TFLAG_ANS);
 
-			if (to) {
-				to_user = (char *) to->a_url->url_user;
-				to_host = (char *) to->a_url->url_host;
+		if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
+			char *sdp = NULL;
+			switch_set_flag_locked(tech_pvt, TFLAG_NOMEDIA);
+			if ((sdp = switch_channel_get_variable(channel, SWITCH_B_SDP_VARIABLE))) {
+				tech_pvt->local_sdp_str = switch_core_session_strdup(session, sdp);
 			}
-
-
-			if (strstr(to_user, "ext+") || strstr(to_user, "user+") || strstr(to_user, "conf+")) {
-				char proto[80];
-				char *p;
-
-				switch_copy_string(proto, to_user, sizeof(proto));
-				if ((p = strchr(proto, '+'))) {
-					*p = '\0';
-				}
-				
-				if (switch_event_create(&sevent, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
-					switch_event_add_header(sevent, SWITCH_STACK_BOTTOM, "proto", SOFIA_CHAT_PROTO);
-					switch_event_add_header(sevent, SWITCH_STACK_BOTTOM, "login", "%s", profile->name);
-					switch_event_add_header(sevent, SWITCH_STACK_BOTTOM, "from", "%s@%s",  to_user, to_host);
-					switch_event_add_header(sevent, SWITCH_STACK_BOTTOM, "rpid", "unknown");
-					switch_event_add_header(sevent, SWITCH_STACK_BOTTOM, "status", "Click To Call");
-					switch_event_fire(&sevent);
+		} else {
+			if (switch_test_flag(tech_pvt, TFLAG_LATE_NEGOTIATION)) {
+				char *r_sdp = switch_channel_get_variable(channel, SWITCH_R_SDP_VARIABLE);
+				if (sofia_glue_tech_media(tech_pvt, r_sdp) != SWITCH_STATUS_SUCCESS) {
+					switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "CODEC NEGOTIATION ERROR");
+					nua_respond(tech_pvt->nh, SIP_488_NOT_ACCEPTABLE, TAG_END());
+					return SWITCH_STATUS_FALSE;
 				}
+				switch_clear_flag_locked(tech_pvt, TFLAG_LATE_NEGOTIATION);
 			}
 
-			if (strchr(to_user, '+')) {
-				char *h;
-				if ((proto = (d_user = strdup(to_user)))) {
-					if ((to_user = strchr(d_user, '+'))) {
-						*to_user++ = '\0';
-						if ((h = strchr(to_user, '+')) || (h = strchr(to_user, '@'))) {
-							*h++ = '\0';
-							to_host = h;
-						}
-					}
-				}
-
-				if (!(proto && to_user && to_host)) {
-					nua_respond(nh, SIP_404_NOT_FOUND, NUTAG_WITH_THIS(nua), TAG_END());
-					goto end;
-				}
+			if ((status = sofia_glue_tech_choose_port(tech_pvt)) != SWITCH_STATUS_SUCCESS) {
+				switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+				return status;
 			}
 
-			call_id = sip_header_as_string(profile->home, (void *)sip->sip_call_id);
-			event = sip_header_as_string(profile->home, (void *)sip->sip_event);
-			full_from = sip_header_as_string(profile->home, (void *)sip->sip_from);
-			full_via = sip_header_as_string(profile->home, (void *)sip->sip_via);
-
-			exp_raw = (sip->sip_expires ? sip->sip_expires->ex_delta : 3600);
-			exp = (long) time(NULL) + exp_raw;
-			
-            if (sip && sip->sip_from) {
-                from_user = (char *) sip->sip_from->a_url->url_user;
-                from_host = (char *) sip->sip_from->a_url->url_host;
-            } else {
-                from_user = "n/a";
-                from_host = "n/a";
-            }
-
-			if ((sql = switch_mprintf("delete from sip_subscriptions where "
-											  "proto='%q' and user='%q' and host='%q' and sub_to_user='%q' and sub_to_host='%q' and event='%q';\n"
-											  "insert into sip_subscriptions values ('%q','%q','%q','%q','%q','%q','%q','%q','%q','%q',%ld)",
-											  proto,
-											  from_user,
-											  from_host,
-											  to_user,
-											  to_host,
-											  event,
-											  proto,
-											  from_user,
-											  from_host,
-											  to_user,
-											  to_host,
-											  event,
-											  contact_str,
-											  call_id,
-											  full_from,
-											  full_via,
-											  exp
-									  ))) {
-				execute_sql(profile->dbname, sql, profile->ireg_mutex);
-				switch_safe_free(sql);
+			sofia_glue_set_local_sdp(tech_pvt, NULL, 0, NULL, 0);
+			if (sofia_glue_activate_rtp(tech_pvt) != SWITCH_STATUS_SUCCESS) {
+				switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 			}
 
-			sstr = switch_mprintf("active;expires=%ld", exp_raw);
-
-			nua_respond(nh, SIP_202_ACCEPTED,
-						NUTAG_WITH_THIS(nua),
-						SIPTAG_SUBSCRIPTION_STATE_STR(sstr),
-						SIPTAG_FROM(sip->sip_to),
-						SIPTAG_TO(sip->sip_from),
-						SIPTAG_CONTACT_STR(to_str),
-						TAG_END());
-
-
-
-			switch_safe_free(sstr);
-			
-			if (!(db = switch_core_db_open_file(profile->dbname))) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-				goto end;
-			}
-			if ((sql = switch_mprintf("select * from sip_subscriptions where user='%q' and host='%q'", 
-									  to_user, to_host, to_user, to_host))) {
-				switch_mutex_lock(profile->ireg_mutex);
-				switch_core_db_exec(db, sql, sub_reg_callback, profile, &errmsg);
-				switch_mutex_unlock(profile->ireg_mutex);
-				switch_safe_free(sql);
-			}
-			switch_core_db_close(db);
-		end:
-		
-			if (event) {
-				su_free(profile->home, event);
-			}
-			if (call_id) {
-				su_free(profile->home, call_id);
-			}
-			if (full_from) {
-				su_free(profile->home, full_from);
-			}
-			if (full_via) {
-				su_free(profile->home, full_via);
+			if (tech_pvt->nh) {
+				if (tech_pvt->local_sdp_str) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Local SDP %s:\n%s\n", switch_channel_get_name(channel),
+									  tech_pvt->local_sdp_str);
+				}
 			}
-
-			switch_safe_free(d_user);
-			switch_safe_free(to_str);
-			switch_safe_free(contact_str);
 		}
-}
-
-static void sip_r_subscribe(int status,
-						char const *phrase, 
-						nua_t *nua,
-						sofia_profile_t *profile,
-						nua_handle_t *nh,
-						sofia_private_t *sofia_private,
-						sip_t const *sip,
-						tagi_t tags[])
-{
+		nua_respond(tech_pvt->nh, SIP_200_OK,
+					SIPTAG_CONTACT_STR(tech_pvt->profile->url),
+					SOATAG_USER_SDP_STR(tech_pvt->local_sdp_str), SOATAG_AUDIO_AUX("cn telephone-event"), NUTAG_INCLUDE_EXTRA_SDP(1), TAG_END());
+	}
 
+	return SWITCH_STATUS_SUCCESS;
 }
 
 
-/*---------------------------------------*/
-static void sip_i_refer(nua_t *nua,
-						sofia_profile_t *profile,
-						nua_handle_t *nh,
-                        switch_core_session_t *session,
-						sip_t const *sip,
-						tagi_t tags[])
-{
-	/* Incoming refer */
-	sip_from_t const *from;
-	sip_to_t const *to;
-	sip_refer_to_t const *refer_to;
-    private_object_t *tech_pvt = NULL;
-    char *etmp = NULL, *exten = NULL;
-    switch_channel_t *channel_a = NULL, *channel_b = NULL;
-
-    tech_pvt = switch_core_session_get_private(session);
-    channel_a = switch_core_session_get_channel(session);
-
-    if (!sip->sip_cseq || !(etmp = switch_mprintf("refer;id=%u", sip->sip_cseq->cs_seq))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n");
-        goto done;
-    }
-
-
-    if (switch_channel_test_flag(channel_a, CF_NOMEDIA)) {
-        nua_notify(tech_pvt->nh, SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
-                   NUTAG_SUBSTATE(nua_substate_terminated),
-                   SIPTAG_PAYLOAD_STR("SIP/2.0 403 Forbidden"),
-                   SIPTAG_EVENT_STR(etmp),
-                   TAG_END());
-        goto done;
-    }
-		
-    from = sip->sip_from;
-    to = sip->sip_to;
-
-    if ((refer_to = sip->sip_refer_to)) {
-        if (profile->pflags & PFLAG_FULL_ID) {
-            exten = switch_mprintf("%s@%s", (char *) refer_to->r_url->url_user, (char *) refer_to->r_url->url_host);
-        } else {
-            exten = (char *) refer_to->r_url->url_user;
-        }
-
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Process REFER to [%s@%s]\n", exten, (char *) refer_to->r_url->url_host);
-
-        if (refer_to->r_url->url_headers) {
-            sip_replaces_t *replaces;
-            nua_handle_t *bnh;
-            char *rep;
-
-            if ((rep = strchr(refer_to->r_url->url_headers, '='))) {
-                char *br_a = NULL, *br_b = NULL;
-                char *buf;
-                rep++;
-
-					
-
-                if ((buf = switch_core_session_alloc(session, strlen(rep) + 1))) {
-                    rep = url_unescape(buf, (const char *) rep); 
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Replaces: [%s]\n", rep);
-                } else {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n");
-                    goto done;
-                }
-                if ((replaces = sip_replaces_make(tech_pvt->home, rep)) && (bnh = nua_handle_by_replaces(nua, replaces))) {
-                    sofia_private_t *b_private = NULL;
-                    private_object_t *b_tech_pvt = NULL;
-                    switch_core_session_t *b_session = NULL;
-
-                    switch_channel_set_variable(channel_a, SOFIA_REPLACES_HEADER, rep);	
-                    if ((b_private = nua_handle_magic(bnh))) {
-                        if (!(b_session = switch_core_session_locate(b_private->uuid))) {
-                            goto done;
-                        }
-                        b_tech_pvt = (private_object_t *) switch_core_session_get_private(b_session);
-                        channel_b = switch_core_session_get_channel(b_session);
-				
-                        br_a = switch_channel_get_variable(channel_a, SWITCH_BRIDGE_VARIABLE);
-                        br_b = switch_channel_get_variable(channel_b, SWITCH_BRIDGE_VARIABLE);
-
-                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Attended Transfer [%s][%s]\n", br_a, br_b);
-                            
-                        if (br_a && br_b) {
-                            switch_ivr_uuid_bridge(br_a, br_b);
-                            switch_channel_set_variable(channel_b, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "ATTENDED_TRANSFER");
-                            switch_set_flag_locked(tech_pvt, TFLAG_BYE);
-                            switch_set_flag_locked(b_tech_pvt, TFLAG_BYE);
-                            nua_notify(tech_pvt->nh, SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
-                                       NUTAG_SUBSTATE(nua_substate_terminated),
-                                       SIPTAG_PAYLOAD_STR("SIP/2.0 200 OK"),
-                                       SIPTAG_EVENT_STR(etmp),
-                                       TAG_END());
-                                
-                        } else {
-                            if (!br_a && !br_b) {
-                                switch_set_flag_locked(tech_pvt, TFLAG_NOHUP);
-                                switch_set_flag_locked(b_tech_pvt, TFLAG_XFER);
-                                b_tech_pvt->xferto = switch_core_session_strdup(b_session, switch_core_session_get_uuid(session));
-                            } else if (!br_a && br_b) {
-                                switch_core_session_t *br_b_session;
-
-                                if ((br_b_session = switch_core_session_locate(br_b))) {
-                                    private_object_t *br_b_tech_pvt = switch_core_session_get_private(br_b_session);
-                                    switch_channel_t *br_b_channel = switch_core_session_get_channel(br_b_session);
-                                    
-                                    switch_set_flag_locked(tech_pvt, TFLAG_NOHUP);
-										
-                                    switch_channel_clear_state_handler(br_b_channel, NULL);
-                                    switch_channel_set_state_flag(br_b_channel, CF_TRANSFER);
-                                    switch_channel_set_state(br_b_channel, CS_TRANSMIT);
-
-                                    switch_set_flag_locked(tech_pvt, TFLAG_REINVITE);
-                                    tech_pvt->local_sdp_audio_ip = switch_core_session_strdup(session, b_tech_pvt->local_sdp_audio_ip);
-                                    tech_pvt->local_sdp_audio_port = b_tech_pvt->local_sdp_audio_port;
-
-                                    tech_pvt->remote_sdp_audio_ip = switch_core_session_strdup(session, br_b_tech_pvt->remote_sdp_audio_ip);
-                                    tech_pvt->remote_sdp_audio_port = br_b_tech_pvt->remote_sdp_audio_port;
-                                    activate_rtp(tech_pvt);
-	
-                                    br_b_tech_pvt->kick = switch_core_session_strdup(br_b_session, switch_core_session_get_uuid(session));
-										
-
-                                    switch_core_session_rwunlock(br_b_session);
-                                }
-
-                                switch_channel_hangup(channel_b, SWITCH_CAUSE_ATTENDED_TRANSFER);
-                            }
-                            switch_set_flag_locked(tech_pvt, TFLAG_BYE);
-                            nua_notify(tech_pvt->nh, SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
-                                       NUTAG_SUBSTATE(nua_substate_terminated),
-                                       SIPTAG_PAYLOAD_STR("SIP/2.0 200 OK"),
-                                       SIPTAG_EVENT_STR(etmp),
-                                       TAG_END());
-
-                        }
-                        if (b_session) {
-                            switch_core_session_rwunlock(b_session);
-                        }
-                    }
-                    nua_handle_unref(bnh);
-                } else { /* the other channel is on a different box, we have to go find them */
-                    if (exten && (br_a = switch_channel_get_variable(channel_a, SWITCH_BRIDGE_VARIABLE))) {
-                        switch_core_session_t *a_session;
-                        switch_channel_t *channel = switch_core_session_get_channel(session);
-							
-                        if ((a_session = switch_core_session_locate(br_a))) {
-                            switch_core_session_t *tsession;
-                            switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
-                            uint32_t timeout = 60;
-                            char *tuuid_str;
-
-                            channel = switch_core_session_get_channel(a_session);
-
-                            exten = switch_mprintf("sofia/%s/%s@%s:%s", 
-                                                   profile->name,
-                                                   (char *) refer_to->r_url->url_user,
-                                                   (char *) refer_to->r_url->url_host,
-                                                   refer_to->r_url->url_port
-                                                   );
-
-                            switch_channel_set_variable(channel, SOFIA_REPLACES_HEADER, rep);
-								
-                            if (switch_ivr_originate(a_session,
-                                                     &tsession,
-                                                     &cause,
-                                                     exten,
-                                                     timeout,
-                                                     &noop_state_handler,
-                                                     NULL,
-                                                     NULL,
-                                                     NULL) != SWITCH_STATUS_SUCCESS) {
-                                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Create Outgoing Channel! [%s]\n", exten);
-                                nua_notify(tech_pvt->nh, SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
-                                           NUTAG_SUBSTATE(nua_substate_terminated),
-                                           SIPTAG_PAYLOAD_STR("SIP/2.0 403 Forbidden"),
-                                           SIPTAG_EVENT_STR(etmp),
-                                           TAG_END());
-                                goto done;
-                            } 
-
-                            switch_core_session_rwunlock(a_session);
-                            tuuid_str = switch_core_session_get_uuid(tsession);
-                            switch_ivr_uuid_bridge(br_a, tuuid_str);
-                            switch_channel_set_variable(channel_a, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "ATTENDED_TRANSFER");
-                            switch_set_flag_locked(tech_pvt, TFLAG_BYE);
-                            nua_notify(tech_pvt->nh, SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
-                                       NUTAG_SUBSTATE(nua_substate_terminated),
-                                       SIPTAG_PAYLOAD_STR("SIP/2.0 200 OK"),
-                                       SIPTAG_EVENT_STR(etmp),
-                                       TAG_END());
-                        } else {
-                            goto error;
-                        }
-
-                    } else { error:
-                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Transfer! [%s]\n", br_a);
-                        switch_channel_set_variable(channel_a, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "ATTENDED_TRANSFER_ERROR");
-                        nua_notify(tech_pvt->nh, SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
-                                   NUTAG_SUBSTATE(nua_substate_terminated),
-                                   SIPTAG_PAYLOAD_STR("SIP/2.0 403 Forbidden"),
-                                   SIPTAG_EVENT_STR(etmp),
-                                   TAG_END());
-                    }
-                }
-            } else {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot parse Replaces!\n");
-            }
-            goto done;
-        }
-
-    } else {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing Refer-To\n");
-        goto done;
-    }
-
-    if (exten) {
-        switch_channel_t *channel = switch_core_session_get_channel(session);
-        char *br;
-				
-        if ((br = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE))) {
-            switch_core_session_t *b_session;
-				
-            if ((b_session = switch_core_session_locate(br))) {
-                switch_channel_set_variable(channel, "TRANSFER_FALLBACK", from->a_user);
-                switch_ivr_session_transfer(b_session, exten, profile->dialplan, profile->context);
-                switch_core_session_rwunlock(b_session);
-            } 
-
-            switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "BLIND_TRANSFER");
-                
-            /*
-              nua_notify(tech_pvt->nh, SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
-              NUTAG_SUBSTATE(nua_substate_terminated),
-              SIPTAG_PAYLOAD_STR("SIP/2.0 200 OK"),
-              SIPTAG_EVENT_STR(etmp),
-              TAG_END());
-            */
-        } else {
-            exten = switch_mprintf("sip:%s@%s:%s", 
-                                   (char *) refer_to->r_url->url_user,
-                                   (char *) refer_to->r_url->url_host,
-                                   refer_to->r_url->url_port);
-            tech_pvt->dest = switch_core_session_strdup(session, exten);
-				
-				
-            switch_set_flag_locked(tech_pvt, TFLAG_NOHUP);
 
-            /*
-              nua_notify(tech_pvt->nh, SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
-              NUTAG_SUBSTATE(nua_substate_terminated),
-              SIPTAG_PAYLOAD_STR("SIP/2.0 200 OK"),
-              SIPTAG_EVENT_STR(etmp),
-              TAG_END());
-            */
-            do_xfer_invite(session);
-
-        }
-    }
-
- done:
-    if (exten && strchr(exten, '@')) {
-        switch_safe_free(exten);
-    }
-    if (etmp) {
-        switch_safe_free(etmp);
-    }
+static switch_status_t sofia_read_video_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id)
+{
+	private_object_t *tech_pvt = NULL;
+	switch_channel_t *channel = NULL;
+	int payload = 0;
 	
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-}
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
+	if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
+		return SWITCH_STATUS_FALSE;
+	}
 
-static void sip_i_publish(nua_t *nua, 
-						  sofia_profile_t *profile,
-						  nua_handle_t *nh, 
-						  sofia_private_t *sofia_private,
-						  sip_t const *sip,
-						  tagi_t tags[])
-{
-	if (sip) {
-		sip_from_t const *from = sip->sip_from;
-		char *from_user = NULL;
-		char *from_host = NULL;
-		char *rpid = "unknown";
-		sip_payload_t *payload = sip->sip_payload;
-		char *event_type;
-
-		if (from) {
-			from_user = (char *) from->a_url->url_user;
-			from_host = (char *) from->a_url->url_host;
+	while (!(tech_pvt->video_read_codec.implementation && switch_rtp_ready(tech_pvt->video_rtp_session))) {
+		if (switch_channel_ready(channel)) {
+			switch_yield(10000);
+		} else {
+			return SWITCH_STATUS_GENERR;
 		}
+	}
 
-		if (payload) {
-			switch_xml_t xml, note, person, tuple, status, basic, act;
-			switch_event_t *event;
-			uint8_t in = 0;
-			char *sql;
 
-			if ((xml = switch_xml_parse_str(payload->pl_data, strlen(payload->pl_data)))) {
-				char *status_txt = "", *note_txt = "";
-				
-				if ((tuple = switch_xml_child(xml, "tuple")) && (status = switch_xml_child(tuple, "status")) && (basic = switch_xml_child(status, "basic"))) {
-					status_txt = basic->txt;
-				}
-					
-				if ((person = switch_xml_child(xml, "dm:person")) && (note = switch_xml_child(person, "dm:note"))) {
-					note_txt = note->txt;
-				}
+	tech_pvt->video_read_frame.datalen = 0;
 
-				if (person && (act = switch_xml_child(person, "rpid:activities"))) {
-					if ((rpid = strchr(act->child->name, ':'))) {
-						rpid++;
-					} else {
-						rpid = act->child->name;
-					}
-				}
 
-				if (!strcasecmp(status_txt, "open")) {
-					if (switch_strlen_zero(note_txt)) {
-						note_txt = "Available";
-					}
-					in = 1;
-				} else if (!strcasecmp(status_txt, "closed")) {
-					if (switch_strlen_zero(note_txt)) {
-						note_txt = "Unavailable";
-					}
-				}
-				
-				if ((sql = switch_mprintf("update sip_registrations set status='%q',rpid='%q' where user='%q' and host='%q'", 
-										  note_txt, rpid, from_user, from_host))) {
-					execute_sql(profile->dbname, sql, profile->ireg_mutex);
-					switch_safe_free(sql);
-				}
-				
-				event_type = sip_header_as_string(profile->home, (void *)sip->sip_event);
+	if (switch_test_flag(tech_pvt, TFLAG_IO)) {
+		switch_status_t status;
 
-				if (in) {
-					if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_IN) == SWITCH_STATUS_SUCCESS) {
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", SOFIA_CHAT_PROTO);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "%s", rpid);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->url);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", from_user, from_host);
-						
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "status", "%s", note_txt);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "%s", event_type);
-						switch_event_fire(&event);
-					}
-				} else {
-					if (switch_event_create(&event, SWITCH_EVENT_PRESENCE_OUT) == SWITCH_STATUS_SUCCESS) {
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "proto", SOFIA_CHAT_PROTO);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "rpid", "%s", rpid);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "login", "%s", profile->url);
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "from", "%s@%s", from_user, from_host);
+		if (!switch_test_flag(tech_pvt, TFLAG_RTP)) {
+			return SWITCH_STATUS_GENERR;
+		}
 
-						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "event_type", "%s", event_type);
-						switch_event_fire(&event);
-					}
-				}
+		assert(tech_pvt->rtp_session != NULL);
+		tech_pvt->video_read_frame.datalen = 0;
 
-				if (event_type) {
-					su_free(profile->home, event_type);
-				}				
+		while (switch_test_flag(tech_pvt, TFLAG_IO) && tech_pvt->video_read_frame.datalen == 0) {
+			tech_pvt->video_read_frame.flags = SFF_NONE;
 
-				switch_xml_free(xml);
+			status = switch_rtp_zerocopy_read_frame(tech_pvt->video_rtp_session, &tech_pvt->video_read_frame);
+			if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
+				return SWITCH_STATUS_FALSE;
 			}
 			
+			payload = tech_pvt->video_read_frame.payload;
+
+			if (tech_pvt->video_read_frame.datalen > 0) {
+				break;
+			}
 		}
-		
 	}
 
-	nua_respond(nh, SIP_200_OK, NUTAG_WITH_THIS(nua), TAG_END());
-
-}
-
-static void sip_i_info(nua_t *nua,
-                       sofia_profile_t *profile,
-                       nua_handle_t *nh,
-                       switch_core_session_t *session,
-                       sip_t const *sip,
-                       tagi_t tags[]) {
-
-	//placeholder for string searching
-	char *signal_ptr;
-
-	//Try and find signal information in the payload
-	signal_ptr = strstr(sip->sip_payload->pl_data, "Signal=");
-
-	//See if we found a match
-	if(signal_ptr) {
-		struct private_object *tech_pvt = NULL;
-		switch_channel_t *channel = NULL;
-		char dtmf_digit[2] = {0,0};
-
-		//Get the channel
-		channel = switch_core_session_get_channel(session);
-
-		//Barf if we didn't get it
-		assert(channel != NULL);
-
-		//make sure we have our privates
-		tech_pvt = switch_core_session_get_private(session);
-
-		//Barf if we didn't get it
-		assert(tech_pvt != NULL);
+	if (tech_pvt->video_read_frame.datalen == 0) {
+		*frame = NULL;
+		return SWITCH_STATUS_GENERR;
+	}
 
-		//move signal_ptr where we need it (right past Signal=)
-		signal_ptr = signal_ptr + 7;
+	*frame = &tech_pvt->video_read_frame;
 
-		//put the digit somewhere we can muck with
-		strncpy(dtmf_digit, signal_ptr, 1);
+	return SWITCH_STATUS_SUCCESS;
+}
 
-		//queue it up
-		switch_channel_queue_dtmf(channel, dtmf_digit);
-		
-		//print debug info
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "INFO DTMF(%s)\n", dtmf_digit);
+static switch_status_t sofia_write_video_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id)
+{
+	private_object_t *tech_pvt;
+	switch_channel_t *channel = NULL;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
 
-	} else { //unknown info type
-		sip_from_t const *from;
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-		from = sip->sip_from;
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-		//print in the logs if something comes through we don't understand
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Unknown INFO Recieved: %s%s" URL_PRINT_FORMAT "[%s]\n",
-		                  from->a_display ? from->a_display : "", from->a_display ? " " : "",
-		                  URL_PRINT_ARGS(from->a_url), sip->sip_payload->pl_data);
+	while (!(tech_pvt->video_read_codec.implementation && switch_rtp_ready(tech_pvt->video_rtp_session))) {
+		if (switch_channel_ready(channel)) {
+			switch_yield(10000);
+		} else {
+			return SWITCH_STATUS_GENERR;
+		}
 	}
 
-	return;
-}
-
-
-#define url_set_chanvars(session, url, varprefix) _url_set_chanvars(session, url, #varprefix "_user", #varprefix "_host", #varprefix "_port", #varprefix "_uri")
-static const char * _url_set_chanvars(switch_core_session_t *session, url_t *url, const char * user_var, const char * host_var, const char * port_var, const char * uri_var)
-{
-	const char *user = NULL, *host = NULL, *port = NULL;
-	char *uri = NULL;
-	switch_channel_t *channel = switch_core_session_get_channel(session);
-
-	if (url) {
-		user = url->url_user;
-		host = url->url_host;
-		port = url->url_port;
+	if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
+		return SWITCH_STATUS_FALSE;
 	}
 
-	if (user) {
-		switch_channel_set_variable(channel, user_var, user);
+	if (!switch_test_flag(tech_pvt, TFLAG_RTP)) {
+		return SWITCH_STATUS_GENERR;
 	}
 
-	if (!port) {
-		port = "5060";
+	if (!switch_test_flag(tech_pvt, TFLAG_IO)) {
+		return SWITCH_STATUS_SUCCESS;
 	}
 
-	switch_channel_set_variable(channel, port_var, port);
-	if (host) {
-		if (user) {
-			uri = switch_core_session_sprintf(session, "%s@%s:%s", user, host, port);
-		} else {
-			uri = switch_core_session_sprintf(session, "%s:%s", host, port);
-		}
-		switch_channel_set_variable_nodup(channel, uri_var, uri);
-		switch_channel_set_variable(channel, host_var, host);
+	if (!switch_test_flag(frame, SFF_CNG)) {
+		switch_rtp_write_frame(tech_pvt->video_rtp_session, frame, 0);
 	}
-
-	return uri;
+	
+	return status;
 }
 
-static void process_rpid(sip_unknown_t *un, private_object_t *tech_pvt)
-{
-	int argc, x, screen = 1;
-	char *mydata, *argv[10] = { 0 };
-	if (!switch_strlen_zero(un->un_value)) { 
-		if ((mydata = strdup(un->un_value))) {
-			argc = switch_separate_string(mydata, ';', argv, (sizeof(argv) / sizeof(argv[0]))); 
-
-			// Do We really need this at this time 
-			// clid_uri = argv[0];
-
-			for (x=1; x < argc && argv[x]; x++){
-				// we dont need to do anything with party yet we should only be seeing party=calling here anyway
-				// maybe thats a dangerous assumption bit oh well yell at me later
-				// if (!strncasecmp(argv[x], "party", 5)) {
-				//	party = argv[x];
-				// } else 
-				if (!strncasecmp(argv[x], "privacy=", 8)) {
-					char *arg = argv[x] + 9;
-
-					if (!strcasecmp(arg, "yes")) {
-						switch_set_flag(tech_pvt->caller_profile, SWITCH_CPF_HIDE_NAME | SWITCH_CPF_HIDE_NUMBER);
-					} else if (!strcasecmp(arg, "full")) {
-						switch_set_flag(tech_pvt->caller_profile, SWITCH_CPF_HIDE_NAME | SWITCH_CPF_HIDE_NUMBER);
-					} else if (!strcasecmp(arg, "name")) {
-						switch_set_flag(tech_pvt->caller_profile, SWITCH_CPF_HIDE_NAME);
-					} else if (!strcasecmp(arg, "number")) {
-						switch_set_flag(tech_pvt->caller_profile, SWITCH_CPF_HIDE_NUMBER);
-					} else {
-						switch_clear_flag(tech_pvt->caller_profile, SWITCH_CPF_HIDE_NAME);
-						switch_clear_flag(tech_pvt->caller_profile, SWITCH_CPF_HIDE_NUMBER);
-					}
-
-				} else if (!strncasecmp(argv[x], "screen=", 7) && screen > 0) {
-					char *arg = argv[x] + 8;
-					if (!strcasecmp(arg, "no")) {
-						screen = 0;
-						switch_clear_flag(tech_pvt->caller_profile, SWITCH_CPF_SCREEN);
-					}
-				}
-			}
-			free(mydata);
-		}
-	}
-}
 
-static void sip_i_invite(nua_t *nua, 
-						 sofia_profile_t *profile,
-						 nua_handle_t *nh, 
-						 sofia_private_t *sofia_private,
-						 sip_t const *sip,
-						 tagi_t tags[])
+static switch_status_t sofia_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
-	switch_core_session_t *session = NULL;
-	char key[128] = "";
-	sip_unknown_t *un;
 	private_object_t *tech_pvt = NULL;
 	switch_channel_t *channel = NULL;
-	const char *channel_name = NULL;
-	const char *displayname = NULL;
-	const char *destination_number = NULL;
-	const char *from_user = NULL, *from_host = NULL;
-	const char *context;
-	char network_ip[80];
-
-	if (!sip) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Received an invite callback with no packet!\n");
-		nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
-		return;
-	}
-
-	if (!(sip->sip_contact && sip->sip_contact->m_url)) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "NO CONTACT!\n");
-		nua_respond(nh, 400, "Missing Contact Header", TAG_END());
-		return;
-	}
-
-	if ((profile->pflags & PFLAG_AUTH_CALLS)) {
-		if (handle_register(nua, profile, nh, sip, REG_INVITE, key, sizeof(key))) {
-			return;
-		}
-	}
+	int payload = 0;
+	
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-	if (!(session = switch_core_session_request(&sofia_endpoint_interface, NULL))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Session Alloc Failed!\n");
-		nua_respond(nh, SIP_503_SERVICE_UNAVAILABLE, TAG_END());
-		return;
-	}
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-	if (!(tech_pvt = (private_object_t *) switch_core_session_alloc(session, sizeof(private_object_t)))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Hey where is my memory pool?\n");
-		terminate_session(&session, SWITCH_CAUSE_SWITCH_CONGESTION, __LINE__);
-		return;
+	if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
+		return SWITCH_STATUS_FALSE;
 	}
 
-	if (!switch_strlen_zero(key)) {
-		tech_pvt->key = switch_core_session_strdup(session, key);
+	while (!(tech_pvt->read_codec.implementation && switch_rtp_ready(tech_pvt->rtp_session))) {
+		if (switch_channel_ready(channel)) {
+			switch_yield(10000);
+		} else {
+			return SWITCH_STATUS_GENERR;
+		}
 	}
 
-	get_addr(network_ip, sizeof(network_ip), &((struct sockaddr_in *)msg_addrinfo(nua_current_request(nua))->ai_addr)->sin_addr);
-
-	channel = switch_core_session_get_channel(session);
 
-	if (sip->sip_from && sip->sip_from->a_url) {
-		from_user = sip->sip_from->a_url->url_user;
-		from_host = sip->sip_from->a_url->url_host;
-		channel_name = url_set_chanvars(session, sip->sip_from->a_url, "sip_from");
-
-		if (!switch_strlen_zero(from_user)) {
-			if (*from_user == '+') {
-				switch_channel_set_variable(channel, "sip_from_user_stripped", (const char *)(from_user+1));
-			} else {
-				switch_channel_set_variable(channel, "sip_from_user_stripped", from_user);
-			}
-		}
+	tech_pvt->read_frame.datalen = 0;
+	switch_set_flag_locked(tech_pvt, TFLAG_READING);
 
-		if (!switch_strlen_zero(sip->sip_from->a_display)) {
-			char *tmp;
-			tmp = switch_core_session_strdup(session, sip->sip_from->a_display);
-			if (*tmp == '"') {
-				char *p;
-
-				tmp++;
-				if ((p = strchr(tmp, '"'))) {
-					*p = '\0';
-				}
-			}
-			displayname = tmp;
-		} else {
-			displayname = switch_strlen_zero(from_user) ? "unkonwn" : from_user;
-		}
-	}
+	if (switch_test_flag(tech_pvt, TFLAG_IO)) {
+		switch_status_t status;
 
-	if (sip->sip_request && sip->sip_request->rq_url) {
-		const char * req_uri = url_set_chanvars(session, sip->sip_request->rq_url, "sip_req");
-		if (profile->pflags & PFLAG_FULL_ID)  {
-			destination_number = req_uri;
-		} else {
-			destination_number = sip->sip_request->rq_url->url_user;
+		if (!switch_test_flag(tech_pvt, TFLAG_RTP)) {
+			return SWITCH_STATUS_GENERR;
 		}
-	}
 
-	if (sip->sip_to && sip->sip_to->a_url) {
-		url_set_chanvars(session, sip->sip_to->a_url, "sip_to");
-	}
+		assert(tech_pvt->rtp_session != NULL);
+		tech_pvt->read_frame.datalen = 0;
 
-	if (sip->sip_contact && sip->sip_contact->m_url) {
-		const char *contact_uri = url_set_chanvars(session, sip->sip_contact->m_url, "sip_contact");
-		if (!channel_name) {
-			channel_name = contact_uri;
-		}
-	}
 
-	attach_private(session, profile, tech_pvt, channel_name);
-	tech_set_codecs(tech_pvt);
+		while (switch_test_flag(tech_pvt, TFLAG_IO) && tech_pvt->read_frame.datalen == 0) {
+			tech_pvt->read_frame.flags = SFF_NONE;
 
-	switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "INBOUND CALL");
-	set_chat_hash(tech_pvt, sip);
+			status = switch_rtp_zerocopy_read_frame(tech_pvt->rtp_session, &tech_pvt->read_frame);
+			if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
+				return SWITCH_STATUS_FALSE;
+			}
 
-	if (switch_test_flag(tech_pvt, TFLAG_INB_NOMEDIA)) {
-		switch_set_flag_locked(tech_pvt, TFLAG_NOMEDIA);
-		switch_channel_set_flag(channel, CF_NOMEDIA);
-	}
 
-	if (!tech_pvt->call_id && sip->sip_call_id && sip->sip_call_id->i_id) {
-		tech_pvt->call_id = switch_core_session_strdup(session, sip->sip_call_id->i_id);
-		switch_channel_set_variable(channel, "sip_call_id", tech_pvt->call_id);
-	}
 
-	if (sip->sip_via) {
-		if (sip->sip_via->v_host) {
-			switch_channel_set_variable(channel, "sip_via_host", sip->sip_via->v_host);
-		}
-		if (sip->sip_via->v_port) {
-			switch_channel_set_variable(channel, "sip_via_port", sip->sip_via->v_port);
-		}
-		if (sip->sip_via->v_rport) {
-			switch_channel_set_variable(channel, "sip_via_rport", sip->sip_via->v_rport);
-		}
-	}
+			payload = tech_pvt->read_frame.payload;
 
-	if (sip->sip_max_forwards) {
-		char max_forwards[32];
-		snprintf(max_forwards, sizeof(max_forwards), "%u", sip->sip_max_forwards->mf_count);
-		switch_channel_set_variable(channel, SWITCH_MAX_FORWARDS_VARIABLE, max_forwards);
-	}
+			if (switch_rtp_has_dtmf(tech_pvt->rtp_session)) {
+				char dtmf[128];
+				switch_rtp_dequeue_dtmf(tech_pvt->rtp_session, dtmf, sizeof(dtmf));
+				switch_channel_queue_dtmf(channel, dtmf);
+			}
 
-	if (profile->context && !strcasecmp(profile->context, "_domain_")) {
-		context = from_host;
-	} else {
-		context = profile->context;
-	}
 
-	tech_pvt->caller_profile = switch_caller_profile_new(switch_core_session_get_pool(session),
-														from_user,
-														profile->dialplan,
-														displayname,
-														from_user,
-														network_ip,
-														NULL,
-														NULL,
-														NULL,
-														modname,
-														context,
-														destination_number);
+			if (tech_pvt->read_frame.datalen > 0) {
+				size_t bytes = 0;
+				int frames = 1;
 
-	if (tech_pvt->caller_profile) {
-				
-		/* Loop thru unknown Headers Here so we can do something with them */
-		for (un=sip->sip_unknown; un; un=un->un_next) {
-			if (!strncasecmp(un->un_name, "Alert-Info", 10)) {
-				if (!switch_strlen_zero(un->un_value)) { 
-					switch_channel_set_variable(channel, "alert_info", un->un_value);
-				}
-			} else if (!strncasecmp(un->un_name, "Remote-Party-ID", 15)) {
-				process_rpid(un, tech_pvt);
-			} else if (!strncasecmp(un->un_name, "X-", 2)) {
-				if (!switch_strlen_zero(un->un_value)) { 
-					char *new_name;
-					if ((new_name = switch_mprintf("%s%s", SOFIA_SIP_HEADER_PREFIX, un->un_name))) {
-						switch_channel_set_variable(channel, new_name, un->un_value);
-						free(new_name);
+				if (!switch_test_flag((&tech_pvt->read_frame), SFF_CNG)) {
+					if ((bytes = tech_pvt->read_codec.implementation->encoded_bytes_per_frame)) {
+						frames = (tech_pvt->read_frame.datalen / bytes);
 					}
+					tech_pvt->read_frame.samples = (int) (frames * tech_pvt->read_codec.implementation->samples_per_frame);
 				}
+				break;
 			}
 		}
-
-		switch_channel_set_caller_profile(channel, tech_pvt->caller_profile);
 	}
 
-	if (!(tech_pvt->sofia_private = malloc(sizeof(*tech_pvt->sofia_private)))) {
-		abort();
+	switch_clear_flag_locked(tech_pvt, TFLAG_READING);
+
+	if (tech_pvt->read_frame.datalen == 0) {
+		*frame = NULL;
+		return SWITCH_STATUS_GENERR;
 	}
-	memset(tech_pvt->sofia_private, 0, sizeof(*tech_pvt->sofia_private));
-	switch_copy_string(tech_pvt->sofia_private->uuid, switch_core_session_get_uuid(session), sizeof(tech_pvt->sofia_private->uuid));
-	nua_handle_bind(nh, tech_pvt->sofia_private);
-	tech_pvt->nh = nh;
-}
 
-static void sip_i_register(nua_t *nua,
-						   sofia_profile_t *profile,
-						   nua_handle_t *nh,
-						   sofia_private_t *sofia_private,
-						   sip_t const *sip,
-						   tagi_t tags[])
-{
-    char key[128] = "";
-	handle_register(nua, profile, nh, sip, REG_REGISTER, key, sizeof(key));
+	*frame = &tech_pvt->read_frame;
+
+	return SWITCH_STATUS_SUCCESS;
 }
 
 
-static void sip_i_options(int status,
-						  char const *phrase,
-						  nua_t *nua,
-						  sofia_profile_t *profile,
-						  nua_handle_t *nh,
-						  sofia_private_t *sofia_private,
-						  sip_t const *sip,
-						  tagi_t tags[])
+static switch_status_t sofia_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
-	nua_respond(nh, SIP_200_OK, 
-				//SOATAG_USER_SDP_STR(tech_pvt->local_sdp_str),
-				//SOATAG_AUDIO_AUX("cn telephone-event"),
-				//NUTAG_INCLUDE_EXTRA_SDP(1),
-				TAG_END());
-}
+	private_object_t *tech_pvt;
+	switch_channel_t *channel = NULL;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
+	int bytes = 0, samples = 0, frames = 0;
+
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-static void sip_r_register(int status,
-						   char const *phrase,
-						   nua_t *nua,
-						   sofia_profile_t *profile,
-						   nua_handle_t *nh,
-						   sofia_private_t *sofia_private,
-						   sip_t const *sip,
-						   tagi_t tags[])
-{
-	if (sofia_private && sofia_private->oreg) {
-		if (status == 200) {
-			sofia_private->oreg->state = REG_STATE_REGISTER;
+	while (!(tech_pvt->read_codec.implementation && switch_rtp_ready(tech_pvt->rtp_session))) {
+		if (switch_channel_ready(channel)) {
+			switch_yield(10000);
 		} else {
-			sofia_private->oreg->state = REG_STATE_FAILED;
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "received %d on register!\n", status);
+			return SWITCH_STATUS_GENERR;
 		}
 	}
-}
 
-static void sip_r_challenge(int status,
-                            char const *phrase,
-                            nua_t *nua,
-                            sofia_profile_t *profile,
-                            nua_handle_t *nh,
-                            switch_core_session_t *session,
-                            sip_t const *sip,
-                            tagi_t tags[])
-{
-	outbound_reg_t *oreg = NULL;
-	sip_www_authenticate_t const *authenticate = NULL;
-	char const *realm = NULL; 
-	char *p = NULL, *duprealm = NULL, *qrealm = NULL;
-	char const *scheme = NULL;
-	int indexnum;
-	char *cur;
-	char authentication[256] = "";
-	int ss_state;
-	
-	if (session) {
-		private_object_t *tech_pvt;
-		if ((tech_pvt = switch_core_session_get_private(session)) && switch_test_flag(tech_pvt, TFLAG_REFER)) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "received reply from refer\n");
-			return;
-		}
+	if (switch_test_flag(tech_pvt, TFLAG_HUP)) {
+		return SWITCH_STATUS_FALSE;
 	}
 
-
-	if (sip->sip_www_authenticate) {
-		authenticate = sip->sip_www_authenticate;
-	} else if (sip->sip_proxy_authenticate) {
-		authenticate = sip->sip_proxy_authenticate;
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Missing Authenticate Header!\n");
-		return;
-	}
-	scheme = (char const *) authenticate->au_scheme;
-	if (authenticate->au_params) {
-		for(indexnum = 0; (cur=(char*)authenticate->au_params[indexnum]); indexnum++) {
-			if ((realm = strstr(cur, "realm="))) {
-				realm += 6;
-				break;
-			}
-		}
+	if (!switch_test_flag(tech_pvt, TFLAG_RTP)) {
+		return SWITCH_STATUS_GENERR;
 	}
 
-	if (!(scheme && realm)) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No scheme and realm!\n");
-		return;
+	if (!switch_test_flag(tech_pvt, TFLAG_IO)) {
+		return SWITCH_STATUS_SUCCESS;
 	}
 
-	if (profile) {
-		outbound_reg_t *oregp;
-
-		if ((duprealm = strdup(realm))) {
-			qrealm = duprealm;
-	
-			while(*qrealm && *qrealm == '"') {
-				qrealm++;
-			}
+	switch_set_flag_locked(tech_pvt, TFLAG_WRITING);
 
-			if ((p = strchr(qrealm, '"'))) {
-				*p = '\0';
-			}
+	if (!switch_test_flag(frame, SFF_CNG)) {
+		if (tech_pvt->read_codec.implementation->encoded_bytes_per_frame) {
+			bytes = tech_pvt->read_codec.implementation->encoded_bytes_per_frame;
+			frames = ((int) frame->datalen / bytes);
+		} else
+			frames = 1;
 
-			for (oregp = profile->registrations; oregp; oregp = oregp->next) {
-				if (scheme && qrealm && !strcasecmp(oregp->register_scheme, scheme) && !strcasecmp(oregp->register_realm, qrealm)) {
-					oreg = oregp;
-					break;
-				}
-			}
-			if (!oreg) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No Match for Scheme [%s] Realm [%s]\n", scheme, qrealm);
-				return;
-			}
-			switch_safe_free(duprealm);
-		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n");
-			return;
-		}
+		samples = frames * tech_pvt->read_codec.implementation->samples_per_frame;
 	}
-		
-	snprintf(authentication, sizeof(authentication), "%s:%s:%s:%s", scheme, realm, 
-			 oreg->register_username,
-			 oreg->register_password);
-		
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Authenticating '%s' with '%s'.\n",
-					  profile->username, authentication);
-		
-		
-	ss_state = nua_callstate_authenticating;
-		
-	tl_gets(tags,
-			NUTAG_CALLSTATE_REF(ss_state),
-			SIPTAG_WWW_AUTHENTICATE_REF(authenticate),
-			TAG_END());
-		
-	nua_authenticate(nh, SIPTAG_EXPIRES_STR(oreg->expires_str), NUTAG_AUTH(authentication), TAG_END());
-	
+#if 0
+	printf("%s %s->%s send %d bytes %d samples in %d frames ts=%d\n",
+		   switch_channel_get_name(channel),
+		   tech_pvt->local_sdp_audio_ip, tech_pvt->remote_sdp_audio_ip, frame->datalen, samples, frames, tech_pvt->timestamp_send);
+#endif
+
+	tech_pvt->timestamp_send += samples;
+	//switch_rtp_write_frame(tech_pvt->rtp_session, frame, tech_pvt->timestamp_send);
+	switch_rtp_write_frame(tech_pvt->rtp_session, frame, 0);
+
+	switch_clear_flag_locked(tech_pvt, TFLAG_WRITING);
+	return status;
 }
 
-static void event_callback(nua_event_t event,
-						   int status,
-						   char const *phrase,
-						   nua_t *nua,
-						   sofia_profile_t *profile,
-						   nua_handle_t *nh,
-						   sofia_private_t *sofia_private,
-						   sip_t const *sip,
-						   tagi_t tags[])
+
+
+static switch_status_t sofia_kill_channel(switch_core_session_t *session, int sig)
 {
-	struct private_object *tech_pvt = NULL;
-	auth_res_t auth_res = AUTH_FORBIDDEN;
-	switch_core_session_t *session = NULL;
-    switch_channel_t *channel = NULL;
-
-    if (sofia_private) {
-        if (!switch_strlen_zero(sofia_private->uuid)) {
-
-            if ((session = switch_core_session_locate(sofia_private->uuid))) {
-                tech_pvt = switch_core_session_get_private(session);
-                channel = switch_core_session_get_channel(tech_pvt->session);
-                if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
-                    switch_set_flag(tech_pvt, TFLAG_NOMEDIA);
-                }
-                if (!tech_pvt->call_id && sip && sip->sip_call_id && sip->sip_call_id->i_id) {
-                    tech_pvt->call_id = switch_core_session_strdup(session, (char *)sip->sip_call_id->i_id);
-                    switch_channel_set_variable(channel, "sip_call_id", tech_pvt->call_id);
-                }
-            } else {
-                /* too late */
-                return;            
-            }
-        }
-    }
-
-
-	if (status != 100 && status != 200) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "event [%s] status [%d][%s] session: %s\n",
-						  nua_event_name (event), status, phrase,
-						  session ? switch_channel_get_name(channel) : "n/a"
-						  );
-	}
-
-	if ((profile->pflags & PFLAG_AUTH_ALL) && tech_pvt && tech_pvt->key && sip) {
-		sip_authorization_t const *authorization = NULL;
-
-        if (sip->sip_authorization) {
-			authorization = sip->sip_authorization;
-		} else if (sip->sip_proxy_authorization) {
-			authorization = sip->sip_proxy_authorization;
-		}
+	private_object_t *tech_pvt;
+	switch_channel_t *channel = NULL;
 
-		if (authorization) {
-			auth_res = parse_auth(profile, authorization, (char *)sip->sip_request->rq_method_name, tech_pvt->key, strlen(tech_pvt->key));
-		}
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-		if (auth_res != AUTH_OK) {
-			switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			nua_respond(nh, SIP_401_UNAUTHORIZED, TAG_END());
-			goto done;
-		}
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-		if (channel) {
-			switch_channel_set_variable(channel, "sip_authorized", "true");
-		}
-	}
 
-	if (sip && (status == 401 || status == 407)) {
-		sip_r_challenge(status, phrase, nua, profile, nh, session, sip, tags);
-		goto done;
-	}
-	
-	switch (event) {
-	case nua_r_shutdown:    
-	case nua_r_get_params:    
-	case nua_r_invite:
-    case nua_r_unregister:
-    case nua_r_options:
-	case nua_i_fork:
-	case nua_r_info:
-    case nua_r_bye:
-	case nua_i_bye:
-	case nua_r_unsubscribe:
-	case nua_r_publish:
-	case nua_r_message:
-	case nua_r_notify:
-    case nua_i_notify:
-	case nua_i_cancel:
-	case nua_i_error:
-	case nua_i_active:
-	case nua_i_ack:
-	case nua_i_terminated:
-	case nua_r_set_params:
-        break;
-	case nua_r_register:
-		sip_r_register(status, phrase, nua, profile, nh, sofia_private, sip, tags);
-		break;
-	case nua_i_options:
-		sip_i_options(status, phrase, nua, profile, nh, sofia_private, sip, tags);
-		break;
-    case nua_i_invite:
-        if (!session) {
-            sip_i_invite(nua, profile, nh, sofia_private, sip, tags);
-        }
-		break;
-	case nua_i_publish:
-		sip_i_publish(nua, profile, nh, sofia_private, sip, tags);
-		break;
-    case nua_i_register:
- 		sip_i_register (nua, profile, nh, sofia_private, sip, tags);
-        break;
-	case nua_i_prack:
-		break;
-	case nua_i_state:
-		sip_i_state(status, phrase, nua, profile, nh, sofia_private, sip, tags);
-		break;
-	case nua_i_message:
-		sip_i_message(status, phrase, nua, profile, nh, sofia_private, sip, tags);
-		break;
-	case nua_i_info:
-		sip_i_info(nua, profile, nh, session, sip, tags);
-		break;
-	case nua_r_refer:
-		break;
-	case nua_i_refer:
-        if (session) {
-            sip_i_refer(nua, profile, nh, session, sip, tags);
-        }
-		break;
-    case nua_r_subscribe:
-		sip_r_subscribe(status, phrase, nua, profile, nh, sofia_private, sip, tags);
-		break;
-	case nua_i_subscribe:
-		sip_i_subscribe(status, phrase, nua, profile, nh, sofia_private, sip, tags);
+	switch (sig) {
+	case SWITCH_SIG_BREAK:
+		if (switch_rtp_ready(tech_pvt->rtp_session)) {
+			switch_rtp_set_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_BREAK);
+		}
+		if (switch_rtp_ready(tech_pvt->video_rtp_session)) {
+			switch_rtp_set_flag(tech_pvt->video_rtp_session, SWITCH_RTP_FLAG_BREAK);
+		}
 		break;
+	case SWITCH_SIG_KILL:
 	default:
-		if (status > 100) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s: unknown event %d: %03d %s\n", 
-							  nua_event_name (event), event, status, phrase);
-        } else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s: unknown event %d\n", nua_event_name (event), event);
-        }
+		switch_clear_flag_locked(tech_pvt, TFLAG_IO);
+		switch_set_flag_locked(tech_pvt, TFLAG_HUP);
+
+		if (switch_rtp_ready(tech_pvt->rtp_session)) {
+			switch_rtp_kill_socket(tech_pvt->rtp_session);
+		}
+		if (switch_rtp_ready(tech_pvt->video_rtp_session)) {
+			switch_rtp_kill_socket(tech_pvt->video_rtp_session);
+		}
 		break;
 	}
 
- done:
+	return SWITCH_STATUS_SUCCESS;
 
-	if (session) {
-		switch_core_session_rwunlock(session);
-	}
 }
 
-
-static void unreg(sofia_profile_t *profile)
+static switch_status_t sofia_waitfor_read(switch_core_session_t *session, int ms, int stream_id)
 {
-	outbound_reg_t *oregp;
-    for (oregp = profile->registrations; oregp; oregp = oregp->next) {
-        if (oregp->sofia_private) {
-            free(oregp->sofia_private);
-            nua_handle_bind(oregp->nh, NULL);
-            oregp->sofia_private = NULL;
-        }
-		nua_handle_destroy(oregp->nh);
-	}
-}
+	private_object_t *tech_pvt;
+	switch_channel_t *channel = NULL;
 
-static void check_oreg(sofia_profile_t *profile, time_t now)
-{
-	outbound_reg_t *oregp;
-	for (oregp = profile->registrations; oregp; oregp = oregp->next) {
-		int ss_state = nua_callstate_authenticating;
-		reg_state_t ostate = oregp->state;
-
-		switch(ostate) {
-		case REG_STATE_REGISTER:
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,  "registered %s\n", oregp->name);
-			oregp->expires = now + oregp->freq;
-			oregp->state = REG_STATE_REGED;
-			break;
-		case REG_STATE_UNREGED:
-			if ((oregp->nh = nua_handle(oregp->profile->nua, NULL,
-										NUTAG_URL(oregp->register_proxy),
-										SIPTAG_TO_STR(oregp->register_to),
-										NUTAG_CALLSTATE_REF(ss_state),
-										SIPTAG_FROM_STR(oregp->register_from), TAG_END()))) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,  "registering %s\n", oregp->name);	
-                
-                if (!(oregp->sofia_private = malloc(sizeof(*oregp->sofia_private)))) {
-                    abort();
-                }
-                memset(oregp->sofia_private, 0, sizeof(*oregp->sofia_private));
-
-				oregp->sofia_private->oreg = oregp;
-				nua_handle_bind(oregp->nh, oregp->sofia_private);
-
-				nua_register(oregp->nh,
-							SIPTAG_FROM_STR(oregp->register_from),
-							SIPTAG_CONTACT_STR(oregp->register_from),
-							SIPTAG_EXPIRES_STR(oregp->expires_str),
-							NUTAG_REGISTRAR(oregp->register_proxy),
-							NUTAG_OUTBOUND("no-options-keepalive"),
-							NUTAG_OUTBOUND("no-validate"),
-							NUTAG_KEEPALIVE(0),
-							TAG_NULL());
-				oregp->retry = now + 10;
-				oregp->state = REG_STATE_TRYING;
-			} else {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,  "Error registering %s\n", oregp->name);
-				oregp->state = REG_STATE_FAILED;
-			}
-			break;
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-		case REG_STATE_TRYING:
-			if (oregp->retry && now >= oregp->retry) {
-				oregp->state = REG_STATE_UNREGED;
-				oregp->retry = 0;
-			}
-			break;
-		default:
-			if (oregp->expires && now >= oregp->expires) {
-				oregp->state = REG_STATE_UNREGED;
-				oregp->expires = 0;
-			}
-			break;
-		}
-	}
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
+	return SWITCH_STATUS_SUCCESS;
 }
 
-#define IREG_SECONDS 30
-#define OREG_SECONDS 1
-static void *SWITCH_THREAD_FUNC profile_thread_run(switch_thread_t *thread, void *obj)
-{
-	sofia_profile_t *profile = (sofia_profile_t *) obj;
-	switch_memory_pool_t *pool;
-	sip_alias_node_t *node;
-	uint32_t ireg_loops = 0;
-	uint32_t oreg_loops = 0;
-	switch_core_db_t *db;
-	switch_event_t *s_event;
-
-	profile->s_root = su_root_create(NULL);
-	profile->home = su_home_new(sizeof(*profile->home));
-
-	profile->nua = nua_create(profile->s_root, /* Event loop */
-							  event_callback, /* Callback for processing events */
-							  profile, /* Additional data to pass to callback */
-							  NUTAG_URL(profile->bindurl),
-							  NTATAG_UDP_MTU(65536),
-							  TAG_END()); /* Last tag should always finish the sequence */
-
-	nua_set_params(profile->nua,
-				   //NUTAG_EARLY_MEDIA(1),				   
-				   NUTAG_AUTOANSWER(0),
-				   NUTAG_AUTOALERT(0),
-				   NUTAG_ALLOW("REGISTER"),
-				   NUTAG_ALLOW("REFER"),
-				   NUTAG_ALLOW("INFO"),
-				   TAG_IF((profile->pflags & PFLAG_PRESENCE), NUTAG_ALLOW("PUBLISH")),
-				   TAG_IF((profile->pflags & PFLAG_PRESENCE), NUTAG_ALLOW("NOTIFY")),
-				   TAG_IF((profile->pflags & PFLAG_PRESENCE), NUTAG_ALLOW("SUBSCRIBE")),
-				   TAG_IF((profile->pflags & PFLAG_PRESENCE), NUTAG_ENABLEMESSAGE(1)),
-				   TAG_IF((profile->pflags & PFLAG_PRESENCE), NUTAG_ALLOW_EVENTS("presence")),
-				   TAG_IF((profile->pflags & PFLAG_PRESENCE), NUTAG_ALLOW_EVENTS("presence.winfo")),
-				   SIPTAG_SUPPORTED_STR("100rel, precondition"),
-				   SIPTAG_USER_AGENT_STR(SOFIA_USER_AGENT),
-				   TAG_END());
-				   
-
-	for (node = profile->aliases; node; node = node->next) {
-		node->nua = nua_create(profile->s_root, /* Event loop */
-							   event_callback, /* Callback for processing events */
-							   profile, /* Additional data to pass to callback */
-							   NUTAG_URL(node->url),
-							   TAG_END()); /* Last tag should always finish the sequence */
-
-		nua_set_params(node->nua,
-				   NUTAG_EARLY_MEDIA(1),				   
-					   NUTAG_AUTOANSWER(0),
-					   NUTAG_AUTOALERT(0),
-					   NUTAG_ALLOW("REGISTER"),
-					   NUTAG_ALLOW("REFER"),
-					   NUTAG_ALLOW("INFO"),
-					   TAG_IF((profile->pflags & PFLAG_PRESENCE), NUTAG_ALLOW("PUBLISH")),
-					   TAG_IF((profile->pflags & PFLAG_PRESENCE), NUTAG_ENABLEMESSAGE(1)),
-					   SIPTAG_SUPPORTED_STR("100rel, precondition"),
-					   SIPTAG_USER_AGENT_STR(SOFIA_USER_AGENT),
-					   TAG_END());
-		
-	}
-
-
-	if ((db = switch_core_db_open_file(profile->dbname))) {
-		switch_core_db_test_reactive(db, "select contact from sip_registrations", reg_sql);
-		switch_core_db_test_reactive(db, "select contact from sip_subscriptions", sub_sql);
-		switch_core_db_test_reactive(db, "select * from sip_authentication", auth_sql);
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Cannot Open SQL Database!\n");
-		return NULL;
-	}
-
-
-	switch_mutex_init(&profile->ireg_mutex, SWITCH_MUTEX_NESTED, profile->pool);
-	switch_mutex_init(&profile->oreg_mutex, SWITCH_MUTEX_NESTED, profile->pool);
-
-	ireg_loops = IREG_SECONDS;
-	oreg_loops = OREG_SECONDS;
-
-	if (switch_event_create(&s_event, SWITCH_EVENT_PUBLISH) == SWITCH_STATUS_SUCCESS) {
-		switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "service", "_sip._udp");
-		switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "port", "%d", profile->sip_port);
-		switch_event_fire(&s_event);
-	}
-
-	if (switch_event_create(&s_event, SWITCH_EVENT_PUBLISH) == SWITCH_STATUS_SUCCESS) {
-		switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "service", "_sip._tcp");
-		switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "port", "%d", profile->sip_port);
-		switch_event_fire(&s_event);
-	}
-
-	if (switch_event_create(&s_event, SWITCH_EVENT_PUBLISH) == SWITCH_STATUS_SUCCESS) {
-		switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "service", "_sip._sctp");
-		switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "port", "%d", profile->sip_port);
-		switch_event_fire(&s_event);
-	}
-
-
-	switch_mutex_lock(globals.hash_mutex);
-	switch_core_hash_insert(globals.profile_hash, profile->name, profile);
-	switch_mutex_unlock(globals.hash_mutex);
-
-	if (profile->pflags & PFLAG_PRESENCE) {
-		establish_presence(profile);
-	}
 
+static switch_status_t sofia_waitfor_write(switch_core_session_t *session, int ms, int stream_id)
+{
+	private_object_t *tech_pvt;
+	switch_channel_t *channel = NULL;
 
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-	while(globals.running == 1) {
-		if (++ireg_loops >= IREG_SECONDS) {
-			check_expire(db, profile, time(NULL));
-			ireg_loops = 0;
-		}
+	return SWITCH_STATUS_SUCCESS;
 
-		if (++oreg_loops >= OREG_SECONDS) {
-			check_oreg(profile, time(NULL));
-			oreg_loops = 0;
-		}
+}
 
-		su_root_step(profile->s_root, 1000);
-	}
+static switch_status_t sofia_send_dtmf(switch_core_session_t *session, char *digits)
+{
+	private_object_t *tech_pvt;
 
-	switch_core_db_close(db);
-	unreg(profile);
-	su_home_unref(profile->home);
-	
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-	if (switch_event_create(&s_event, SWITCH_EVENT_UNPUBLISH) == SWITCH_STATUS_SUCCESS) {
-		switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "service", "_sip._udp");
-		switch_event_add_header(s_event, SWITCH_STACK_BOTTOM, "port", "%d", profile->sip_port);
-		switch_event_fire(&s_event);
-	}
+	return switch_rtp_queue_rfc2833(tech_pvt->rtp_session,
+									digits, tech_pvt->profile->dtmf_duration * (tech_pvt->read_codec.implementation->samples_per_second / 1000));
 
-	su_root_destroy(profile->s_root);
-	pool = profile->pool;
-	switch_core_destroy_memory_pool(&pool);
-	switch_mutex_lock(globals.mutex);
-	globals.running = 0;
-	switch_mutex_unlock(globals.mutex);
-	
-	return NULL;
 }
 
-static void launch_profile_thread(sofia_profile_t *profile)
+static switch_status_t sofia_receive_message(switch_core_session_t *session, switch_core_session_message_t *msg)
 {
-	switch_thread_t *thread;
-	switch_threadattr_t *thd_attr = NULL;
-	
-	switch_threadattr_create(&thd_attr, profile->pool);
-	switch_threadattr_detach_set(thd_attr, 1);
-	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-	switch_thread_create(&thread, thd_attr, profile_thread_run, profile, profile->pool);
-}
+	switch_channel_t *channel;
+	private_object_t *tech_pvt;
+	switch_status_t status;
 
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
+	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
-static switch_status_t config_sofia(int reload)
-{
-	char *cf = "sofia.conf";
-	switch_xml_t cfg, xml = NULL, xprofile, param, settings, profiles, registration, registrations;
-	switch_status_t status = SWITCH_STATUS_SUCCESS;
-	sofia_profile_t *profile = NULL;
-	char url[512] = "";
-	char bindurl[512] ="";
-	switch_mutex_lock(globals.mutex);
-	globals.running = 1;
-	switch_mutex_unlock(globals.mutex);
-
-	if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", cf);
-		status = SWITCH_STATUS_FALSE;
-		goto done;
-	}
 
-	if ((settings = switch_xml_child(cfg, "global_settings"))) {
-		for (param = switch_xml_child(settings, "param"); param; param = param->next) {
-			char *var = (char *) switch_xml_attr_soft(param, "name");
-			char *val = (char *) switch_xml_attr_soft(param, "value");
-			if (!strcasecmp(var, "log-level")) {
-				su_log_set_level(NULL, atoi(val));
-			} else if (!strcasecmp(var, "log-level-trace")) {
-				su_log_set_level(tport_log, atoi(val));
+	switch (msg->message_id) {
+	case SWITCH_MESSAGE_INDICATE_NOMEDIA:{
+			char *uuid;
+			switch_core_session_t *other_session;
+			switch_channel_t *other_channel;
+			char *ip = NULL, *port = NULL;
+
+			switch_set_flag_locked(tech_pvt, TFLAG_NOMEDIA);
+			tech_pvt->local_sdp_str = NULL;
+			if ((uuid = switch_channel_get_variable(channel, SWITCH_SIGNAL_BOND_VARIABLE))
+				&& (other_session = switch_core_session_locate(uuid))) {
+				other_channel = switch_core_session_get_channel(other_session);
+				ip = switch_channel_get_variable(other_channel, SWITCH_REMOTE_MEDIA_IP_VARIABLE);
+				port = switch_channel_get_variable(other_channel, SWITCH_REMOTE_MEDIA_PORT_VARIABLE);
+				switch_core_session_rwunlock(other_session);
+				if (ip && port) {
+					sofia_glue_set_local_sdp(tech_pvt, ip, atoi(port), NULL, 1);
+				}
+			}
+			if (!tech_pvt->local_sdp_str) {
+				sofia_glue_tech_absorb_sdp(tech_pvt);
+			}
+			sofia_glue_do_invite(session);
+		}
+		break;
+	case SWITCH_MESSAGE_INDICATE_MEDIA:{
+			switch_clear_flag_locked(tech_pvt, TFLAG_NOMEDIA);
+			tech_pvt->local_sdp_str = NULL;
+			if (!switch_rtp_ready(tech_pvt->rtp_session)) {
+				sofia_glue_tech_prepare_codecs(tech_pvt);
+				if ((status = sofia_glue_tech_choose_port(tech_pvt)) != SWITCH_STATUS_SUCCESS) {
+					switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					return status;
+				}
+			}
+			sofia_glue_set_local_sdp(tech_pvt, NULL, 0, NULL, 1);
+			sofia_glue_do_invite(session);
+			while (!switch_rtp_ready(tech_pvt->rtp_session) && switch_channel_get_state(channel) < CS_HANGUP) {
+				switch_yield(1000);
 			}
 		}
-	}
+		break;
 
-	if ((profiles = switch_xml_child(cfg, "profiles"))) {
-		for (xprofile = switch_xml_child(profiles, "profile"); xprofile; xprofile = xprofile->next) {
-			if (!(settings = switch_xml_child(xprofile, "settings"))) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No Settings, check the new config!\n", cf);
-			} else {
-				char *xprofilename = (char *) switch_xml_attr_soft(xprofile, "name");
-				switch_memory_pool_t *pool = NULL;
+	case SWITCH_MESSAGE_INDICATE_HOLD:{
+			switch_set_flag_locked(tech_pvt, TFLAG_SIP_HOLD);
+			sofia_glue_do_invite(session);
+		}
+		break;
 
-				
-				/* Setup the pool */
-				if ((status = switch_core_new_memory_pool(&pool)) != SWITCH_STATUS_SUCCESS) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-					goto done;
-				}
+	case SWITCH_MESSAGE_INDICATE_UNHOLD:{
+			switch_clear_flag_locked(tech_pvt, TFLAG_SIP_HOLD);
+			sofia_glue_do_invite(session);
+		}
+		break;
+	case SWITCH_MESSAGE_INDICATE_BRIDGE:
 
-				if (!(profile = (sofia_profile_t *) switch_core_alloc(pool, sizeof(*profile)))) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n");
-					goto done;
-				}
+		if (switch_test_flag(tech_pvt, TFLAG_XFER)) {
+			switch_clear_flag_locked(tech_pvt, TFLAG_XFER);
+			if (msg->pointer_arg) {
+				switch_core_session_t *a_session, *b_session = msg->pointer_arg;
 
-				if (!xprofilename) {
-					xprofilename = "unnamed";
-				}
-		
-				profile->pool = pool;
+				if ((a_session = switch_core_session_locate(tech_pvt->xferto))) {
+					private_object_t *a_tech_pvt = switch_core_session_get_private(a_session);
+					private_object_t *b_tech_pvt = switch_core_session_get_private(b_session);
 
-				profile->name = switch_core_strdup(profile->pool, xprofilename);
-				snprintf(url, sizeof(url), "sofia_reg_%s", xprofilename);
-				profile->dbname = switch_core_strdup(profile->pool, url);
-				switch_core_hash_init(&profile->chat_hash, profile->pool);
-
-				profile->dtmf_duration = 100;		
-				profile->codec_ms = 20;
-
-				for (param = switch_xml_child(settings, "param"); param; param = param->next) {
-					char *var = (char *) switch_xml_attr_soft(param, "name");
-					char *val = (char *) switch_xml_attr_soft(param, "value");
-
-					if (!strcasecmp(var, "debug")) {
-						profile->debug = atoi(val);
-					} else if (!strcasecmp(var, "use-rtp-timer") && switch_true(val)) {
-						switch_set_flag(profile, TFLAG_TIMER);
-					} else if (!strcasecmp(var, "inbound-no-media") && switch_true(val)) {
-						switch_set_flag(profile, TFLAG_INB_NOMEDIA);
-					} else if (!strcasecmp(var, "inbound-late-negotiation") && switch_true(val)) {
-						switch_set_flag(profile, TFLAG_LATE_NEGOTIATION);
-					} else if (!strcasecmp(var, "rfc2833-pt")) {
-						profile->te = (switch_payload_t) atoi(val);
-					} else if (!strcasecmp(var, "sip-port")) {
-						profile->sip_port = atoi(val);
-					} else if (!strcasecmp(var, "vad")) {
-						if (!strcasecmp(val, "in")) {
-							switch_set_flag(profile, TFLAG_VAD_IN);
-						} else if (!strcasecmp(val, "out")) {
-							switch_set_flag(profile, TFLAG_VAD_OUT);
-						} else if (!strcasecmp(val, "both")) {
-							switch_set_flag(profile, TFLAG_VAD_IN);
-							switch_set_flag(profile, TFLAG_VAD_OUT);
-						} else {
-							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invald option %s for VAD\n", val);
-						}
-					} else if (!strcasecmp(var, "ext-rtp-ip")) {
-						profile->extrtpip = switch_core_strdup(profile->pool, strcasecmp(val, "auto") ? val : globals.guess_ip);
-					} else if (!strcasecmp(var, "rtp-ip")) {
-						profile->rtpip = switch_core_strdup(profile->pool, strcasecmp(val, "auto") ? val : globals.guess_ip);
-					} else if (!strcasecmp(var, "sip-ip")) {
-						profile->sipip = switch_core_strdup(profile->pool, strcasecmp(val, "auto") ? val : globals.guess_ip);
-					} else if (!strcasecmp(var, "sip-domain")) {
-						profile->sipdomain = switch_core_strdup(profile->pool, val);
-					} else if (!strcasecmp(var, "rtp-timer-name")) {
-						profile->timer_name = switch_core_strdup(profile->pool, val);
-					} else if (!strcasecmp(var, "manage-presence")) {
-						if (switch_true(val)) {
-							profile->pflags |= PFLAG_PRESENCE;
-						}
-					} else if (!strcasecmp(var, "pass-rfc2833")) {
-						if (switch_true(val)) {
-							profile->pflags |= PFLAG_PASS_RFC2833;
-						}
-					} else if (!strcasecmp(var, "disable-transcoding")) {
-						if (switch_true(val)) {
-							profile->pflags |= PFLAG_DISABLE_TRANSCODING;
-						}
-					} else if (!strcasecmp(var, "auth-calls")) {
-						if (switch_true(val)) {
-							profile->pflags |= PFLAG_AUTH_CALLS;
-						}
-					} else if (!strcasecmp(var, "nonce-ttl")) {
-                        profile->nonce_ttl = atoi(val);
-					} else if (!strcasecmp(var, "accept-blind-reg")) {
-						if (switch_true(val)) {
-							profile->pflags |= PFLAG_BLIND_REG;
-						}
-					} else if (!strcasecmp(var, "auth-all-packets")) {
-						if (switch_true(val)) {
-							profile->pflags |= PFLAG_AUTH_ALL;
-						}
-					} else if (!strcasecmp(var, "full-id-in-dialplan")) {
-						if (switch_true(val)) {
-							profile->pflags |= PFLAG_FULL_ID;
-						}
-					} else if (!strcasecmp(var, "ext-sip-ip")) {
-						profile->extsipip = switch_core_strdup(profile->pool, strcasecmp(val, "auto") ? val : globals.guess_ip);
-					} else if (!strcasecmp(var, "bitpacking")) {
-						if (!strcasecmp(val, "aal2")) {
-							profile->codec_flags = SWITCH_CODEC_FLAG_AAL2;
-						} 
-					} else if (!strcasecmp(var, "username")) {
-						profile->username = switch_core_strdup(profile->pool, val);
-					} else if (!strcasecmp(var, "context")) {
-						profile->context = switch_core_strdup(profile->pool, val);
-					} else if (!strcasecmp(var, "alias")) {
-						sip_alias_node_t *node;
-						if ((node = switch_core_alloc(profile->pool, sizeof(*node)))) {
-							if ((node->url = switch_core_strdup(profile->pool, val))) {
-								node->next = profile->aliases;
-								profile->aliases = node;
-							}
-						}
-					} else if (!strcasecmp(var, "dialplan")) {
-						profile->dialplan = switch_core_strdup(profile->pool, val);
-					} else if (!strcasecmp(var, "max-calls")) {
-						profile->max_calls = atoi(val);
-					} else if (!strcasecmp(var, "codec-prefs")) {
-						profile->codec_string = switch_core_strdup(profile->pool, val);
-					} else if (!strcasecmp(var, "codec-ms")) {
-						profile->codec_ms = atoi(val);
-					} else if (!strcasecmp(var, "dtmf-duration")) {
-						int dur = atoi(val);
-						if (dur > 10 && dur < 8000) {
-							profile->dtmf_duration = dur;
-						} else {
-							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Duration out of bounds!\n");
-						}
+					switch_set_flag_locked(a_tech_pvt, TFLAG_REINVITE);
+					a_tech_pvt->remote_sdp_audio_ip = switch_core_session_strdup(a_session, b_tech_pvt->remote_sdp_audio_ip);
+					a_tech_pvt->remote_sdp_audio_port = b_tech_pvt->remote_sdp_audio_port;
+					a_tech_pvt->local_sdp_audio_ip = switch_core_session_strdup(a_session, b_tech_pvt->local_sdp_audio_ip);
+					a_tech_pvt->local_sdp_audio_port = b_tech_pvt->local_sdp_audio_port;
+					if (sofia_glue_activate_rtp(a_tech_pvt) != SWITCH_STATUS_SUCCESS) {
+						switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 					}
+					b_tech_pvt->kick = switch_core_session_strdup(b_session, tech_pvt->xferto);
+					switch_core_session_rwunlock(a_session);
 				}
 
-                if (!profile->sipip) {
-                    profile->sipip = switch_core_strdup(profile->pool, globals.guess_ip);
-                }
-
-                if (!profile->rtpip) {
-                    profile->rtpip = switch_core_strdup(profile->pool, globals.guess_ip);
-                }
-
-                if (profile->nonce_ttl < 60) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Setting nonce TTL to 60 seconds\n");
-                    profile->nonce_ttl = 60;
-                }
-
-				if (switch_test_flag(profile, TFLAG_TIMER) && !profile->timer_name) {
-					profile->timer_name = switch_core_strdup(profile->pool, "soft");			
-				}
-
-				if (!profile->username) {
-					profile->username = switch_core_strdup(profile->pool, "FreeSWITCH");
-				}
 
-				if (!profile->rtpip) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Setting ip to '127.0.0.1'\n");
-					profile->rtpip = switch_core_strdup(profile->pool, "127.0.0.1");
-				}
+				msg->pointer_arg = NULL;
+				return SWITCH_STATUS_FALSE;
+			}
+		}
+		if (tech_pvt->rtp_session && switch_test_flag(tech_pvt, TFLAG_TIMER)) {
+			switch_rtp_clear_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_USE_TIMER);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "De-activate timed RTP!\n");
+		}
+		break;
+	case SWITCH_MESSAGE_INDICATE_UNBRIDGE:
+		if (tech_pvt->rtp_session && switch_test_flag(tech_pvt, TFLAG_TIMER)) {
+			switch_rtp_set_flag(tech_pvt->rtp_session, SWITCH_RTP_FLAG_USE_TIMER);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Re-activate timed RTP!\n");
+		}
+		break;
+	case SWITCH_MESSAGE_INDICATE_REDIRECT:
+		if (msg->string_arg) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Re-directing to %s\n", msg->string_arg);
+			nua_respond(tech_pvt->nh, SIP_302_MOVED_TEMPORARILY, SIPTAG_CONTACT_STR(msg->string_arg), TAG_END());
+		}
+		break;
+	case SWITCH_MESSAGE_INDICATE_REJECT:
+		if (msg->string_arg) {
+			int code = 0;
+			char *reason;
+			
+			if (switch_channel_test_flag(channel, CF_ANSWERED)) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Call is already answered, Rejecting with hangup\n");
+				switch_channel_hangup(channel, SWITCH_CAUSE_CALL_REJECTED);
+			} else {
 
-				if (!profile->sip_port) {
-					profile->sip_port = 5060;
+				if ((reason = strchr(msg->string_arg, ' '))) {
+					reason++;
+					code = atoi(msg->string_arg);
+				} else {
+					reason = "Call Refused";
 				}
 
-				if (!profile->dialplan) {
-					profile->dialplan = switch_core_strdup(profile->pool, "XML");
+				if (!(code > 400 && code < 600)) {
+					code = 488;
 				}
 
-				if (!profile->sipdomain) {
-					profile->sipdomain = switch_core_strdup(profile->pool, profile->sipip);
-				}
-				if (profile->extsipip) {
-					snprintf(url, sizeof(url), "sip:mod_sofia@%s:%d", profile->extsipip, profile->sip_port);
-					snprintf(bindurl, sizeof(url), "sip:mod_sofia@%s:%d", profile->sipip, profile->sip_port);
-					profile->url = switch_core_strdup(profile->pool, url);
-					profile->bindurl = switch_core_strdup(profile->pool, bindurl);
-				} else {
-					snprintf(url, sizeof(url), "sip:mod_sofia@%s:%d", profile->sipip, profile->sip_port);
-					profile->url = switch_core_strdup(profile->pool, url);
-					profile->bindurl = profile->url;
-				}
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Rejecting with %d %s\n", code, reason);
+				nua_respond(tech_pvt->nh, code, reason, TAG_END());
 			}
-			if (profile) {
-				if ((registrations = switch_xml_child(xprofile, "registrations"))) {
-					for (registration = switch_xml_child(registrations, "registration"); registration; registration = registration->next) {
-						char *name = (char *) switch_xml_attr_soft(registration, "name");
-						outbound_reg_t *oreg;
-
-						if (switch_strlen_zero(name)) {
-							name = "anonymous";
-						}
-
-						if ((oreg = switch_core_alloc(profile->pool, sizeof(*oreg)))) {
-							oreg->pool = profile->pool;
-							oreg->profile = profile;
-							oreg->name = switch_core_strdup(oreg->pool, name);
-							oreg->freq = 0;
-
-							for (param = switch_xml_child(registration, "param"); param; param = param->next) {
-								char *var = (char *) switch_xml_attr_soft(param, "name");
-								char *val = (char *) switch_xml_attr_soft(param, "value");
-								
-								if (!strcmp(var, "register-scheme")) {
-									oreg->register_scheme = switch_core_strdup(oreg->pool, val);
-								} else if (!strcmp(var, "register-realm")) {
-									oreg->register_realm = switch_core_strdup(oreg->pool, val);
-								} else if (!strcmp(var, "register-username")) {
-									oreg->register_username = switch_core_strdup(oreg->pool, val);
-								} else if (!strcmp(var, "register-password")) {
-									oreg->register_password = switch_core_strdup(oreg->pool, val);
-								} else if (!strcmp(var, "register-from")) {
-									oreg->register_from = switch_core_strdup(oreg->pool, val);
-								} else if (!strcmp(var, "register-to")) {
-									oreg->register_to = switch_core_strdup(oreg->pool, val);
-								} else if (!strcmp(var, "register-proxy")) {
-									oreg->register_proxy = switch_core_strdup(oreg->pool, val);
-								} else if (!strcmp(var, "register-frequency")) {
-									oreg->expires_str = switch_core_strdup(oreg->pool, val);
-								}
-							}
-							if (switch_strlen_zero(oreg->register_scheme)) {
-								oreg->register_scheme = switch_core_strdup(oreg->pool, "Digest");
-							}
-							if (switch_strlen_zero(oreg->register_realm)) {
-								oreg->register_realm = switch_core_strdup(oreg->pool, "freeswitch.org");
-							}
-							if (switch_strlen_zero(oreg->register_username)) {
-								oreg->register_username = switch_core_strdup(oreg->pool, "freeswitch");
-							}
-							if (switch_strlen_zero(oreg->register_password)) {
-								oreg->register_password = switch_core_strdup(oreg->pool, "works");
-							}							
-							if (switch_strlen_zero(oreg->register_from)) {
-								oreg->register_from = switch_core_strdup(oreg->pool, "FreeSWITCH <sip:freeswitch at freeswitch.org>");
-							}
-							if (switch_strlen_zero(oreg->register_to)) {
-								oreg->register_to = switch_core_strdup(oreg->pool, "sip:freeswitch at freeswitch.org");
-							}
-							if (switch_strlen_zero(oreg->register_proxy)) {
-								oreg->register_proxy = switch_core_strdup(oreg->pool, "sip:freeswitch at freeswitch.org");
-							}
-
-							if (switch_strlen_zero(oreg->expires_str)) {
-								oreg->expires_str = switch_core_strdup(oreg->pool, "300");
-							}
-
-							if ((oreg->freq = atoi(oreg->expires_str)) < 5) {
-                                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid Freq: %d.  Setting Register-Frequency to 5\n", oreg->freq);
-                                oreg->freq = 5;
-                            }
-                            oreg->freq -= 2;
-
-							oreg->next = profile->registrations;
-							profile->registrations = oreg;
+		}
+		break;
+	case SWITCH_MESSAGE_INDICATE_RINGING:
+		nua_respond(tech_pvt->nh, SIP_180_RINGING, SIPTAG_CONTACT_STR(tech_pvt->profile->url), TAG_END());
+		switch_channel_mark_ring_ready(channel);
+		break;
+	case SWITCH_MESSAGE_INDICATE_ANSWER:
+		sofia_answer_channel(session);
+		break;
+	case SWITCH_MESSAGE_INDICATE_PROGRESS:{
+			if (!switch_test_flag(tech_pvt, TFLAG_ANS)) {
+				
+				switch_set_flag_locked(tech_pvt, TFLAG_EARLY_MEDIA);
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Asked to send early media by %s\n", msg->from);
 
+				/* Transmit 183 Progress with SDP */
+				if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
+					char *sdp = NULL;
+					switch_set_flag_locked(tech_pvt, TFLAG_NOMEDIA);
+					if ((sdp = switch_channel_get_variable(channel, SWITCH_B_SDP_VARIABLE))) {
+						tech_pvt->local_sdp_str = switch_core_session_strdup(session, sdp);
+					}
+				} else {
+					if (switch_test_flag(tech_pvt, TFLAG_LATE_NEGOTIATION)) {
+						char *r_sdp = switch_channel_get_variable(channel, SWITCH_R_SDP_VARIABLE);
+						if (sofia_glue_tech_media(tech_pvt, r_sdp) != SWITCH_STATUS_SUCCESS) {
+							switch_channel_set_variable(channel, SWITCH_ENDPOINT_DISPOSITION_VARIABLE, "CODEC NEGOTIATION ERROR");
+							nua_respond(tech_pvt->nh, SIP_488_NOT_ACCEPTABLE, TAG_END());
+							return SWITCH_STATUS_FALSE;
 						}
+						switch_clear_flag_locked(tech_pvt, TFLAG_LATE_NEGOTIATION);
 					}
-				}
 
-				if (profile->sipip) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Started Profile %s [%s]\n", profile->name, url);
-					launch_profile_thread(profile);
-				} else {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Unable to start Profile %s due to no configured sip-ip\n", profile->name);
+					if ((status = sofia_glue_tech_choose_port(tech_pvt)) != SWITCH_STATUS_SUCCESS) {
+						switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+						return status;
+					}
+					sofia_glue_set_local_sdp(tech_pvt, NULL, 0, NULL, 0);
+					if (sofia_glue_activate_rtp(tech_pvt) != SWITCH_STATUS_SUCCESS) {
+						switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					}
+					if (tech_pvt->local_sdp_str) {
+						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Ring SDP:\n%s\n", tech_pvt->local_sdp_str);
+					}
 				}
-				profile = NULL;
+				switch_channel_mark_pre_answered(channel);
+				nua_respond(tech_pvt->nh,
+							SIP_183_SESSION_PROGRESS,
+							SIPTAG_CONTACT_STR(tech_pvt->profile->url),
+							SOATAG_USER_SDP_STR(tech_pvt->local_sdp_str), SOATAG_AUDIO_AUX("cn telephone-event"), TAG_END());
 			}
 		}
+		break;
+	default:
+		break;
 	}
- done:
-	if (xml) {
-		switch_xml_free(xml);
-	}
-
-	return status;
 
+	return SWITCH_STATUS_SUCCESS;
 }
 
-static void event_handler(switch_event_t *event)
+static switch_status_t sofia_receive_event(switch_core_session_t *session, switch_event_t *event)
 {
-	char *subclass, *sql;
-
-	if ((subclass = switch_event_get_header(event, "orig-event-subclass")) && !strcasecmp(subclass, MY_EVENT_REGISTER)) {
-		char *from_user = switch_event_get_header(event, "orig-from-user");
-		char *from_host = switch_event_get_header(event, "orig-from-host");
-		char *contact_str = switch_event_get_header(event, "orig-contact");
-		char *exp_str = switch_event_get_header(event, "orig-expires");
-		char *rpid = switch_event_get_header(event, "orig-rpid");
-		long expires = (long)time(NULL) + atol(exp_str);
-		char *profile_name = switch_event_get_header(event, "orig-profile-name");
-		sofia_profile_t *profile;
-		char buf[512];
+	switch_channel_t *channel;
+	struct private_object *tech_pvt;
+	char *body;
+	nua_handle_t *msg_nh;
 
-		if (!rpid) {
-			rpid = "unknown";
-		}
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-		if (!profile_name || !(profile = (sofia_profile_t *) switch_core_hash_find(globals.profile_hash, profile_name))) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Profile\n");
-			return;
-		}
+	tech_pvt = switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
 
 
-		if (!find_reg_url(profile, from_user, from_host, buf, sizeof(buf))) {
-			sql = switch_mprintf("insert into sip_registrations values ('%q','%q','%q','Regestered', '%q', %ld)", 
-								 from_user,
-								 from_host,
-								 contact_str,
-								 rpid,
-								 expires);
-		} else {
-			sql = switch_mprintf("update sip_registrations set contact='%q', rpid='%q', expires=%ld where user='%q' and host='%q'",
-								 contact_str,
-								 rpid,
-								 expires,
-								 from_user,
-								 from_host);
-			
-		}
-	
-		if (sql) {
-			execute_sql(profile->dbname, sql, profile->ireg_mutex);
-			switch_safe_free(sql);
-			sql = NULL;
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Propagating registration for %s@%s->%s\n", 
-							  from_user, from_host, contact_str);
+	if (!(body = switch_event_get_body(event))) {
+		body = "";
+	}
 
-		}
+	if (tech_pvt->hash_key) {
+		msg_nh = nua_handle(tech_pvt->profile->nua, NULL,
+							SIPTAG_FROM_STR(tech_pvt->chat_from),
+							NUTAG_URL(tech_pvt->chat_to), SIPTAG_TO_STR(tech_pvt->chat_to), SIPTAG_CONTACT_STR(tech_pvt->profile->url), TAG_END());
 
+		nua_message(msg_nh, SIPTAG_CONTENT_TYPE_STR("text/html"), SIPTAG_PAYLOAD_STR(body), TAG_END());
 	}
-}
-
 
-static switch_status_t chat_send(char *proto, char *from, char *to, char *subject, char *body, char *hint)
-{
-	char buf[256];
-	char *user, *host;
-	sofia_profile_t *profile;
-	char *ffrom = NULL;
-	nua_handle_t *msg_nh;
-	char *contact;
+	return SWITCH_STATUS_SUCCESS;
+}
 
-	if (to && (user = strdup(to))) {
-		if ((host = strchr(user, '@'))) {
-			*host++ = '\0';
-		}
-		
-		if (!host || !(profile = (sofia_profile_t *) switch_core_hash_find(globals.profile_hash, host))) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Chat proto [%s]\nfrom [%s]\nto [%s]\n%s\nInvalid Profile %s\n", 
-                              proto,
-                              from,
-                              to,
-                              body ? body : "[no body]",
-                              host ? host : "NULL");
-			return SWITCH_STATUS_FALSE;
-		}
+static const switch_io_routines_t sofia_io_routines = {
+	/*.outgoing_channel */ sofia_outgoing_channel,
+	/*.read_frame */ sofia_read_frame,
+	/*.write_frame */ sofia_write_frame,
+	/*.kill_channel */ sofia_kill_channel,
+	/*.waitfor_read */ sofia_waitfor_read,
+	/*.waitfor_read */ sofia_waitfor_write,
+	/*.send_dtmf */ sofia_send_dtmf,
+	/*.receive_message */ sofia_receive_message,
+	/*.receive_event */ sofia_receive_event,
+	/*.state_change*/ NULL,
+	/*.read_video_frame*/ sofia_read_video_frame,
+	/*.write_video_frame*/ sofia_write_video_frame
+};
 
-        if (!find_reg_url(profile, user, host, buf, sizeof(buf))) {
-			return SWITCH_STATUS_FALSE;
-		}
+static const switch_state_handler_table_t sofia_event_handlers = {
+	/*.on_init */ sofia_on_init,
+	/*.on_ring */ sofia_on_ring,
+	/*.on_execute */ sofia_on_execute,
+	/*.on_hangup */ sofia_on_hangup,
+	/*.on_loopback */ sofia_on_loopback,
+	/*.on_transmit */ sofia_on_transmit
+};
 
-		if (!strcmp(proto, SOFIA_CHAT_PROTO)) {
-			from = hint;
-		} else {
-			char *fp, *p, *fu = NULL;
+const switch_endpoint_interface_t sofia_endpoint_interface = {
+	/*.interface_name */ "sofia",
+	/*.io_routines */ &sofia_io_routines,
+	/*.event_handlers */ &sofia_event_handlers,
+	/*.private */ NULL,
+	/*.next */ NULL
+};
 
-			if (!(fp = strdup(from))) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-				return SWITCH_STATUS_FALSE;
-			}
+static const switch_chat_interface_t sofia_chat_interface = {
+	/*.name */ SOFIA_CHAT_PROTO,
+	/*.sofia_presence_chat_send */ sofia_presence_chat_send,
 
-			if ((p = strchr(fp, '@'))) {
-				*p = '\0';
-				fu = strdup(fp);
-				*p = '+';
-			}
-			
-			ffrom = switch_mprintf("\"%s\" <sip:%s+%s@%s>", fu, proto, fp, profile->name);			
-			from = ffrom;
-			switch_safe_free(fu);
-			switch_safe_free(fp);
-		}
+};
 
-		contact = get_url_from_contact(buf, 1);
-		msg_nh = nua_handle(profile->nua, NULL,
-							SIPTAG_FROM_STR(from),
-							NUTAG_URL(contact),
-							SIPTAG_TO_STR(buf), // if this cries, add contact here too, change the 1 to 0 and omit the safe_free
-							SIPTAG_CONTACT_STR(profile->url),
-							TAG_END());
-
-		switch_safe_free(contact);
-
-
-		nua_message(msg_nh,
-					SIPTAG_CONTENT_TYPE_STR("text/html"),
-					SIPTAG_PAYLOAD_STR(body),
-					TAG_END());
-		
-		
-		switch_safe_free(ffrom);
-		free(user);
-	}
-		
+static switch_status_t sofia_manage(char *relative_oid, switch_management_action_t action, char *data, switch_size_t datalen)
+{
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static void cancel_presence(void) 
-{
-	char *sql, *errmsg = NULL;
-	switch_core_db_t *db;
-	sofia_profile_t *profile;
-	switch_hash_index_t *hi;
-    void *val;
+static const switch_management_interface_t sofia_management_interface = {
+	/*.relative_oid */ "1",
+	/*.management_function */ sofia_manage
+};
 
-	if ((sql = switch_mprintf("select 0,'unavailable','unavailable',* from sip_subscriptions where event='presence'"))) {
-		for (hi = switch_hash_first(apr_hash_pool_get(globals.profile_hash), globals.profile_hash); hi; hi = switch_hash_next(hi)) {
-			switch_hash_this(hi, NULL, NULL, &val);
-			profile = (sofia_profile_t *) val;
-			if (!(profile->pflags & PFLAG_PRESENCE)) {
-				continue;
-			}
+static const switch_loadable_module_interface_t sofia_module_interface = {
+	/*.module_name */ modname,
+	/*.endpoint_interface */ &sofia_endpoint_interface,
+	/*.timer_interface */ NULL,
+	/*.dialplan_interface */ NULL,
+	/*.codec_interface */ NULL,
+	/*.application_interface */ NULL,
+	/*.api_interface */ NULL,
+	/*.file_interface */ NULL,
+	/*.speech_interface */ NULL,
+	/*.directory_interface */ NULL,
+	/*.chat_interface */ &sofia_chat_interface,
+	/*.say_interface */ NULL,
+	/*.asr_interface */ NULL,
+	/*.management_interface */ &sofia_management_interface
+};
 
-			if (!(db = switch_core_db_open_file(profile->dbname))) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-				continue;
-			}
-			switch_mutex_lock(profile->ireg_mutex);
-			switch_core_db_exec(db, sql, sub_callback, profile, &errmsg);
-			switch_mutex_unlock(profile->ireg_mutex);
-			switch_core_db_close(db);
-		}
-		switch_safe_free(sql);
-	}
 
-}
 
-static void establish_presence(sofia_profile_t *profile) 
+static switch_call_cause_t sofia_outgoing_channel(switch_core_session_t *session,
+												  switch_caller_profile_t *outbound_profile, switch_core_session_t **new_session,
+												  switch_memory_pool_t **pool)
 {
-	char *sql, *errmsg = NULL;
-	switch_core_db_t *db;
-
-	if (!(db = switch_core_db_open_file(profile->dbname))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-		return;
-	}
+	switch_call_cause_t cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+	switch_core_session_t *nsession;
+	char *data, *profile_name, *dest;
+	sofia_profile_t *profile;
+	switch_caller_profile_t *caller_profile = NULL;
+	private_object_t *tech_pvt = NULL;
+	switch_channel_t *nchannel;
+	char *host, *dest_to;
 
-	if ((sql = switch_mprintf("select user,host,'Registered','unknown','' from sip_registrations"))) {
-		switch_mutex_lock(profile->ireg_mutex);
-		switch_core_db_exec(db, sql, resub_callback, profile, &errmsg);
-		switch_mutex_unlock(profile->ireg_mutex);
-		switch_safe_free(sql);
-	}
+	*new_session = NULL;
 
-	if ((sql = switch_mprintf("select sub_to_user,sub_to_host,'Online','unknown',proto from sip_subscriptions "
-							  "where proto='ext' or proto='user' or proto='conf'"))) {
-		switch_mutex_lock(profile->ireg_mutex);
-		switch_core_db_exec(db, sql, resub_callback, profile, &errmsg);
-		switch_mutex_unlock(profile->ireg_mutex);
-		switch_safe_free(sql);
+	if (!(nsession = switch_core_session_request(&sofia_endpoint_interface, pool))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Error Creating Session\n");
+		goto done;
 	}
 
-	switch_core_db_close(db);
-
-}
-
-
-
-static char *translate_rpid(char *in, char *ext)
-{
-	char *r = NULL;
-
-	if (in && (strstr(in, "null") || strstr(in, "NULL"))) {
-		in = NULL;
+	if (!(tech_pvt = (struct private_object *) switch_core_session_alloc(nsession, sizeof(*tech_pvt)))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Error Creating Session\n");
+		switch_core_session_destroy(&nsession);
+		goto done;
 	}
+	switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(nsession));
 
-	if (!in) {
-		in = ext;
-	}
+	data = switch_core_session_strdup(nsession, outbound_profile->destination_number);
+	profile_name = data;
 
-	if (!in) {
-		return NULL;
-	}
-	
-	if (!strcasecmp(in, "dnd")) {
-		r = "busy";
-	}
+	if (!strncasecmp(profile_name, "gateway", 7)) {
+		char *gw;
+		outbound_reg_t *gateway_ptr;
+
+		if (!(gw = strchr(profile_name, '/'))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid URL\n");
+			switch_core_session_destroy(&nsession);
+			cause = SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
+			goto done;
+		}
 
-	if (ext && !strcasecmp(ext, "away")) {
-		r = "idle";
-	}
-	
-	return r;
-}
+		*gw++ = '\0';
 
-static void pres_event_handler(switch_event_t *event)
-{
-	sofia_profile_t *profile;
-	switch_hash_index_t *hi;
-    void *val;
-	char *from = switch_event_get_header(event, "from");
-	char *proto = switch_event_get_header(event, "proto");
-	char *rpid = switch_event_get_header(event, "rpid");
-	char *status= switch_event_get_header(event, "status");
-	char *event_type = switch_event_get_header(event, "event_type");
-	//char *event_subtype = switch_event_get_header(event, "event_subtype");
-	char *sql = NULL;
-	char *euser = NULL, *user = NULL, *host = NULL;
-	char *errmsg;
-	switch_core_db_t *db;
-
-
-	if (rpid && !strcasecmp(rpid, "n/a")) {
-		rpid = NULL;
-	}
-
-	if (status && !strcasecmp(status, "n/a")) {
-		status = NULL;
-	}
-
-	if (rpid) {
-		rpid = translate_rpid(rpid, status);
-	} 
-
-	if (!status) {
-		status = "Available";
-
-		if (rpid) {
-			if (!strcasecmp(rpid, "busy")) {
-				status = "Busy";
-			} else if (!strcasecmp(rpid, "unavailable")) {
-				status = "Idle";
-			} else if (!strcasecmp(rpid, "away")) {
-				status = "Idle";
-			}
+		if (!(dest = strchr(gw, '/'))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid URL\n");
+			switch_core_session_destroy(&nsession);
+			cause = SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
+			goto done;
 		}
-	}
 
-	if (!rpid) {
-		rpid = "unknown";
-	}
+		*dest++ = '\0';
 
-	if (event->event_id == SWITCH_EVENT_ROSTER) {
+		if (!(gateway_ptr = sofia_reg_find_gateway(gw))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Gateway\n");
+			switch_core_session_destroy(&nsession);
+			cause = SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
+			goto done;
+		}
 
-		if (from) {
-			sql = switch_mprintf("select 1,'%q','%q',* from sip_subscriptions where event='presence' and full_from like '%%%q%%'", status, rpid, from);
+		profile = gateway_ptr->profile;
+		if (!switch_test_flag(gateway_ptr, REG_FLAG_CALLERID)) {
+			tech_pvt->gateway_from_str = switch_core_session_strdup(nsession, gateway_ptr->register_from);
+		}
+		if (!strchr(dest, '@')) {
+			tech_pvt->dest = switch_core_session_sprintf(nsession, "sip:%s@%s", dest, gateway_ptr->register_proxy + 4);
 		} else {
-			sql = switch_mprintf("select 1,'%q','%q',* from sip_subscriptions where event='presence'", status, rpid);
+			tech_pvt->dest = switch_core_session_sprintf(nsession, "sip:%s", dest);
 		}
+		tech_pvt->invite_contact = switch_core_session_strdup(nsession, gateway_ptr->register_contact);
+	} else {
+		if (!(dest = strchr(profile_name, '/'))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid URL\n");
+			switch_core_session_destroy(&nsession);
+			cause = SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
+			goto done;
+		}
+		*dest++ = '\0';
 
-		for (hi = switch_hash_first(apr_hash_pool_get(globals.profile_hash), globals.profile_hash); hi; hi = switch_hash_next(hi)) {
-			switch_hash_this(hi, NULL, NULL, &val);
-			profile = (sofia_profile_t *) val;
-			if (!(profile->pflags & PFLAG_PRESENCE)) {
-				continue;
-			}
-
-			if (sql) {
-				if (!(db = switch_core_db_open_file(profile->dbname))) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-					continue;
-				}
-				switch_mutex_lock(profile->ireg_mutex);
-				switch_core_db_exec(db, sql, sub_callback, profile, &errmsg);
-				switch_mutex_unlock(profile->ireg_mutex);
-				switch_core_db_close(db);
-			}
+		if (!(profile = sofia_glue_find_profile(profile_name))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Profile\n");
+			switch_core_session_destroy(&nsession);
+			cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+			goto done;
+		}
 
+		if ((dest_to = strchr(dest, '^'))) {
+			*dest_to++ = '\0';
+			tech_pvt->dest_to = switch_core_session_alloc(nsession, strlen(dest_to) + 5);
+			snprintf(tech_pvt->dest_to, strlen(dest_to) + 5, "sip:%s", dest_to);
 		}
 
-		return;
-	}
+		if ((host = strchr(dest, '%'))) {
+			char buf[128];
+			*host = '@';
+			tech_pvt->e_dest = switch_core_session_strdup(nsession, dest);
+			*host++ = '\0';
+			if (sofia_reg_find_reg_url(profile, dest, host, buf, sizeof(buf))) {
+				tech_pvt->dest = switch_core_session_strdup(nsession, buf);
 
-	if (switch_strlen_zero(event_type)) {
-		event_type="presence";
-	}
+			} else {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Cannot locate registered user %s@%s\n", dest, host);
+				cause = SWITCH_CAUSE_NO_ROUTE_DESTINATION;
+				switch_core_session_destroy(&nsession);
+				goto done;
+			}
+		} else if (!strchr(dest, '@')) {
+			char buf[128];
+			tech_pvt->e_dest = switch_core_session_strdup(nsession, dest);
+			if (sofia_reg_find_reg_url(profile, dest, profile_name, buf, sizeof(buf))) {
+				tech_pvt->dest = switch_core_session_strdup(nsession, buf);
 
-	if ((user = strdup(from))) {
-		if ((host = strchr(user, '@'))) {
-			char *p;
-			*host++ = '\0';
-			if ((p = strchr(host, '/'))) {
-				*p = '\0';
+			} else {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Cannot locate registered user %s@%s\n", dest, profile_name);
+				cause = SWITCH_CAUSE_NO_ROUTE_DESTINATION;
+				switch_core_session_destroy(&nsession);
+				goto done;
 			}
 		} else {
-			switch_safe_free(user);
-			return;
-		}
-		if ((euser = strchr(user, '+'))) {
-			euser++;
-		} else {
-			euser = user;
+			tech_pvt->dest = switch_core_session_alloc(nsession, strlen(dest) + 5);
+			snprintf(tech_pvt->dest, strlen(dest) + 5, "sip:%s", dest);
 		}
-		
-	} else {
-		return;
 	}
 
-
-	switch(event->event_id) {
-    case SWITCH_EVENT_PRESENCE_PROBE: 
-        if (proto) {
-            switch_core_db_t *db = NULL;
-            char *to = switch_event_get_header(event, "to");
-            char *user, *euser, *host, *p;
-
-            if (!to || !(user = strdup(to))) {
-                return;
-            }
-
-            if ((host = strchr(user, '@'))) {
-                *host++ = '\0';
-            }
-            euser = user;
-            if ((p = strchr(euser, '+'))) {
-                euser = (p+1);
-            }
-
-            if (euser && host && 
-                (sql = switch_mprintf("select user,host,status,rpid,'' from sip_registrations where user='%q' and host='%q'", euser, host)) &&
-                (profile = (sofia_profile_t *) switch_core_hash_find(globals.profile_hash, host))) {
-                if (!(db = switch_core_db_open_file(profile->dbname))) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-                    switch_safe_free(user);
-                    switch_safe_free(sql);
-                    return;
-                }
-
-                switch_mutex_lock(profile->ireg_mutex);
-                switch_core_db_exec(db, sql, resub_callback, profile, &errmsg);
-                switch_mutex_unlock(profile->ireg_mutex);
-                switch_safe_free(sql);
-            }
-            switch_safe_free(user);
-            switch_core_db_close(db);
-        }
-        return;
-	case SWITCH_EVENT_PRESENCE_IN:
-		sql = switch_mprintf("select 1,'%q','%q',* from sip_subscriptions where proto='%q' and event='%q' and sub_to_user='%q' and sub_to_host='%q'", 
-							 status , rpid, proto, event_type, euser, host);
-		break;
-	case SWITCH_EVENT_PRESENCE_OUT:
-		sql = switch_mprintf("select 0,'%q','%q',* from sip_subscriptions where proto='%q' and event='%q' and sub_to_user='%q' and sub_to_host='%q'", 
-							 status, rpid, proto, event_type, euser, host);
-		break;
-	default:
-		break;
+	if (!tech_pvt->dest_to) {
+		tech_pvt->dest_to = tech_pvt->dest;
 	}
 
-    for (hi = switch_hash_first(apr_hash_pool_get(globals.profile_hash), globals.profile_hash); hi; hi = switch_hash_next(hi)) {
-        switch_hash_this(hi, NULL, NULL, &val);
-        profile = (sofia_profile_t *) val;
-        if (!(profile->pflags & PFLAG_PRESENCE)) {
-			continue;
-        }
-
-		if (sql) {
-			if (!(db = switch_core_db_open_file(profile->dbname))) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB %s\n", profile->dbname);
-				continue;
-			}
-			switch_mutex_lock(profile->ireg_mutex);
-			switch_core_db_exec(db, sql, sub_callback, profile, &errmsg);
-			switch_mutex_unlock(profile->ireg_mutex);
-			
-			switch_core_db_close(db);
+	sofia_glue_attach_private(nsession, profile, tech_pvt, dest);
+
+	nchannel = switch_core_session_get_channel(nsession);
+	caller_profile = switch_caller_profile_clone(nsession, outbound_profile);
+	switch_channel_set_caller_profile(nchannel, caller_profile);
+	switch_channel_set_flag(nchannel, CF_OUTBOUND);
+	switch_set_flag_locked(tech_pvt, TFLAG_OUTBOUND);
+	switch_channel_set_state(nchannel, CS_INIT);
+	*new_session = nsession;
+	cause = SWITCH_CAUSE_SUCCESS;
+	if (session) {
+		//char *val;
+		//switch_channel_t *channel = switch_core_session_get_channel(session);
+		switch_ivr_transfer_variable(session, nsession, SOFIA_REPLACES_HEADER);
+		switch_ivr_transfer_variable(session, nsession, SOFIA_SIP_HEADER_PREFIX_T);
+		if (switch_core_session_compare(session, nsession)) {
+			/* It's another sofia channel! so lets cache what they use as a pt for telephone event so 
+			   we can keep it the same
+			 */
+			private_object_t *ctech_pvt;
+			ctech_pvt = switch_core_session_get_private(session);
+			assert(ctech_pvt != NULL);
+			tech_pvt->bte = ctech_pvt->te;
+			tech_pvt->bcng_pt = ctech_pvt->cng_pt;
 		}
 	}
 
-	switch_safe_free(sql);
-	switch_safe_free(user);
+  done:
+	return cause;
 }
 
-
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
 
@@ -5788,42 +1119,54 @@
 		return SWITCH_STATUS_TERM;
 	}
 
-	memset(&globals, 0, sizeof(globals));
-	switch_mutex_init(&globals.mutex, SWITCH_MUTEX_NESTED, module_pool);
+	memset(&mod_sofia_globals, 0, sizeof(mod_sofia_globals));
+	switch_mutex_init(&mod_sofia_globals.mutex, SWITCH_MUTEX_NESTED, module_pool);
 
-    switch_find_local_ip(globals.guess_ip, sizeof(globals.guess_ip), AF_INET);
+	switch_find_local_ip(mod_sofia_globals.guess_ip, sizeof(mod_sofia_globals.guess_ip), AF_INET);
 
 	if (switch_event_bind((char *) modname, SWITCH_EVENT_CUSTOM, MULTICAST_EVENT, event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 		return SWITCH_STATUS_TERM;
 	}
 
-	su_init();
-	su_log_redirect(NULL, logger, NULL);
-	su_log_redirect(tport_log, logger, NULL);
+	switch_core_hash_init(&mod_sofia_globals.profile_hash, module_pool);
+	switch_core_hash_init(&mod_sofia_globals.gateway_hash, module_pool);
+	switch_mutex_init(&mod_sofia_globals.hash_mutex, SWITCH_MUTEX_NESTED, module_pool);
 
-	switch_core_hash_init(&globals.profile_hash, module_pool);
-	switch_mutex_init(&globals.hash_mutex, SWITCH_MUTEX_NESTED, module_pool);
+	if (config_sofia(0) != SWITCH_STATUS_SUCCESS) {
+		return SWITCH_STATUS_GENERR;
+	}
 
-	config_sofia(0);
+	switch_mutex_lock(mod_sofia_globals.mutex);
+	mod_sofia_globals.running = 1;
+	switch_mutex_unlock(mod_sofia_globals.mutex);
 
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_PRESENCE_IN, SWITCH_EVENT_SUBCLASS_ANY, sofia_presence_event_handler, NULL)
+		!= SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
+		return SWITCH_STATUS_GENERR;
+	}
 
-	if (switch_event_bind((char *) modname, SWITCH_EVENT_PRESENCE_IN, SWITCH_EVENT_SUBCLASS_ANY, pres_event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_PRESENCE_OUT, SWITCH_EVENT_SUBCLASS_ANY, sofia_presence_event_handler, NULL)
+		!= SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 		return SWITCH_STATUS_GENERR;
 	}
 
-	if (switch_event_bind((char *) modname, SWITCH_EVENT_PRESENCE_OUT, SWITCH_EVENT_SUBCLASS_ANY, pres_event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_PRESENCE_PROBE, SWITCH_EVENT_SUBCLASS_ANY, sofia_presence_event_handler, NULL)
+		!= SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 		return SWITCH_STATUS_GENERR;
 	}
 
-	if (switch_event_bind((char *) modname, SWITCH_EVENT_PRESENCE_PROBE, SWITCH_EVENT_SUBCLASS_ANY, pres_event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_ROSTER, SWITCH_EVENT_SUBCLASS_ANY, sofia_presence_event_handler, NULL)
+		!= SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 		return SWITCH_STATUS_GENERR;
 	}
 
-	if (switch_event_bind((char *) modname, SWITCH_EVENT_ROSTER, SWITCH_EVENT_SUBCLASS_ANY, pres_event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_MESSAGE_WAITING, SWITCH_EVENT_SUBCLASS_ANY, sofia_presence_mwi_event_handler, NULL)
+		!= SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 		return SWITCH_STATUS_GENERR;
 	}
@@ -5838,17 +1181,21 @@
 
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_shutdown(void)
 {
+	int sanity = 0;
+	
+	sofia_presence_cancel();
 
-	cancel_presence();
-
-	switch_mutex_lock(globals.mutex);
-	if (globals.running == 1) {
-		globals.running = -1;
+	switch_mutex_lock(mod_sofia_globals.mutex);
+	if (mod_sofia_globals.running == 1) {
+		mod_sofia_globals.running = 0;
 	}
-	switch_mutex_unlock(globals.mutex);
+	switch_mutex_unlock(mod_sofia_globals.mutex);
 
-	while(globals.running) {
+	while (mod_sofia_globals.threads) {
 		switch_yield(1000);
+		if (++sanity >= 5000) {
+			break;
+		}
 	}
 
 	su_deinit();
@@ -5866,3 +1213,5 @@
  * For VIM:
  * vim:set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:
  */
+
+

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/mod_sofia.vcproj
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/mod_sofia.vcproj	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_sofia/mod_sofia.vcproj	Tue Apr 24 10:14:28 2007
@@ -194,16 +194,19 @@
 			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
 			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
 			>
-			<File
-				RelativePath=".\mod_sofia.c"
-				>
-			</File>
+			<File RelativePath=".\mod_sofia.c"></File>
+			<File RelativePath=".\sofia_reg.c"></File>
+			<File RelativePath=".\sofia_glue.c"></File>
+			<File RelativePath=".\sofia_presence.c"></File>
+			<File RelativePath=".\sofia.c"></File>
+			
 		</Filter>
 		<Filter
 			Name="Header Files"
 			Filter="h;hpp;hxx;hm;inl;inc;xsd"
 			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
 			>
+			<File RelativePath=".\mod_sofia.h"></File>
 		</Filter>
 		<Filter
 			Name="Resource Files"

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,25 +1,39 @@
-CFLAGS +=-I/usr/local/include -I/usr/src/libpri -I/usr/src/linux/include -I. -I/usr/include
-CFLAGS +=-D__LINUX__ -D_REENTRANT -D_GNU_SOURCE -DAFT_A104 -DWANPIPE_TDM_API
-LDFLAGS += -lsangoma
+BASE=../../../..
+LIBPRI_HOST=http://ftp.digium.com/pub/libpri
+LIBPRI=libpri-1.2.4
+LIBPRI_FILE=$(LIBPRI).tar.gz
+LIBPRI_DIR=$(BASE)/libs/$(LIBPRI)
+WANPIPE=wanpipe-3.1.0.p18
+WANPIPE_HOST=ftp://ftp.sangoma.com/linux/custom/3.1
+WANPIPE_FILE=$(WANPIPE).tgz
+WANPIPE_DIR=$(BASE)/libs/$(WANPIPE)
+WANPIPE_INCLUDE=$(WANPIPE_DIR)/patches/kdrivers/include
+WANPIPE_KO=$(WANPIPE_DIR)/patches/kdrivers/src/net/wanpipe.ko
+WANPIPE_INSTALLED_KO=$(shell echo "/lib/modules/`uname -r`/kernel/drivers/net/wan/wanpipe.ko")
+LIBSANGOMA_DIR=./libsangoma
+LOCAL_CFLAGS  =-w -I$(WANPIPE_INCLUDE) -I$(LIBSANGOMA_DIR) -I/usr/local/include -I$(LIBPRI_DIR) -I/usr/src/linux/include -I. -I/usr/include 
+LOCAL_CFLAGS +=-D__LINUX__ -D_REENTRANT -D_GNU_SOURCE -DAFT_A104 -DWANPIPE_TDM_API -I$(switch_srcdir)/libs/libteletone/src -D_GNUC_ -DWANPIPE_TDM_API
+LOCAL_OBJS = ss7boost_client.o $(LIBPRI_DIR)/copy_string.o $(LIBPRI_DIR)/pri.o $(LIBPRI_DIR)/q921.o $(LIBPRI_DIR)/prisched.o $(LIBPRI_DIR)/q931.o $(LIBPRI_DIR)/pri_facility.o $(LIBSANGOMA_DIR)/libsangoma.o $(LIBSANGOMA_DIR)/sangoma_pri.o 
+
+include $(BASE)/build/modmake.rules 
+
+testapp: testapp.c $(LIBSANGOMA_DIR)/libsangoma.o
+	$(CC) -I$(WANPIPE_DIR)/api/lib $(CFLAGS) $(LOCAL_CFLAGS) lib_api.c testapp.c $(LIBSANGOMA_DIR)/libsangoma.o -o testapp
+
+$(LIBPRI_DIR):
+	$(GETLIB) $(LIBPRI_HOST) $(LIBPRI_FILE)
+
+$(WANPIPE_DIR):
+	$(GETLIB) $(WANPIPE_HOST) $(WANPIPE_FILE)
+
+$(WANPIPE_KO): $(WANPIPE_DIR)
+	cd $(WANPIPE_DIR) && $(MAKE)
+	@$(TOUCH_TARGET)
 
+$(WANPIPE_INSTALLED_KO): $(WANPIPE_KO)
+	cd $(WANPIPE_DIR) && $(MAKE) install
 
-ifeq ($(OSARCH),Darwin)
-	LINKER=g++
-else
-	LINKER=$(CC)
-endif
+local_depend: $(LIBPRI_DIR) $(WANPIPE_KO)
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+local_install: $(WANPIPE_INSTALLED_KO)
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install libsangoma --prefix=$(PREFIX) --with-libpri=/usr/src/libpri
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(LINKER) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/mod_wanpipe.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/mod_wanpipe.c	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_wanpipe/mod_wanpipe.c	Tue Apr 24 10:14:28 2007
@@ -34,6 +34,7 @@
 #include <libsangoma.h>
 #include <sangoma_pri.h>
 #include <libteletone.h>
+#include <ss7boost_client.h>
 
 #ifndef INVALID_HANDLE_VALUE
 #define INVALID_HANDLE_VALUE -1
@@ -67,11 +68,40 @@
 	TFLAG_ABORT = (1 << 8),
 	TFLAG_SWITCH = (1 << 9),
 	TFLAG_NOSIG = (1 << 10),
-	TFLAG_BYE = (1 << 11)
+	TFLAG_BYE = (1 << 11),
+	TFLAG_CODEC = (1 << 12),
+	TFLAG_HANGUP = (1 << 13)
 } TFLAGS;
 
 
 #define DEFAULT_SAMPLES_PER_FRAME 160
+#define MAX_SPANS 128
+
+struct channel_map {
+	char map[SANGOMA_MAX_CHAN_PER_SPAN][SWITCH_UUID_FORMATTED_LENGTH + 1];
+	switch_mutex_t *mutex;
+};
+
+unsigned int txseq=0;
+unsigned int rxseq=0;
+
+#define SETUP_LEN CORE_MAX_CHAN_PER_SPAN*CORE_MAX_SPANS+1
+
+struct ss7boost_handle {
+	char *local_ip;
+	char *remote_ip;
+	int local_port;
+	int remote_port;
+	ss7boost_client_connection_t mcon;
+	switch_mutex_t *mutex;
+	struct channel_map span_chanmap[MAX_SPANS];
+	char setup_array[SETUP_LEN][SWITCH_UUID_FORMATTED_LENGTH + 1];
+	uint32_t setup_index;
+};
+
+typedef struct ss7boost_handle ss7boost_handle_t;
+
+static int isup_exec_command(ss7boost_handle_t *ss7boost_handle, int span, int chan, int id, int cmd, int cause);
 
 static struct {
 	int debug;
@@ -81,10 +111,14 @@
 	int dtmf_off;
 	int supress_dtmf_tone;
 	int configured_spans;
+	int configured_boost_spans;
 	char *dialplan;
 	switch_hash_t *call_hash;
 	switch_mutex_t *hash_mutex;
 	switch_mutex_t *channel_mutex;
+	ss7boost_handle_t *ss7boost_handle;
+	uint32_t fxo_index;
+	uint32_t fxs_index;
 } globals;
 
 struct wanpipe_pri_span {
@@ -102,15 +136,42 @@
 struct wpsock {
 	sng_fd_t fd;
 	char *name;
-	struct private_object *tech_pvt;
 };
 
 typedef struct wpsock wpsock_t;
 
+typedef enum {
+	ANALOG_TYPE_UNKNOWN,
+	ANALOG_TYPE_PHONE_FXS,
+	ANLOG_TYPE_LINE_FXO
+} analog_type_t;
 
-#define MAX_SPANS 128
-static struct wanpipe_pri_span *SPANS[MAX_SPANS];
+typedef enum {
+	ANALOG_STATE_DOWN,
+	ANALOG_STATE_ONHOOK,
+	ANALOG_STATE_OFFHOOK,
+	ANALOG_STATE_RING
+} analog_state_t;
+
+struct analog_channel {
+	analog_type_t a_type;
+	analog_state_t state;
+	wpsock_t *sock;
+	int chan;
+	int span;
+	char *device;
+	char *user;
+	char *domain;
+	char *cid_name;
+	char *cid_num;
+};
+typedef struct analog_channel analog_channel_t;
 
+#define MAX_ANALOG_CHANNELS 128
+static struct analog_channel *FXS_ANALOG_CHANNELS[MAX_ANALOG_CHANNELS];
+static struct analog_channel *FXO_ANALOG_CHANNELS[MAX_ANALOG_CHANNELS];
+
+static struct wanpipe_pri_span *SPANS[MAX_SPANS];
 
 struct private_object {
 	unsigned int flags;			/* FLAGS */
@@ -118,8 +179,8 @@
 	switch_core_session_t *session;
 	switch_codec_t read_codec;
 	switch_codec_t write_codec;
-	unsigned char databuf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-	unsigned char auxbuf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
+	unsigned char databuf[SWITCH_RECOMMENDED_BUFFER_SIZE];
+	unsigned char auxbuf[SWITCH_RECOMMENDED_BUFFER_SIZE];
 	struct sangoma_pri *spri;
 	sangoma_api_hdr_t hdrframe;
 	switch_caller_profile_t *caller_profile;
@@ -135,6 +196,12 @@
 	unsigned int skip_write_frames;
 	switch_mutex_t *flag_mutex;
 	int frame_size;
+	ss7boost_handle_t *ss7boost_handle;
+	int boost_chan_number;
+	int boost_span_number;
+	int boost_trunk_group;
+	uint32_t setup_index;
+	uint32_t boost_pres;
 #ifdef DOTRACE
 	int fd;
 	int fd2;
@@ -142,25 +209,119 @@
 };
 typedef struct private_object private_object_t;
 
-struct channel_map {
-	char map[SANGOMA_MAX_CHAN_PER_SPAN][SWITCH_UUID_FORMATTED_LENGTH + 1];
-};
 
-static int wp_close(private_object_t *tech_pvt)
+
+static void wp_logger(char *file, const char *func, int line, int level, char *fmt, ...)
 {
-	int ret = 0;
+	va_list ap;
+	char *data = NULL;
+	int ret;
 
-	switch_mutex_lock(globals.hash_mutex);
-	if (tech_pvt->wpsock && tech_pvt->wpsock->tech_pvt == tech_pvt) {
-		tech_pvt->wpsock->tech_pvt = NULL;
-		ret = 1;
+	va_start(ap, fmt);
+	if ((ret = switch_vasprintf(&data, fmt, ap)) != -1) {
+		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, level, "%s", data);
 	}
-	switch_mutex_unlock(globals.hash_mutex);
+	va_end(ap);
+}
+
+static int local_sangoma_tdm_read_event(sng_fd_t fd, wp_tdm_api_rx_hdr_t *rx_event)
+{
+	wanpipe_tdm_api_t tdm_api[1];
 	
-	return ret;
+#if defined(WIN32)
+    rx_event = &last_tdm_api_event_buffer;
+#else
+    int err;
+
+    tdm_api->wp_tdm_cmd.cmd = SIOC_WP_TDM_READ_EVENT;
+
+    if ((err = sangoma_tdm_cmd_exec(fd, tdm_api))) {
+        return err;
+    }
+
+    rx_event = &tdm_api->wp_tdm_cmd.event;
+#endif
+
+	return 0;
+}
+
+static int analog_set_state(analog_channel_t *alc, analog_state_t state)
+{
+	alc->state = state;
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Changing State to %d\n", state);
+}
+
+static void analog_check_state(analog_channel_t *alc)
+{
+	wanpipe_tdm_api_t tdm_api;
+
+	switch(alc->state) {
+	case ANALOG_STATE_DOWN:
+		sangoma_tdm_enable_rxhook_events(alc->sock->fd, &tdm_api);
+		analog_set_state(alc, ANALOG_STATE_ONHOOK);
+		break;
+	default:
+		break;
+	}
+}
+
+static void analog_parse_event(analog_channel_t *alc)
+{
+	wp_tdm_api_rx_hdr_t rx_event;
+	int err = local_sangoma_tdm_read_event(alc->sock->fd, &rx_event);
+	
+	if (err < 0) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error reading event!\n");
+		return;
+	}
+
+	switch (rx_event.wp_tdm_api_event_type) {
+	case WP_TDM_EVENT_RXHOOK:
+		printf("hook\n");
+		break;
+	}
+
+}
+
+static void *SWITCH_THREAD_FUNC fxs_thread_run(switch_thread_t *thread, void *obj)
+{
+
+	for(;;) {
+		int i = 0, sel_on = -1;
+		fd_set oob;
+		FD_ZERO(&oob);
+		
+		for(i = 0; i < globals.fxs_index; i++) {
+			int fd;
+			assert(FXS_ANALOG_CHANNELS[i]);
+			assert(FXS_ANALOG_CHANNELS[i]->sock);
+
+			fd = FXS_ANALOG_CHANNELS[i]->sock->fd;
+			
+			analog_check_state(FXS_ANALOG_CHANNELS[i]);
+
+			FD_SET(fd, &oob);
+
+			if (fd > sel_on) {
+				sel_on = fd;
+			}
+		}
+
+		if (sel_on > -1) {
+			if (select(++sel_on, NULL, NULL, &oob, NULL)) {
+				for(i = 0; i < globals.fxs_index; i++) {
+					int fd = FXS_ANALOG_CHANNELS[i]->sock->fd;
+					if (FD_ISSET(fd, &oob)) {
+						analog_parse_event(FXS_ANALOG_CHANNELS[i]);
+					}
+				}
+			}
+		}
+	}
 }
 
-static int wp_open(private_object_t *tech_pvt, int span, int chan)
+
+static wpsock_t *wp_open(int span, int chan)
 {
 	sng_fd_t fd;
 	wpsock_t *sock;
@@ -182,20 +343,9 @@
 		}
 	}
 
-	if (sock) {
-		if (sock->tech_pvt) {
-			if (tech_pvt->session) {
-				switch_channel_t *channel = switch_core_session_get_channel(tech_pvt->session);
-				switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			}
-		}
-		sock->tech_pvt = tech_pvt;
-		tech_pvt->wpsock = sock;
-	}
-
 	switch_mutex_unlock(globals.hash_mutex);
 
-	return sock ? 1 : 0;
+	return sock;
 }
 
 static int wp_restart(int span, int chan)
@@ -300,7 +450,7 @@
 static switch_status_t wanpipe_on_loopback(switch_core_session_t *session);
 static switch_status_t wanpipe_on_transmit(switch_core_session_t *session);
 static switch_call_cause_t wanpipe_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-													switch_core_session_t **new_session, switch_memory_pool_t *pool);
+													switch_core_session_t **new_session, switch_memory_pool_t **pool);
 static switch_status_t wanpipe_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
 										switch_io_flag_t flags, int stream_id);
 static switch_status_t wanpipe_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
@@ -315,27 +465,20 @@
 static switch_status_t config_wanpipe(int reload);
 
 
-/* 
-   State methods they get called when the state changes to the specific state 
-   returning SWITCH_STATUS_SUCCESS tells the core to execute the standard state method next
-   so if you fully implement the state you can return SWITCH_STATUS_FALSE to skip it.
-*/
-static switch_status_t wanpipe_on_init(switch_core_session_t *session)
+static switch_status_t wanpipe_codec_init(private_object_t *tech_pvt)
 {
-	private_object_t *tech_pvt;
-	switch_channel_t *channel = NULL;
-	wanpipe_tdm_api_t tdm_api = {{0}};
 	int err = 0;
+	wanpipe_tdm_api_t tdm_api = {{0}};
 	unsigned int rate = 8000;
+	switch_channel_t *channel = NULL;
 
+	if (switch_test_flag(tech_pvt, TFLAG_CODEC)) {
+		return SWITCH_STATUS_SUCCESS;
+	}
 
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	tech_pvt = switch_core_session_get_private(session);
-	assert(tech_pvt != NULL);
 
-	tech_pvt->read_frame.data = tech_pvt->databuf;
+	channel = switch_core_session_get_channel(tech_pvt->session);
+	assert(channel != NULL);
 
 	err = sangoma_tdm_set_codec(tech_pvt->wpsock->fd, &tdm_api, WP_SLINEAR);
 	
@@ -344,7 +487,7 @@
 
 	if (switch_core_codec_init
 		(&tech_pvt->read_codec, "L16", NULL, rate, globals.samples_per_frame / 8, 1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL,
-		 switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
+		 switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "%s Cannot set read codec\n", switch_channel_get_name(channel));
 		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 		return SWITCH_STATUS_FALSE;
@@ -352,15 +495,15 @@
 
 	if (switch_core_codec_init
 		(&tech_pvt->write_codec, "L16", NULL, rate, globals.samples_per_frame / 8, 1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL,
-		 switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
+		 switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "%s Cannot set read codec\n", switch_channel_get_name(channel));
 		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
 		return SWITCH_STATUS_FALSE;
 	}
 	tech_pvt->read_frame.rate = rate;
 	tech_pvt->read_frame.codec = &tech_pvt->read_codec;
-	switch_core_session_set_read_codec(session, &tech_pvt->read_codec);
-	switch_core_session_set_write_codec(session, &tech_pvt->write_codec);
+	switch_core_session_set_read_codec(tech_pvt->session, &tech_pvt->read_codec);
+	switch_core_session_set_write_codec(tech_pvt->session, &tech_pvt->write_codec);
 
 #ifdef DOTRACE	
 						tech_pvt->fd = open("/tmp/wp-in.raw", O_WRONLY | O_TRUNC | O_CREAT);
@@ -381,11 +524,74 @@
 	tech_pvt->tone_session.wait = globals.dtmf_off * (tech_pvt->tone_session.rate / 1000);
 	
 	teletone_dtmf_detect_init (&tech_pvt->dtmf_detect, rate);
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Audio init %s\n", switch_channel_get_name(channel));
+
+	switch_set_flag(tech_pvt, TFLAG_CODEC);
+
+	return SWITCH_STATUS_SUCCESS;
+
+}
+
+
+/* 
+   State methods they get called when the state changes to the specific state 
+   returning SWITCH_STATUS_SUCCESS tells the core to execute the standard state method next
+   so if you fully implement the state you can return SWITCH_STATUS_FALSE to skip it.
+*/
+static switch_status_t wanpipe_on_init(switch_core_session_t *session)
+{
+	private_object_t *tech_pvt;
+	switch_channel_t *channel = NULL;
+	switch_status_t status;
+
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
+
+	tech_pvt = switch_core_session_get_private(session);
+	assert(tech_pvt != NULL);
+
+	tech_pvt->read_frame.data = tech_pvt->databuf;
+
+	if (tech_pvt->ss7boost_handle)  {
+		if (switch_channel_test_flag(channel, CF_OUTBOUND)) {
+			ss7boost_client_event_t event;
+
+			event.calling_number_presentation = tech_pvt->boost_pres;
+			event.trunk_group = tech_pvt->boost_trunk_group;
+		
+			switch_mutex_lock(tech_pvt->ss7boost_handle->mutex);
+			tech_pvt->setup_index = ++tech_pvt->ss7boost_handle->setup_index;
+			if (tech_pvt->ss7boost_handle->setup_index == SETUP_LEN - 1) {
+				tech_pvt->ss7boost_handle->setup_index = 0;
+			}
+			switch_mutex_unlock(tech_pvt->ss7boost_handle->mutex);
+		
+			switch_copy_string(tech_pvt->ss7boost_handle->setup_array[tech_pvt->setup_index],
+							   switch_core_session_get_uuid(session), 
+							   sizeof(tech_pvt->ss7boost_handle->setup_array[tech_pvt->setup_index]));
+		
+			
+			ss7boost_client_call_init(&event, tech_pvt->caller_profile->caller_id_number, tech_pvt->caller_profile->destination_number, tech_pvt->setup_index);
+			
+			if (ss7boost_client_connection_write(&tech_pvt->ss7boost_handle->mcon, &event) <= 0) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Critical System Error: Failed to tx on ISUP socket [%s]\n", strerror(errno));
+			}
+			
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Call Called Event TG=%d\n", tech_pvt->boost_trunk_group);
+			goto done;
+		}
+	} 
 
+	if ((status = wanpipe_codec_init(tech_pvt)) != SWITCH_STATUS_SUCCESS) {
+		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+		return status;
+	}
+	
 	if (switch_test_flag(tech_pvt, TFLAG_NOSIG)) {
 		switch_channel_mark_answered(channel);
 	}
 
+ done:
 
 	/* Move Channel's State Machine to RING */
 	switch_channel_set_state(channel, CS_RING);
@@ -423,31 +629,44 @@
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
-	switch_set_flag_locked(tech_pvt, TFLAG_BYE);
-
-	if (!switch_test_flag(tech_pvt, TFLAG_NOSIG)) {
-		chanmap = tech_pvt->spri->private_info;
-	}
-
-	//sangoma_socket_close(&tech_pvt->wpsock->fd);
-	wp_close(tech_pvt);
-
 	switch_core_codec_destroy(&tech_pvt->read_codec);
 	switch_core_codec_destroy(&tech_pvt->write_codec);
 
 
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "WANPIPE HANGUP\n");
 
-	if (!switch_test_flag(tech_pvt, TFLAG_NOSIG)) {
-		pri_hangup(tech_pvt->spri->pri, tech_pvt->call, switch_channel_get_cause(channel));
-		pri_destroycall(tech_pvt->spri->pri, tech_pvt->call);
+	if (tech_pvt->ss7boost_handle) {
+		switch_mutex_lock(tech_pvt->ss7boost_handle->mutex);
+		*tech_pvt->ss7boost_handle->span_chanmap[tech_pvt->boost_span_number].map[tech_pvt->boost_chan_number] = '\0';
+		switch_mutex_unlock(tech_pvt->ss7boost_handle->mutex);
+		if (!switch_test_flag(tech_pvt, TFLAG_BYE)) {
+			isup_exec_command(tech_pvt->ss7boost_handle,
+							  tech_pvt->boost_span_number,
+							  tech_pvt->boost_chan_number,
+							  -1,
+							  SIGBOOST_EVENT_CALL_STOPPED,
+							  SIGBOOST_RELEASE_CAUSE_NORMAL);
+		}
+	} else if (tech_pvt->spri) {
+		chanmap = tech_pvt->spri->private_info;
+
+		if (!switch_test_flag(tech_pvt, TFLAG_HANGUP)) {
+			switch_set_flag_locked(tech_pvt, TFLAG_HANGUP);
+			switch_mutex_lock(chanmap->mutex);
+			pri_hangup(tech_pvt->spri->pri, tech_pvt->call, switch_channel_get_cause(channel));
+			pri_destroycall(tech_pvt->spri->pri, tech_pvt->call);
+			switch_mutex_unlock(chanmap->mutex);
+		}
+
 
 		switch_mutex_lock(globals.channel_mutex);
 		*chanmap->map[tech_pvt->callno] = '\0';
-
 		switch_mutex_unlock(globals.channel_mutex);
+		
 	}
 
+	switch_set_flag_locked(tech_pvt, TFLAG_BYE);
+
 	teletone_destroy_session(&tech_pvt->tone_session);
 
 	switch_buffer_destroy(&tech_pvt->dtmf_buffer);
@@ -490,9 +709,23 @@
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
-	if (switch_test_flag(tech_pvt, TFLAG_INBOUND) && !switch_test_flag(tech_pvt, TFLAG_NOSIG)) {
-		pri_answer(tech_pvt->spri->pri, tech_pvt->call, 0, 1);
+	if (tech_pvt->spri) {
+		struct channel_map *chanmap = tech_pvt->spri->private_info;
+			
+		if (switch_test_flag(tech_pvt, TFLAG_INBOUND)) {
+			switch_mutex_lock(chanmap->mutex);
+			pri_answer(tech_pvt->spri->pri, tech_pvt->call, 0, 1);
+			switch_mutex_unlock(chanmap->mutex);
+		}
+	} else if (tech_pvt->ss7boost_handle) {
+		isup_exec_command(tech_pvt->ss7boost_handle,
+						  tech_pvt->boost_span_number,
+						  tech_pvt->boost_chan_number,
+						  -1,
+						  SIGBOOST_EVENT_CALL_ANSWERED,
+						  0);
 	}
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -598,7 +831,8 @@
 
 		switch_buffer_read(tech_pvt->dtmf_buffer, tech_pvt->auxbuf, len);		
 		if (len < frame->datalen) {
-			memcpy(frame->data + len, tech_pvt->auxbuf + len, frame->datalen - len);
+			uint8_t *data = frame->data;
+			memcpy(data + len, tech_pvt->auxbuf + len, frame->datalen - len);
 		}
 		data= tech_pvt->auxbuf;
 	} 
@@ -635,6 +869,10 @@
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
+	if (switch_test_flag(tech_pvt, TFLAG_BYE) || tech_pvt->wpsock->fd < 0) {
+		return SWITCH_STATUS_GENERR;
+	}
+
 	if (!tech_pvt->dtmf_buffer) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Allocate DTMF Buffer....");
 		if (switch_buffer_create_dynamic(&tech_pvt->dtmf_buffer, 1024, 3192, 0) != SWITCH_STATUS_SUCCESS) {
@@ -659,7 +897,6 @@
 {
 	switch_channel_t *channel;
 	private_object_t *tech_pvt;
-    switch_status_t status;
 
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
@@ -667,6 +904,9 @@
 	tech_pvt = (private_object_t *) switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
+	if (switch_test_flag(tech_pvt, TFLAG_BYE) || tech_pvt->wpsock->fd < 0) {
+		return SWITCH_STATUS_GENERR;
+	}
 
 	switch (msg->message_id) {
 	case SWITCH_MESSAGE_INDICATE_NOMEDIA:
@@ -683,10 +923,15 @@
 		break;
 	case SWITCH_MESSAGE_INDICATE_REDIRECT:
 		break;
+	case SWITCH_MESSAGE_INDICATE_ANSWER:
+		wanpipe_answer_channel(session);
+		break;
 	case SWITCH_MESSAGE_INDICATE_PROGRESS:
 		break;
 	case SWITCH_MESSAGE_INDICATE_RINGING:
 		break;
+	default:
+		break;
 	}
 
 	return SWITCH_STATUS_SUCCESS;
@@ -705,16 +950,11 @@
 
 	switch(sig) {
 	case SWITCH_SIG_KILL:
-		switch_mutex_lock(tech_pvt->flag_mutex);
-		switch_set_flag(tech_pvt, TFLAG_BYE);
-		switch_clear_flag(tech_pvt, TFLAG_MEDIA);
-		switch_mutex_unlock(tech_pvt->flag_mutex);
+		switch_clear_flag_locked(tech_pvt, TFLAG_MEDIA);
 		break;
 	default:
 		break;
 	}
-	//sangoma_socket_close(&tech_pvt->wpsock->fd);
-	//wp_close(tech_pvt);
 
 	return SWITCH_STATUS_SUCCESS;
 
@@ -723,7 +963,6 @@
 
 static const switch_io_routines_t wanpipe_io_routines = {
 	/*.outgoing_channel */ wanpipe_outgoing_channel,
-	/*.answer_channel */ wanpipe_answer_channel,
 	/*.read_frame */ wanpipe_read_frame,
 	/*.write_frame */ wanpipe_write_frame,
 	/*.kill_channel */ wanpipe_kill_channel,
@@ -761,225 +1000,289 @@
 
 
 static switch_call_cause_t wanpipe_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-													switch_core_session_t **new_session, switch_memory_pool_t *pool)
+													switch_core_session_t **new_session, switch_memory_pool_t **pool)
 {
 	char *bchan = NULL;
 	char name[128] = "";
-		
+	char *protocol = NULL;
+	char *dest;
+	int ready = 0, is_pri = 0, is_boost = 0, is_raw = 0;
+	switch_call_cause_t cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+	private_object_t *tech_pvt;
+	switch_channel_t *channel;
+	switch_caller_profile_t *caller_profile = NULL;
+	int callno = 0;
+	struct sangoma_pri *spri;
+	int span = 0, autospan = 0, autochan = 0;
+	char *num, *p;
+	struct channel_map *chanmap = NULL;
+	
+	if (!outbound_profile) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Doh! no caller profile\n");
+		cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+		goto error;
+	}
 
-	if (outbound_profile && outbound_profile->destination_number) {
-		bchan = strchr(outbound_profile->destination_number, '=');
-	} else {
-		return SWITCH_STATUS_FALSE;
+	protocol = strdup(outbound_profile->destination_number);
+	assert(protocol != NULL);
+
+	if (!(dest = strchr(protocol, '/'))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error No protocol specified!\n");
+		cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+		goto error;
 	}
+	
+	*dest++ = '\0';
 
-	if (bchan) {
-		bchan++;
-		if (!bchan) {
-			return SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL;
+	if (!strcasecmp(protocol, "raw")) {
+		bchan = dest;
+		is_raw = ready = 1;
+	} else if (!strcasecmp(protocol, "pri")) {
+		if ((is_pri = globals.configured_spans)) {
+			ready = is_pri;
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error No PRI Spans Configured.\n");
+		}
+	} else if (!strcasecmp(protocol, "ss7boost")) {
+		if ((is_boost = globals.configured_boost_spans)) {
+			ready = is_boost;
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error No SS7BOOST Spans Configured.\n");
 		}
-		outbound_profile->destination_number++;
-	} else if (!globals.configured_spans) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error No Spans Configured.\n");
-		SWITCH_CAUSE_NETWORK_OUT_OF_ORDER;
+	}
+	
+	if (!ready) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Continue!\n");
+		cause = SWITCH_CAUSE_NETWORK_OUT_OF_ORDER;
+		goto error;
 	}
 
+	outbound_profile->destination_number = dest;
 
-	if ((*new_session = switch_core_session_request(&wanpipe_endpoint_interface, pool))) {
-		private_object_t *tech_pvt;
-		switch_channel_t *channel;
+	if (!(*new_session = switch_core_session_request(&wanpipe_endpoint_interface, pool))) {
+		cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+        goto error;
+	}
 
-		switch_core_session_add_stream(*new_session, NULL);
-		if ((tech_pvt = (private_object_t *) switch_core_session_alloc(*new_session, sizeof(private_object_t)))) {
-			memset(tech_pvt, 0, sizeof(*tech_pvt));
-			switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(*new_session));
-			channel = switch_core_session_get_channel(*new_session);
-			switch_core_session_set_private(*new_session, tech_pvt);
-			tech_pvt->session = *new_session;
-		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Hey where is my memory pool?\n");
-			switch_core_session_destroy(new_session);
-			SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-		}
+	switch_core_session_add_stream(*new_session, NULL);
+	if ((tech_pvt = (private_object_t *) switch_core_session_alloc(*new_session, sizeof(private_object_t)))) {
+		memset(tech_pvt, 0, sizeof(*tech_pvt));
+		switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(*new_session));
+		channel = switch_core_session_get_channel(*new_session);
+		switch_core_session_set_private(*new_session, tech_pvt);
+		tech_pvt->session = *new_session;
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
+		switch_core_session_destroy(new_session);
+		cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+		goto error;
+	}
 
 		
-		if (outbound_profile) {
-			switch_caller_profile_t *caller_profile;
-			struct sangoma_pri *spri;
-			int span = 0, autospan = 0, autochan = 0;
-			char *num, *p;
-			int callno = 0;
-			struct channel_map *chanmap = NULL;
-
-			caller_profile = switch_caller_profile_clone(*new_session, outbound_profile);
-			if (!bchan) {
-				num = caller_profile->destination_number;
-				if ((p = strchr(num, '/'))) {
-					*p++ = '\0';
-
-					if (*num == 'a') {
-						span = 1;
-						autospan = 1;
-					} else if (*num = 'A') {
-						span = MAX_SPANS - 1;
-						autospan = -1;
-					} else {
-						if (num && *num > 47 && *num < 58) {
-							span = atoi(num);
-						} else {
-							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invlid Syntax\n");
-							switch_core_session_destroy(new_session);
-							return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-						}
-					}
-					num = p;
-					if ((p = strchr(num, '/'))) {
-						*p++ = '\0';
-						if (*num == 'a') {
-							autochan = 1;
-						} else if (*num == 'A') {
-							autochan = -1;
-						} else if (num && *num > 47 && *num < 58) {
-							callno = atoi(num);
-						} else {
-							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invlid Syntax\n");
-                            switch_core_session_destroy(new_session);
-                            return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-						}
-						caller_profile->destination_number = p;
-					} else {
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invlid Syntax\n");
-						switch_core_session_destroy(new_session);
-						return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-					}
+	caller_profile = switch_caller_profile_clone(*new_session, outbound_profile);
+
+	if (is_pri) {
+		num = caller_profile->destination_number;
+		if ((p = strchr(num, '/'))) {
+			*p++ = '\0';
+
+			if (*num == 'a') {
+				span = 1;
+				autospan = 1;
+			} else if (*num == 'A') {
+				span = MAX_SPANS - 1;
+				autospan = -1;
+			} else {
+				if (num && *num > 47 && *num < 58) {
+					span = atoi(num);
+				} else {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invlid Syntax\n");
+					switch_core_session_destroy(new_session);
+					cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+					goto error;
 				}
 			}
-
-			tech_pvt->caller_profile = caller_profile;
-
-			if (bchan) {
-				int chan, span;
-
-				if (sangoma_span_chan_fromif(bchan, &span, &chan)) {
-					if (!wp_open(tech_pvt, span, chan)) {
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open fd for s%dc%d! [%s]\n", span, chan, strerror(errno));
-						switch_core_session_destroy(new_session);
-						return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-					}
-					switch_set_flag_locked(tech_pvt, TFLAG_NOSIG);
-					snprintf(name, sizeof(name), "WanPipe/%s/nosig", bchan);
-					switch_channel_set_name(channel, name);			
-					switch_channel_set_caller_profile(channel, caller_profile);
+			num = p;
+			if ((p = strchr(num, '/'))) {
+				*p++ = '\0';
+				if (*num == 'a') {
+					autochan = 1;
+				} else if (*num == 'A') {
+					autochan = -1;
+				} else if (num && *num > 47 && *num < 58) {
+					callno = atoi(num);
 				} else {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid address\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invlid Syntax\n");
 					switch_core_session_destroy(new_session);
-					return SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL;
+					cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+					goto error;
 				}
+				caller_profile->destination_number = p;
 			} else {
-				switch_mutex_lock(globals.channel_mutex);
-				callno = 0;
-				while (!callno) {
-					if (autospan > 0 && span == MAX_SPANS - 1) {
-						break;
-					}
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invlid Syntax\n");
+				switch_core_session_destroy(new_session);
+				cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+				goto error;
+			}
+		}
+	}
 
-					if (autospan < 0 && span == 0) {
-						break;
-					}
+	tech_pvt->caller_profile = caller_profile;
+
+	if (is_raw) {
+		int chan, span;
+
+		if (sangoma_span_chan_fromif(bchan, &span, &chan)) {
+			if (!(tech_pvt->wpsock = wp_open(span, chan))) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open fd for s%dc%d! [%s]\n", span, chan, strerror(errno));
+				switch_core_session_destroy(new_session);
+				cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+				goto error;
+			}
+			switch_set_flag_locked(tech_pvt, TFLAG_NOSIG);
+			snprintf(name, sizeof(name), "wanpipe/%s/nosig", bchan);
+			switch_channel_set_name(channel, name);			
+			switch_channel_set_caller_profile(channel, caller_profile);
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid address\n");
+			switch_core_session_destroy(new_session);
+			cause = SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL;
+			goto error;
+		}
+	} else if (is_pri) {
+		switch_mutex_lock(globals.channel_mutex);
+		callno = 0;
+		while (!callno) {
+			if (autospan > 0 && span == MAX_SPANS - 1) {
+				break;
+			}
 
-					if (SPANS[span] && (spri = &SPANS[span]->spri) && switch_test_flag(spri, SANGOMA_PRI_READY)) {
-						chanmap = spri->private_info;
+			if (autospan < 0 && span == 0) {
+				break;
+			}
+
+			if (SPANS[span] && (spri = &SPANS[span]->spri) && switch_test_flag(spri, SANGOMA_PRI_READY)) {
+				chanmap = spri->private_info;
 						
-						if (autochan > 0) {
-							for(callno = 1; callno < SANGOMA_MAX_CHAN_PER_SPAN; callno++) {
-								if ((SPANS[span]->bchans & (1 << callno)) && ! *chanmap->map[callno]) {
-									switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Choosing channel s%dc%d\n", span, callno);
-									goto done;
-								}
-							}
-							callno = 0;
-						} else if (autochan < 0) {
-							for(callno = SANGOMA_MAX_CHAN_PER_SPAN; callno > 0; callno--) {
-								if ((SPANS[span]->bchans & (1 << callno)) && ! *chanmap->map[callno]) {
-									switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Choosing channel s%dc%d\n", span, callno);
-									goto done;
-								}
-							}
-							callno = 0;
+				if (autochan > 0) {
+					for(callno = 1; callno < SANGOMA_MAX_CHAN_PER_SPAN; callno++) {
+						if ((SPANS[span]->bchans & (1 << callno)) && ! *chanmap->map[callno]) {
+							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Choosing channel s%dc%d\n", span, callno);
+							goto done;
 						}
 					}
-
-					if (autospan > 0) {
-						span++;
-					} else if (autospan < 0) {
-						span--;
+					callno = 0;
+				} else if (autochan < 0) {
+					for(callno = SANGOMA_MAX_CHAN_PER_SPAN; callno > 0; callno--) {
+						if ((SPANS[span]->bchans & (1 << callno)) && ! *chanmap->map[callno]) {
+							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Choosing channel s%dc%d\n", span, callno);
+							goto done;
+						}
 					}
+					callno = 0;
 				}
-			done:
-				switch_mutex_unlock(globals.channel_mutex);
+			}
 
-				if (!spri || callno == 0 || callno == (SANGOMA_MAX_CHAN_PER_SPAN)) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "No Free Channels!\n");
-					switch_core_session_destroy(new_session);
-					return SWITCH_CAUSE_SWITCH_CONGESTION;
-				}
+			if (autospan > 0) {
+				span++;
+			} else if (autospan < 0) {
+				span--;
+			}
+		}
+	done:
+		switch_mutex_unlock(globals.channel_mutex);
+
+		if (!spri || callno == 0 || callno == (SANGOMA_MAX_CHAN_PER_SPAN)) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "No Free Channels!\n");
+			switch_core_session_destroy(new_session);
+			cause = SWITCH_CAUSE_SWITCH_CONGESTION;
+			goto error;
+		}
 				
-				tech_pvt->callno = callno;
+		tech_pvt->callno = callno;
 				
-				if (spri && (tech_pvt->call = pri_new_call(spri->pri))) {
-					struct pri_sr *sr;
+		if (spri) {
+			struct channel_map *chanmap = spri->private_info;
+			switch_mutex_lock(chanmap->mutex);
+			if (tech_pvt->call = pri_new_call(spri->pri)) {
+				struct pri_sr *sr;
 					
-					snprintf(name, sizeof(name), "WanPipe/s%dc%d/%s", spri->span, callno, caller_profile->destination_number);
-					switch_channel_set_name(channel, name);			
-					switch_channel_set_caller_profile(channel, caller_profile);
-					sr = pri_sr_new();
-					pri_sr_set_channel(sr, callno, 0, 0);
-					pri_sr_set_bearer(sr, 0, SPANS[span]->l1);
-					pri_sr_set_called(sr, caller_profile->destination_number, SPANS[span]->dp, 1);
-					pri_sr_set_caller(sr,
-									  caller_profile->caller_id_number,
-									  caller_profile->caller_id_name,
-									  SPANS[span]->dp,
-									  PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN);
-					pri_sr_set_redirecting(sr,
-										   caller_profile->caller_id_number,
-										   SPANS[span]->dp,
-										   PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN,
-										   PRI_REDIR_UNCONDITIONAL);
+				snprintf(name, sizeof(name), "wanpipe/pri/s%dc%d/%s", spri->span, callno, caller_profile->destination_number);
+				switch_channel_set_name(channel, name);			
+				switch_channel_set_caller_profile(channel, caller_profile);
+				sr = pri_sr_new();
+				pri_sr_set_channel(sr, callno, 0, 0);
+				pri_sr_set_bearer(sr, 0, SPANS[span]->l1);
+				pri_sr_set_called(sr, caller_profile->destination_number, SPANS[span]->dp, 1);
+				pri_sr_set_caller(sr,
+								  caller_profile->caller_id_number,
+								  caller_profile->caller_id_name,
+								  SPANS[span]->dp,
+								  PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN);
+				pri_sr_set_redirecting(sr,
+									   caller_profile->caller_id_number,
+									   SPANS[span]->dp,
+									   PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN,
+									   PRI_REDIR_UNCONDITIONAL);
 				
-					if (pri_setup(spri->pri, tech_pvt->call , sr)) {
-						switch_core_session_destroy(new_session);
-						pri_sr_free(sr);
-						return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-					}
-
-					if (!wp_open(tech_pvt, spri->span, callno)) {
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open fd!\n");
-						switch_core_session_destroy(new_session);
-						pri_sr_free(sr);
-						return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-					}
+				if (pri_setup(spri->pri, tech_pvt->call , sr)) {
+					switch_core_session_destroy(new_session);
+					pri_sr_free(sr);
+					cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+					switch_mutex_unlock(chanmap->mutex);
+					goto error;
+				}
+				
+				if (!(tech_pvt->wpsock = wp_open(spri->span, callno))) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open fd!\n");
+					switch_core_session_destroy(new_session);
 					pri_sr_free(sr);
-					switch_copy_string(chanmap->map[callno],
-									   switch_core_session_get_uuid(*new_session),
-									   sizeof(chanmap->map[callno]));
-					tech_pvt->spri = spri;
+					cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+					switch_mutex_unlock(chanmap->mutex);
+					goto error;
 				}
+				pri_sr_free(sr);
+				switch_copy_string(chanmap->map[callno],
+								   switch_core_session_get_uuid(*new_session),
+								   sizeof(chanmap->map[callno]));
+				tech_pvt->spri = spri;
 			}
-		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Doh! no caller profile\n");
-			switch_core_session_destroy(new_session);
-			return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+			switch_mutex_unlock(chanmap->mutex);
 		}
+	} else if (is_boost) {
+		char *p;
 
-		switch_channel_set_flag(channel, CF_OUTBOUND);
-		switch_set_flag_locked(tech_pvt, TFLAG_OUTBOUND);
-		switch_channel_set_state(channel, CS_INIT);
-		return SWITCH_CAUSE_SUCCESS;
-	}
+		if ((p = strchr(caller_profile->destination_number, '/'))) {
+			char *grp = caller_profile->destination_number;
+			*p = '\0';
+			caller_profile->destination_number = p+1;
+			tech_pvt->boost_trunk_group = atoi(grp+1) - 1;
+			if (tech_pvt->boost_trunk_group < 0) {
+				tech_pvt->boost_trunk_group = 0;
+			}
+		}
+		sprintf(name, "wanpipe/ss7boost/%s", caller_profile->destination_number);
+		switch_channel_set_name(channel, name);
+		tech_pvt->ss7boost_handle = globals.ss7boost_handle;
 
-	return SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-}
+		if (session && switch_core_session_compare(session, *new_session)) {
+			private_object_t *otech_pvt = switch_core_session_get_private(session);
+			tech_pvt->boost_pres = otech_pvt->boost_pres;
+		}
+
+	}
+
+	tech_pvt->caller_profile = caller_profile;
+	switch_channel_set_flag(channel, CF_OUTBOUND);
+	switch_set_flag_locked(tech_pvt, TFLAG_OUTBOUND);
+	switch_channel_set_state(channel, CS_INIT);
+	cause = SWITCH_CAUSE_SUCCESS;
+	
+
+ error:
+	switch_safe_free(protocol);
+	return cause;
+}
 
 
 #ifdef WIN32
@@ -1009,6 +1312,8 @@
 {
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
 
+	sangoma_set_logger(wp_logger);
+
 	memset(SPANS, 0, sizeof(SPANS));
 
 	pri_set_error(s_pri_error);
@@ -1061,25 +1366,32 @@
 		channel = switch_core_session_get_channel(session);
 		assert(channel != NULL);
 
-		tech_pvt = switch_core_session_get_private(session);
-		assert(tech_pvt != NULL);
-
-		if (!tech_pvt->call) {
-			tech_pvt->call = pevent->hangup.call;
-		}
-
-		tech_pvt->cause = pevent->hangup.cause;
+		if (switch_channel_get_state(channel) < CS_HANGUP) {
 
-		switch_channel_hangup(channel, tech_pvt->cause);
 
-		switch_mutex_lock(globals.channel_mutex);
-		*chanmap->map[pevent->hangup.channel] = '\0';
-		switch_mutex_unlock(globals.channel_mutex);
+			tech_pvt = switch_core_session_get_private(session);
+			assert(tech_pvt != NULL);
+			chanmap = tech_pvt->spri->private_info;
+			if (!tech_pvt->call) {
+				tech_pvt->call = pevent->hangup.call;
+			}
 
+			tech_pvt->cause = pevent->hangup.cause;
+			switch_set_flag_locked(tech_pvt, TFLAG_HANGUP);
+			switch_channel_hangup(channel, tech_pvt->cause);
+			switch_mutex_lock(chanmap->mutex);
+			pri_destroycall(tech_pvt->spri->pri, tech_pvt->call);
+			switch_mutex_unlock(chanmap->mutex);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "-- Hanging up channel s%dc%d\n", spri->span, pevent->hangup.channel);
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "-- Duplicate Hang up on channel s%dc%d\n", spri->span, pevent->hangup.channel);
+		}
 		switch_core_session_rwunlock(session);
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "-- Hanging up nonexistant channel s%dc%d\n", spri->span, pevent->hangup.channel);
 	}
 
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "-- Hanging up channel s%dc%d\n", spri->span, pevent->hangup.channel);
+
 	return 0;
 }
 
@@ -1115,7 +1427,6 @@
 	chanmap = spri->private_info;
 
 	if ((session = switch_core_session_locate(chanmap->map[pevent->proceeding.channel]))) {
-		char *uuid;
 		switch_core_session_message_t *msg;
 
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "-- Proceeding on channel s%dc%d\n", spri->span, pevent->proceeding.channel);
@@ -1123,16 +1434,8 @@
 		channel = switch_core_session_get_channel(session);
 		assert(channel != NULL);
 		
-		if ((msg = malloc(sizeof(*msg)))) {
-			memset(msg, 0, sizeof(*msg));
-			msg->message_id = SWITCH_MESSAGE_INDICATE_PROGRESS;
-			msg->from = __FILE__;
-			switch_core_session_queue_message(session, msg);
-			switch_set_flag(msg, SCSMF_DYNAMIC);
-			switch_channel_mark_pre_answered(channel);
-		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-		}
+		switch_core_session_pass_indication(session, SWITCH_MESSAGE_INDICATE_PROGRESS);
+		switch_channel_mark_pre_answered(channel);
 		
 		switch_core_session_rwunlock(session);
 	} else {
@@ -1149,7 +1452,7 @@
 	switch_core_session_t *session;
 	switch_channel_t *channel;
 	struct channel_map *chanmap;
-	switch_core_session_message_t *msg;
+
 
 	chanmap = spri->private_info;
 
@@ -1158,7 +1461,7 @@
 		channel = switch_core_session_get_channel(session);
 		assert(channel != NULL);
 
-		switch_core_session_queue_indication(session, SWITCH_MESSAGE_INDICATE_RINGING);
+		switch_core_session_pass_indication(session, SWITCH_MESSAGE_INDICATE_RINGING);
 		switch_channel_mark_ring_ready(channel);
 
 		switch_core_session_rwunlock(session);
@@ -1173,7 +1476,7 @@
 static int on_ring(struct sangoma_pri *spri, sangoma_pri_event_t event_type, pri_event *pevent)
 {
 	char name[128];
-	switch_core_session_t *session;
+	switch_core_session_t *session = NULL;
 	switch_channel_t *channel;
 	struct channel_map *chanmap;
 	int ret = 0;
@@ -1181,7 +1484,7 @@
 	switch_mutex_lock(globals.channel_mutex);
 
 	chanmap = spri->private_info;
-	if (switch_core_session_locate(chanmap->map[pevent->ring.channel])) {
+	if ((session = switch_core_session_locate(chanmap->map[pevent->ring.channel]))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "--Duplicate Ring on channel s%dc%d (ignored)\n",
 							  spri->span, pevent->ring.channel);
 		switch_core_session_rwunlock(session);
@@ -1192,9 +1495,10 @@
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "-- Ring on channel s%dc%d (from %s to %s)\n", spri->span, pevent->ring.channel,
 						  pevent->ring.callingnum, pevent->ring.callednum);
 
-
+	switch_mutex_unlock(chanmap->mutex);
 	pri_proceeding(spri->pri, pevent->ring.call, pevent->ring.channel, 0);
 	pri_acknowledge(spri->pri, pevent->ring.call, pevent->ring.channel, 0);
+	switch_mutex_unlock(chanmap->mutex);
 
 	if ((session = switch_core_session_request(&wanpipe_endpoint_interface, NULL))) {
 		private_object_t *tech_pvt;
@@ -1207,9 +1511,9 @@
 			switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
 			channel = switch_core_session_get_channel(session);
 			switch_core_session_set_private(session, tech_pvt);
-			sprintf(name, "s%dc%d", spri->span, pevent->ring.channel);
+			sprintf(name, "wanpipe/pri/s%dc%d", spri->span, pevent->ring.channel);
 			switch_channel_set_name(channel, name);
-
+			tech_pvt->session = session;
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Hey where is my memory pool?\n");
 			switch_core_session_destroy(&session);
@@ -1251,7 +1555,7 @@
 		tech_pvt->callno = pevent->ring.channel;
 		tech_pvt->span = spri->span;
 
-		if (!wp_open(tech_pvt, spri->span, pevent->ring.channel)) {
+		if (!(tech_pvt->wpsock = wp_open(spri->span, pevent->ring.channel))) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open fd!\n");
 		}
 
@@ -1337,9 +1641,14 @@
 static void *SWITCH_THREAD_FUNC pri_thread_run(switch_thread_t *thread, void *obj)
 {
 	struct sangoma_pri *spri = obj;
-	struct channel_map chanmap = {0};
+	struct channel_map chanmap;
+
+	memset(&chanmap, 0, sizeof(chanmap));
 
 	switch_event_t *s_event;
+
+
+	switch_mutex_init(&chanmap.mutex, SWITCH_MUTEX_NESTED, module_pool);
 	SANGOMA_MAP_PRI_EVENT((*spri), SANGOMA_PRI_EVENT_ANY, on_anything);
 	SANGOMA_MAP_PRI_EVENT((*spri), SANGOMA_PRI_EVENT_RING, on_ring);
 	SANGOMA_MAP_PRI_EVENT((*spri), SANGOMA_PRI_EVENT_RINGING, on_ringing);
@@ -1379,11 +1688,503 @@
 
 }
 
+
+static int isup_exec_command(ss7boost_handle_t *ss7boost_handle, int span, int chan, int id, int cmd, int cause)
+{
+	ss7boost_client_event_t oevent;
+	int r = 0;
+
+	switch_mutex_lock(ss7boost_handle->mutex);
+	ss7boost_client_event_init(&oevent, cmd, chan, span);
+	oevent.release_cause = cause;
+	
+	if (id >= 0) {
+		oevent.call_setup_id = id;
+	}
+	
+	if (ss7boost_client_connection_write(&ss7boost_handle->mcon, &oevent) <= 0){
+		r = -1;
+	}
+
+	switch_mutex_unlock(ss7boost_handle->mutex);
+
+	return r;
+}
+
+#ifdef USE_WAITFOR_SOCKET
+static int waitfor_socket(int fd, int timeout, int flags)
+{
+    struct pollfd pfds[1];
+    int res;
+ 
+    memset(&pfds[0], 0, sizeof(pfds[0]));
+    pfds[0].fd = fd;
+    pfds[0].events = flags;
+    res = poll(pfds, 1, timeout);
+
+    if (res > 0) {
+	if(pfds[0].revents & POLLIN) {
+		res = 1;
+	} else if ((pfds[0].revents & POLLERR)) {
+		res = -1;
+    	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,"System Error: Poll Event Error no event!\n");
+		res = -1;
+	}
+    }
+
+    return res;
+}
+#endif
+
+
+static void validate_number(unsigned char *s)
+{
+	unsigned char *p;
+	for (p = s; *p; p++) {
+		if (*p < 48 || *p > 57) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Encountered a non-numeric character [%c]!\n", *p);
+			*p = '\0';
+			break;
+		}
+	}
+}
+
+
+static void handle_call_stop(ss7boost_handle_t *ss7boost_handle, ss7boost_client_event_t *event)
+{
+	char *uuid = ss7boost_handle->span_chanmap[event->span].map[event->chan];
+
+	if (*uuid) {
+		switch_core_session_t *session;
+
+		if ((session = switch_core_session_locate(uuid))) {
+			private_object_t *tech_pvt;
+			switch_channel_t *channel;
+	
+			channel = switch_core_session_get_channel(session);
+			assert(channel != NULL);
+
+			tech_pvt = switch_core_session_get_private(session);
+			assert(tech_pvt != NULL);
+			switch_set_flag_locked(tech_pvt, TFLAG_BYE);
+			switch_channel_hangup(channel, event->release_cause);
+			switch_core_session_rwunlock(session);
+		}
+		*uuid = '\0';
+
+	} 
+
+	isup_exec_command(ss7boost_handle,
+					  event->span, 
+					  event->chan, 
+					  -1,
+					  SIGBOOST_EVENT_CALL_STOPPED_ACK,
+					  0);
+
+
+}
+
+static void handle_call_start(ss7boost_handle_t *ss7boost_handle, ss7boost_client_event_t *event)
+{
+	switch_core_session_t *session = NULL;
+	switch_channel_t *channel = NULL;
+	char name[128];
+
+	if (*ss7boost_handle->span_chanmap[event->span].map[event->chan]) {
+		isup_exec_command(ss7boost_handle,
+						  event->span, 
+						  event->chan, 
+						  -1,
+						  SIGBOOST_EVENT_CALL_START_NACK,
+						  SIGBOOST_RELEASE_CAUSE_BUSY);		
+		return;
+	}
+
+	
+	if ((session = switch_core_session_request(&wanpipe_endpoint_interface, NULL))) {
+		private_object_t *tech_pvt;
+
+		switch_core_session_add_stream(session, NULL);
+		if ((tech_pvt = (private_object_t *) switch_core_session_alloc(session, sizeof(private_object_t)))) {
+			memset(tech_pvt, 0, sizeof(*tech_pvt));
+			switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
+			channel = switch_core_session_get_channel(session);
+			switch_core_session_set_private(session, tech_pvt);
+			sprintf(name, "wanpipe/ss7boost/s%dc%d", event->span+1, event->chan+1);
+			switch_channel_set_name(channel, name);
+			tech_pvt->session = session;
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Hey where is my memory pool?\n");
+			goto fail;
+		}
+
+
+		if ((tech_pvt->caller_profile = switch_caller_profile_new(switch_core_session_get_pool(session),
+																  NULL,
+																  globals.dialplan,
+																  "FreeSWITCH(boost)",
+																  (char *)event->calling_number_digits,
+#ifdef WIN32
+																  NULL,
+#else
+																  (char *)event->calling_number_digits,
+#endif
+																  NULL,
+																  NULL,
+																  NULL,
+																  (char *)modname,
+																  NULL,
+																  (char *)event->called_number_digits))) {
+			switch_channel_set_caller_profile(channel, tech_pvt->caller_profile);
+		}
+
+		switch_set_flag_locked(tech_pvt, TFLAG_INBOUND);
+
+		tech_pvt->cause = -1;
+
+		tech_pvt->ss7boost_handle = ss7boost_handle;
+		tech_pvt->boost_span_number = event->span;
+		tech_pvt->boost_chan_number = event->chan;
+		tech_pvt->boost_pres = event->calling_number_presentation;
+		
+		if (!(tech_pvt->wpsock = wp_open(event->span+1, event->chan+1))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open channel %d:%d\n", event->span+1, event->chan+1);
+			goto fail;
+		}
+
+		switch_copy_string(ss7boost_handle->span_chanmap[event->span].map[event->chan], switch_core_session_get_uuid(session), 
+						   sizeof(ss7boost_handle->span_chanmap[event->span].map[event->chan]));
+		
+		switch_channel_set_state(channel, CS_INIT);
+		isup_exec_command(ss7boost_handle,
+						  event->span, 
+						  event->chan, 
+						  -1,
+						  SIGBOOST_EVENT_CALL_START_ACK,
+						  0);
+		switch_core_session_thread_launch(session);
+		return;
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Create new Inbound Channel!\n");
+	}
+
+	
+ fail:
+	if (session) {
+		switch_core_session_destroy(&session);
+	}
+
+	isup_exec_command(ss7boost_handle,
+					  event->span, 
+					  event->chan, 
+					  -1,
+					  SIGBOOST_EVENT_CALL_STOPPED,
+					  SIGBOOST_RELEASE_CAUSE_BUSY);
+
+}
+
+
+static void handle_heartbeat(ss7boost_handle_t *ss7boost_handle, ss7boost_client_event_t *event)
+{
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Heartbeat!\n");
+
+	isup_exec_command(ss7boost_handle,
+					  event->span, 
+					  event->chan, 
+					  -1,
+					  SIGBOOST_EVENT_HEARTBEAT,
+					  0);
+}
+
+
+static void handle_call_start_ack(ss7boost_handle_t *ss7boost_handle, ss7boost_client_event_t *event)
+{
+	char *uuid = ss7boost_handle->setup_array[event->call_setup_id];
+	
+	if (*uuid) {
+		switch_core_session_t *session;
+
+		if ((session = switch_core_session_locate(uuid))) {
+			private_object_t *tech_pvt;
+			switch_channel_t *channel;
+	
+			channel = switch_core_session_get_channel(session);
+			assert(channel != NULL);
+			
+			tech_pvt = switch_core_session_get_private(session);
+			assert(tech_pvt != NULL);
+			
+			tech_pvt->ss7boost_handle = ss7boost_handle;
+			tech_pvt->boost_span_number = event->span;
+			tech_pvt->boost_chan_number = event->chan;
+			
+			switch_copy_string(ss7boost_handle->span_chanmap[event->span].map[event->chan], switch_core_session_get_uuid(session), 
+							   sizeof(ss7boost_handle->span_chanmap[event->span].map[event->chan]));
+
+
+
+			if (!tech_pvt->wpsock) {
+				if (!(tech_pvt->wpsock = wp_open(tech_pvt->boost_span_number+1, tech_pvt->boost_chan_number+1))) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open fd for s%dc%d! [%s]\n", 
+									  tech_pvt->boost_span_number+1, tech_pvt->boost_chan_number+1, strerror(errno));
+					switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					return;
+				}
+				if (wanpipe_codec_init(tech_pvt) != SWITCH_STATUS_SUCCESS) {
+					switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					return;
+				}
+			}
+
+			switch_channel_mark_pre_answered(channel);
+			
+			switch_core_session_rwunlock(session);
+		}
+		*uuid = '\0';
+	}
+}
+
+static void handle_call_start_nack_ack(ss7boost_handle_t *ss7boost_handle, ss7boost_client_event_t *event)
+{
+	// WTF IS THIS! ?
+}
+
+static void handle_call_answer(ss7boost_handle_t *ss7boost_handle, ss7boost_client_event_t *event)
+{
+	char *uuid = ss7boost_handle->span_chanmap[event->span].map[event->chan];
+
+	if (*uuid) {
+		switch_core_session_t *session;
+		
+		if ((session = switch_core_session_locate(uuid))) {
+			private_object_t *tech_pvt;
+			switch_channel_t *channel;
+	
+			channel = switch_core_session_get_channel(session);
+			assert(channel != NULL);
+
+			tech_pvt = switch_core_session_get_private(session);
+			assert(tech_pvt != NULL);
+
+			if (!tech_pvt->wpsock) {
+				if (!(tech_pvt->wpsock=wp_open(tech_pvt->boost_span_number+1, tech_pvt->boost_chan_number+1))) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open fd for s%dc%d! [%s]\n", 
+									  tech_pvt->boost_span_number+1, tech_pvt->boost_chan_number+1, strerror(errno));
+					switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					return;
+				}
+				if (wanpipe_codec_init(tech_pvt) != SWITCH_STATUS_SUCCESS) {
+					switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
+					return;
+				}
+			}
+			
+			switch_channel_mark_answered(channel);
+			switch_core_session_rwunlock(session);
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Session %s missing!\n", uuid);
+			*uuid = '\0';
+		}
+
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "No UUID?\n");
+	}
+}
+
+static void handle_call_stop_ack(ss7boost_handle_t *ss7boost_handle, ss7boost_client_event_t *event)
+{
+	// TODO anything here?
+}
+
+
+static void handle_call_start_nack(ss7boost_handle_t *ss7boost_handle, ss7boost_client_event_t *event)
+{
+	char *uuid = ss7boost_handle->setup_array[event->call_setup_id];
+	
+	if (*uuid) {
+		switch_core_session_t *session;
+
+		if ((session = switch_core_session_locate(uuid))) {
+			private_object_t *tech_pvt;
+			switch_channel_t *channel;
+	
+			channel = switch_core_session_get_channel(session);
+			assert(channel != NULL);
+			
+			tech_pvt = switch_core_session_get_private(session);
+			assert(tech_pvt != NULL);
+			
+			tech_pvt->ss7boost_handle = ss7boost_handle;
+			tech_pvt->boost_span_number = event->span;
+			tech_pvt->boost_chan_number = event->chan;
+			
+			switch_channel_hangup(channel, event->release_cause);
+			
+			isup_exec_command(ss7boost_handle,
+							  event->span,
+							  event->chan, 
+							  event->call_setup_id,
+							  SIGBOOST_EVENT_CALL_START_NACK_ACK,
+							  0);
+
+			switch_core_session_rwunlock(session);
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Session %s missing!\n", uuid);
+		}
+		*uuid = '\0';
+	}
+}
+
+static int parse_ss7_event(ss7boost_handle_t *ss7boost_handle, ss7boost_client_event_t *event)
+{
+	int ret = 0;
+
+	switch_mutex_lock(ss7boost_handle->mutex);
+		
+	validate_number((unsigned char*)event->called_number_digits);
+	validate_number((unsigned char*)event->calling_number_digits);
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
+					  "\nRX EVENT\n"
+					  "===================================\n"
+					  "           rType: %s (%0x HEX)\n"
+					  "           rSpan: [%d]\n"
+					  "           rChan: [%d]\n"
+					  "  rCalledNum: %s\n"
+					  " rCallingNum: %s\n"
+					  "      rCause: %s\n"
+					  " rInterface : [w%dg%d]\n"
+					  "  rEvent ID : [%d]\n"
+					  "   rSetup ID: [%d]\n"
+					  "        rSeq: [%d]\n"
+					  "===================================\n"
+					  "\n",
+					  ss7boost_client_event_id_name(event->event_id),
+					  event->event_id,
+					  event->span+1,
+					  event->chan+1,
+					  (event->called_number_digits_count ? (char *) event->called_number_digits : "N/A"),
+					  (event->calling_number_digits_count ? (char *) event->calling_number_digits : "N/A"),
+					  switch_channel_cause2str(event->release_cause),
+					  event->span+1,
+					  event->chan+1,
+					  event->event_id,
+					  event->call_setup_id,
+					  event->seqno
+					  );
+	
+
+	switch(event->event_id) {
+	
+	case SIGBOOST_EVENT_CALL_START:
+		handle_call_start(ss7boost_handle, event);
+		break;
+	case SIGBOOST_EVENT_CALL_STOPPED:
+		handle_call_stop(ss7boost_handle, event);
+		break;
+	case SIGBOOST_EVENT_CALL_START_ACK:
+		handle_call_start_ack(ss7boost_handle, event);
+		break;
+	case SIGBOOST_EVENT_CALL_START_NACK:
+		handle_call_start_nack(ss7boost_handle, event);
+		break;
+	case SIGBOOST_EVENT_CALL_ANSWERED:
+		handle_call_answer(ss7boost_handle, event);
+		break;
+	case SIGBOOST_EVENT_HEARTBEAT:
+		handle_heartbeat(ss7boost_handle, event);
+		break;
+	case SIGBOOST_EVENT_CALL_START_NACK_ACK:
+		handle_call_start_nack_ack(ss7boost_handle, event);
+		break;
+	case SIGBOOST_EVENT_CALL_STOPPED_ACK:
+		handle_call_stop_ack(ss7boost_handle, event);
+		break;
+	default:
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Warning no handler implemented for [%s]\n", 
+						  ss7boost_client_event_id_name(event->event_id));
+		break;
+	}
+	switch_mutex_unlock(ss7boost_handle->mutex);
+	return ret;
+}
+
+static void *SWITCH_THREAD_FUNC boost_thread_run(switch_thread_t *thread, void *obj)
+{
+	ss7boost_handle_t *ss7boost_handle = (ss7boost_handle_t *) obj;
+	ss7boost_client_event_t *event;
+
+	if (ss7boost_client_connection_open(&ss7boost_handle->mcon,
+									ss7boost_handle->local_ip, 
+									ss7boost_handle->local_port,
+									ss7boost_handle->remote_ip,
+									ss7boost_handle->remote_port,
+									module_pool) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "FATAL ERROR CREATING CLIENT CONNECTION\n");
+		return NULL;
+	}
+			
+	isup_exec_command(ss7boost_handle,
+					  0,
+					  0, 
+					  -1,
+					  SIGBOOST_EVENT_SYSTEM_RESTART,
+					  0);
+	
+	
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Monitor Thread Started\n");
+	
+	switch_mutex_lock(globals.hash_mutex);
+	globals.configured_boost_spans++;
+	switch_mutex_unlock(globals.hash_mutex);
+
+	globals.ss7boost_handle = ss7boost_handle;
+	
+	for(;;) {
+		if (ss7boost_client_connection_read(&ss7boost_handle->mcon, &event) == SWITCH_STATUS_SUCCESS) {
+				struct timeval current;
+				struct timeval difftime;
+				gettimeofday(&current,NULL);
+				timersub (&current, &event->tv, &difftime);
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Socket Event [%s] T=%d:%d\n",
+								  ss7boost_client_event_id_name(event->event_id),
+								  (int)difftime.tv_sec, (int)difftime.tv_usec);
+				
+				parse_ss7_event(ss7boost_handle, event);
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error: Reading from Boost Socket! %s\n", strerror(errno));
+			break;
+		}
+	}
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Close udp socket\n");
+	ss7boost_client_connection_close(&ss7boost_handle->mcon);
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Monitor Thread Ended\n");	
+	
+
+	return NULL;
+}
+
+static void launch_ss7boost_handle(ss7boost_handle_t *ss7boost_handle)
+{
+	switch_thread_t *thread;
+	switch_threadattr_t *thd_attr = NULL;
+	
+	switch_threadattr_create(&thd_attr, module_pool);
+	switch_threadattr_detach_set(thd_attr, 1);
+	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
+	switch_thread_create(&thread, thd_attr, boost_thread_run, ss7boost_handle, module_pool);
+}
+
+
+
 static switch_status_t config_wanpipe(int reload)
 {
 	char *cf = "wanpipe.conf";
 	int current_span = 0, min_span = 0, max_span = 0;
-	switch_xml_t cfg, xml, settings, param, span;
+	switch_xml_t cfg, xml, settings, param, pri_spans, ss7boost_handles, span, analog_channels, channel;
 
 	globals.samples_per_frame = DEFAULT_SAMPLES_PER_FRAME;
 	globals.dtmf_on = 150;
@@ -1410,14 +2211,151 @@
 				globals.dtmf_on = atoi(val);
 			} else if (!strcmp(var, "dtmf-off")) {
 				globals.dtmf_off = atoi(val);
+			} else if (!strcmp(var, "dialplan")) {
+				set_global_dialplan(val);
 			} else if (!strcmp(var, "supress-dtmf-tone")) {
 				globals.supress_dtmf_tone = switch_true(val);
 			}
 		}
 	}
 
+	ss7boost_handles = switch_xml_child(cfg, "ss7boost_handles");
+	for (span = switch_xml_child(ss7boost_handles, "handle"); span; span = span->next) {
+		char *local_ip = NULL, *remote_ip = NULL;
+		int local_port = 0, remote_port = 0;
+		ss7boost_handle_t *ss7boost_handle;
+
+		for (param = switch_xml_child(span, "param"); param; param = param->next) {
+			char *var = (char *) switch_xml_attr_soft(param, "name");
+			char *val = (char *) switch_xml_attr_soft(param, "value");
+			
+			if (!strcasecmp(var, "local-ip")) {
+				local_ip = val;
+			} else if (!strcasecmp(var, "local-port")) {
+				local_port = atoi(val);
+			} else if (!strcasecmp(var, "remote-ip")) {
+				remote_ip = val;
+			} else if (!strcasecmp(var, "remote-port")) {
+				remote_port = atoi(val);
+			}
+		}
+
+
+		if (!(local_ip && local_port && remote_ip && remote_port)) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Config, skipping...\n");
+			continue;
+		}
+
+		assert(ss7boost_handle = malloc(sizeof(*ss7boost_handle)));
+		memset(ss7boost_handle, 0, sizeof(*ss7boost_handle));
+		ss7boost_handle->local_ip = switch_core_strdup(module_pool, local_ip);
+		ss7boost_handle->local_port = local_port;
+		ss7boost_handle->remote_ip = switch_core_strdup(module_pool, remote_ip);
+		ss7boost_handle->remote_port = remote_port;
+
+		switch_mutex_init(&ss7boost_handle->mutex, SWITCH_MUTEX_NESTED, module_pool);
+		launch_ss7boost_handle(ss7boost_handle);
+		break;
+	}
+
+	analog_channels = switch_xml_child(cfg, "analog_channels");
+	for(channel = switch_xml_child(analog_channels, "channel"); channel; channel = channel->next) {
+		char *c_type = (char *) switch_xml_attr(channel, "type");
+		char *c_dev = (char *) switch_xml_attr(channel, "device");
+		char *user = NULL;
+		char *domain = NULL;
+		char *cid_name = NULL, *cid_num = NULL;
+		analog_channel_t *alc;
+		analog_type_t a_type = ANALOG_TYPE_UNKNOWN;
+		wpsock_t *sock;
+		int chan, span;
+		
+		if (!c_type) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing required attribute 'type'\n");
+			continue;
+		}
+
+		if (!strcasecmp(c_type, "phone") || !strcasecmp(c_type, "fxs")) {
+			a_type = ANALOG_TYPE_PHONE_FXS;
+		} else if (!strcasecmp(c_type, "line") || !strcasecmp(c_type, "fxo")) {
+			a_type = ANLOG_TYPE_LINE_FXO;
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid type '%s'\n", c_type);
+			continue;
+		}
+
+		if (!c_dev) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing required attribute 'device'\n");
+			continue;
+		}
+
+		if (!sangoma_span_chan_fromif(c_dev, &span, &chan)) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid device name '%s'\n", c_dev);
+			continue;
+		}
+		
+		if (!(sock = wp_open(span, chan))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot open device '%s' (%s)\n", c_dev, strerror(errno));
+			continue;
+		}
+
+		for (param = switch_xml_child(channel, "param"); param; param = param->next) {
+            char *var = (char *) switch_xml_attr_soft(param, "name");
+            char *val = (char *) switch_xml_attr_soft(param, "value");
+			
+			if (!strcasecmp(var, "user")) {
+				user = var;
+			} else if (!strcasecmp(var, "domain")) {
+				domain = val;
+			} else if (!strcasecmp(var, "caller-id-name")) {
+				cid_name = val;
+			} else if (!strcasecmp(var, "caller-id-number")) {
+				cid_num = val;
+			}
+		}
+
+		assert((alc = malloc(sizeof(*alc))));
+		memset(alc, 0, sizeof(*alc));
+		if (user) {
+			alc->user = strdup(user);
+		}
+		if (domain) {
+			alc->domain = strdup(domain);
+		}
+		if (cid_name) {
+			alc->cid_name = strdup(cid_name);
+		}
+		if (cid_num) {
+			alc->cid_name = strdup(cid_num);
+		}
+		
+		alc->a_type = a_type;
+		alc->sock = sock;
+		alc->chan = chan;
+		alc->span = span;
+
+		if (a_type == ANALOG_TYPE_PHONE_FXS) {
+			FXS_ANALOG_CHANNELS[globals.fxs_index++] = alc;
+		} else {
+			FXO_ANALOG_CHANNELS[globals.fxo_index++] = alc;
+		}
+	}
+
+
+	if (globals.fxs_index) {
+		switch_thread_t *thread;
+		switch_threadattr_t *thd_attr = NULL;
 	
-	for (span = switch_xml_child(cfg, "span"); span; span = span->next) {
+		switch_threadattr_create(&thd_attr, module_pool);
+		switch_threadattr_detach_set(thd_attr, 1);
+		switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
+		switch_thread_create(&thread, thd_attr, fxs_thread_run, NULL, module_pool);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Starting FXS Thread!\n");
+	}
+
+
+	pri_spans = switch_xml_child(cfg, "pri_spans");
+	for (span = switch_xml_child(pri_spans, "span"); span; span = span->next) {
 		char *id = (char *) switch_xml_attr(span, "id");
 		int32_t i = 0;
 
@@ -1498,8 +2436,6 @@
 					SPANS[current_span]->dp = str2dp(val);
 				} else if (!strcmp(var, "l1")) {
 					SPANS[current_span]->l1 = str2l1(val);
-				} else if (!strcmp(var, "dialplan")) {
-					set_global_dialplan(val);
 				}
 			}
 		}
@@ -1507,7 +2443,7 @@
 	switch_xml_free(xml);
 
 	if (!globals.dialplan) {
-		set_global_dialplan("default");
+		set_global_dialplan("XML");
 	}
 
 
@@ -1529,7 +2465,9 @@
 			}
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Launch span %d\n", current_span);
 			pri_thread_launch(&SPANS[current_span]->spri);
+			switch_mutex_lock(globals.hash_mutex);
 			globals.configured_spans++;
+			switch_mutex_unlock(globals.hash_mutex);
 		}
 	}
 

Modified: freeswitch/branches/cparker/src/mod/endpoints/mod_woomera/mod_woomera.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/endpoints/mod_woomera/mod_woomera.c	(original)
+++ freeswitch/branches/cparker/src/mod/endpoints/mod_woomera/mod_woomera.c	Tue Apr 24 10:14:28 2007
@@ -117,7 +117,7 @@
 struct woomera_profile {
 	char *name;
 	switch_socket_t *woomera_socket;
-	apr_thread_mutex_t *iolock;
+	switch_mutex_t *iolock;
 	char woomera_host[WOOMERA_STRLEN];
 	switch_port_t woomera_port;
 	char audio_ip[WOOMERA_STRLEN];
@@ -134,10 +134,10 @@
 	switch_codec_t read_codec;
 	switch_codec_t write_codec;
 	switch_core_session_t *session;
-	switch_pollfd_t read_poll;
-	switch_pollfd_t write_poll;
-	switch_pollfd_t command_poll;
-	char databuf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
+	switch_pollfd_t *read_poll;
+	switch_pollfd_t *write_poll;
+	switch_pollfd_t *command_poll;
+	char databuf[SWITCH_RECOMMENDED_BUFFER_SIZE];
 	switch_mutex_t *iolock;
 	switch_sockaddr_t *udpread;
 	switch_sockaddr_t *udpwrite;
@@ -169,25 +169,23 @@
 static switch_status_t woomera_on_ring(switch_core_session_t *session);
 static switch_status_t woomera_on_loopback(switch_core_session_t *session);
 static switch_status_t woomera_on_transmit(switch_core_session_t *session);
-static switch_call_cause_t woomera_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-												  switch_core_session_t **new_session, switch_memory_pool_t *pool);
-static switch_status_t woomera_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-											switch_io_flag_t flags, int stream_id);
-static switch_status_t woomera_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-											 switch_io_flag_t flags, int stream_id);
+static switch_call_cause_t woomera_outgoing_channel(switch_core_session_t *session,
+													switch_caller_profile_t *outbound_profile,
+													switch_core_session_t **new_session, switch_memory_pool_t **pool);
+static switch_status_t woomera_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id);
+static switch_status_t woomera_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id);
 static switch_status_t woomera_kill_channel(switch_core_session_t *session, int sig);
 static void tech_destroy(private_object * tech_pvt);
-static void woomera_printf(woomera_profile * profile, switch_socket_t *socket, char *fmt, ...);
+static void woomera_printf(woomera_profile * profile, switch_socket_t * socket, char *fmt, ...);
 static char *woomera_message_header(woomera_message * wmsg, char *key);
 static int woomera_enqueue_event(woomera_event_queue * event_queue, woomera_message * wmsg);
 static int woomera_dequeue_event(woomera_event_queue * event_queue, woomera_message * wmsg);
-static int woomera_message_parse(switch_socket_t *fd, woomera_message * wmsg, int timeout, woomera_profile * profile,
-								 woomera_event_queue * event_queue);
-static int connect_woomera(switch_socket_t **new_sock, woomera_profile * profile, int flags);
+static int woomera_message_parse(switch_socket_t * fd, woomera_message * wmsg, int timeout, woomera_profile * profile, woomera_event_queue * event_queue);
+static int connect_woomera(switch_socket_t ** new_sock, woomera_profile * profile, int flags);
 static int woomera_profile_thread_running(woomera_profile * profile, int set, int new);
-static int woomera_locate_socket(woomera_profile * profile, switch_socket_t **woomera_socket);
+static int woomera_locate_socket(woomera_profile * profile, switch_socket_t ** woomera_socket);
 static int tech_create_read_socket(private_object * tech_pvt);
-static void *woomera_channel_thread_run(switch_thread_t *thread, void *obj);
+static void *woomera_channel_thread_run(switch_thread_t * thread, void *obj);
 static void *woomera_thread_run(void *obj);
 static int tech_activate(private_object * tech_pvt);
 
@@ -294,7 +292,7 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static void woomera_socket_close(switch_socket_t **socket)
+static void woomera_socket_close(switch_socket_t ** socket)
 {
 	if (*socket) {
 		switch_socket_close(*socket);
@@ -306,7 +304,7 @@
 static void udp_socket_close(struct private_object *tech_pvt)
 {
 	if (tech_pvt->udp_socket) {
-		apr_socket_shutdown(tech_pvt->udp_socket, APR_SHUTDOWN_READWRITE);
+		switch_socket_shutdown(tech_pvt->udp_socket, SWITCH_SHUTDOWN_READWRITE);
 		woomera_socket_close(&tech_pvt->udp_socket);
 	}
 }
@@ -327,19 +325,19 @@
 		return SWITCH_STATUS_FALSE;
 	}
 
-    switch(sig) {
-    case SWITCH_SIG_KILL:
-        udp_socket_close(tech_pvt);
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s WOOMERA KILL\n", switch_channel_get_name(channel));
-        break;
-    case SWITCH_SIG_BREAK:
-        {
-            const char p = 0;
-            switch_size_t len = sizeof(p);
-            switch_socket_sendto(tech_pvt->udp_socket, tech_pvt->udpwrite, 0, &p, &len);
-        }
-        break;
-    }
+	switch (sig) {
+	case SWITCH_SIG_KILL:
+		udp_socket_close(tech_pvt);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s WOOMERA KILL\n", switch_channel_get_name(channel));
+		break;
+	case SWITCH_SIG_BREAK:
+		{
+			const char p = 0;
+			switch_size_t len = sizeof(p);
+			switch_socket_sendto(tech_pvt->udp_socket, tech_pvt->udpwrite, 0, &p, &len);
+		}
+		break;
+	}
 
 
 	return SWITCH_STATUS_SUCCESS;
@@ -364,7 +362,7 @@
 	tech_pvt = switch_core_session_get_private(session);
 	assert(tech_pvt != NULL);
 
-	return switch_socket_waitfor(&tech_pvt->read_poll, ms) ? SWITCH_STATUS_FALSE : SWITCH_STATUS_SUCCESS;
+	return switch_socket_waitfor(tech_pvt->read_poll, ms) ? SWITCH_STATUS_FALSE : SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t woomera_waitfor_write(switch_core_session_t *session, int ms, int stream_id)
@@ -375,11 +373,10 @@
 	assert(tech_pvt != NULL);
 
 	return SWITCH_STATUS_SUCCESS;
-//	return switch_socket_waitfor(&tech_pvt->write_poll, ms);
+//  return switch_socket_waitfor(tech_pvt->write_poll, ms);
 }
 
-static switch_status_t woomera_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout,
-											switch_io_flag_t flags, int stream_id)
+static switch_status_t woomera_read_frame(switch_core_session_t *session, switch_frame_t **frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
 	switch_channel_t *channel = NULL;
 	struct private_object *tech_pvt = NULL;
@@ -405,7 +402,7 @@
 
 	len = sizeof(tech_pvt->databuf);
 	if (switch_socket_recvfrom(tech_pvt->udpread, tech_pvt->udp_socket, 0, tech_pvt->databuf, &len) == SWITCH_STATUS_SUCCESS) {
-		pframe->datalen = (uint32_t)len;
+		pframe->datalen = (uint32_t) len;
 		pframe->samples = (int) pframe->datalen / 2;
 		return SWITCH_STATUS_SUCCESS;
 	}
@@ -413,14 +410,13 @@
 	return SWITCH_STATUS_FALSE;
 }
 
-static switch_status_t woomera_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout,
-											 switch_io_flag_t flags, int stream_id)
+static switch_status_t woomera_write_frame(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id)
 {
 	switch_channel_t *channel = NULL;
 	struct private_object *tech_pvt = NULL;
 	switch_size_t len;
 	//switch_frame_t *pframe;
-	
+
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
 
@@ -430,11 +426,10 @@
 	if (!tech_pvt->udp_socket) {
 		return SWITCH_STATUS_GENERR;
 	}
-
 	//pframe = &tech_pvt->frame;
 	len = frame->datalen;
 	if (switch_socket_sendto(tech_pvt->udp_socket, tech_pvt->udpwrite, 0, frame->data, &len) == SWITCH_STATUS_SUCCESS) {
-		frame->datalen = (uint32_t)len;
+		frame->datalen = (uint32_t) len;
 		return SWITCH_STATUS_SUCCESS;
 	}
 
@@ -452,7 +447,6 @@
 
 static const switch_io_routines_t woomera_io_routines = {
 	/*.outgoing_channel */ woomera_outgoing_channel,
-	/*.answer_channel */ NULL,
 	/*.read_frame */ woomera_read_frame,
 	/*.write_frame */ woomera_write_frame,
 	/*.kill_channel */ woomera_kill_channel,
@@ -481,16 +475,16 @@
 /* Make sure when you have 2 sessions in the same scope that you pass the appropriate one to the routines
    that allocate memory or you will have 1 channel with memory allocated from another channel's pool!
 */
-static switch_call_cause_t woomera_outgoing_channel(switch_core_session_t *session, switch_caller_profile_t *outbound_profile,
-													switch_core_session_t **new_session, switch_memory_pool_t *pool)
+static switch_call_cause_t woomera_outgoing_channel(switch_core_session_t *session,
+													switch_caller_profile_t *outbound_profile,
+													switch_core_session_t **new_session, switch_memory_pool_t **pool)
 {
 	if ((*new_session = switch_core_session_request(&woomera_endpoint_interface, pool)) != 0) {
 		struct private_object *tech_pvt;
 		switch_channel_t *channel;
 
 		switch_core_session_add_stream(*new_session, NULL);
-		if ((tech_pvt =
-			 (struct private_object *) switch_core_session_alloc(*new_session, sizeof(struct private_object))) != 0) {
+		if ((tech_pvt = (struct private_object *) switch_core_session_alloc(*new_session, sizeof(struct private_object))) != 0) {
 			memset(tech_pvt, 0, sizeof(*tech_pvt));
 			switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(*new_session));
 			tech_pvt->profile = &default_profile;
@@ -538,10 +532,8 @@
 	}
 
 
-	woomera_printf(tech_pvt->profile, tech_pvt->command_channel, "hangup %s%s", tech_pvt->call_info.callid,
-				   WOOMERA_RECORD_SEPERATOR);
-	if (woomera_message_parse
-		(tech_pvt->command_channel, &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue) < 0) {
+	woomera_printf(tech_pvt->profile, tech_pvt->command_channel, "hangup %s%s", tech_pvt->call_info.callid, WOOMERA_RECORD_SEPERATOR);
+	if (woomera_message_parse(tech_pvt->command_channel, &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue) < 0) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "{%s} Already Disconnected\n", tech_pvt->profile->name);
 	}
 
@@ -551,7 +543,7 @@
 }
 
 
-static void woomera_printf(woomera_profile * profile, switch_socket_t *socket, char *fmt, ...)
+static void woomera_printf(woomera_profile * profile, switch_socket_t * socket, char *fmt, ...)
 {
 	char *stuff;
 	size_t res = 0, len = 0;
@@ -570,7 +562,7 @@
 	} else {
 		if (profile && globals.debug) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Send Message: {%s} [%s/%d]\n%s\n%s", profile->name,
-								  profile->woomera_host, profile->woomera_port, WOOMERA_DEBUG_LINE, stuff);
+							  profile->woomera_host, profile->woomera_port, WOOMERA_DEBUG_LINE, stuff);
 		}
 		len = strlen(stuff);
 		switch_socket_send(socket, stuff, &len);
@@ -637,8 +629,7 @@
 	return 0;
 }
 
-static int woomera_message_parse(switch_socket_t *fd, woomera_message * wmsg, int timeout, woomera_profile * profile,
-								 woomera_event_queue * event_queue)
+static int woomera_message_parse(switch_socket_t * fd, woomera_message * wmsg, int timeout, woomera_profile * profile, woomera_event_queue * event_queue)
 {
 	char *cur, *cr, *next = NULL;
 	char buf[2048] = "", *ptr;
@@ -660,7 +651,7 @@
 	bytes = 0;
 	while (!strstr(buf, WOOMERA_RECORD_SEPERATOR)) {
 		size_t len = 1;
-        switch_status_t status;
+		switch_status_t status;
 
 		if (!profile->thread_running) {
 			return -1;
@@ -668,16 +659,16 @@
 
 		status = switch_socket_recv(fd, ptr, &len);
 
-        if (status == 70007) {
-            char bbuf = '\n';
-            switch_size_t blen = sizeof(bbuf);
-            switch_socket_send(fd, &bbuf, &blen);
-            continue;
-        }
-        
-        if (status != SWITCH_STATUS_SUCCESS) {
-                return -1;
-        }
+		if (status == 70007) {
+			char bbuf = '\n';
+			switch_size_t blen = sizeof(bbuf);
+			switch_socket_send(fd, &bbuf, &blen);
+			continue;
+		}
+
+		if (status != SWITCH_STATUS_SUCCESS) {
+			return -1;
+		}
 
 		ptr++;
 		bytes++;
@@ -687,7 +678,7 @@
 
 	if (globals.debug) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Receive Message: {%s} [%s/%d]\n%s\n%s", profile->name,
-							  profile->woomera_host, profile->woomera_port, WOOMERA_DEBUG_LINE, buf);
+						  profile->woomera_host, profile->woomera_port, WOOMERA_DEBUG_LINE, buf);
 	}
 
 	while ((cur = next) != 0) {
@@ -796,7 +787,7 @@
 }
 
 
-static int connect_woomera(switch_socket_t **new_sock, woomera_profile * profile, int flags)
+static int connect_woomera(switch_socket_t ** new_sock, woomera_profile * profile, int flags)
 {
 
 	switch_sockaddr_t *sa;
@@ -809,8 +800,8 @@
 		return -1;
 	}
 
-    switch_socket_timeout_set((*new_sock), 10000000);
-    switch_socket_opt_set((*new_sock), SWITCH_SO_KEEPALIVE, 1);
+	switch_socket_timeout_set((*new_sock), 10000000);
+	switch_socket_opt_set((*new_sock), SWITCH_SO_KEEPALIVE, 1);
 
 	/*
 	   status = switch_socket_bind((*new_sock), sa);
@@ -841,7 +832,7 @@
 
 }
 
-static int woomera_locate_socket(woomera_profile * profile, switch_socket_t **woomera_socket)
+static int woomera_locate_socket(woomera_profile * profile, switch_socket_t ** woomera_socket)
 {
 	woomera_message wmsg;
 
@@ -851,16 +842,14 @@
 			if (!woomera_profile_thread_running(profile, 0, 0)) {
 				break;
 			}
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "{%s} Cannot Reconnect to Woomera! retry in 5 seconds\n",
-								  profile->name);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "{%s} Cannot Reconnect to Woomera! retry in 5 seconds\n", profile->name);
 			switch_sleep(WOOMERA_RECONNECT_TIME);
 		}
 
 		if (*woomera_socket) {
 			if (switch_test_flag(profile, PFLAG_INBOUND)) {
 				woomera_printf(profile, *woomera_socket, "LISTEN%s", WOOMERA_RECORD_SEPERATOR);
-				if (woomera_message_parse(*woomera_socket,
-										  &wmsg, WOOMERA_HARD_TIMEOUT, profile, &profile->event_queue) < 0) {
+				if (woomera_message_parse(*woomera_socket, &wmsg, WOOMERA_HARD_TIMEOUT, profile, &profile->event_queue) < 0) {
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! Woomera is broken!\n", profile->name);
 					globals.panic = 1;
 					woomera_profile_thread_running(&default_profile, 1, 0);
@@ -927,18 +916,14 @@
 						   tech_pvt->profile->audio_ip,
 						   tech_pvt->port,
 						   WOOMERA_LINE_SEPERATOR,
-						   tech_pvt->caller_profile->caller_id_name,
-						   tech_pvt->caller_profile->caller_id_number, WOOMERA_RECORD_SEPERATOR);
+						   tech_pvt->caller_profile->caller_id_name, tech_pvt->caller_profile->caller_id_number, WOOMERA_RECORD_SEPERATOR);
 
-			woomera_message_parse(tech_pvt->command_channel,
-								  &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue);
+			woomera_message_parse(tech_pvt->command_channel, &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue);
 		} else {
 			switch_set_flag_locked(tech_pvt, TFLAG_PARSE_INCOMING);
 			woomera_printf(tech_pvt->profile, tech_pvt->command_channel, "LISTEN%s", WOOMERA_RECORD_SEPERATOR);
-			if (woomera_message_parse(tech_pvt->command_channel,
-									  &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue) < 0) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! Woomera is broken!\n",
-									  tech_pvt->profile->name);
+			if (woomera_message_parse(tech_pvt->command_channel, &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue) < 0) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! Woomera is broken!\n", tech_pvt->profile->name);
 				switch_set_flag_locked(tech_pvt, TFLAG_ABORT);
 				globals.panic = 1;
 			}
@@ -952,7 +937,7 @@
 
 
 
-static void *woomera_channel_thread_run(switch_thread_t *thread, void *obj)
+static void *woomera_channel_thread_run(switch_thread_t * thread, void *obj)
 {
 	switch_core_session_t *session = obj;
 	switch_channel_t *channel = NULL;
@@ -992,13 +977,9 @@
 		if (switch_test_flag(tech_pvt, TFLAG_ANSWER)) {
 			switch_clear_flag_locked(tech_pvt, TFLAG_ANSWER);
 #ifdef USE_ANSWER
-			woomera_printf(tech_pvt->profile, tech_pvt->command_channel, "ANSWER %s%s", tech_pvt->call_info.callid,
-						   WOOMERA_RECORD_SEPERATOR);
-			if (woomera_message_parse
-				(tech_pvt->command_channel, &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile,
-				 &tech_pvt->event_queue) < 0) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! Woomera is broken!\n",
-									  tech_pvt->profile->name);
+			woomera_printf(tech_pvt->profile, tech_pvt->command_channel, "ANSWER %s%s", tech_pvt->call_info.callid, WOOMERA_RECORD_SEPERATOR);
+			if (woomera_message_parse(tech_pvt->command_channel, &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue) < 0) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! Woomera is broken!\n", tech_pvt->profile->name);
 				switch_set_flag_locked(tech_pvt, TFLAG_ABORT);
 				globals.panic = 1;
 				continue;
@@ -1010,11 +991,8 @@
 			switch_mutex_lock(tech_pvt->iolock);
 			woomera_printf(tech_pvt->profile, tech_pvt->command_channel, "DTMF %s %s%s", tech_pvt->call_info.callid,
 						   tech_pvt->dtmfbuf, WOOMERA_RECORD_SEPERATOR);
-			if (woomera_message_parse
-				(tech_pvt->command_channel, &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile,
-				 &tech_pvt->event_queue) < 0) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! Woomera is broken!\n",
-									  tech_pvt->profile->name);
+			if (woomera_message_parse(tech_pvt->command_channel, &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue) < 0) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! Woomera is broken!\n", tech_pvt->profile->name);
 				switch_set_flag_locked(tech_pvt, TFLAG_ABORT);
 				globals.panic = 1;
 				continue;
@@ -1028,9 +1006,7 @@
 			struct timeval now;
 			int elapsed;
 			gettimeofday(&now, NULL);
-			elapsed =
-				(((now.tv_sec * 1000) + now.tv_usec / 1000) -
-				 ((tech_pvt->started.tv_sec * 1000) + tech_pvt->started.tv_usec / 1000));
+			elapsed = (((now.tv_sec * 1000) + now.tv_usec / 1000) - ((tech_pvt->started.tv_sec * 1000) + tech_pvt->started.tv_usec / 1000));
 			if (elapsed > tech_pvt->timeout) {
 				/* call timed out! */
 				switch_set_flag_locked(tech_pvt, TFLAG_ABORT);
@@ -1095,10 +1071,9 @@
 				if ((tech_pvt->caller_profile = switch_caller_profile_new(switch_core_session_get_pool(session),
 																		  NULL,
 																		  tech_pvt->profile->dialplan,
-																		  cid_name, cid_num, ip, NULL, NULL, NULL, (char *)modname, NULL, exten)) != 0) {
+																		  cid_name, cid_num, ip, NULL, NULL, NULL, (char *) modname, NULL, exten)) != 0) {
 					char name[128];
-					snprintf(name, sizeof(name), "Woomera/%s-%04x", tech_pvt->caller_profile->destination_number,
-							 rand() & 0xffff);
+					snprintf(name, sizeof(name), "Woomera/%s-%04x", tech_pvt->caller_profile->destination_number, rand() & 0xffff);
 					switch_channel_set_name(channel, name);
 					switch_channel_set_caller_profile(channel, tech_pvt->caller_profile);
 
@@ -1107,15 +1082,10 @@
 				woomera_printf(tech_pvt->profile, tech_pvt->command_channel,
 							   "%s %s%s"
 							   "Raw-Audio: %s/%d%s",
-							   MEDIA_ANSWER,
-							   wmsg.callid,
-							   WOOMERA_LINE_SEPERATOR,
-							   tech_pvt->profile->audio_ip, tech_pvt->port, WOOMERA_RECORD_SEPERATOR);
-
-				if (woomera_message_parse(tech_pvt->command_channel,
-										  &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue) < 0) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! Woomera is broken!\n",
-										  tech_pvt->profile->name);
+							   MEDIA_ANSWER, wmsg.callid, WOOMERA_LINE_SEPERATOR, tech_pvt->profile->audio_ip, tech_pvt->port, WOOMERA_RECORD_SEPERATOR);
+
+				if (woomera_message_parse(tech_pvt->command_channel, &wmsg, WOOMERA_HARD_TIMEOUT, tech_pvt->profile, &tech_pvt->event_queue) < 0) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! Woomera is broken!\n", tech_pvt->profile->name);
 					switch_set_flag_locked(tech_pvt, TFLAG_ABORT);
 					globals.panic = 1;
 					continue;
@@ -1135,23 +1105,17 @@
 					if ((ptr = strchr(ip, '/')) != 0) {
 						*ptr = '\0';
 						ptr++;
-						port = (switch_port_t)atoi(ptr);
+						port = (switch_port_t) atoi(ptr);
 					}
 					/* Move Channel's State Machine to RING */
 					switch_channel_answer(channel);
 					switch_channel_set_state(channel, CS_RING);
 
 					if (switch_sockaddr_info_get(&tech_pvt->udpwrite,
-												 ip,
-												 SWITCH_UNSPEC,
-												 port,
-												 0,
-												 switch_core_session_get_pool(tech_pvt->session)) !=
-						SWITCH_STATUS_SUCCESS) {
+												 ip, SWITCH_UNSPEC, port, 0, switch_core_session_get_pool(tech_pvt->session)) != SWITCH_STATUS_SUCCESS) {
 						if (globals.debug) {
 							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
-												  WOOMERA_DEBUG_PREFIX "{%s} Cannot resolve %s\n",
-												  tech_pvt->profile->name, ip);
+											  WOOMERA_DEBUG_PREFIX "{%s} Cannot resolve %s\n", tech_pvt->profile->name, ip);
 						}
 						switch_channel_hangup(channel, SWITCH_CAUSE_NETWORK_OUT_OF_ORDER);
 					}
@@ -1159,13 +1123,11 @@
 			}
 		}
 		if (globals.debug > 2) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, WOOMERA_DEBUG_PREFIX "CHECK {%s}(%d)\n",
-								  tech_pvt->profile->name, res);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, WOOMERA_DEBUG_PREFIX "CHECK {%s}(%d)\n", tech_pvt->profile->name, res);
 		}
 	}
 	if (globals.debug > 1) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, WOOMERA_DEBUG_PREFIX "Monitor thread for %s done.\n",
-							  tech_pvt->profile->name);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, WOOMERA_DEBUG_PREFIX "Monitor thread for %s done.\n", tech_pvt->profile->name);
 	}
 
 	return NULL;
@@ -1204,7 +1166,7 @@
 				break;
 			}
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Woomera Thread Up {%s} %s/%d\n", profile->name,
-								  profile->woomera_host, profile->woomera_port);
+							  profile->woomera_host, profile->woomera_port);
 
 		}
 
@@ -1219,20 +1181,18 @@
 			continue;
 		}
 
-		if ((((res = woomera_dequeue_event(&profile->event_queue, &wmsg)) != 0) ||
-			 ((res = woomera_message_parse(profile->woomera_socket, &wmsg,
-										  /* if we are not stingy with threads we can block forever */
-										  0, profile, NULL))) != 0)) {
+		if ((((res = woomera_dequeue_event(&profile->event_queue, &wmsg)) != 0) || ((res = woomera_message_parse(profile->woomera_socket, &wmsg,
+																												 /* if we are not stingy with threads we can block forever */
+																												 0, profile, NULL))) != 0)) {
 			if (res < 0) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! I lost my connection to woomera!\n",
-									  profile->name);
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT, "{%s} HELP! I lost my connection to woomera!\n", profile->name);
 				woomera_socket_close(&profile->woomera_socket);
 
 				//global_set_flag(TFLAG_ABORT);
 				globals.panic = 1;
 				continue;
 
-		/* Can't get to the following code --Commented out for now.*/
+				/* Can't get to the following code --Commented out for now. */
 /*				if (profile->woomera_socket) 
 					if (switch_test_flag(profile, PFLAG_INBOUND)) {
 						woomera_printf(profile, profile->woomera_socket, "LISTEN%s", WOOMERA_RECORD_SEPERATOR);
@@ -1267,8 +1227,7 @@
 
 					switch_core_session_add_stream(session, NULL);
 
-					if ((tech_pvt =
-						 (struct private_object *) switch_core_session_alloc(session, sizeof(struct private_object))) != 0) {
+					if ((tech_pvt = (struct private_object *) switch_core_session_alloc(session, sizeof(struct private_object))) != 0) {
 						memset(tech_pvt, 0, sizeof(*tech_pvt));
 						switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
 						tech_pvt->profile = &default_profile;
@@ -1346,7 +1305,7 @@
 	strncpy(profile->dialplan, "default", sizeof(profile->dialplan) - 1);
 	strncpy(profile->audio_ip, "127.0.0.1", sizeof(profile->audio_ip) - 1);
 	strncpy(profile->woomera_host, "127.0.0.1", sizeof(profile->woomera_host) - 1);
-	profile->woomera_port = (switch_port_t)42420;
+	profile->woomera_port = (switch_port_t) 42420;
 
 	if ((settings = switch_xml_child(cfg, "settings"))) {
 		for (param = switch_xml_child(settings, "param"); param; param = param->next) {
@@ -1371,7 +1330,7 @@
 			} else if (!strcmp(var, "host")) {
 				strncpy(profile->woomera_host, val, sizeof(profile->woomera_host) - 1);
 			} else if (!strcmp(var, "port")) {
-				profile->woomera_port = (switch_port_t)atoi(val);
+				profile->woomera_port = (switch_port_t) atoi(val);
 			} else if (!strcmp(var, "disabled")) {
 				if (atoi(val) > 0) {
 					switch_set_flag(profile, PFLAG_DISABLED);

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/Makefile	Tue Apr 24 10:14:28 2007
@@ -7,16 +7,11 @@
 OBJS += radiuscdr.o
 LDFLAGS += -lfreeradius-client
 
-# uncomment to build mysqlcdr
-#OBJS += mysqlcdr.o
-#CFLAGS  += $(shell mysql_config --include) 
-#LDFLAGS += $(shell mysql_config --libs)
-
-ifneq ($(shell which mysql_config),)
-  CFLAGS  += $(shell mysql_config --include)
-  LDFLAGS += $(shell mysql_config --libs)
-  OBJS    += mysqlcdr.o
-endif
+#ifneq ($(shell which mysql_config),)
+#  CFLAGS  += $(shell mysql_config --include)
+#  LDFLAGS += $(shell mysql_config --libs)
+#  OBJS    += mysqlcdr.o
+#endif
 
 all:	depends $(OBJS) $(MODNAME).$(DYNAMIC_LIB_EXTEN)
 

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/basecdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/basecdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/basecdr.cpp	Tue Apr 24 10:14:28 2007
@@ -24,6 +24,7 @@
  * Contributor(s):
  * 
  * Yossi Neiman <freeswitch AT cartissolutions.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * Description: This C++ source file describes the BaseCDR class that all other CDR classes inherit from.
  * It handles the bulk of the processing of data from the switch_channel_t objects.
@@ -214,7 +215,7 @@
 		{
 			if(fixed)
 			{
-				switch_console_printf(SWITCH_CHANNEL_LOG,"Wildcards are not allow in the fixed chanvars list.  Item removed.\n");
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Wildcards are not allow in the fixed chanvars list.  Item removed.\n");
 				iItr = chanvarlist.erase(iItr);
 			}
 			else
@@ -271,19 +272,19 @@
 						sql_type = CDR_TINY;
 						break;
 					default:
-						switch_console_printf(SWITCH_CHANNEL_LOG,"Valid fixed channel variable types are x (decimal), d (double), i (integer), t (tiny), s (string).  You tried to give a type of %s to chanvar %s.\nReverting this chanvar type to a string type.\n",tempstring2.c_str(),tempstring.c_str());
+						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Valid fixed channel variable types are x (decimal), d (double), i (integer), t (tiny), s (string).  You tried to give a type of %s to chanvar %s.\nReverting this chanvar type to a string type.\n", tempstring2.c_str(), tempstring.c_str());
 						sql_type = CDR_STRING;
 				}
 			}
 			else
 			{
-				switch_console_printf(SWITCH_CHANNEL_LOG,"Valid fixed channel variable types are x (decimal), d (double), i (integer), t (tiny), s (string).  You tried to give a type of %s to chanvar %s.\nReverting this chanvar type to a string type.\n",tempstring2.c_str(),tempstring.c_str());
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Valid fixed channel variable types are x (decimal), d (double), i (integer), t (tiny), s (string).  You tried to give a type of %s to chanvar %s.\nReverting this chanvar type to a string type.\n", tempstring2.c_str(), tempstring.c_str());
 				sql_type = CDR_STRING;
 			}
 		}
 		else
 		{
-			switch_console_printf(SWITCH_CHANNEL_LOG,"No parameter set, for channel variable %s, using default type of string.\n",iItr->c_str());
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "No parameter set, for channel variable %s, using default type of string.\n", iItr->c_str());
 			sql_type = CDR_STRING;
 			tempstring = *iItr;
 		}

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/basecdr.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/basecdr.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/basecdr.h	Tue Apr 24 10:14:28 2007
@@ -46,8 +46,7 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 
-struct switch_mod_cdr_newchannel_t 
-{
+struct switch_mod_cdr_newchannel_t {
 	switch_core_session_t *session;
 	switch_channel_t *channel;
 	//switch_channel_timetable_t *timetable;
@@ -57,7 +56,7 @@
 	//bool originate;
 };
 
-enum switch_mod_cdr_sql_types_t { CDR_INTEGER,CDR_STRING,CDR_DECIMAL,CDR_DOUBLE,CDR_TINY };
+enum switch_mod_cdr_sql_types_t { CDR_INTEGER, CDR_STRING, CDR_DECIMAL, CDR_DOUBLE, CDR_TINY };
 
 #ifdef WIN32
 #define STDCALL __stdcall
@@ -65,54 +64,54 @@
 #define STDCALL
 #endif
 
-typedef apr_status_t (STDCALL *modcdr_time_convert_t)(apr_time_exp_t*,apr_time_t);
+typedef switch_status_t (STDCALL * modcdr_time_convert_t) (switch_time_exp_t *, switch_time_t);
 
 class BaseCDR {
-	public:
-		BaseCDR();
-		virtual ~BaseCDR();
-		BaseCDR(switch_mod_cdr_newchannel_t *newchannel);
-		virtual void connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param) = 0;
-		virtual void disconnect() = 0;
-		virtual bool process_record() = 0;
-		virtual bool is_activated() = 0;
-		virtual void tempdump_record() = 0;
-		virtual void reread_tempdumped_records() = 0;
-		virtual std::string get_display_name() = 0; // Get the module name
-	protected:
-		void parse_channel_variables_xconfig(std::string& unparsed,std::list<std::string>& chanvarslist,bool fixed);
-		void parse_channel_variables_xconfig(std::string& unparsed,std::list<std::string>& chanvarslist,std::vector<switch_mod_cdr_sql_types_t>& chanvars_fixed_types);  // Typically used for SQL types
-		void process_channel_variables(const std::list<std::string>& stringlist,const std::list<std::string>& fixedlist,switch_channel_t *channel,bool repeat = 1); //This is used for supplemental chanvars
-		void process_channel_variables(const std::list<std::string>& stringlist,switch_channel_t *channel); // This is used for fixed chanvars
-		void escape_string(std::string& src);
-		std::string escape_chararray(char* src);
-		switch_time_t callstartdate;
-		switch_time_t callanswerdate;
-		switch_time_t callenddate;
-		switch_time_t calltransferdate;
-		switch_call_cause_t hangupcause;
-		char *hangupcause_text;
-		char clid[80];
-		bool originated;  // Did they originate this call?
-		char dialplan[80];
-		char myuuid[37]; // 36 + 1 to hold \0
-		char destuuid[37];
-		char src[80];
-		char dst[80];
-		char srcchannel[80];
-		char dstchannel[80];
-		char ani[80];
-		char aniii[80];
-		char network_addr[40];
-		char lastapp[80];
-		char lastdata[255]; 
-		switch_time_t billusec; // Yes, you heard me, we're measuring in microseconds
-		int disposition; // Currently 0 = Busy/Unanswered, 1 = Answered
-		int amaflags;
-		switch_core_session_t *coresession;
-		std::list<std::pair<std::string,std::string> > chanvars_fixed;
-		std::map<std::string,std::string> chanvars_supp;
-		bool errorstate; // True if there is an error writing the log
+  public:
+	BaseCDR();
+	virtual ~ BaseCDR();
+	BaseCDR(switch_mod_cdr_newchannel_t * newchannel);
+	virtual void connect(switch_xml_t & cfg, switch_xml_t & xml, switch_xml_t & settings, switch_xml_t & param) = 0;
+	virtual void disconnect() = 0;
+	virtual bool process_record() = 0;
+	virtual bool is_activated() = 0;
+	virtual void tempdump_record() = 0;
+	virtual void reread_tempdumped_records() = 0;
+	virtual std::string get_display_name() = 0;	// Get the module name
+  protected:
+	void parse_channel_variables_xconfig(std::string & unparsed, std::list < std::string > &chanvarslist, bool fixed);
+	void parse_channel_variables_xconfig(std::string & unparsed, std::list < std::string > &chanvarslist, std::vector < switch_mod_cdr_sql_types_t > &chanvars_fixed_types);	// Typically used for SQL types
+	void process_channel_variables(const std::list < std::string > &stringlist, const std::list < std::string > &fixedlist, switch_channel_t *channel, bool repeat = 1);	//This is used for supplemental chanvars
+	void process_channel_variables(const std::list < std::string > &stringlist, switch_channel_t *channel);	// This is used for fixed chanvars
+	void escape_string(std::string & src);
+	     std::string escape_chararray(char *src);
+	switch_time_t callstartdate;
+	switch_time_t callanswerdate;
+	switch_time_t callenddate;
+	switch_time_t calltransferdate;
+	switch_call_cause_t hangupcause;
+	char *hangupcause_text;
+	char clid[80];
+	bool originated;			// Did they originate this call?
+	char dialplan[80];
+	char myuuid[37];			// 36 + 1 to hold \0
+	char destuuid[37];
+	char src[80];
+	char dst[80];
+	char srcchannel[80];
+	char dstchannel[80];
+	char ani[80];
+	char aniii[80];
+	char network_addr[40];
+	char lastapp[80];
+	char lastdata[255];
+	switch_time_t billusec;		// Yes, you heard me, we're measuring in microseconds
+	int disposition;			// Currently 0 = Busy/Unanswered, 1 = Answered
+	int amaflags;
+	switch_core_session_t *coresession;
+	                      std::list < std::pair < std::string, std::string > >chanvars_fixed;
+	                      std::map < std::string, std::string > chanvars_supp;
+	bool errorstate;			// True if there is an error writing the log
 };
 
 #endif

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/baseregistry.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/baseregistry.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/baseregistry.h	Tue Apr 24 10:14:28 2007
@@ -42,34 +42,32 @@
 #ifdef __cplusplus
 #include <vector>
 
-template<class T> BaseCDR* basecdr_factory(switch_mod_cdr_newchannel_t *newchannel)
+template < class T > BaseCDR * basecdr_factory(switch_mod_cdr_newchannel_t * newchannel)
 {
 	return new T(newchannel);
 }
 
-typedef BaseCDR* (*basecdr_creator)(switch_mod_cdr_newchannel_t *newchannel);
+typedef BaseCDR *(*basecdr_creator) (switch_mod_cdr_newchannel_t * newchannel);
 
-class BaseRegistry
-{
-	private:
-		std::vector<basecdr_creator> m_bases; // Stores all modules
-		std::vector<basecdr_creator> active_bases; // Stores only active modules
-	public:
-		typedef std::vector<basecdr_creator>::iterator iterator;
-		static BaseRegistry& get();
-		void add(basecdr_creator);
-		void reset_active(); // Clears the active vector for reloading of configuration.
-		void add_active(iterator);
-		iterator begin();
-		iterator end();
-		iterator active_begin();
-		iterator active_end();
+class BaseRegistry {
+  private:
+	std::vector < basecdr_creator > m_bases;	// Stores all modules
+	std::vector < basecdr_creator > active_bases;	// Stores only active modules
+  public:
+	typedef std::vector < basecdr_creator >::iterator iterator;
+	static BaseRegistry & get();
+	void add(basecdr_creator);
+	void reset_active();		// Clears the active vector for reloading of configuration.
+	void add_active(iterator);
+	iterator begin();
+	iterator end();
+	iterator active_begin();
+	iterator active_end();
 };
 
-class BaseRegistration
-{
-	public:
-		BaseRegistration(basecdr_creator);
+class BaseRegistration {
+  public:
+	BaseRegistration(basecdr_creator);
 };
 
 #define AUTO_REGISTER_BASECDR(basecdr) BaseRegistration _basecdr_registration_ ## basecdr(&basecdr_factory<basecdr>);

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/cdrcontainer.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/cdrcontainer.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/cdrcontainer.cpp	Tue Apr 24 10:14:28 2007
@@ -24,6 +24,7 @@
  * Contributor(s):
  * 
  * Yossi Neiman <freeswitch AT cartissolutions.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * Description: This C++ source file describes the CDRContainer singleton object used by mod_cdr to control
  * the creation, processing, and destruction of various CDR logger objects.
@@ -53,7 +54,7 @@
 	newchannel = 0;
 	
 	if (!(xml = switch_xml_open_cfg(configfile, &cfg, NULL))) 
-		switch_console_printf(SWITCH_CHANNEL_LOG,"open of %s failed\n", configfile);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", configfile);
 	else
 	{	
 		BaseRegistry& registry(BaseRegistry::get());
@@ -89,7 +90,7 @@
 		ptr->disconnect();
 	}
 		
-	switch_console_printf(SWITCH_CHANNEL_LOG,"mod_cdr shutdown gracefully.");
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "mod_cdr shutdown gracefully.");
 }
 
 #ifdef SWITCH_QUEUE_ENHANCED
@@ -225,7 +226,7 @@
 			basecdr_creator func = *it;
 			
 			BaseCDR* newloggerobject = func(newchannel);
-			switch_console_printf(SWITCH_CHANNEL_LOG,"Adding a new logger object to the queue.\n");
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Adding a new logger object to the queue.\n");
 			switch_queue_push(cdrqueue,newloggerobject);
 		}
 		newchannel->callerprofile = newchannel->callerprofile->next;

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/cdrcontainer.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/cdrcontainer.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/cdrcontainer.h	Tue Apr 24 10:14:28 2007
@@ -51,11 +51,11 @@
 extern "C" {
 #endif
 
-class CDRContainer {
-	public:
+	class CDRContainer {
+	  public:
 		CDRContainer();
 		CDRContainer(switch_memory_pool_t *module_pool);
-		~CDRContainer();
+		                    ~CDRContainer();
 		void add_cdr(switch_core_session_t *session);
 		void process_records();
 #ifdef SWITCH_QUEUE_ENHANCED
@@ -65,21 +65,19 @@
 #endif
 		void active(switch_stream_handle_t *stream);
 		void available(switch_stream_handle_t *stream);
-	protected:
-	private:
-		switch_xml_t cfg, xml, settings, param;
+	  protected:
+	  private:
+		                       switch_xml_t cfg, xml, settings, param;
 		switch_queue_t *cdrqueue;
-		std::string tempfilepath;
+		               std::string tempfilepath;
 		char configfile[13];
 		bool queue_paused;
-};
+	};
 
 #ifdef __cplusplus
 }
 #endif
-
 #endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c++

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/csvcdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/csvcdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/csvcdr.cpp	Tue Apr 24 10:14:28 2007
@@ -24,6 +24,7 @@
  * Contributor(s):
  * 
  * Yossi Neiman <freeswitch AT cartissolutions.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * Description: This C++ source file describes the CsvCDR class that handles processing CDRs to a CSV format.
  * This is the standard CSV module, and has a list of predefined variables to log out which can be
@@ -67,7 +68,7 @@
 		convert_time(&tempcallend, callenddate);
 		
 		// Format the times
-		apr_size_t retsizecsd, retsizecad, retsizectd, retsizeced;  //csd == callstartdate, cad == callanswerdate, ced == callenddate, ceff == callenddate_forfile
+		switch_size_t retsizecsd, retsizecad, retsizectd, retsizeced;  //csd == callstartdate, cad == callanswerdate, ced == callenddate, ceff == callenddate_forfile
 		char format[] = "%Y-%m-%d %H:%M:%S";
 		switch_strftime(formattedcallstartdate,&retsizecsd,sizeof(formattedcallstartdate),format,&tempcallstart);
 		switch_strftime(formattedcallanswerdate,&retsizecad,sizeof(formattedcallanswerdate),format,&tempcallanswer);
@@ -101,7 +102,7 @@
 
 void CsvCDR::connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param)
 {
-	switch_console_printf(SWITCH_CHANNEL_LOG, "CsvCDR::connect() - Loading configuration file.\n");
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "CsvCDR::connect() - Loading configuration file.\n");
 	activated = 0; // Set it as inactive initially
 	connectionstate = 0; // Initialize it to false to show that we aren't yet connected.
 	
@@ -170,7 +171,7 @@
 					convert_time = switch_time_exp_lt;
 				else
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n",val);
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n", val);
 					convert_time = switch_time_exp_lt;
 				}
 			}
@@ -182,11 +183,11 @@
 			if(outputfile.good())
 			{
 				activated = 1;
-				switch_console_printf(SWITCH_CHANNEL_LOG,"CsvCDR activated, log rotation will occur at or after %d MB\n",(int)(filesize_limit >> 20));
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "CsvCDR activated, log rotation will occur at or after %d MB\n", (int)(filesize_limit >> 20));
 			}
 		}
 		else
-			switch_console_printf(SWITCH_CHANNEL_LOG,"CsvCDR::connect(): You did not specify the minimum parameters for using this module.  You must specify at least a path to have the records logged to.\n");
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "CsvCDR::connect(): You did not specify the minimum parameters for using this module.  You must specify at least a path to have the records logged to.\n");
 	}
 }
 
@@ -213,7 +214,7 @@
 		
 	switch_time_exp_lt(&now_converted,now);
 		
-	apr_size_t retsize;		
+	switch_size_t retsize;		
 	char format[] = "%Y-%m-%d-%H-%M-%S";
 	char formatteddate[100];
 	memset(formatteddate,0,100);
@@ -228,7 +229,7 @@
 	outputfile.open(filename.c_str(),std::ios_base::app|std::ios_base::binary);
 	if(outputfile.fail())
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Could not open the CSV file %s .  CsvCDR logger will not be functional until this is resolved and a reload is issued.  Failbit is set to %d.\n",filename.c_str(),outputfile.fail());
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not open the CSV file %s .  CsvCDR logger will not be functional until this is resolved and a reload is issued.  Failbit is set to %d.\n", filename.c_str(), outputfile.fail());
 		activated = 0;
 	}
 	else
@@ -332,7 +333,7 @@
 	chanvars_fixed_list.clear();
 	chanvars_supp_list.clear();
 	connectionstate = 0;
-	switch_console_printf(SWITCH_CHANNEL_LOG,"Shutting down CsvCDR...  Done!\n");	
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Shutting down CsvCDR...  Done!\n");	
 }
 
 AUTO_REGISTER_BASECDR(CsvCDR);

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/csvcdr.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/csvcdr.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/csvcdr.h	Tue Apr 24 10:14:28 2007
@@ -44,38 +44,38 @@
 #ifndef CSVCDR
 #define CSVCDR
 
-class CsvCDR : public BaseCDR {
-	public:
-		CsvCDR();
-		CsvCDR(switch_mod_cdr_newchannel_t *newchannel);
-		//CsvCDR(const CsvCDR& copyFrom);
-		virtual ~CsvCDR();
-		virtual bool process_record();
-		virtual void connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param); // connect and disconnect need to be static because we're persisting connections until shutdown
-		virtual void disconnect();
-		virtual bool is_activated();
-		virtual void tempdump_record();
-		virtual void reread_tempdumped_records();
-		virtual std::string get_display_name();
+class CsvCDR:public BaseCDR {
+  public:
+	CsvCDR();
+	CsvCDR(switch_mod_cdr_newchannel_t * newchannel);
+	//CsvCDR(const CsvCDR& copyFrom);
+	virtual ~ CsvCDR();
+	virtual bool process_record();
+	virtual void connect(switch_xml_t & cfg, switch_xml_t & xml, switch_xml_t & settings, switch_xml_t & param);	// connect and disconnect need to be static because we're persisting connections until shutdown
+	virtual void disconnect();
+	virtual bool is_activated();
+	virtual void tempdump_record();
+	virtual void reread_tempdumped_records();
+	virtual std::string get_display_name();
 
-	private:
-		static bool activated; // Is this module activated?
-		static bool connectionstate; // What is the status of the connection?
-		static bool logchanvars;
-		static modcdr_time_convert_t convert_time;
-		static bool repeat_fixed_in_supp; // Repeat the fixed chanvars in the supplemental?
-		static std::string outputfile_path; // The directory we'll dump these into
-		static std::list<std::string> chanvars_fixed_list; // Normally this would be used, but not in this class
-		static std::list<std::string> chanvars_supp_list; // This will hold the list for all chanvars here
-		static std::string display_name;
-		char formattedcallstartdate[100];
-		char formattedcallanswerdate[100];
-		char formattedcalltransferdate[100];
-		char formattedcallenddate[100];
-		static std::ofstream outputfile;
-		static std::ofstream::pos_type filesize_limit;
-		void check_file_size_and_open(); // Checks the size of the file, and if it's greater than size allowed, rotates it.
-		void open_file();
+  private:
+	static bool activated;		// Is this module activated?
+	static bool connectionstate;	// What is the status of the connection?
+	static bool logchanvars;
+	static modcdr_time_convert_t convert_time;
+	static bool repeat_fixed_in_supp;	// Repeat the fixed chanvars in the supplemental?
+	static std::string outputfile_path;	// The directory we'll dump these into
+	static std::list < std::string > chanvars_fixed_list;	// Normally this would be used, but not in this class
+	static std::list < std::string > chanvars_supp_list;	// This will hold the list for all chanvars here
+	static std::string display_name;
+	char formattedcallstartdate[100];
+	char formattedcallanswerdate[100];
+	char formattedcalltransferdate[100];
+	char formattedcallenddate[100];
+	static std::ofstream outputfile;
+	static std::ofstream::pos_type filesize_limit;
+	void check_file_size_and_open();	// Checks the size of the file, and if it's greater than size allowed, rotates it.
+	void open_file();
 };
 
 #endif

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/curlcdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/curlcdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/curlcdr.cpp	Tue Apr 24 10:14:28 2007
@@ -28,6 +28,7 @@
  * Yossi Neiman <freeswitch AT cartissolutions.com>
  * Bret McDanel <trixter AT 0xdecafbad.com>
  * Anthony Minessale II <anthmct at yahoo.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * Description: This C++ source file describes the CurlCDR class that handles processing CDRs to HTTP endpoint.
  * This is the standard Curl module, and has a list of predefined variables to log out which can be
@@ -106,14 +107,14 @@
 
 void CurlCDR::connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param)
 {
-	switch_console_printf(SWITCH_CHANNEL_LOG, "CurlCDR::connect() - Loading configuration file.\n");
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "CurlCDR::connect() - Loading configuration file.\n");
 	activated = 0; // Set it as inactive initially
 	connectionstate = 0; // Initialize it to false to show that we aren't yet connected.
 
-    switch_console_printf(SWITCH_CHANNEL_LOG,"Checking to see if curlcdr is valid\n");
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Checking to see if curlcdr is valid\n");
 	if ((settings = switch_xml_child(cfg, "curlcdr"))) 
 	{
-        switch_console_printf(SWITCH_CHANNEL_LOG,"curlcdr appears to be!!!\n");
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "curlcdr appears to be!!!\n");
 		int count_config_params = 0;  // Need to make sure all params are set before we load
 		for (param = switch_xml_child(settings, "param"); param; param = param->next) 
 		{
@@ -168,7 +169,7 @@
 					convert_time = switch_time_exp_lt;
 				else
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n",val);
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n", val);
 					convert_time = switch_time_exp_lt;
 				}
 			}
@@ -179,13 +180,13 @@
             if(strlen(gateway_url))
 			{
 				activated = 1;
-				switch_console_printf(SWITCH_CHANNEL_LOG,"CurlCDR activated");
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "CurlCDR activated");
 			}
             else
-                switch_console_printf(SWITCH_CHANNEL_LOG,"CurlCDR::connect(): You must specify a gateway_url to have the records logged to.\n");
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "CurlCDR::connect(): You must specify a gateway_url to have the records logged to.\n");
 		}
 		else
-			switch_console_printf(SWITCH_CHANNEL_LOG,"CurlCDR::connect(): You did not specify the minimum parameters for using this module.  You must specify at least a gateway_url to have the records logged to.\n");
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "CurlCDR::connect(): You did not specify the minimum parameters for using this module.  You must specify at least a gateway_url to have the records logged to.\n");
 	}
 }
 
@@ -370,7 +371,7 @@
 	chanvars_fixed_list.clear();
 	chanvars_supp_list.clear();
 	connectionstate = 0;
-	switch_console_printf(SWITCH_CHANNEL_LOG,"Shutting down CurlCDR...  Done!");	
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Shutting down CurlCDR...  Done!");	
 }
 
 AUTO_REGISTER_BASECDR(CurlCDR);

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/curlcdr.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/curlcdr.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/curlcdr.h	Tue Apr 24 10:14:28 2007
@@ -50,37 +50,37 @@
 #ifndef CURLCDR
 #define CURLCDR
 
-class CurlCDR : public BaseCDR {
-	public:
-		CurlCDR();
-		CurlCDR(switch_mod_cdr_newchannel_t *newchannel);
-		//CurlCDR(const CurlCDR& copyFrom);
-		virtual ~CurlCDR();
-		virtual bool process_record();
-		virtual void connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param); // connect and disconnect need to be static because we're persisting connections until shutdown
-		virtual void disconnect();
-		virtual bool is_activated();
-		virtual void tempdump_record();
-		virtual void reread_tempdumped_records();
-		virtual std::string get_display_name();
-    virtual std::string itos(int i);
-    virtual std::string lltos(long long ll);
+class CurlCDR:public BaseCDR {
+  public:
+	CurlCDR();
+	CurlCDR(switch_mod_cdr_newchannel_t * newchannel);
+	//CurlCDR(const CurlCDR& copyFrom);
+	virtual ~ CurlCDR();
+	virtual bool process_record();
+	virtual void connect(switch_xml_t & cfg, switch_xml_t & xml, switch_xml_t & settings, switch_xml_t & param);	// connect and disconnect need to be static because we're persisting connections until shutdown
+	virtual void disconnect();
+	virtual bool is_activated();
+	virtual void tempdump_record();
+	virtual void reread_tempdumped_records();
+	virtual std::string get_display_name();
+	virtual std::string itos(int i);
+	virtual std::string lltos(long long ll);
 
-	private:
-		static bool activated; // Is this module activated?
-		static bool connectionstate; // What is the status of the connection?
-		static bool logchanvars;
-		static modcdr_time_convert_t convert_time;
-		static const char *gateway_url; // The URL to send data to
-		static const char *gateway_credentials; // The credentials for http auth
-		static std::list<std::string> chanvars_fixed_list; // Normally this would be used, but not in this class
-		static std::list<std::string> chanvars_supp_list; // This will hold the list for all chanvars here
-		static std::string display_name;
-        static std::string postdata;
-		char formattedcallstartdate[100];
-		char formattedcallanswerdate[100];
-		char formattedcalltransferdate[100];
-		char formattedcallenddate[100];
+  private:
+	static bool activated;		// Is this module activated?
+	static bool connectionstate;	// What is the status of the connection?
+	static bool logchanvars;
+	static modcdr_time_convert_t convert_time;
+	static const char *gateway_url;	// The URL to send data to
+	static const char *gateway_credentials;	// The credentials for http auth
+	static std::list < std::string > chanvars_fixed_list;	// Normally this would be used, but not in this class
+	static std::list < std::string > chanvars_supp_list;	// This will hold the list for all chanvars here
+	static std::string display_name;
+	static std::string postdata;
+	char formattedcallstartdate[100];
+	char formattedcallanswerdate[100];
+	char formattedcalltransferdate[100];
+	char formattedcallenddate[100];
 };
 
 #endif

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mod_cdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mod_cdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mod_cdr.cpp	Tue Apr 24 10:14:28 2007
@@ -24,6 +24,7 @@
  * Contributor(s):
  * 
  * Yossi Neiman <freeswitch AT cartissolutions.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * Description: This source file describes the most basic portions of the CDR module.  These are the functions
  * and structures that the Freeswitch core looks for when opening up the DSO file to create the load, shutdown
@@ -130,7 +131,7 @@
 	
 	if (switch_core_new_memory_pool(&module_pool) != SWITCH_STATUS_SUCCESS) 
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG, "OH OH - Can't swim, no pool\n");
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "OH OH - Can't swim, no pool\n");
 		return SWITCH_STATUS_TERM;
 	}
 
@@ -144,7 +145,7 @@
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_runtime(void)
 {
 	RUNNING = 1;
-	switch_console_printf(SWITCH_CHANNEL_LOG, "mod_cdr made it to runtime.  Wee!\n");
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "mod_cdr made it to runtime.  Wee!\n");
 	newcdrcontainer->process_records();
 	
 	return RUNNING ? SWITCH_STATUS_SUCCESS : SWITCH_STATUS_TERM;

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mod_cdr.vcproj
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mod_cdr.vcproj	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mod_cdr.vcproj	Tue Apr 24 10:14:28 2007
@@ -397,6 +397,10 @@
 				>
 			</File>
 			<File
+				RelativePath=".\sqlitecdr.cpp"
+				>
+			</File>
+			<File
 				RelativePath=".\xmlcdr.cpp"
 				>
 			</File>
@@ -431,6 +435,10 @@
 				>
 			</File>
 			<File
+				RelativePath=".\sqlitecdr.h"
+				>
+			</File>
+			<File
 				RelativePath=".\xmlcdr.h"
 				>
 			</File>

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mysqlcdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mysqlcdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mysqlcdr.cpp	Tue Apr 24 10:14:28 2007
@@ -24,6 +24,7 @@
  * Contributor(s):
  * 
  * Yossi Neiman <freeswitch AT cartissolutions.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * Description: This C++ source file describes the MysqlCDR class which handles formatting a CDR out to
  * a MySQL 4.1.x or greater server using prepared statements.
@@ -183,7 +184,7 @@
 					convert_time = switch_time_exp_lt;
 				else
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n",val);
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n", val);
 					convert_time = switch_time_exp_lt;
 				}
 			}
@@ -192,7 +193,7 @@
 		if (count_config_params==4)
 			activated = 1;
 		else
-			switch_console_printf(SWITCH_CHANNEL_LOG,"You did not specify the minimum parameters for using this module.  You must specify a hostname, username, password, and database to use MysqlCDR.  You only supplied %d parameters.\n",count_config_params);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You did not specify the minimum parameters for using this module.  You must specify a hostname, username, password, and database to use MysqlCDR.  You only supplied %d parameters.\n", count_config_params);
 		
 		if(activated)
 		{
@@ -241,10 +242,13 @@
 	if(mysql_real_connect(conn,hostname,username,password,dbname,0,NULL,0) == NULL)
 	{
 		const char *error1 = mysql_error(conn);
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Cannot connect to MySQL Server.  The error was: %s\n",error1);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot connect to MySQL Server.  The error was: %s\n", error1);
 	}
 	else
+	{
 		connectionstate = 1;
+		conn->reconnect = false;
+	}
 	
 	mysql_autocommit(conn,0);
 	stmt = mysql_stmt_init(conn);
@@ -446,7 +450,7 @@
 					break;
 				}
 				default:
-					switch_console_printf(SWITCH_CHANNEL_LOG,"We should not get to this point in this switch/case statement.\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "We should not get to this point in this switch/case statement.\n");
 			}
 			i++;
 		}
@@ -466,13 +470,13 @@
 				case CR_SERVER_GONE_ERROR:
 				case CR_SERVER_LOST:
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"We lost connection to the MySQL server.  Trying to reconnect.\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "We lost connection to the MySQL server.  Trying to reconnect.\n");
 					connect_to_database();
 					break;
 				}
 				default:
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"We have encountered an unknown error when pinging the MySQL server.  Attempting to reconnect anyways.\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "We have encountered an unknown error when pinging the MySQL server.  Attempting to reconnect anyways.\n");
 					connect_to_database();
 				}
 			}
@@ -485,10 +489,10 @@
 			if(mysql_stmt_error_code != 0)
 			{
 				errorstate = 1;
-				switch_console_printf(SWITCH_CHANNEL_LOG,"MysqlCDR::process_record() - Statement executed? Error: %d\n",mysql_stmt_error_code);
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "MysqlCDR::process_record() - Statement executed? Error: %d\n", mysql_stmt_error_code);
 			
 				const char* mysql_stmt_error_string = mysql_stmt_error(stmt);
-				switch_console_printf(SWITCH_CHANNEL_LOG,"MySQL encountered error: %s\n",mysql_stmt_error_string);
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "MySQL encountered error: %s\n", mysql_stmt_error_string);
 			}
 			else
 				errorstate = 0;
@@ -585,7 +589,7 @@
 					break;
 				}
 				default:
-					switch_console_printf(SWITCH_CHANNEL_LOG,"We should not get to this point in this switch/case statement.\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "We should not get to this point in this switch/case statement.\n");
 			}
 			
 			bool* tempbool = (bool*) temp_chanvars_holder.front();

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mysqlcdr.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mysqlcdr.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/mysqlcdr.h	Tue Apr 24 10:14:28 2007
@@ -41,66 +41,66 @@
 #ifndef MYSQLCDR
 #define MYSQLCDR
 
-class MysqlCDR : public BaseCDR {
-	public:
-		MysqlCDR();
-		MysqlCDR(switch_mod_cdr_newchannel_t *newchannel);
-		//MysqlCDR(const MysqlCDR& copyFrom);
-		virtual ~MysqlCDR();
-		virtual bool process_record();
-		virtual void connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param);
-		virtual void disconnect();
-		virtual bool is_activated();
-		virtual void tempdump_record();
-		virtual void reread_tempdumped_records();
-		virtual std::string get_display_name();
+class MysqlCDR:public BaseCDR {
+  public:
+	MysqlCDR();
+	MysqlCDR(switch_mod_cdr_newchannel_t * newchannel);
+	//MysqlCDR(const MysqlCDR& copyFrom);
+	virtual ~ MysqlCDR();
+	virtual bool process_record();
+	virtual void connect(switch_xml_t & cfg, switch_xml_t & xml, switch_xml_t & settings, switch_xml_t & param);
+	virtual void disconnect();
+	virtual bool is_activated();
+	virtual void tempdump_record();
+	virtual void reread_tempdumped_records();
+	virtual std::string get_display_name();
 
-	private:
-		static bool activated;
-		static char sql_query[1024];
-		static std::string tmp_sql_query; // Object must exist to bind the statement, this used for generating the sql
-		static char sql_query_chanvars[100];
-		static MYSQL *conn;
-		static MYSQL_STMT *stmt;
-		static MYSQL_STMT *stmt_chanvars;
-		static bool connectionstate;
-		static bool logchanvars;
-		static std::list<std::string> chanvars_fixed_list;
-		static std::vector<switch_mod_cdr_sql_types_t> chanvars_fixed_types;
-		static std::list<std::string> chanvars_supp_list; // The supplemental list
-		static bool repeat_fixed_in_supp;
-		static char hostname[255];
-		static char username[255];
-		static char dbname[255];
-		static char password[255];
-		static modcdr_time_convert_t convert_time;
-		static std::string display_name;
-		//static fstream tmpfile;
-		std::vector<MYSQL_BIND> bindme;
-		//MYSQL_BIND *bindme;
-		MYSQL_TIME my_callstartdate;
-		MYSQL_TIME my_callanswerdate;
-		MYSQL_TIME my_calltransferdate;
-		MYSQL_TIME my_callenddate;
-		// Why all these long unsigned int's?  MySQL's prep statement API expects these to actually exist and not just be params passed to the function calls.  The are to measure the length of actual data in the char* arrays.
-		long unsigned int clid_length;
-		long unsigned int dialplan_length;
-		long unsigned int myuuid_length;
-		long unsigned int destuuid_length;
-		long unsigned int src_length;
-		long unsigned int dst_length;
-		long unsigned int srcchannel_length;
-		long unsigned int dstchannel_length;
-		long unsigned int ani_length;
-		long unsigned int aniii_length;
-		long unsigned int lastapp_length;
-		long unsigned int lastdata_length;
-		long unsigned int network_addr_length;
-		// Now a couple internal methods
-		template <typename T> void add_parameter(T& param, enum_field_types type, bool *is_null=0);
-		void add_string_parameter(char* param, long unsigned int& param_length, enum_field_types type, bool* is_null=0);
-		void set_mysql_time(switch_time_exp_t& param, MYSQL_TIME& destination);
-		void connect_to_database();
+  private:
+	static bool activated;
+	static char sql_query[1024];
+	static std::string tmp_sql_query;	// Object must exist to bind the statement, this used for generating the sql
+	static char sql_query_chanvars[100];
+	static MYSQL *conn;
+	static MYSQL_STMT *stmt;
+	static MYSQL_STMT *stmt_chanvars;
+	static bool connectionstate;
+	static bool logchanvars;
+	static std::list < std::string > chanvars_fixed_list;
+	static std::vector < switch_mod_cdr_sql_types_t > chanvars_fixed_types;
+	static std::list < std::string > chanvars_supp_list;	// The supplemental list
+	static bool repeat_fixed_in_supp;
+	static char hostname[255];
+	static char username[255];
+	static char dbname[255];
+	static char password[255];
+	static modcdr_time_convert_t convert_time;
+	static std::string display_name;
+	//static fstream tmpfile;
+	       std::vector < MYSQL_BIND > bindme;
+	//MYSQL_BIND *bindme;
+	MYSQL_TIME my_callstartdate;
+	MYSQL_TIME my_callanswerdate;
+	MYSQL_TIME my_calltransferdate;
+	MYSQL_TIME my_callenddate;
+	// Why all these long unsigned int's?  MySQL's prep statement API expects these to actually exist and not just be params passed to the function calls.  The are to measure the length of actual data in the char* arrays.
+	long unsigned int clid_length;
+	long unsigned int dialplan_length;
+	long unsigned int myuuid_length;
+	long unsigned int destuuid_length;
+	long unsigned int src_length;
+	long unsigned int dst_length;
+	long unsigned int srcchannel_length;
+	long unsigned int dstchannel_length;
+	long unsigned int ani_length;
+	long unsigned int aniii_length;
+	long unsigned int lastapp_length;
+	long unsigned int lastdata_length;
+	long unsigned int network_addr_length;
+	// Now a couple internal methods
+	    template < typename T > void add_parameter(T & param, enum_field_types type, bool * is_null = 0);
+	void add_string_parameter(char *param, long unsigned int &param_length, enum_field_types type, bool * is_null = 0);
+	void set_mysql_time(switch_time_exp_t & param, MYSQL_TIME & destination);
+	void connect_to_database();
 };
 
 #endif

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/odbccdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/odbccdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/odbccdr.cpp	Tue Apr 24 10:14:28 2007
@@ -24,6 +24,7 @@
  * Contributor(s):
  * 
  * Yossi Neiman <freeswitch AT cartissolutions.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * Description: This C++ source file describes the OdbcCDR class which handles formatting a CDR out to
  * an ODBC backend using prepared statements.
@@ -201,7 +202,7 @@
 					convert_time = switch_time_exp_lt;
 				else
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n",val);
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n", val);
 					convert_time = switch_time_exp_lt;
 				}
 			}
@@ -216,7 +217,7 @@
 		if (count_config_params==4)
 			activated = 1;
 		else
-			switch_console_printf(SWITCH_CHANNEL_LOG,"You did not specify the minimum parameters for using this module.  You must specify a DSN,hostname, username, password, and database to use OdbcCDR.  You only supplied %d parameters.\n",count_config_params);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "You did not specify the minimum parameters for using this module.  You must specify a DSN,hostname, username, password, and database to use OdbcCDR.  You only supplied %d parameters.\n", count_config_params);
 		
 		if(activated)
 		{
@@ -275,7 +276,7 @@
 		ODBC_res = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &ODBC_env);
 		if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) 
 		{
-			switch_console_printf(SWITCH_CHANNEL_LOG,"Error allocating a new ODBC handle.\n");
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error allocating a new ODBC handle.\n");
 			connectionstate = 0;
 		}
 	}
@@ -284,7 +285,7 @@
 	
 	if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) 
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Error with ODBCSetEnv\n");
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error with ODBCSetEnv\n");
 		SQLFreeHandle(SQL_HANDLE_ENV, ODBC_env);
 		connectionstate = 0;
 	}
@@ -293,7 +294,7 @@
 
 	if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO))
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Error AllocHDB %d\n",ODBC_res);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error AllocHDB %d\n", ODBC_res);
 		SQLFreeHandle(SQL_HANDLE_ENV, ODBC_env);
 		connectionstate = 0;
 	}
@@ -306,14 +307,14 @@
 	ODBC_res = SQLConnect(ODBC_con, (SQLCHAR*)dsn, SQL_NTS, (SQLCHAR*)username, SQL_NTS, (SQLCHAR*)password, SQL_NTS);
 	if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) 
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Error connecting to the ODBC database on %d\n",ODBC_res);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error connecting to the ODBC database on %d\n", ODBC_res);
 		SQLFreeHandle(SQL_HANDLE_DBC, ODBC_con);
 		SQLFreeHandle(SQL_HANDLE_ENV, ODBC_env);
 		connectionstate = 0;
 	}
 	else 
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Connected to %s\n", dsn);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Connected to %s\n", dsn);
 		connectionstate = 1;
 	}
 	
@@ -325,7 +326,7 @@
 
 	if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO))
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Failure in allocating a prepared statement %d\n", ODBC_res);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failure in allocating a prepared statement %d\n", ODBC_res);
 		SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
 	}
 		
@@ -333,7 +334,7 @@
 
 	if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO))
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Error in preparing a statement: %d\n", ODBC_res);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error in preparing a statement: %d\n", ODBC_res);
 		SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
 	}
 		
@@ -343,7 +344,7 @@
 
 		if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO))
 		{
-			switch_console_printf(SWITCH_CHANNEL_LOG,"Failure in allocating a prepared statement %d\n", ODBC_res);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failure in allocating a prepared statement %d\n", ODBC_res);
 			SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt_chanvars);
 		}
 		
@@ -351,7 +352,7 @@
 
 		if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO))
 		{
-			switch_console_printf(SWITCH_CHANNEL_LOG,"Error in preparing a statement: %d\n", ODBC_res);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error in preparing a statement: %d\n", ODBC_res);
 			SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
 		}
 	}
@@ -360,7 +361,7 @@
 	
 	if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO))
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Failure in allocating a prepared statement %d\n", ODBC_res);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failure in allocating a prepared statement %d\n", ODBC_res);
 		SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt_ping);
 	}
 	
@@ -368,7 +369,7 @@
 	
 	if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO))
 	{
-		switch_console_printf(SWITCH_CHANNEL_LOG,"Error in preparing a statement: %d\n", ODBC_res);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error in preparing a statement: %d\n", ODBC_res);
 		SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt_ping);
 	}
 	
@@ -400,7 +401,7 @@
 		if(ODBC_res != SQL_SUCCESS && ODBC_res != SQL_SUCCESS_WITH_INFO)
 		{
 			// Try to reconnect and reprepare
-			switch_console_printf(SWITCH_CHANNEL_LOG,"Error pinging the ODBC backend.  Attempt #%d to reconnect.\n",count+1);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Error pinging the ODBC backend.  Attempt #%d to reconnect.\n", count+1);
 			connect_to_database();
 		}
 	}
@@ -502,7 +503,7 @@
 					break;
 				}
 				default:
-					switch_console_printf(SWITCH_CHANNEL_LOG,"We should not get to this point in this switch/case statement.\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "We should not get to this point in this switch/case statement.\n");
 			}
 			i++;
 		}
@@ -585,7 +586,7 @@
 					break;
 				}
 				default:
-					switch_console_printf(SWITCH_CHANNEL_LOG,"We should not get to this point in this switch/case statement.\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "We should not get to this point in this switch/case statement.\n");
 			}
 		}
 	}

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/odbccdr.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/odbccdr.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/odbccdr.h	Tue Apr 24 10:14:28 2007
@@ -52,53 +52,53 @@
 #ifndef ODBCCDR
 #define ODBCCDR
 
-class OdbcCDR : public BaseCDR {
-	public:
-		OdbcCDR();
-		OdbcCDR(switch_mod_cdr_newchannel_t *newchannel);
-		//OdbcCDR(const MysqlCDR& copyFrom);
-		virtual ~OdbcCDR();
-		virtual bool process_record();
-		virtual void connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param);
-		virtual void disconnect();
-		virtual bool is_activated();
-		virtual void tempdump_record();
-		virtual void reread_tempdumped_records();
-		virtual std::string get_display_name();
+class OdbcCDR:public BaseCDR {
+  public:
+	OdbcCDR();
+	OdbcCDR(switch_mod_cdr_newchannel_t * newchannel);
+	//OdbcCDR(const MysqlCDR& copyFrom);
+	virtual ~ OdbcCDR();
+	virtual bool process_record();
+	virtual void connect(switch_xml_t & cfg, switch_xml_t & xml, switch_xml_t & settings, switch_xml_t & param);
+	virtual void disconnect();
+	virtual bool is_activated();
+	virtual void tempdump_record();
+	virtual void reread_tempdumped_records();
+	virtual std::string get_display_name();
 
-	private:
-		static bool activated;
-		static char sql_query[1024];
-		static modcdr_time_convert_t convert_time;
-		static std::string display_name;
-		static std::string tmp_sql_query; // Object must exist to bind the statement, this used for generating the sql
-		static char sql_query_chanvars[355];
-		static char sql_query_ping[10];
-		static bool connectionstate;
-		static bool logchanvars;
-		static SQLHENV ODBC_env;     /* global ODBC Environment */
-		static SQLHDBC ODBC_con;     /* global ODBC Connection Handle */
-		static SQLHSTMT ODBC_stmt;
-		static SQLHSTMT ODBC_stmt_chanvars;
-		static SQLHSTMT ODBC_stmt_ping;
-		static std::list<std::string> chanvars_fixed_list;
-		static std::vector<switch_mod_cdr_sql_types_t> chanvars_fixed_types;
-		static std::list<std::string> chanvars_supp_list; // The supplemental list
-		static bool repeat_fixed_in_supp;
-		static char dsn[255];
-		static char hostname[255];
-		static char username[255];
-		static char dbname[255];
-		static char password[255];
-		static char tablename[255];
-		static char tablename_chanvars[255];
-		//static fstream tmpfile;
-		char odbc_callstartdate[128];
-		char odbc_callanswerdate[128];
-		char odbc_calltransferdate[128];
-		char odbc_callenddate[128];
-		void disconnect_stage_1();
-		void connect_to_database();
+  private:
+	static bool activated;
+	static char sql_query[1024];
+	static modcdr_time_convert_t convert_time;
+	static std::string display_name;
+	static std::string tmp_sql_query;	// Object must exist to bind the statement, this used for generating the sql
+	static char sql_query_chanvars[355];
+	static char sql_query_ping[10];
+	static bool connectionstate;
+	static bool logchanvars;
+	static SQLHENV ODBC_env;	/* global ODBC Environment */
+	static SQLHDBC ODBC_con;	/* global ODBC Connection Handle */
+	static SQLHSTMT ODBC_stmt;
+	static SQLHSTMT ODBC_stmt_chanvars;
+	static SQLHSTMT ODBC_stmt_ping;
+	static std::list < std::string > chanvars_fixed_list;
+	static std::vector < switch_mod_cdr_sql_types_t > chanvars_fixed_types;
+	static std::list < std::string > chanvars_supp_list;	// The supplemental list
+	static bool repeat_fixed_in_supp;
+	static char dsn[255];
+	static char hostname[255];
+	static char username[255];
+	static char dbname[255];
+	static char password[255];
+	static char tablename[255];
+	static char tablename_chanvars[255];
+	//static fstream tmpfile;
+	char odbc_callstartdate[128];
+	char odbc_callanswerdate[128];
+	char odbc_calltransferdate[128];
+	char odbc_callenddate[128];
+	void disconnect_stage_1();
+	void connect_to_database();
 };
 
 #endif

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/pddcdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/pddcdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/pddcdr.cpp	Tue Apr 24 10:14:28 2007
@@ -24,6 +24,7 @@
  * Contributor(s):
  * 
  * Yossi Neiman <freeswitch AT cartissolutions.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * Description: This C++ source file describes the PddCDR class which handles formatting a CDR out to
  * individual text files in a Perl Data Dumper format.
@@ -101,7 +102,7 @@
 
 void PddCDR::connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param)
 {
-	switch_console_printf(SWITCH_CHANNEL_LOG, "PddCDR::connect() - Loading configuration file.\n");
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "PddCDR::connect() - Loading configuration file.\n");
 	activated = 0; // Set it as inactive initially
 	connectionstate = 0; // Initialize it to false to show that we aren't yet connected.
 	
@@ -135,11 +136,11 @@
 			}
 			else if (!strcmp(var, "chanvars_fixed"))
 			{
-				switch_console_printf(SWITCH_CHANNEL_LOG,"PddCDR has no need for a fixed or supplemental list of channel variables due to the nature of the format.  Please use the setting parameter of \"chanvars\" instead and try again.\n");
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "PddCDR has no need for a fixed or supplemental list of channel variables due to the nature of the format.  Please use the setting parameter of \"chanvars\" instead and try again.\n");
 			}
 			else if (!strcmp(var, "chanvars_supp"))
 			{
-				switch_console_printf(SWITCH_CHANNEL_LOG,"PddCDR has no need for a fixed or supplemental list of channel variables due to the nature of the format.  Please use the setting parameter of \"chanvars\" instead and try again.\n");
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "PddCDR has no need for a fixed or supplemental list of channel variables due to the nature of the format.  Please use the setting parameter of \"chanvars\" instead and try again.\n");
 			}
 			else if(!strcmp(var,"timezone"))
 			{
@@ -149,7 +150,7 @@
 					convert_time = switch_time_exp_lt;
 				else
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n",val);
+				 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n", val);
 					convert_time = switch_time_exp_lt;
 				}
 			}
@@ -158,7 +159,7 @@
 		if(count_config_params > 0)
 			activated = 1;
 		else
-			switch_console_printf(SWITCH_CHANNEL_LOG,"PddCDR::connect(): You did not specify the minimum parameters for using this module.  You must specify at least a path to have the records logged to.\n");
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "PddCDR::connect(): You did not specify the minimum parameters for using this module.  You must specify at least a path to have the records logged to.\n");
 	}
 }
 
@@ -168,7 +169,7 @@
 	
 	bool retval = 0;
 	if(!outputfile)
-		switch_console_printf(SWITCH_CHANNEL_LOG, "PddCDR::process_record():  Unable to open file  %s to commit the call record to.  Invalid path name, invalid permissions, or no space available?\n",outputfile_name.c_str());
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "PddCDR::process_record():  Unable to open file  %s to commit the call record to.  Invalid path name, invalid permissions, or no space available?\n",outputfile_name.c_str());
 	else
 	{
 		// Format the call record and proceed from here...
@@ -247,7 +248,7 @@
 	logchanvars = 0;
 	outputfile_path.clear();
 	chanvars_supp_list.clear();
-	switch_console_printf(SWITCH_CHANNEL_LOG,"Shutting down PddCDR...  Done!");	
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Shutting down PddCDR...  Done!");	
 }
 
 AUTO_REGISTER_BASECDR(PddCDR);

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/pddcdr.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/pddcdr.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/pddcdr.h	Tue Apr 24 10:14:28 2007
@@ -43,33 +43,33 @@
 #ifndef PDDCDR
 #define PDDMCDR
 
-class PddCDR : public BaseCDR {
-	public:
-		PddCDR();
-		PddCDR(switch_mod_cdr_newchannel_t *newchannel);
-		virtual ~PddCDR();
-		virtual bool process_record();
-		virtual void connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param); // connect and disconnect need to be static because we're persisting connections until shutdown
-		virtual void disconnect();
-		virtual bool is_activated();
-		virtual void tempdump_record();
-		virtual void reread_tempdumped_records();
-		virtual std::string get_display_name();
-	private:
-		static bool activated; // Is this module activated?
-		static bool connectionstate; // What is the status of the connection?
-		static bool logchanvars;
-		static modcdr_time_convert_t convert_time;
-		static std::string outputfile_path; // The directory we'll dump these into
-		static std::list<std::string> chanvars_fixed_list; // Normally this would be used, but not in this class
-		static std::list<std::string> chanvars_supp_list; // This will hold the list for all chanvars here
-		static std::string display_name;
-		char formattedcallstartdate[100];
-		char formattedcallanswerdate[100];
-		char formattedcalltransferdate[100];
-		char formattedcallenddate[100];
-		std::string outputfile_name;
-		std::ofstream outputfile;
+class PddCDR:public BaseCDR {
+  public:
+	PddCDR();
+	PddCDR(switch_mod_cdr_newchannel_t * newchannel);
+	virtual ~ PddCDR();
+	virtual bool process_record();
+	virtual void connect(switch_xml_t & cfg, switch_xml_t & xml, switch_xml_t & settings, switch_xml_t & param);	// connect and disconnect need to be static because we're persisting connections until shutdown
+	virtual void disconnect();
+	virtual bool is_activated();
+	virtual void tempdump_record();
+	virtual void reread_tempdumped_records();
+	virtual std::string get_display_name();
+  private:
+	static bool activated;		// Is this module activated?
+	static bool connectionstate;	// What is the status of the connection?
+	static bool logchanvars;
+	static modcdr_time_convert_t convert_time;
+	static std::string outputfile_path;	// The directory we'll dump these into
+	static std::list < std::string > chanvars_fixed_list;	// Normally this would be used, but not in this class
+	static std::list < std::string > chanvars_supp_list;	// This will hold the list for all chanvars here
+	static std::string display_name;
+	char formattedcallstartdate[100];
+	char formattedcallanswerdate[100];
+	char formattedcalltransferdate[100];
+	char formattedcallenddate[100];
+	     std::string outputfile_name;
+	     std::ofstream outputfile;
 };
 
 #endif

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/radiuscdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/radiuscdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/radiuscdr.cpp	Tue Apr 24 10:14:28 2007
@@ -114,48 +114,60 @@
 {
 	switch_console_printf(SWITCH_CHANNEL_LOG, "[RadiusCDR] connect() - Loading configuration file.\n");
 	activated = 0; // Set it as inactive initially
+ 	/* Config Variables and Defaults */
+	char    dictionary[PATH_MAX] = "/usr/local/freeswitch/conf/radius/dictionary";
+	int     num_servers = 0;
+	char    *timeout = NULL;
+	char    *retries = NULL;
+
+
+        rh = rc_new();
+        if (rh == NULL) {
+                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "initialization of mod_cdr_radius structure failed\n");
+                return;
+        }
+        timeout = "5";   
+        retries = "3";
 	
 	if ((settings = switch_xml_child(cfg, "radiuscdr"))) 
 	{
-		int count_config_params = 0;  // Need to make sure all params are set before we load
+
 		for (param = switch_xml_child(settings, "param"); param; param = param->next) 
 		{
 			char *var = (char *) switch_xml_attr_soft(param, "name");
 			char *val = (char *) switch_xml_attr_soft(param, "value");
 
-			if (!strcmp(var, "radiuscdr_conf"))
-			{
-				if(val != 0) {
-					strncpy(path_radiusclient_conf,val,strlen(val));
-					count_config_params++;
-				}
-			}
 
-			else if (!strcmp(var, "acct_server1"))
-			{
-				if(val != 0) {
-					strncpy(accounting_server1,val,strlen(val));
-				}
-			}
-			else if (!strcmp(var, "acct_port1"))
-			{
-				if(val != 0)
-					accounting_port1 = atoi(val);
-			}
-			else if (!strcmp(var, "acct_secret1"))
-			{
+                        if (!strcmp(var, "acctserver")) {
+                                if (num_servers < SERVER_MAX) {
+                                        if (rc_add_config(rh, var, val, "xml config", 0) != 0) {
+                                                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+                                                                "failed setting %s = %s failed\n", var, val);
+                                                rc_destroy(rh);
+                                                return;
+                                        }
+                                        num_servers++;
+                                } else {
+                                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+                                                "you can only specify %d radius servers, ignoring excess server entry\n", SERVER_MAX);
+                                }
+                        }
+                        else if (!strcmp(var, "dictionary")) {
+                                strncpy(dictionary,val,PATH_MAX-1);
+                        }
+                        else if (!strcmp(var, "radius_timeout")) {
+                                timeout = strdup(val);
+                        }
+                        else if (!strcmp(var, "radius_retries")) {
+                                retries = strdup(val);
+                        }
+
+
+			else if (!strcmp(var, "chanvars_supp")) {
 				if(val != 0) {
-					strncpy(accounting_secret1,val,strlen(val));
-				}
-			}
-			else if (!strcmp(var, "chanvars_supp")) 
-			{
-				if(val != 0)
-				{
 					std::string unparsed;
 					unparsed = val;
-					if(unparsed.size() > 0)
-					{
+					if(unparsed.size() > 0) {
 						bool fixed = 0;
 						parse_channel_variables_xconfig(unparsed,chanvars_supp_list,fixed);
 						logchanvars=1;
@@ -163,14 +175,11 @@
 				}
 			}
 
-			else if (!strcmp(var, "chanvars_fixed"))
-			{
-				if(val != 0)
-				{
+			else if (!strcmp(var, "chanvars_fixed")) {
+				if(val != 0) {
 					std::string unparsed;
 					unparsed = val;
-					if(unparsed.size() > 0)
-					{
+					if(unparsed.size() > 0) {
 						bool fixed = 1;
 						parse_channel_variables_xconfig(unparsed,chanvars_fixed_list,fixed);
 						logchanvars=1;
@@ -178,22 +187,58 @@
 				}
 			}
 		}
-		
-		if(	count_config_params > 0 &&
-			(accounting_server1 != NULL && accounting_secret1 != NULL))
-		{
-			if ((rh = rc_read_config(path_radiusclient_conf)) == NULL) {
-				switch_console_printf(SWITCH_CHANNEL_LOG,"[RadiusCDR] Failed to initialize radius config\n");
-			} else if (rc_read_dictionary(rh, rc_conf_str(rh, "dictionary")) != 0) {
-				switch_console_printf(SWITCH_CHANNEL_LOG,"[RadiusCDR] Failed to initialize radius dictionary\n");
-			} else {
-				activated = 1;
-				switch_console_printf(SWITCH_CHANNEL_LOG,"[RadiusCDR] activated\n");
-			}
-		} else {
-			switch_console_printf(SWITCH_CHANNEL_LOG,"[RadiusCDR]You did not specify the minimum parameters for using this module.  You must specify at least one radius server to send records to.\n");
-		}
-	}
+	}	
+
+	if(num_servers > 0) {
+                        
+                if (rc_add_config(rh, "dictionary", dictionary, "xml config", 0) != 0) {
+               	        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+                                 "failed setting dictionary = %s failed\n", dictionary);
+            		rc_destroy(rh);
+                        return;
+	        }
+                if (rc_add_config(rh, "radius_timeout", timeout, "xml config", 0) != 0) {
+                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+                                        "failed setting radius_timeout = %s failed\n", timeout);
+                        rc_destroy(rh);  
+                        return;
+                }
+                if (rc_add_config(rh, "radius_timeout", timeout, "xml config", 0) != 0) {
+                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+                                        "failed setting radius_retries = %s failed\n", retries);
+                        rc_destroy(rh);
+                        return;
+                }
+	                
+                /* Some hardcoded ( for now ) defaults needed to initialize radius */
+                if (rc_add_config(rh, "auth_order", "radius", "internal radius config", 0) != 0) {
+                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+                                        "failed setting auth_order = radius failed\n");
+                        rc_destroy(rh);
+                        return;
+                }
+                if (rc_add_config(rh, "seqfile", "/var/run/radius.seq", "internal radius config", 0) != 0) {
+                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+                                        "failed setting seqfile =  /var/run/radius.seq\n");
+                        rc_destroy(rh);
+                        return;
+                }
+                                        
+                /* Read the dictionary file(s) */
+                if (rc_read_dictionary(rh, rc_conf_str(rh, "dictionary")) != 0) {
+                        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+                                        "failed reading dictionary file(s): %s\n", dictionary);
+                        rc_destroy(rh);
+			return;
+                }
+		activated = 1;
+		switch_console_printf(SWITCH_CHANNEL_LOG, "[RadiusCDR] activated\n");
+                        
+        } else { 
+                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+                                "you must specify at least 1 radius server\n");
+                rc_destroy(rh);
+        }
 }
 
 bool RadiusCDR::process_record()
@@ -232,11 +277,11 @@
 		switch_console_printf(SWITCH_CHANNEL_LOG,"[RadiusCDR] Failed adding Calling-Station-ID: to %s\n", src);		
                 return -1;
 	}
-        if (rc_avpair_add(rh, &send, PW_ACCT_SESSION_TIME, &billusec, -1, 0) == NULL)
-	{	
-		switch_console_printf(SWITCH_CHANNEL_LOG,"[RadiusCDR] Failed adding Acct-Session-Time: to %d\n", billusec);		
-                return -1;
-	}
+//        if (rc_avpair_add(rh, &send, PW_ACCT_SESSION_TIME, &billusec, -1, 0) == NULL)
+//	{	
+//		switch_console_printf(SWITCH_CHANNEL_LOG,"[RadiusCDR] Failed adding Acct-Session-Time: to %u\n", billusec);		
+//                return -1;
+//	}
 
 	// Format the call record and proceed from here...
 	//callstartdate

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/sqlitecdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/sqlitecdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/sqlitecdr.cpp	Tue Apr 24 10:14:28 2007
@@ -24,6 +24,7 @@
  * Contributor(s):
  * 
  * Yossi Neiman <freeswitch AT cartissolutions.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  * Description: his C++ header file describes the SqliteCDR class which handles formatting a CDR out to
  * a SQLite database using prepared statements.
@@ -141,7 +142,7 @@
 					use_utc_time = 0;
 				else
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n",val);
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n", val);
 					use_utc_time = 0;
 				}
 			}
@@ -150,7 +151,7 @@
 		if (count_config_params==1)
 			activated = 1;
 		else
-			switch_console_printf(SWITCH_CHANNEL_LOG,"You did not specify the minimum parameters for using this module.  You must specify an explicit (complete) path to the location of the database file in order to use SqliteCDR.\n");
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "You did not specify the minimum parameters for using this module.  You must specify an explicit (complete) path to the location of the database file in order to use SqliteCDR.\n");
 		
 		if(activated)
 		{
@@ -190,9 +191,9 @@
 			
 			int sql_rc = switch_core_db_open(db_filename.c_str(),&db);
 			
-			if(sql_rc != SQLITE_OK)
+			if(sql_rc != SWITCH_CORE_DB_OK)
 			{
-				switch_console_printf(SWITCH_CHANNEL_LOG,"There was an error opening database filename %s.  The error was: %s.  SqliteCDR logging has been disabled until the problem is resolved and modcdr_reload is initiated.\n",db_filename.c_str(),switch_core_db_errmsg(db));
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "There was an error opening database filename %s.  The error was: %s.  SqliteCDR logging has been disabled until the problem is resolved and modcdr_reload is initiated.\n", db_filename.c_str(), switch_core_db_errmsg(db));
 				activated = 0;
 				switch_core_db_close(db);
 			}
@@ -211,7 +212,7 @@
 				temp_sql_tables["freeswitchcdr"] = 0;
 				temp_sql_tables["chanvars"] = 0;
 			
-				if(sql_rc == SQLITE_OK)
+				if(sql_rc == SWITCH_CORE_DB_OK)
 				{
 					for(int i = 0; i < ((nrow+1)*ncol); i++)
 					{
@@ -223,13 +224,13 @@
 					}
 				}
 				else
-					switch_console_printf(SWITCH_CHANNEL_LOG,"There was an error in executing query %s: The error was %s.\n",sql_query_check_tables,errormessage);
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "There was an error in executing query %s: The error was %s.\n", sql_query_check_tables, errormessage);
 				
 				switch_core_db_free_table(result);
 			
 				if(!temp_sql_tables["freeswitchcdr"])
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Creating the freeswitchcdr table in the SQLite mod_cdr database file.\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Creating the freeswitchcdr table in the SQLite mod_cdr database file.\n");
 					// Must create the missing freeswitchcdr table.
 					char sql_query_create_freeswitchcdr[] = "CREATE TABLE freeswitchcdr (\n"
 						"callid INTEGER PRIMARY KEY AUTOINCREMENT,\n"
@@ -262,7 +263,7 @@
 			
 				if(!temp_sql_tables["chanvars"])
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Creating the chanvars table in the SQLite mod_cdr database file.\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Creating the chanvars table in the SQLite mod_cdr database file.\n");
 					// Must create the missing chanvars table.
 					char sql_query_create_chanvars[] = "CREATE TABLE chanvars (\n"
 						"callid INTEGER default 0,\n"
@@ -284,7 +285,7 @@
 					char *errormessage2;
 					sql_rc = switch_core_db_get_table(db,sql_query_get_schema_of_freeswitchcdr,&result2,&nrow,&ncol,&errormessage2);
 					
-					if(sql_rc == SQLITE_OK)
+					if(sql_rc == SWITCH_CORE_DB_OK)
 					{
 						for(int k = 0; k < nrow; k++)
 						{
@@ -321,13 +322,13 @@
 										tempstring2 = resultstring.substr(i,(j-i));
 								
 									freeswitchcdr_columns[tempstring1] = tempstring2;
-									// switch_console_printf(SWITCH_CHANNEL_LOG,"tempstring1 = %s, tempstring2 = %s\n",tempstring1.c_str(),tempstring2.c_str());
+									//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "tempstring1 = %s, tempstring2 = %s\n", tempstring1.c_str(), tempstring2.c_str());
 									if(resultstring.find('\n',j+1) == (j+1))
 										j++;
 									i = j+1;
 								}
 								else
-									switch_console_printf(SWITCH_CHANNEL_LOG,"There has been a parsing problem with the freeswitchcdr schema.\n");
+									switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "There has been a parsing problem with the freeswitchcdr schema.\n");
 							}
 						}
 					}
@@ -346,9 +347,9 @@
 							case CDR_TINY:
 								if(freeswitchcdr_columns.find(*iItr) != freeswitchcdr_columns.end())
 								{
-									//switch_console_printf(SWITCH_CHANNEL_LOG,"freeswitchcdr_columns[%s] == %s.\n",iItr->c_str(),freeswitchcdr_columns[*iItr].c_str());
+									//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "freeswitchcdr_columns[%s] == %s.\n", iItr->c_str(), freeswitchcdr_columns[*iItr].c_str());
 									if(freeswitchcdr_columns[*iItr].find("INTEGER",0) == std::string::npos)
-										switch_console_printf(SWITCH_CHANNEL_LOG,"WARNING: SqliteCDR freeswitchcdr table column type mismatch: Column \"%s\" is not of an INTEGER type.  This is not necessarily fatal, but may result in unexpected behavior.\n",iItr->c_str());
+										switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "SqliteCDR freeswitchcdr table column type mismatch: Column \"%s\" is not of an INTEGER type.  This is not necessarily fatal, but may result in unexpected behavior.\n", iItr->c_str());
 								}
 								else
 									freeswitchcdr_add_columns[*iItr] = "INTEGER";
@@ -357,7 +358,7 @@
 								if(freeswitchcdr_columns.find(*iItr) != freeswitchcdr_columns.end())
 								{
 									if(freeswitchcdr_columns[*iItr].find("REAL",0) == std::string::npos)
-										switch_console_printf(SWITCH_CHANNEL_LOG,"WARNING: SqliteCDR freeswitchcdr table column type mismatch: Column \"%s\" is not of a REAL type.  This is not necessarily fatal, but may result in unexpected behavior.\n",iItr->c_str());
+										switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "SqliteCDR freeswitchcdr table column type mismatch: Column \"%s\" is not of a REAL type.  This is not necessarily fatal, but may result in unexpected behavior.\n", iItr->c_str());
 								}
 								else
 									freeswitchcdr_add_columns[*iItr] = "REAL";
@@ -367,19 +368,19 @@
 								if(freeswitchcdr_columns.find(*iItr) != freeswitchcdr_columns.end())
 								{
 									if(freeswitchcdr_columns[*iItr].find("TEXT",0) == std::string::npos)
-										switch_console_printf(SWITCH_CHANNEL_LOG,"WARNING: SqliteCDR freeswitchcdr table column type mismatch: Column \"%s\" is not of a TEXT type.  This is not necessarily fatal, but may result in unexpected behavior.\n",iItr->c_str());
+										switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "SqliteCDR freeswitchcdr table column type mismatch: Column \"%s\" is not of a TEXT type.  This is not necessarily fatal, but may result in unexpected behavior.\n", iItr->c_str());
 								}
 								else
 									freeswitchcdr_add_columns[*iItr] = "TEXT";
 								break;
 							default:
-								switch_console_printf(SWITCH_CHANNEL_LOG,"Oh bother, I should not have fallen into this hole in the switch/case statement.  Please notify the author.\n");
+								switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Oh bother, I should not have fallen into this hole in the switch/case statement.  Please notify the author.\n");
 						}
 					}
 					
 					if(freeswitchcdr_add_columns.size())
 					{
-						switch_console_printf(SWITCH_CHANNEL_LOG,"Updating the freeswitchcdr table schema.\n");
+						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Updating the freeswitchcdr table schema.\n");
 						std::string tempsql_freeswitchcdr_alter_table = "ALTER TABLE freeswitchcdr ADD ";
 						std::map<std::string, std::string>::iterator iItr, iEnd;
 						for(iItr = freeswitchcdr_add_columns.begin(), iEnd = freeswitchcdr_add_columns.end(); iItr != iEnd; iItr++)
@@ -388,7 +389,7 @@
 							sql_query_freeswitchcdr_alter_table.append(iItr->first);
 							sql_query_freeswitchcdr_alter_table.append(" ");
 							sql_query_freeswitchcdr_alter_table.append(iItr->second);
-							switch_console_printf(SWITCH_CHANNEL_LOG,"Updating the freeswitchcdr table with the following SQL command: %s.\n",sql_query_freeswitchcdr_alter_table.c_str());
+							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Updating the freeswitchcdr table with the following SQL command: %s.\n", sql_query_freeswitchcdr_alter_table.c_str());
 							switch_core_db_exec(db, sql_query_freeswitchcdr_alter_table.c_str(), NULL, NULL, NULL);
 						}
 					}
@@ -451,25 +452,25 @@
 	int column = 1;
 	switch_core_db_step(stmt_begin);
 	switch_core_db_reset(stmt_begin);
-	switch_core_db_bind_int64(stmt, column++, (sqlite_int64) sqlite_callstartdate);
-	switch_core_db_bind_int64(stmt, column++, (sqlite_int64) sqlite_callanswerdate);
-	switch_core_db_bind_int64(stmt, column++, (sqlite_int64) sqlite_calltransferdate);
-	switch_core_db_bind_int64(stmt, column++, (sqlite_int64) sqlite_callenddate);
+	switch_core_db_bind_int64(stmt, column++, sqlite_callstartdate);
+	switch_core_db_bind_int64(stmt, column++, sqlite_callanswerdate);
+	switch_core_db_bind_int64(stmt, column++, sqlite_calltransferdate);
+	switch_core_db_bind_int64(stmt, column++, sqlite_callenddate);
 	switch_core_db_bind_int(stmt, column++, (int) originated);
-	switch_core_db_bind_text(stmt, column++, clid,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, src,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, dst,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, ani,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, aniii,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, dialplan,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, myuuid,36,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, destuuid,36,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, srcchannel,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, dstchannel,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, network_addr,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, lastapp,-1,SQLITE_STATIC);
-	switch_core_db_bind_text(stmt, column++, lastdata,-1,SQLITE_STATIC);
-	switch_core_db_bind_int64(stmt, column++, (sqlite_int64) billusec);
+	switch_core_db_bind_text(stmt, column++, clid,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, src,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, dst,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, ani,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, aniii,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, dialplan,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, myuuid,36,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, destuuid,36,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, srcchannel,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, dstchannel,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, network_addr,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, lastapp,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_text(stmt, column++, lastdata,-1,SWITCH_CORE_DB_STATIC);
+	switch_core_db_bind_int64(stmt, column++, billusec);
 	switch_core_db_bind_int(stmt, column++, disposition);
 	switch_core_db_bind_int(stmt, column++, (int) hangupcause);
 	switch_core_db_bind_int(stmt, column++, amaflags);
@@ -510,43 +511,43 @@
 				case CDR_DECIMAL:
 				case CDR_STRING:
 				{
-					switch_core_db_bind_text(stmt,column++,iItr->second.c_str(),-1,SQLITE_STATIC);
+					switch_core_db_bind_text(stmt,column++,iItr->second.c_str(),-1,SWITCH_CORE_DB_STATIC);
 					break;
 				}
 				default:
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Oh bother, I should not have fallen into this hole in the switch/case statement.  Please notify the author.\n");
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Oh bother, I should not have fallen into this hole in the switch/case statement.  Please notify the author.\n");
 			}
 		}
 	}
 	
 	int sql_rc = switch_core_db_step(stmt);
-	if(sql_rc != SQLITE_DONE)
+	if(sql_rc != SWITCH_CORE_DB_DONE)
 	{
-		if(sql_rc == SQLITE_BUSY)
+		if(sql_rc == SWITCH_CORE_DB_BUSY)
 			sql_rc = switch_core_db_step(stmt);
-		else if (sql_rc == SQLITE_ERROR || sql_rc == SQLITE_MISUSE)
-			switch_console_printf(SWITCH_CHANNEL_LOG,"There was an error executing switch_core_db_step on SqliteCDR::stmt.  The error was: %s\n",switch_core_db_errmsg(db));
+		else if (sql_rc == SWITCH_CORE_DB_ERROR || sql_rc == SWITCH_CORE_DB_MISUSE)
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "There was an error executing switch_core_db_step on SqliteCDR::stmt.  The error was: %s\n", switch_core_db_errmsg(db));
 	}
 	
 	sql_rc = switch_core_db_reset(stmt);
 	
 	if(logchanvars && chanvars_supp.size())
 	{
-		sqlite_int64 rowid = switch_core_db_last_insert_rowid(db);
+		int64_t rowid = switch_core_db_last_insert_rowid(db);
 		int column2 = 1;
 		std::map<std::string,std::string>::iterator iItr, iEnd;
 		for(iItr = chanvars_supp.begin(), iEnd = chanvars_supp.end(); iItr != iEnd; iItr++)
 		{
 			switch_core_db_bind_int64(stmt_chanvars, column2++, rowid);
-			switch_core_db_bind_text(stmt_chanvars, column2++, iItr->first.c_str(),-1,SQLITE_STATIC);
-			switch_core_db_bind_text(stmt_chanvars, column2++, iItr->second.c_str(),-1,SQLITE_STATIC);
+			switch_core_db_bind_text(stmt_chanvars, column2++, iItr->first.c_str(),-1,SWITCH_CORE_DB_STATIC);
+			switch_core_db_bind_text(stmt_chanvars, column2++, iItr->second.c_str(),-1,SWITCH_CORE_DB_STATIC);
 			int sql_rc = switch_core_db_step(stmt_chanvars);
-			if(sql_rc != SQLITE_DONE)
+			if(sql_rc != SWITCH_CORE_DB_DONE)
 			{
-				if(sql_rc == SQLITE_BUSY)
+				if(sql_rc == SWITCH_CORE_DB_BUSY)
 					sql_rc = switch_core_db_step(stmt_chanvars);
-				else if (sql_rc == SQLITE_ERROR || sql_rc == SQLITE_MISUSE)
-					switch_console_printf(SWITCH_CHANNEL_LOG,"There was an error executing switch_core_db_step on SqliteCDR::stmt_chanvars.  The error was: %s\n",switch_core_db_errmsg(db));
+				else if (sql_rc == SWITCH_CORE_DB_ERROR || sql_rc == SWITCH_CORE_DB_MISUSE)
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "There was an error executing switch_core_db_step on SqliteCDR::stmt_chanvars.  The error was: %s\n", switch_core_db_errmsg(db));
 			}
 			
 			switch_core_db_reset(stmt_chanvars);

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/sqlitecdr.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/sqlitecdr.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/sqlitecdr.h	Tue Apr 24 10:14:28 2007
@@ -39,43 +39,43 @@
 #ifndef SQLITECDR
 #define SQLITECDR
 
-class SqliteCDR : public BaseCDR {
-	public:
-		SqliteCDR();
-		SqliteCDR(switch_mod_cdr_newchannel_t *newchannel);
-		//SqliteCDR(const SqliteCDR& copyFrom);
-		virtual ~SqliteCDR();
-		virtual bool process_record();
-		virtual void connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param);
-		virtual void disconnect();
-		virtual bool is_activated();
-		virtual void tempdump_record();
-		virtual void reread_tempdumped_records();
-		virtual std::string get_display_name();
+class SqliteCDR:public BaseCDR {
+  public:
+	SqliteCDR();
+	SqliteCDR(switch_mod_cdr_newchannel_t * newchannel);
+	//SqliteCDR(const SqliteCDR& copyFrom);
+	virtual ~ SqliteCDR();
+	virtual bool process_record();
+	virtual void connect(switch_xml_t & cfg, switch_xml_t & xml, switch_xml_t & settings, switch_xml_t & param);
+	virtual void disconnect();
+	virtual bool is_activated();
+	virtual void tempdump_record();
+	virtual void reread_tempdumped_records();
+	virtual std::string get_display_name();
 
-	private:
-		static bool activated;
-		static char sql_query[1024];
-		static std::string tmp_sql_query; // Object must exist to bind the statement, this used for generating the sql
-		static char sql_query_chanvars[100];
-		static std::string db_filename;
-		static bool use_utc_time;
-		switch_time_t sqlite_callstartdate;
-		switch_time_t sqlite_callanswerdate;
-		switch_time_t sqlite_calltransferdate;
-		switch_time_t sqlite_callenddate;
-		static switch_core_db_t *db;
-		static switch_core_db_stmt_t *stmt;
-		static switch_core_db_stmt_t *stmt_chanvars;
-		static switch_core_db_stmt_t *stmt_begin;
-		static switch_core_db_stmt_t *stmt_commit;
-		static bool connectionstate;
-		static bool logchanvars;
-		static std::list<std::string> chanvars_fixed_list;
-		static std::vector<switch_mod_cdr_sql_types_t> chanvars_fixed_types;
-		static std::list<std::string> chanvars_supp_list; // The supplemental list
-		static bool repeat_fixed_in_supp;
-		static std::string display_name;
+  private:
+	static bool activated;
+	static char sql_query[1024];
+	static std::string tmp_sql_query;	// Object must exist to bind the statement, this used for generating the sql
+	static char sql_query_chanvars[100];
+	static std::string db_filename;
+	static bool use_utc_time;
+	switch_time_t sqlite_callstartdate;
+	switch_time_t sqlite_callanswerdate;
+	switch_time_t sqlite_calltransferdate;
+	switch_time_t sqlite_callenddate;
+	static switch_core_db_t *db;
+	static switch_core_db_stmt_t *stmt;
+	static switch_core_db_stmt_t *stmt_chanvars;
+	static switch_core_db_stmt_t *stmt_begin;
+	static switch_core_db_stmt_t *stmt_commit;
+	static bool connectionstate;
+	static bool logchanvars;
+	static std::list < std::string > chanvars_fixed_list;
+	static std::vector < switch_mod_cdr_sql_types_t > chanvars_fixed_types;
+	static std::list < std::string > chanvars_supp_list;	// The supplemental list
+	static bool repeat_fixed_in_supp;
+	static std::string display_name;
 };
 
 #endif

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/xmlcdr.cpp
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/xmlcdr.cpp	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/xmlcdr.cpp	Tue Apr 24 10:14:28 2007
@@ -25,6 +25,7 @@
  * 
  * Yossi Neiman <freeswitch AT cartissolutions.com>
  * Ken Rice of Asteria Solutions Group, INC <ken AT asteriasgi.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  * 
  * Description: This C++ source file describes the XmlCDR class which handles formatting a CDR out to
  * individual text files in a XML format.
@@ -103,7 +104,7 @@
 
 void XmlCDR::connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param)
 {
-	switch_console_printf(SWITCH_CHANNEL_LOG, "XmlCDR::connect() - Loading configuration file.\n");
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "XmlCDR::connect() - Loading configuration file.\n");
 	activated = 0; // Set it as inactive initially
 	connectionstate = 0; // Initialize it to false to show that we aren't yet connected.
 	
@@ -137,11 +138,11 @@
 			}
 			else if (!strcmp(var, "chanvars_fixed"))
 			{
-				switch_console_printf(SWITCH_CHANNEL_LOG,"XmlCDR has no need for a fixed or supplemental list of channel variables due to the nature of the format.  Please use the setting parameter of \"chanvars\" instead and try again.\n");
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "XmlCDR has no need for a fixed or supplemental list of channel variables due to the nature of the format.  Please use the setting parameter of \"chanvars\" instead and try again.\n");
 			}
 			else if (!strcmp(var, "chanvars_supp"))
 			{
-				switch_console_printf(SWITCH_CHANNEL_LOG,"XmlCDR has no need for a fixed or supplemental list of channel variables due to the nature of the format.  Please use the setting parameter of \"chanvars\" instead and try again.\n");
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "XmlCDR has no need for a fixed or supplemental list of channel variables due to the nature of the format.  Please use the setting parameter of \"chanvars\" instead and try again.\n");
 			}
 			else if(!strcmp(var,"timezone"))
 			{
@@ -151,7 +152,7 @@
 					convert_time = switch_time_exp_lt;
 				else
 				{
-					switch_console_printf(SWITCH_CHANNEL_LOG,"Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n",val);
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid configuration parameter for timezone.  Possible values are utc and local.  You entered: %s\nDefaulting to local.\n", val);
 					convert_time = switch_time_exp_lt;
 				}
 			}
@@ -160,7 +161,7 @@
 		if(count_config_params > 0)
 			activated = 1;
 		else
-			switch_console_printf(SWITCH_CHANNEL_LOG,"XmlCDR::connect(): You did not specify the minimum parameters for using this module.  You must specify at least a path to have the records logged to.\n");
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "XmlCDR::connect(): You did not specify the minimum parameters for using this module.  You must specify at least a path to have the records logged to.\n");
 	}
 }
 
@@ -170,10 +171,10 @@
 	outputfile.open(outputfile_name.c_str());
 	
 	if(!outputfile)
-		switch_console_printf(SWITCH_CHANNEL_LOG, "XmlCDR::process_record():  Unable to open file  %s to commit the call record to.  Invalid path name, invalid permissions, or no space available?\n",outputfile_name.c_str());
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "XmlCDR::process_record():  Unable to open file  %s to commit the call record to.  Invalid path name, invalid permissions, or no space available?\n", outputfile_name.c_str());
 	else
 	{
-		//switch_console_printf(SWITCH_CHANNEL_LOG, "XmlCDR::process_record():  Preping the CDR to %s.\n",outputfile_name.c_str());
+		//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "XmlCDR::process_record():  Preping the CDR to %s.\n", outputfile_name.c_str());
 		// Format the call record and proceed from here...
 		outputfile << "<?xml version=\"1.0\"?>" << std::endl;
 		outputfile << "<document type=\"freeswitch-cdr/xml\">" << std::endl;
@@ -215,7 +216,7 @@
 		}
 		outputfile << "\t</chanvars>" << std::endl << "</document>" << std::endl << std::endl;
 
-		//switch_console_printf(SWITCH_CHANNEL_LOG, "XmlCDR::process_record():  Dumping the CDR to %s.\n",outputfile_name.c_str());
+		//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "XmlCDR::process_record():  Dumping the CDR to %s.\n", outputfile_name.c_str());
 		retval = 1;
 	}
 	
@@ -249,7 +250,7 @@
 	logchanvars = 0;
 	outputfile_path.clear();
 	chanvars_supp_list.clear();
-	switch_console_printf(SWITCH_CHANNEL_LOG,"Shutting down XmlCDR...  Done!");	
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Shutting down XmlCDR...  Done!");	
 }
 
 AUTO_REGISTER_BASECDR(XmlCDR);

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/xmlcdr.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/xmlcdr.h	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_cdr/xmlcdr.h	Tue Apr 24 10:14:28 2007
@@ -43,34 +43,34 @@
 #ifndef XMLCDR
 #define XMLCDR
 
-class XmlCDR : public BaseCDR {
-	public:
-		XmlCDR();
-		XmlCDR(switch_mod_cdr_newchannel_t *newchannel);
-		virtual ~XmlCDR();
-		virtual bool process_record();
-		virtual void connect(switch_xml_t& cfg, switch_xml_t& xml, switch_xml_t& settings, switch_xml_t& param); // connect and disconnect need to be static because we're persisting connections until shutdown
-		virtual void disconnect();
-		virtual bool is_activated();
-		virtual void tempdump_record();
-		virtual void reread_tempdumped_records();
-		virtual std::string get_display_name();
+class XmlCDR:public BaseCDR {
+  public:
+	XmlCDR();
+	XmlCDR(switch_mod_cdr_newchannel_t * newchannel);
+	virtual ~ XmlCDR();
+	virtual bool process_record();
+	virtual void connect(switch_xml_t & cfg, switch_xml_t & xml, switch_xml_t & settings, switch_xml_t & param);	// connect and disconnect need to be static because we're persisting connections until shutdown
+	virtual void disconnect();
+	virtual bool is_activated();
+	virtual void tempdump_record();
+	virtual void reread_tempdumped_records();
+	virtual std::string get_display_name();
 
-	private:
-		static bool activated; // Is this module activated?
-		static bool connectionstate; // What is the status of the connection?
-		static bool logchanvars;
-		static modcdr_time_convert_t convert_time;
-		static std::string outputfile_path; // The directory we'll dump these into
-		static std::list<std::string> chanvars_fixed_list; // Normally this would be used, but not in this class
-		static std::list<std::string> chanvars_supp_list; // This will hold the list for all chanvars here
-		static std::string display_name;
-		char formattedcallstartdate[100];
-		char formattedcallanswerdate[100];
-		char formattedcalltransferdate[100];
-		char formattedcallenddate[100];
-		std::string outputfile_name;
-		std::ofstream outputfile;
+  private:
+	static bool activated;		// Is this module activated?
+	static bool connectionstate;	// What is the status of the connection?
+	static bool logchanvars;
+	static modcdr_time_convert_t convert_time;
+	static std::string outputfile_path;	// The directory we'll dump these into
+	static std::list < std::string > chanvars_fixed_list;	// Normally this would be used, but not in this class
+	static std::list < std::string > chanvars_supp_list;	// This will hold the list for all chanvars here
+	static std::string display_name;
+	char formattedcallstartdate[100];
+	char formattedcallanswerdate[100];
+	char formattedcalltransferdate[100];
+	char formattedcallenddate[100];
+	     std::string outputfile_name;
+	     std::ofstream outputfile;
 };
 
 #endif

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_event_multicast/mod_event_multicast.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_event_multicast/mod_event_multicast.c	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_event_multicast/mod_event_multicast.c	Tue Apr 24 10:14:28 2007
@@ -46,17 +46,13 @@
 	switch_sockaddr_t *addr;
 	switch_socket_t *udp_socket;
 	switch_hash_t *event_hash;
-	uint8_t event_list[SWITCH_EVENT_ALL+1];
+	uint8_t event_list[SWITCH_EVENT_ALL + 1];
 	int running;
 } globals;
 
 SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_address, globals.address)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_bindings, globals.bindings)
-
-
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_bindings, globals.bindings)
 #define MULTICAST_EVENT "multicast::event"
-
-
 	 static switch_status_t load_config(void)
 {
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
@@ -65,10 +61,10 @@
 	char *next, *cur;
 	uint32_t count = 0;
 	uint8_t custom = 0;
-	apr_ssize_t hlen = APR_HASH_KEY_STRING;
+	switch_ssize_t hlen = SWITCH_HASH_KEY_STRING;
 
 	gethostname(globals.hostname, sizeof(globals.hostname));
-	globals.host_hash = apr_hashfunc_default(globals.hostname, &hlen);
+	globals.host_hash = switch_hashfunc_default(globals.hostname, &hlen);
 	globals.key_count = 0;
 
 	if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) {
@@ -80,7 +76,7 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass!");
 		return SWITCH_STATUS_GENERR;
 	}
-	
+
 	if ((settings = switch_xml_child(cfg, "settings"))) {
 		for (param = switch_xml_child(settings, "param"); param; param = param->next) {
 			char *var = (char *) switch_xml_attr_soft(param, "name");
@@ -91,7 +87,7 @@
 			} else if (!strcasecmp(var, "bindings")) {
 				set_global_bindings(val);
 			} else if (!strcasecmp(var, "port")) {
-				globals.port = (switch_port_t)atoi(val);
+				globals.port = (switch_port_t) atoi(val);
 			}
 		}
 	}
@@ -100,13 +96,13 @@
 
 
 	if (globals.bindings) {
-		for(cur = globals.bindings; cur; count++) {
+		for (cur = globals.bindings; cur; count++) {
 			switch_event_types_t type;
 
 			if ((next = strchr(cur, ' '))) {
 				*next++ = '\0';
 			}
-				
+
 			if (custom) {
 				switch_core_hash_insert_dup(globals.event_hash, cur, MARKER);
 			} else if (switch_name_event(cur, &type) == SWITCH_STATUS_SUCCESS) {
@@ -143,22 +139,21 @@
 
 
 	if (event->subclass && !strcmp(event->subclass->name, MULTICAST_EVENT)) {
-		/* ignore our own events to avoid ping pong*/
+		/* ignore our own events to avoid ping pong */
 		return;
 	}
 
-	if (globals.event_list[(uint8_t)SWITCH_EVENT_ALL]) {
+	if (globals.event_list[(uint8_t) SWITCH_EVENT_ALL]) {
 		send = 1;
-	} else if ((globals.event_list[(uint8_t)event->event_id])) {
-		if (event->event_id != SWITCH_EVENT_CUSTOM || 
-			(event->subclass && switch_core_hash_find(globals.event_hash, event->subclass->name))) {
+	} else if ((globals.event_list[(uint8_t) event->event_id])) {
+		if (event->event_id != SWITCH_EVENT_CUSTOM || (event->subclass && switch_core_hash_find(globals.event_hash, event->subclass->name))) {
 			send = 1;
 		}
 	}
 
 	if (send) {
 		char *packet;
-		
+
 		switch (event->event_id) {
 		case SWITCH_EVENT_LOG:
 			return;
@@ -199,7 +194,7 @@
 	}
 
 	switch_core_hash_init(&globals.event_hash, module_pool);
-	
+
 	if (load_config() != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Configure\n");
 		return SWITCH_STATUS_TERM;
@@ -214,7 +209,7 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Error\n");
 		return SWITCH_STATUS_TERM;
 	}
-	
+
 	if (switch_socket_opt_set(globals.udp_socket, SWITCH_SO_REUSEADDR, 1) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Option Error\n");
 		switch_socket_close(globals.udp_socket);
@@ -224,7 +219,7 @@
 	if (switch_mcast_join(globals.udp_socket, globals.addr, NULL, NULL) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Multicast Error\n");
 		switch_socket_close(globals.udp_socket);
-        return SWITCH_STATUS_TERM;
+		return SWITCH_STATUS_TERM;
 	}
 
 	if (switch_socket_bind(globals.udp_socket, globals.addr) != SWITCH_STATUS_SUCCESS) {
@@ -238,9 +233,8 @@
 	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &event_test_module_interface;
 
-	
-	if (switch_event_bind((char *) modname, SWITCH_EVENT_ALL, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) !=
-		SWITCH_STATUS_SUCCESS) {
+
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_ALL, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 		switch_socket_close(globals.udp_socket);
 		return SWITCH_STATUS_GENERR;
@@ -256,9 +250,9 @@
 {
 	int x = 0;
 
-	switch_socket_shutdown(globals.udp_socket, APR_SHUTDOWN_READWRITE);
+	switch_socket_shutdown(globals.udp_socket, SWITCH_SHUTDOWN_READWRITE);
 	globals.running = -1;
-	while(x < 100000 && globals.running) {
+	while (x < 100000 && globals.running) {
 		x++;
 		switch_yield(1000);
 	}
@@ -269,16 +263,16 @@
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_runtime(void)
 {
 	switch_event_t *local_event;
-	char buf[65536] = {0};
+	char buf[65536] = { 0 };
 	switch_sockaddr_t *addr;
 
 	switch_sockaddr_info_get(&addr, NULL, SWITCH_UNSPEC, 0, 0, module_pool);
 	globals.running = 1;
-	while(globals.running == 1) {
+	while (globals.running == 1) {
 		char *myaddr;
 		size_t len = sizeof(buf);
 		memset(buf, 0, len);
-		
+
 		switch_sockaddr_ip_get(&myaddr, globals.addr);
 
 		if (switch_socket_recvfrom(addr, globals.udp_socket, 0, buf, &len) == SWITCH_STATUS_SUCCESS) {
@@ -287,25 +281,24 @@
 
 			memcpy(&host_hash, buf, sizeof(host_hash));
 			packet = buf + sizeof(host_hash);
-			
+
 			if (host_hash == globals.host_hash) {
 				continue;
 			}
-
 			//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "\nEVENT %d\n--------------------------------\n%s\n", (int) len, packet);
 			if (switch_event_create_subclass(&local_event, SWITCH_EVENT_CUSTOM, MULTICAST_EVENT) == SWITCH_STATUS_SUCCESS) {
 				char *var, *val, *term = NULL, tmpname[128];
 				switch_event_add_header(local_event, SWITCH_STACK_BOTTOM, "Multicast", "yes");
 				var = packet;
-				while(*var) {
+				while (*var) {
 					if ((val = strchr(var, ':')) != 0) {
 						*val++ = '\0';
-						while(*val == ' ') {
+						while (*val == ' ') {
 							val++;
 						}
-						if ((term = strchr(val, '\r')) != 0 || (term=strchr(val, '\n')) != 0) {
+						if ((term = strchr(val, '\r')) != 0 || (term = strchr(val, '\n')) != 0) {
 							*term = '\0';
-							while(*term == '\r' || *term == '\n') {
+							while (*term == '\r' || *term == '\n') {
 								term++;
 							}
 						}
@@ -315,18 +308,18 @@
 					} else {
 						break;
 					}
-				} 
+				}
 
 				if (var && strlen(var) > 1) {
 					switch_event_add_body(local_event, var);
 				}
 
 				switch_event_fire(&local_event);
-			
+
 			}
 		}
 	}
-		
+
 	globals.running = 0;
 	return SWITCH_STATUS_TERM;
 }

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_event_socket/mod_event_socket.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_event_socket/mod_event_socket.c	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_event_socket/mod_event_socket.c	Tue Apr 24 10:14:28 2007
@@ -61,10 +61,10 @@
 	uint32_t flags;
 	switch_log_level_t level;
 	char *ebuf;
-	uint8_t event_list[SWITCH_EVENT_ALL+1];
+	uint8_t event_list[SWITCH_EVENT_ALL + 1];
 	switch_hash_t *event_hash;
 	switch_thread_rwlock_t *rwlock;
-    switch_core_session_t *session;
+	switch_core_session_t *session;
 	struct listener *next;
 };
 
@@ -86,15 +86,15 @@
 } prefs;
 
 SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_pref_ip, prefs.ip)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_pref_pass, prefs.password)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_pref_pass, prefs.password)
 
-static void *SWITCH_THREAD_FUNC listener_run(switch_thread_t *thread, void *obj);
-static void launch_listener_thread(listener_t *listener);
+	 static void *SWITCH_THREAD_FUNC listener_run(switch_thread_t * thread, void *obj);
+	 static void launch_listener_thread(listener_t * listener);
 
-static switch_status_t socket_logger(const switch_log_node_t *node, switch_log_level_t level)
+	 static switch_status_t socket_logger(const switch_log_node_t *node, switch_log_level_t level)
 {
 	listener_t *l;
-	
+
 	switch_mutex_lock(listen_list.mutex);
 	for (l = listen_list.listeners; l; l = l->next) {
 		if (switch_test_flag(l, LFLAG_LOG) && l->level >= node->level) {
@@ -121,7 +121,7 @@
 	if (!listen_list.ready) {
 		return;
 	}
-	
+
 	switch_mutex_lock(listen_list.mutex);
 	for (l = listen_list.listeners; l; l = l->next) {
 		uint8_t send = 0;
@@ -130,21 +130,21 @@
 			continue;
 		}
 
-        if (l->event_list[(uint8_t)SWITCH_EVENT_ALL]) {
+		if (l->event_list[(uint8_t) SWITCH_EVENT_ALL]) {
 			send = 1;
-		} else if ((l->event_list[(uint8_t)event->event_id])) {
+		} else if ((l->event_list[(uint8_t) event->event_id])) {
 			if (event->event_id != SWITCH_EVENT_CUSTOM || (event->subclass && switch_core_hash_find(l->event_hash, event->subclass->name))) {
 				send = 1;
 			}
 		}
 
-        if (send && switch_test_flag(l, LFLAG_MYEVENTS)) {
-            char *uuid = switch_event_get_header(event, "unique-id");
-            if (!uuid || strcmp(uuid, switch_core_session_get_uuid(l->session))) {
-                send = 1;
-            }
-        }
-        
+		if (send && switch_test_flag(l, LFLAG_MYEVENTS)) {
+			char *uuid = switch_event_get_header(event, "unique-id");
+			if (!uuid || strcmp(uuid, switch_core_session_get_uuid(l->session))) {
+				send = 1;
+			}
+		}
+
 		if (send) {
 			if (switch_event_dup(&clone, event) == SWITCH_STATUS_SUCCESS) {
 				switch_queue_push(l->event_queue, clone);
@@ -159,101 +159,102 @@
 
 static void socket_function(switch_core_session_t *session, char *data)
 {
-    char *host, *port_name;
-    switch_socket_t *new_sock;
-    switch_sockaddr_t *sa;
-    switch_port_t port = 8084;
-    listener_t *listener;
+	char *host, *port_name;
+	switch_socket_t *new_sock;
+	switch_sockaddr_t *sa;
+	switch_port_t port = 8084;
+	listener_t *listener;
 	int argc = 0, x = 0;
-	char *argv[80] = {0};
+	char *argv[80] = { 0 };
 	char *mydata;
 
 	if (data && (mydata = switch_core_session_strdup(session, data))) {
 		argc = switch_separate_string(mydata, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
-	} 
+	}
+
+	if (argc < 1) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Parse Error!\n");
+		return;
+	}
+
+	host = argv[0];
 
-    if (argc < 1) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Parse Error!\n");
-        return;
-    }
-
-    host = argv[0];
-
-    if (switch_strlen_zero(host)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing Host!\n");
-        return;
-    }
-
-    if ((port_name = strchr(host, ':'))) {
-        *port_name++ = '\0';
-        port = (switch_port_t)atoi(port_name);
-    }
+	if (switch_strlen_zero(host)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing Host!\n");
+		return;
+	}
+
+	if ((port_name = strchr(host, ':'))) {
+		*port_name++ = '\0';
+		port = (switch_port_t) atoi(port_name);
+	}
 
 	if (switch_sockaddr_info_get(&sa, host, AF_INET, port, 0, switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Error!\n");
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Error!\n");
 		return;
 	}
 
-	if (switch_socket_create(&new_sock, AF_INET, SOCK_STREAM, APR_PROTO_TCP, switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Error!\n");
+	if (switch_socket_create(&new_sock, AF_INET, SOCK_STREAM, SWITCH_PROTO_TCP, switch_core_session_get_pool(session))
+		!= SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Error!\n");
 		return;
 	}
 
-    switch_socket_opt_set(new_sock, SWITCH_SO_KEEPALIVE, 1);
+	switch_socket_opt_set(new_sock, SWITCH_SO_KEEPALIVE, 1);
 
 	if (switch_socket_connect(new_sock, sa) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Error!\n");
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Error!\n");
+		return;
+	}
+
+
+	if (!(listener = switch_core_session_alloc(session, sizeof(*listener)))) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error\n");
 		return;
 	}
 
+	switch_thread_rwlock_create(&listener->rwlock, switch_core_session_get_pool(session));
+	switch_queue_create(&listener->event_queue, SWITCH_CORE_QUEUE_LEN, switch_core_session_get_pool(session));
+	switch_queue_create(&listener->log_queue, SWITCH_CORE_QUEUE_LEN, switch_core_session_get_pool(session));
+
+	listener->sock = new_sock;
+	listener->pool = switch_core_session_get_pool(session);
+	listener->format = EVENT_FORMAT_PLAIN;
+	listener->session = session;
+
+	switch_mutex_init(&listener->flag_mutex, SWITCH_MUTEX_NESTED, listener->pool);
+	switch_core_hash_init(&listener->event_hash, listener->pool);
+	switch_set_flag(listener, LFLAG_AUTHED);
+	for (x = 1; x < argc; x++) {
+		if (argv[x] && !strcasecmp(argv[x], "full")) {
+			switch_set_flag(listener, LFLAG_FULL);
+		} else if (argv[x] && !strcasecmp(argv[x], "async")) {
+			switch_set_flag(listener, LFLAG_ASYNC);
+		}
+	}
+
+	if (switch_test_flag(listener, LFLAG_ASYNC)) {
+		launch_listener_thread(listener);
+		switch_ivr_park(session, NULL);
+	} else {
+		listener_run(NULL, (void *) listener);
+	}
+
+	while (switch_test_flag(listener, LFLAG_SESSION)) {
+		switch_yield(100000);
+	}
 
-    if (!(listener = switch_core_session_alloc(session, sizeof(*listener)))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error\n");
-        return;
-    }
-		
-    switch_thread_rwlock_create(&listener->rwlock, switch_core_session_get_pool(session));
-    switch_queue_create(&listener->event_queue, SWITCH_CORE_QUEUE_LEN, switch_core_session_get_pool(session));
-    switch_queue_create(&listener->log_queue, SWITCH_CORE_QUEUE_LEN, switch_core_session_get_pool(session));
-
-    listener->sock = new_sock;
-    listener->pool = switch_core_session_get_pool(session);
-    listener->format = EVENT_FORMAT_PLAIN;
-    listener->session = session;
-    
-    switch_mutex_init(&listener->flag_mutex, SWITCH_MUTEX_NESTED, listener->pool);
-    switch_core_hash_init(&listener->event_hash, listener->pool);
-    switch_set_flag(listener, LFLAG_AUTHED);
-    for(x = 1; x < argc; x++) {
-        if (argv[x] && !strcasecmp(argv[x], "full")) {
-            switch_set_flag(listener, LFLAG_FULL);
-        } else if (argv[x] && !strcasecmp(argv[x], "async")) {
-            switch_set_flag(listener, LFLAG_ASYNC);
-        }
-    }
-    
-    if (switch_test_flag(listener, LFLAG_ASYNC)) {
-        launch_listener_thread(listener);
-        switch_ivr_park(session, NULL);
-    } else {
-        listener_run(NULL, (void*) listener);
-    }
-
-    while(switch_test_flag(listener, LFLAG_SESSION)) {
-        switch_yield(100000);
-    }
-    
 }
 
 
 static const switch_application_interface_t socket_application_interface = {
-    /*.interface_name */ "socket",
-    /*.application_function */ socket_function,
-    /* long_desc */ "Connect to a socket",
-    /* short_desc */ "Connect to a socket",
-    /* syntax */ "<ip>[:<port>]",
+	/*.interface_name */ "socket",
+	/*.application_function */ socket_function,
+	/* long_desc */ "Connect to a socket",
+	/* short_desc */ "Connect to a socket",
+	/* syntax */ "<ip>[:<port>]",
 	/* flags */ SAF_SUPPORT_NOMEDIA,
-    /*.next */ NULL
+	/*.next */ NULL
 };
 
 
@@ -268,10 +269,11 @@
 };
 
 
-static void close_socket(switch_socket_t **sock) {
+static void close_socket(switch_socket_t ** sock)
+{
 	switch_mutex_lock(listen_list.sock_mutex);
 	if (*sock) {
-		apr_socket_shutdown(*sock, APR_SHUTDOWN_READWRITE);
+		switch_socket_shutdown(*sock, SWITCH_SHUTDOWN_READWRITE);
 		switch_socket_close(*sock);
 		*sock = NULL;
 	}
@@ -308,7 +310,7 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static void add_listener(listener_t *listener) 
+static void add_listener(listener_t * listener)
 {
 	/* add me to the listeners so I get events */
 	switch_mutex_lock(listen_list.mutex);
@@ -317,7 +319,7 @@
 	switch_mutex_unlock(listen_list.mutex);
 }
 
-static void remove_listener(listener_t *listener)
+static void remove_listener(listener_t * listener)
 {
 	listener_t *l, *last = NULL;
 
@@ -343,7 +345,7 @@
 	}
 }
 
-static switch_status_t read_packet(listener_t *listener, switch_event_t **event, uint32_t timeout) 
+static switch_status_t read_packet(listener_t * listener, switch_event_t **event, uint32_t timeout)
 {
 	switch_size_t mlen, bytes = 0;
 	char mbuf[2048] = "";
@@ -361,7 +363,7 @@
 	start = time(NULL);
 	ptr = mbuf;
 
-	while(listener->sock) {
+	while (listener->sock) {
 		uint8_t do_sleep = 1;
 		mlen = 1;
 		status = switch_socket_recv(listener->sock, ptr, &mlen);
@@ -370,16 +372,16 @@
 			return SWITCH_STATUS_FALSE;
 		}
 
-        if (listener->session && !switch_channel_ready(switch_core_session_get_channel(listener->session))) {
-            status = SWITCH_STATUS_FALSE;
-            break;
-        }
+		if (listener->session && !switch_channel_ready(switch_core_session_get_channel(listener->session))) {
+			status = SWITCH_STATUS_FALSE;
+			break;
+		}
 
 		if (mlen) {
 			bytes += mlen;
 			do_sleep = 0;
 
-			if (*mbuf == '\r' || *mbuf == '\n') { /* bah */
+			if (*mbuf == '\r' || *mbuf == '\n') {	/* bah */
 				ptr = mbuf;
 				mbuf[0] = '\0';
 				bytes = 0;
@@ -401,7 +403,7 @@
 				char *next;
 				char *cur = mbuf;
 				bytes = 0;
-				while(cur) {
+				while (cur) {
 					if ((next = strchr(cur, '\r')) || (next = strchr(cur, '\n'))) {
 						while (*next == '\r' || *next == '\n') {
 							next++;
@@ -418,30 +420,30 @@
 						if (!switch_strlen_zero(var)) {
 							if ((val = strchr(var, ':'))) {
 								*val++ = '\0';
-								while(*val == ' ') {
+								while (*val == ' ') {
 									val++;
 								}
-							} 
+							}
 							if (var && val) {
 								switch_event_add_header(*event, SWITCH_STACK_BOTTOM, var, "%s", val);
 							}
 						}
 					}
-					
+
 					cur = next;
 				}
 				break;
 			}
 		}
-        
+
 		if (timeout) {
-			elapsed = (uint32_t)(time(NULL) - start);
+			elapsed = (uint32_t) (time(NULL) - start);
 			if (elapsed >= timeout) {
 				switch_clear_flag_locked(listener, LFLAG_RUNNING);
 				return SWITCH_STATUS_FALSE;
 			}
 		}
-		
+
 		if (!*mbuf) {
 			if (switch_test_flag(listener, LFLAG_LOG)) {
 				if (switch_queue_trypop(listener->log_queue, &pop) == SWITCH_STATUS_SUCCESS) {
@@ -449,12 +451,12 @@
 
 
 					if (data) {
-						snprintf(buf, sizeof(buf), "Content-Type: log/data\nContent-Length: %"APR_SSIZE_T_FMT"\n\n", strlen(data));
+						snprintf(buf, sizeof(buf), "Content-Type: log/data\nContent-Length: %" SWITCH_SSIZE_T_FMT "\n\n", strlen(data));
 						len = strlen(buf);
 						switch_socket_send(listener->sock, buf, &len);
 						len = strlen(data);
 						switch_socket_send(listener->sock, data, &len);
-					
+
 						free(data);
 					}
 					do_sleep = 0;
@@ -475,7 +477,7 @@
 						switch_xml_t xml;
 						etype = "xml";
 
-						if ((xml = switch_event_xmlize(event, NULL))) {
+						if ((xml = switch_event_xmlize(event, "%s", ""))) {
 							listener->ebuf = switch_xml_toxml(xml);
 							switch_xml_free(xml);
 						} else {
@@ -483,12 +485,10 @@
 							continue;
 						}
 					}
-			
+
 					len = strlen(listener->ebuf);
 
-					snprintf(hbuf, sizeof(hbuf), "Content-Length: %"APR_SSIZE_T_FMT"\n" 
-							 "Content-Type: text/event-%s\n"
-							 "\n", len, etype);
+					snprintf(hbuf, sizeof(hbuf), "Content-Length: %" SWITCH_SSIZE_T_FMT "\n" "Content-Type: text/event-%s\n" "\n", len, etype);
 
 					len = strlen(hbuf);
 					switch_socket_send(listener->sock, hbuf, &len);
@@ -519,13 +519,13 @@
 	uint8_t bg;
 };
 
-static void *SWITCH_THREAD_FUNC api_exec(switch_thread_t *thread, void *obj)
+static void *SWITCH_THREAD_FUNC api_exec(switch_thread_t * thread, void *obj)
 {
 
 	struct api_command_struct *acs = (struct api_command_struct *) obj;
-	switch_stream_handle_t stream = {0};
-    char *reply, *freply = NULL;
-    switch_status_t status;
+	switch_stream_handle_t stream = { 0 };
+	char *reply, *freply = NULL;
+	switch_status_t status;
 
 	if (switch_thread_rwlock_tryrdlock(acs->listener->rwlock) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error! cannot get read lock.\n");
@@ -535,42 +535,42 @@
 
 	SWITCH_STANDARD_STREAM(stream);
 
-    if ((status = switch_api_execute(acs->api_cmd, acs->arg, NULL, &stream)) == SWITCH_STATUS_SUCCESS) {
-        reply = stream.data;
-    } else {
-        freply = switch_mprintf("%s: Command not found!", acs->api_cmd);
-        reply = freply;
-    }
-        
-    if (!reply) {
-        reply = "Command returned no output!";
-    }
-    
-    if (acs->bg) {
-        switch_event_t *event;
-        
-        if (switch_event_create(&event, SWITCH_EVENT_BACKGROUND_JOB) == SWITCH_STATUS_SUCCESS) {
-            switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Job-UUID", "%s", acs->uuid_str);
-            switch_event_add_body(event, "%s", reply);
-            switch_event_fire(&event);
-        }
-    } else {
-        switch_size_t rlen, blen;
-        char buf[1024] = "";
-        rlen = strlen(reply);			
-        snprintf(buf, sizeof(buf), "Content-Type: api/response\nContent-Length: %"APR_SSIZE_T_FMT"\n\n", rlen);
-        blen = strlen(buf);
-        switch_socket_send(acs->listener->sock, buf, &blen);
-        switch_socket_send(acs->listener->sock, reply, &rlen);
-    }
-		
-    switch_safe_free(stream.data);
-    switch_safe_free(freply);
+	if ((status = switch_api_execute(acs->api_cmd, acs->arg, NULL, &stream)) == SWITCH_STATUS_SUCCESS) {
+		reply = stream.data;
+	} else {
+		freply = switch_mprintf("%s: Command not found!", acs->api_cmd);
+		reply = freply;
+	}
+
+	if (!reply) {
+		reply = "Command returned no output!";
+	}
+
+	if (acs->bg) {
+		switch_event_t *event;
+
+		if (switch_event_create(&event, SWITCH_EVENT_BACKGROUND_JOB) == SWITCH_STATUS_SUCCESS) {
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Job-UUID", "%s", acs->uuid_str);
+			switch_event_add_body(event, "%s", reply);
+			switch_event_fire(&event);
+		}
+	} else {
+		switch_size_t rlen, blen;
+		char buf[1024] = "";
+		rlen = strlen(reply);
+		snprintf(buf, sizeof(buf), "Content-Type: api/response\nContent-Length: %" SWITCH_SSIZE_T_FMT "\n\n", rlen);
+		blen = strlen(buf);
+		switch_socket_send(acs->listener->sock, buf, &blen);
+		switch_socket_send(acs->listener->sock, reply, &rlen);
+	}
+
+	switch_safe_free(stream.data);
+	switch_safe_free(freply);
 
 	switch_thread_rwlock_unlock(acs->listener->rwlock);
-	
 
- done:
+
+  done:
 	if (acs && acs->bg) {
 		if (acs->api_cmd) {
 			free(acs->api_cmd);
@@ -581,9 +581,9 @@
 		free(acs);
 	}
 	return NULL;
-	
+
 }
-static switch_status_t parse_command(listener_t *listener, switch_event_t *event, char *reply, uint32_t reply_len)
+static switch_status_t parse_command(listener_t * listener, switch_event_t *event, char *reply, uint32_t reply_len)
 {
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
 	char *cmd = switch_event_get_header(event, "command");
@@ -618,70 +618,70 @@
 	}
 
 
-    if (listener->session) {
-        switch_channel_t *channel = switch_core_session_get_channel(listener->session);
-        assert(channel != NULL);
-
-        if (!strncasecmp(cmd, "connect", 7)) {
-            snprintf(reply, reply_len, "+OK");
-            goto done;
-        } else if (!strncasecmp(cmd, "sendmsg", 4)) {
-            if (switch_test_flag(listener, LFLAG_ASYNC)) {
-                if ((status = switch_core_session_queue_private_event(listener->session, &event)) == SWITCH_STATUS_SUCCESS) {
-                    snprintf(reply, reply_len, "+OK");
-                } else {
-                    snprintf(reply, reply_len, "-ERR memory error");
-                }
-            } else {
-                switch_ivr_parse_event(listener->session, event);
-                snprintf(reply, reply_len, "+OK");
-            }
-            goto done;
-        } else if (!strncasecmp(cmd, "getvar", 6)) {
-            char *arg;
-            char *val = "";
-            
-            strip_cr(cmd);
-
-            if ((arg = strchr(cmd, ' '))) {
-                *arg++ = '\0';
-                if (!(val = switch_channel_get_variable(channel, arg))) {
-                    val = "";
-                }
-
-            }
-            snprintf(reply, reply_len, "%s", val);
-            goto done;
-        } else if (!strncasecmp(cmd, "myevents", 8)) {
-            listener->event_list[SWITCH_EVENT_CHANNEL_CREATE] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_DESTROY] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_STATE] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_ANSWER] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_HANGUP] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_EXECUTE] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_BRIDGE] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_UNBRIDGE] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_PROGRESS] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_OUTGOING] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_PARK] = 1;
-            listener->event_list[SWITCH_EVENT_CHANNEL_UNPARK] = 1;
-            listener->event_list[SWITCH_EVENT_TALK] = 1;
-            listener->event_list[SWITCH_EVENT_DTMF] = 1;
-            listener->event_list[SWITCH_EVENT_NOTALK] = 1;
-            listener->event_list[SWITCH_EVENT_DETECTED_SPEECH] = 1;
-            switch_set_flag_locked(listener, LFLAG_MYEVENTS);
-            switch_set_flag_locked(listener, LFLAG_EVENTS);
-            if (strstr(cmd, "xml") || strstr(cmd, "XML")) {
-                listener->format = EVENT_FORMAT_XML;
-            }
-            snprintf(reply, reply_len, "+OK Events Enabled");
-            goto done;
-        }
-
-        if (!switch_test_flag(listener, LFLAG_FULL)) {
-            goto done;
-        }
-    }
+	if (listener->session) {
+		switch_channel_t *channel = switch_core_session_get_channel(listener->session);
+		assert(channel != NULL);
+
+		if (!strncasecmp(cmd, "connect", 7)) {
+			snprintf(reply, reply_len, "+OK");
+			goto done;
+		} else if (!strncasecmp(cmd, "sendmsg", 4)) {
+			if (switch_test_flag(listener, LFLAG_ASYNC)) {
+				if ((status = switch_core_session_queue_private_event(listener->session, &event)) == SWITCH_STATUS_SUCCESS) {
+					snprintf(reply, reply_len, "+OK");
+				} else {
+					snprintf(reply, reply_len, "-ERR memory error");
+				}
+			} else {
+				switch_ivr_parse_event(listener->session, event);
+				snprintf(reply, reply_len, "+OK");
+			}
+			goto done;
+		} else if (!strncasecmp(cmd, "getvar", 6)) {
+			char *arg;
+			char *val = "";
+
+			strip_cr(cmd);
+
+			if ((arg = strchr(cmd, ' '))) {
+				*arg++ = '\0';
+				if (!(val = switch_channel_get_variable(channel, arg))) {
+					val = "";
+				}
+
+			}
+			snprintf(reply, reply_len, "%s", val);
+			goto done;
+		} else if (!strncasecmp(cmd, "myevents", 8)) {
+			listener->event_list[SWITCH_EVENT_CHANNEL_CREATE] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_DESTROY] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_STATE] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_ANSWER] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_HANGUP] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_EXECUTE] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_BRIDGE] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_UNBRIDGE] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_PROGRESS] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_OUTGOING] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_PARK] = 1;
+			listener->event_list[SWITCH_EVENT_CHANNEL_UNPARK] = 1;
+			listener->event_list[SWITCH_EVENT_TALK] = 1;
+			listener->event_list[SWITCH_EVENT_DTMF] = 1;
+			listener->event_list[SWITCH_EVENT_NOTALK] = 1;
+			listener->event_list[SWITCH_EVENT_DETECTED_SPEECH] = 1;
+			switch_set_flag_locked(listener, LFLAG_MYEVENTS);
+			switch_set_flag_locked(listener, LFLAG_EVENTS);
+			if (strstr(cmd, "xml") || strstr(cmd, "XML")) {
+				listener->format = EVENT_FORMAT_XML;
+			}
+			snprintf(reply, reply_len, "+OK Events Enabled");
+			goto done;
+		}
+
+		if (!switch_test_flag(listener, LFLAG_FULL)) {
+			goto done;
+		}
+	}
 
 	if (!strncasecmp(cmd, "sendevent", 9)) {
 		char *ename;
@@ -691,7 +691,7 @@
 		if (*ename == '\r' || *ename == '\n') {
 			ename = NULL;
 		}
-		
+
 		if (ename) {
 			switch_event_types_t etype;
 			if (switch_name_event(ename, &etype) == SWITCH_STATUS_SUCCESS) {
@@ -707,7 +707,7 @@
 		char *uuid = cmd + 8;
 
 		if (uuid) {
-			while(*uuid == ' ') {
+			while (*uuid == ' ') {
 				uuid++;
 			}
 
@@ -729,7 +729,7 @@
 				session = NULL;
 			}
 		}
-		
+
 		if (session) {
 			if ((status = switch_core_session_queue_private_event(session, &event)) == SWITCH_STATUS_SUCCESS) {
 				snprintf(reply, reply_len, "+OK");
@@ -742,9 +742,9 @@
 		}
 
 		goto done;
-	
+
 	} else if (!strncasecmp(cmd, "api ", 4)) {
-		struct api_command_struct acs = {0};
+		struct api_command_struct acs = { 0 };
 		char *api_cmd = cmd + 4;
 		char *arg = NULL;
 		strip_cr(api_cmd);
@@ -766,7 +766,7 @@
 		struct api_command_struct *acs;
 		char *api_cmd = cmd + 6;
 		char *arg = NULL;
-        char *uuid_str = NULL;
+		char *uuid_str = NULL;
 		strip_cr(api_cmd);
 
 		if ((arg = strchr(api_cmd, ' '))) {
@@ -786,17 +786,17 @@
 			if (arg) {
 				acs->arg = strdup(arg);
 			}
-			acs->bg = 1;	
+			acs->bg = 1;
 			switch_threadattr_create(&thd_attr, listener->pool);
 			switch_threadattr_detach_set(thd_attr, 1);
 			switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
 			switch_thread_create(&thread, thd_attr, api_exec, acs, listener->pool);
 			if ((uuid_str = switch_event_get_header(event, "job-uuid"))) {
-                switch_copy_string(acs->uuid_str, uuid_str, sizeof(acs->uuid_str));
-            } else {
-                switch_uuid_get(&uuid);
-                switch_uuid_format(acs->uuid_str, &uuid);
-            }
+				switch_copy_string(acs->uuid_str, uuid_str, sizeof(acs->uuid_str));
+			} else {
+				switch_uuid_get(&uuid);
+				switch_uuid_format(acs->uuid_str, &uuid);
+			}
 			snprintf(reply, reply_len, "+OK Job-UUID: %s", acs->uuid_str);
 		} else {
 			snprintf(reply, reply_len, "-ERR memory error!");
@@ -809,16 +809,15 @@
 
 		//pull off the first newline/carriage return
 		strip_cr(cmd);
-		
+
 		//move past the command
 		level_s = cmd + 3;
 
 		//see if we got an argument
-		if(!switch_strlen_zero(level_s)) {
+		if (!switch_strlen_zero(level_s)) {
 			//if so move to the argument
 			level_s++;
 		}
-			
 		//see if we lined up on an argument or not
 		if (switch_strlen_zero(level_s)) {
 			level_s = "debug";
@@ -833,7 +832,7 @@
 	} else if (!strncasecmp(cmd, "nolog", 5)) {
 		void *pop;
 		while (switch_queue_trypop(listener->log_queue, &pop) == SWITCH_STATUS_SUCCESS);
-		
+
 		if (switch_test_flag(listener, LFLAG_LOG)) {
 			switch_clear_flag_locked(listener, LFLAG_LOG);
 			snprintf(reply, reply_len, "+OK no longer logging");
@@ -844,18 +843,18 @@
 		char *next, *cur;
 		uint32_t count = 0, key_count = 0;
 		uint8_t custom = 0;
-		
+
 		strip_cr(cmd);
 		cur = cmd + 5;
 
 		if (cur && (cur = strchr(cur, ' '))) {
-			for(cur++; cur; count++) {
+			for (cur++; cur; count++) {
 				switch_event_types_t type;
 
 				if ((next = strchr(cur, ' '))) {
 					*next++ = '\0';
 				}
-				
+
 				if (!count) {
 					if (!strcasecmp(cur, "xml")) {
 						listener->format = EVENT_FORMAT_XML;
@@ -882,10 +881,10 @@
 					}
 				}
 
-			end:
+			  end:
 				cur = next;
 			}
-		} 
+		}
 
 		if (!key_count) {
 			snprintf(reply, reply_len, "-ERR no keywords supplied");
@@ -902,18 +901,18 @@
 		char *next, *cur;
 		uint32_t count = 0, key_count = 0;
 		uint8_t custom = 0;
-		
+
 		strip_cr(cmd);
 		cur = cmd + 5;
 
 		if (cur && (cur = strchr(cur, ' '))) {
-			for(cur++; cur; count++) {
+			for (cur++; cur; count++) {
 				switch_event_types_t type;
 
 				if ((next = strchr(cur, ' '))) {
 					*next++ = '\0';
 				}
-				
+
 				if (custom) {
 					switch_core_hash_delete(listener->event_hash, cur);
 				} else if (switch_name_event(cur, &type) == SWITCH_STATUS_SUCCESS) {
@@ -942,7 +941,7 @@
 
 				cur = next;
 			}
-		} 
+		}
 
 		if (!key_count) {
 			snprintf(reply, reply_len, "-ERR no keywords supplied");
@@ -954,7 +953,7 @@
 		}
 
 		snprintf(reply, reply_len, "+OK events nixed");
-		
+
 	} else if (!strncasecmp(cmd, "noevents", 8)) {
 		void *pop;
 		while (switch_queue_trypop(listener->event_queue, &pop) == SWITCH_STATUS_SUCCESS);
@@ -971,9 +970,9 @@
 		} else {
 			snprintf(reply, reply_len, "-ERR not listening for events");
 		}
-	} 
-	
- done:
+	}
+
+  done:
 	if (event) {
 		switch_event_destroy(&event);
 	}
@@ -985,7 +984,7 @@
 	return status;
 }
 
-static void *SWITCH_THREAD_FUNC listener_run(switch_thread_t *thread, void *obj)
+static void *SWITCH_THREAD_FUNC listener_run(switch_thread_t * thread, void *obj)
 {
 	listener_t *listener = (listener_t *) obj;
 	char buf[1024];
@@ -993,100 +992,100 @@
 	switch_status_t status;
 	switch_event_t *event;
 	char reply[512] = "";
-    switch_core_session_t *session = NULL;
-    switch_channel_t *channel = NULL;
-    
+	switch_core_session_t *session = NULL;
+	switch_channel_t *channel = NULL;
+
 
 	assert(listener != NULL);
 
-    if ((session = listener->session)) {
-        channel = switch_core_session_get_channel(session);
-        switch_core_session_read_lock(session);
-    }
+	if ((session = listener->session)) {
+		channel = switch_core_session_get_channel(session);
+		switch_core_session_read_lock(session);
+	}
 
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Connection Open\n");
 
-	switch_socket_opt_set(listener->sock, APR_SO_NONBLOCK, TRUE);
+	switch_socket_opt_set(listener->sock, SWITCH_SO_NONBLOCK, TRUE);
 	switch_set_flag_locked(listener, LFLAG_RUNNING);
 	add_listener(listener);
 
-    if (session && switch_test_flag(listener, LFLAG_AUTHED)) {
-        switch_event_t *event = NULL, *call_event;
-        char *event_str;
-        
-
-        switch_set_flag_locked(listener, LFLAG_SESSION);
-        status = read_packet(listener, &event, 25);
-
-        if (status != SWITCH_STATUS_SUCCESS || !event) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Socket Error!\n");
-            switch_clear_flag_locked(listener, LFLAG_RUNNING);
-            goto done;
-        }
-
-        if (switch_event_create(&call_event, SWITCH_EVENT_MESSAGE) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-            switch_clear_flag_locked(listener, LFLAG_RUNNING);
-            goto done;
-        }
-
-        if (parse_command(listener, event, reply, sizeof(reply)) != SWITCH_STATUS_SUCCESS) {
-            switch_clear_flag_locked(listener, LFLAG_RUNNING);
-            goto done;
-        }
-
-        switch_caller_profile_event_set_data(switch_channel_get_caller_profile(channel), "Channel", call_event);
-        switch_channel_event_set_data(channel, call_event);
-        switch_event_add_header(call_event, SWITCH_STACK_BOTTOM, "Content-Type", "command/reply");
-        
-        switch_event_add_header(call_event, SWITCH_STACK_BOTTOM, "Socket-Mode", switch_test_flag(listener, LFLAG_ASYNC) ? "async" : "static");
-        switch_event_add_header(call_event, SWITCH_STACK_BOTTOM, "Control", switch_test_flag(listener, LFLAG_FULL) ? "full" : "single-channel");
-        
-        switch_event_serialize(call_event, &event_str);
-        if (!event_str) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-            switch_clear_flag_locked(listener, LFLAG_RUNNING);
-            goto done;
-        }
-        len = strlen(event_str);
-        switch_socket_send(listener->sock, event_str, &len);
-
-        switch_safe_free(event_str);
-    } else {
-        snprintf(buf, sizeof(buf), "Content-Type: auth/request\n\n");
-		
-        len = strlen(buf);
-        switch_socket_send(listener->sock, buf, &len);
-		
-        while (!switch_test_flag(listener, LFLAG_AUTHED)) {
-            status = read_packet(listener, &event, 25);
-            if (status != SWITCH_STATUS_SUCCESS) {
-                goto done;
-            }
-            if (!event) {
-                continue;
-            }
-
-            if (parse_command(listener, event, reply, sizeof(reply)) != SWITCH_STATUS_SUCCESS) {
-                switch_clear_flag_locked(listener, LFLAG_RUNNING);
-                goto done;
-            }
-            if (!switch_strlen_zero(reply)) {
-                snprintf(buf, sizeof(buf), "Content-Type: command/reply\nReply-Text: %s\n\n", reply);
-                len = strlen(buf);
-                switch_socket_send(listener->sock, buf, &len);
-            }
-            break;
-        }
-    }
+	if (session && switch_test_flag(listener, LFLAG_AUTHED)) {
+		switch_event_t *event = NULL, *call_event;
+		char *event_str;
+
+
+		switch_set_flag_locked(listener, LFLAG_SESSION);
+		status = read_packet(listener, &event, 25);
+
+		if (status != SWITCH_STATUS_SUCCESS || !event) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Socket Error!\n");
+			switch_clear_flag_locked(listener, LFLAG_RUNNING);
+			goto done;
+		}
+
+		if (switch_event_create(&call_event, SWITCH_EVENT_MESSAGE) != SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
+			switch_clear_flag_locked(listener, LFLAG_RUNNING);
+			goto done;
+		}
 
-	while(switch_test_flag(listener, LFLAG_RUNNING) && listen_list.ready) {
+		if (parse_command(listener, event, reply, sizeof(reply)) != SWITCH_STATUS_SUCCESS) {
+			switch_clear_flag_locked(listener, LFLAG_RUNNING);
+			goto done;
+		}
+
+		switch_caller_profile_event_set_data(switch_channel_get_caller_profile(channel), "Channel", call_event);
+		switch_channel_event_set_data(channel, call_event);
+		switch_event_add_header(call_event, SWITCH_STACK_BOTTOM, "Content-Type", "command/reply");
+
+		switch_event_add_header(call_event, SWITCH_STACK_BOTTOM, "Socket-Mode", switch_test_flag(listener, LFLAG_ASYNC) ? "async" : "static");
+		switch_event_add_header(call_event, SWITCH_STACK_BOTTOM, "Control", switch_test_flag(listener, LFLAG_FULL) ? "full" : "single-channel");
+
+		switch_event_serialize(call_event, &event_str);
+		if (!event_str) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
+			switch_clear_flag_locked(listener, LFLAG_RUNNING);
+			goto done;
+		}
+		len = strlen(event_str);
+		switch_socket_send(listener->sock, event_str, &len);
+
+		switch_safe_free(event_str);
+	} else {
+		snprintf(buf, sizeof(buf), "Content-Type: auth/request\n\n");
+
+		len = strlen(buf);
+		switch_socket_send(listener->sock, buf, &len);
+
+		while (!switch_test_flag(listener, LFLAG_AUTHED)) {
+			status = read_packet(listener, &event, 25);
+			if (status != SWITCH_STATUS_SUCCESS) {
+				goto done;
+			}
+			if (!event) {
+				continue;
+			}
+
+			if (parse_command(listener, event, reply, sizeof(reply)) != SWITCH_STATUS_SUCCESS) {
+				switch_clear_flag_locked(listener, LFLAG_RUNNING);
+				goto done;
+			}
+			if (!switch_strlen_zero(reply)) {
+				snprintf(buf, sizeof(buf), "Content-Type: command/reply\nReply-Text: %s\n\n", reply);
+				len = strlen(buf);
+				switch_socket_send(listener->sock, buf, &len);
+			}
+			break;
+		}
+	}
+
+	while (switch_test_flag(listener, LFLAG_RUNNING) && listen_list.ready) {
 		switch_event_t *event;
 
 		len = sizeof(buf);
 		memset(buf, 0, len);
 		status = read_packet(listener, &event, 0);
-		
+
 		if (status != SWITCH_STATUS_SUCCESS) {
 			break;
 		}
@@ -1105,10 +1104,10 @@
 			len = strlen(buf);
 			switch_socket_send(listener->sock, buf, &len);
 		}
-			
+
 	}
 
- done:
+  done:
 
 	remove_listener(listener);
 	close_socket(&listener->sock);
@@ -1117,29 +1116,29 @@
 
 	switch_thread_rwlock_wrlock(listener->rwlock);
 	switch_thread_rwlock_unlock(listener->rwlock);
-	
+
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Connection Closed\n");
 
-    if (session) {
-        switch_channel_clear_flag(switch_core_session_get_channel(session), CF_CONTROLLED);
-        switch_clear_flag_locked(listener, LFLAG_SESSION);
-        switch_core_session_rwunlock(session);
-    } else if (listener->pool) {
+	if (session) {
+		switch_channel_clear_flag(switch_core_session_get_channel(session), CF_CONTROLLED);
+		switch_clear_flag_locked(listener, LFLAG_SESSION);
+		switch_core_session_rwunlock(session);
+	} else if (listener->pool) {
 		switch_memory_pool_t *pool = listener->pool;
 		switch_core_destroy_memory_pool(&pool);
 	}
 
-    
+
 	return NULL;
 }
 
 
 /* Create a thread for the socket and launch it */
-static void launch_listener_thread(listener_t *listener)
+static void launch_listener_thread(listener_t * listener)
 {
 	switch_thread_t *thread;
 	switch_threadattr_t *thd_attr = NULL;
-	
+
 	switch_threadattr_create(&thd_attr, listener->pool);
 	switch_threadattr_detach_set(thd_attr, 1);
 	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
@@ -1164,15 +1163,15 @@
 				if (!strcmp(var, "listen-ip")) {
 					set_pref_ip(val);
 				} else if (!strcmp(var, "listen-port")) {
-					prefs.port = (uint16_t)atoi(val);
+					prefs.port = (uint16_t) atoi(val);
 				} else if (!strcmp(var, "password")) {
 					set_pref_pass(val);
-				} 
+				}
 			}
 		}
 		switch_xml_free(xml);
 	}
-	
+
 	if (switch_strlen_zero(prefs.ip)) {
 		set_pref_ip("127.0.0.1");
 	}
@@ -1192,9 +1191,9 @@
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_runtime(void)
 {
 	switch_memory_pool_t *pool = NULL, *listener_pool = NULL;
-    switch_status_t rv;
-    switch_sockaddr_t *sa;
-    switch_socket_t  *inbound_socket = NULL;
+	switch_status_t rv;
+	switch_sockaddr_t *sa;
+	switch_socket_t *inbound_socket = NULL;
 	listener_t *listener;
 
 	memset(&listen_list, 0, sizeof(listen_list));
@@ -1207,22 +1206,27 @@
 
 	switch_mutex_init(&listen_list.mutex, SWITCH_MUTEX_NESTED, pool);
 	switch_mutex_init(&listen_list.sock_mutex, SWITCH_MUTEX_NESTED, pool);
-	
-	
-	for(;;) {
-		rv = switch_sockaddr_info_get(&sa, prefs.ip, APR_INET, prefs.port, 0, pool);
-		if (rv) goto fail;
-		rv = switch_socket_create(&listen_list.sock, sa->family, SOCK_STREAM, APR_PROTO_TCP, pool);
-		if (rv) goto sock_fail;
+
+
+	for (;;) {
+		rv = switch_sockaddr_info_get(&sa, prefs.ip, SWITCH_INET, prefs.port, 0, pool);
+		if (rv)
+			goto fail;
+		rv = switch_socket_create(&listen_list.sock, switch_sockaddr_get_family(sa), SOCK_STREAM, SWITCH_PROTO_TCP, pool);
+		if (rv)
+			goto sock_fail;
 		rv = switch_socket_opt_set(listen_list.sock, SWITCH_SO_REUSEADDR, 1);
-		if (rv) goto sock_fail;
+		if (rv)
+			goto sock_fail;
 		rv = switch_socket_bind(listen_list.sock, sa);
-		if (rv) goto sock_fail;
+		if (rv)
+			goto sock_fail;
 		rv = switch_socket_listen(listen_list.sock, 5);
-		if (rv) goto sock_fail;
+		if (rv)
+			goto sock_fail;
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Socket up listening on %s:%u\n", prefs.ip, prefs.port);
 		break;
-	sock_fail:
+	  sock_fail:
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Socket Error!\n");
 		switch_yield(100000);
 	}
@@ -1242,7 +1246,7 @@
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "OH OH no pool\n");
 			goto fail;
 		}
-		
+
 		if ((rv = switch_socket_accept(&inbound_socket, listen_list.sock, listener_pool))) {
 			if (prefs.done) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Shutting Down\n");
@@ -1251,12 +1255,12 @@
 			}
 			break;
 		}
-		
+
 		if (!(listener = switch_core_alloc(listener_pool, sizeof(*listener)))) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error\n");
 			break;
 		}
-		
+
 		switch_thread_rwlock_create(&listener->rwlock, listener_pool);
 		switch_queue_create(&listener->event_queue, SWITCH_CORE_QUEUE_LEN, listener_pool);
 		switch_queue_create(&listener->log_queue, SWITCH_CORE_QUEUE_LEN, listener_pool);
@@ -1268,7 +1272,7 @@
 		switch_mutex_init(&listener->flag_mutex, SWITCH_MUTEX_NESTED, listener->pool);
 		switch_core_hash_init(&listener->event_hash, listener->pool);
 		launch_listener_thread(listener);
-		
+
 	}
 
 	close_socket(&listen_list.sock);
@@ -1281,7 +1285,7 @@
 		switch_core_destroy_memory_pool(&listener_pool);
 	}
 
-	fail:
+  fail:
 	return SWITCH_STATUS_TERM;
 }
 

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_event_test/mod_event_test.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_event_test/mod_event_test.c	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_event_test/mod_event_test.c	Tue Apr 24 10:14:28 2007
@@ -59,7 +59,7 @@
 	}
 
 	switch_safe_free(buf);
-	
+
 	if (dofree) {
 		if (xml) {
 			switch_xml_free(xml);
@@ -88,7 +88,7 @@
 #define TTHREADS 500
 static int THREADS = 0;
 
-static void *torture_thread(switch_thread_t *thread, void *obj)
+static void *torture_thread(switch_thread_t * thread, void *obj)
 {
 	int y = 0;
 	int z = 0;
@@ -135,12 +135,10 @@
 		return SWITCH_STATUS_GENERR;
 	}
 
-	if (switch_event_bind((char *) modname, SWITCH_EVENT_ALL, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) !=
-		SWITCH_STATUS_SUCCESS) {
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_ALL, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 		return SWITCH_STATUS_GENERR;
 	}
-
 #ifdef TORTURE_ME
 	if (1) {
 		int x = 0;

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_radius_cdr/mod_radius_cdr.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_radius_cdr/mod_radius_cdr.c	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_radius_cdr/mod_radius_cdr.c	Tue Apr 24 10:14:28 2007
@@ -93,13 +93,13 @@
 						"you can only specify %d radius servers, ignoring excess server entry\n", SERVER_MAX);
 				}
 			}
-                        if (!strcmp(var, "dictionary")) {
+                        else if (!strcmp(var, "dictionary")) {
 				strncpy(dictionary,val,PATH_MAX-1);
 			}
-			if (!strcmp(var, "radius_timeout")) {
+			else if (!strcmp(var, "radius_timeout")) {
 				timeout = strdup(val);
 			}
-			if (!strcmp(var, "radius_retries")) {
+			else if (!strcmp(var, "radius_retries")) {
 				retries = strdup(val);
 			}
 		}

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_xmpp_event/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_xmpp_event/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_xmpp_event/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,16 +1,18 @@
-LDFLAGS += -liksemel -L/usr/local/lib
+# define these targets in your makefile if you wish
+# local_all local_depend local_clean depend_install local_install local_distclean local_extraclean:
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+# and define these variables to impact your build
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install iksemel --prefix=$(PREFIX)
+BASE=../../../..
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
+IKSEMEL_DIR=$(BASE)/libs/iksemel
+IKSEMELLA=$(IKSEMEL_DIR)/src/libiksemel.la
 
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+LOCAL_CFLAGS=-I$(IKSEMEL_DIR)/include
+LOCAL_LIBADD=$(IKSEMELA)
+LOCAL_OBJS=
+include $(BASE)/build/modmake.rules
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(IKSEMELLA): $(IKSEMEL_DIR) $(IKSEMEL_DIR)/.update
+	cd $(IKSEMEL_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_xmpp_event/mod_xmpp_event.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_xmpp_event/mod_xmpp_event.c	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_xmpp_event/mod_xmpp_event.c	Tue Apr 24 10:14:28 2007
@@ -134,8 +134,7 @@
 
 	if (count == 3) {
 		/* TBD use config to pick what events to bind to */
-		if (switch_event_bind((char *) modname, SWITCH_EVENT_ALL, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) !=
-			SWITCH_STATUS_SUCCESS) {
+		if (switch_event_bind((char *) modname, SWITCH_EVENT_ALL, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 			return SWITCH_STATUS_GENERR;
 		}
@@ -151,7 +150,7 @@
 {
 	iks *msg, *ctag;
 
-	msg = iks_make_pres (IKS_SHOW_AVAILABLE, "Available"); 
+	msg = iks_make_pres(IKS_SHOW_AVAILABLE, "Available");
 	ctag = iks_insert(msg, "c");
 	iks_insert_attrib(ctag, "node", "http://www.freeswitch.org/xmpp/client/caps");
 	iks_insert_attrib(ctag, "ver", "1.0.0.1");
@@ -159,7 +158,7 @@
 	iks_insert_attrib(ctag, "xmlns", "http://jabber.org/protocol/caps");
 
 	iks_send(sess->parser, msg);
-    iks_delete(msg);
+	iks_delete(msg);
 
 	return IKS_FILTER_EAT;
 }
@@ -231,16 +230,16 @@
 }
 
 
-static int on_subscribe(void *user_data, ikspak *pak)
+static int on_subscribe(void *user_data, ikspak * pak)
 {
 	char *from = iks_find_attrib(pak->x, "from");
 	struct session *sess = (struct session *) user_data;
 
-	iks *msg = iks_make_s10n (IKS_TYPE_SUBSCRIBED, from, "mod_xmpp_event"); 
+	iks *msg = iks_make_s10n(IKS_TYPE_SUBSCRIBED, from, "mod_xmpp_event");
 	iks_send(sess->parser, msg);
 	iks_delete(msg);
-		
-	msg = iks_make_s10n (IKS_TYPE_SUBSCRIBE, from, "mod_xmpp_event"); 
+
+	msg = iks_make_s10n(IKS_TYPE_SUBSCRIBE, from, "mod_xmpp_event");
 	iks_send(sess->parser, msg);
 	iks_delete(msg);
 
@@ -251,7 +250,7 @@
 {
 	char *cmd = iks_find_cdata(pak->x, "body");
 	char *arg = NULL;
-	switch_stream_handle_t stream = {0};
+	switch_stream_handle_t stream = { 0 };
 	char retbuf[2048] = "";
 	char *p;
 	iks *msg;
@@ -272,12 +271,12 @@
 	stream.write_function = switch_console_stream_write;
 	switch_api_execute(cmd, arg, NULL, &stream);
 
-	
+
 	msg = iks_make_msg(IKS_TYPE_NONE, globals.target_jid, retbuf);
 	iks_insert_attrib(msg, "subject", "Reply");
 	iks_send(globals.session.parser, msg);
 	iks_delete(msg);
-	
+
 
 	return 0;
 }
@@ -305,19 +304,12 @@
 		iks_filter_delete(my_filter);
 	my_filter = iks_filter_new();
 	iks_filter_add_rule(my_filter, on_msg, 0,
-						IKS_RULE_TYPE, IKS_PAK_MESSAGE,
-						IKS_RULE_SUBTYPE, IKS_TYPE_CHAT, IKS_RULE_FROM, globals.target_jid, IKS_RULE_DONE);
+						IKS_RULE_TYPE, IKS_PAK_MESSAGE, IKS_RULE_SUBTYPE, IKS_TYPE_CHAT, IKS_RULE_FROM, globals.target_jid, IKS_RULE_DONE);
 	iks_filter_add_rule(my_filter, (iksFilterHook *) on_result, sess,
-						IKS_RULE_TYPE, IKS_PAK_IQ,
-						IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, "auth", IKS_RULE_DONE);
-	iks_filter_add_rule(my_filter, on_error, sess,
-						IKS_RULE_TYPE, IKS_PAK_IQ,
-						IKS_RULE_SUBTYPE, IKS_TYPE_ERROR, IKS_RULE_ID, "auth", IKS_RULE_DONE);
-
-	iks_filter_add_rule(my_filter, on_subscribe, sess,
-						IKS_RULE_TYPE, IKS_PAK_S10N,
-						IKS_RULE_SUBTYPE, IKS_TYPE_SUBSCRIBE,
-						IKS_RULE_DONE);
+						IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, "auth", IKS_RULE_DONE);
+	iks_filter_add_rule(my_filter, on_error, sess, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_ERROR, IKS_RULE_ID, "auth", IKS_RULE_DONE);
+
+	iks_filter_add_rule(my_filter, on_subscribe, sess, IKS_RULE_TYPE, IKS_PAK_S10N, IKS_RULE_SUBTYPE, IKS_TYPE_SUBSCRIBE, IKS_RULE_DONE);
 
 }
 

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_zeroconf/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_zeroconf/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_zeroconf/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,19 +1,20 @@
-LDFLAGS += -lhowl
-CFLAGS += -I$(PREFIX)/include/howl
-LINKER=$(CC)
+switch_srcdir=../../../..
 
+HOWL=howl-1.0.0
+HOWL_DIR=$(switch_srcdir)/libs/$(HOWL)
+HOWLLA=$(HOWL_DIR)/src/lib/howl/libhowl.la
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+LOCAL_CFLAGS=-I$(HOWL_DIR)/include
+LOCAL_LIBADD=$(HOWLLA)
 
-depends:
-	$(BASE)/build/buildlib.sh $(BASE) install howl-1.0.0.tar.gz --prefix=$(PREFIX)
+DEFAULT_ARGS=--prefix=$(PREFIX) --disable-shared --with-pic
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(LINKER) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
+include $(switch_srcdir)/build/modmake.rules
 
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+$(HOWL_DIR):
+	$(GETLIB) $(HOWL).tar.gz
+	cd $(HOWL_DIR) && ./configure $(DEFAULT_ARGS)
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(HOWLLA): $(HOWL_DIR)
+	cd $(HOWL_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/event_handlers/mod_zeroconf/mod_zeroconf.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/event_handlers/mod_zeroconf/mod_zeroconf.c	(original)
+++ freeswitch/branches/cparker/src/mod/event_handlers/mod_zeroconf/mod_zeroconf.c	Tue Apr 24 10:14:28 2007
@@ -50,57 +50,54 @@
 static sw_result HOWL_API my_browser(sw_discovery discovery,
 									 sw_discovery_oid oid,
 									 sw_discovery_browse_status status,
-									 sw_uint32 interface_index,
-									 sw_const_string name,
-									 sw_const_string type,
-									 sw_const_string domain,
-									 sw_opaque_t extra) {
+									 sw_uint32 interface_index, sw_const_string name, sw_const_string type, sw_const_string domain, sw_opaque_t extra)
+{
 	//sw_discovery_resolve_id rid;
 
 	switch (status) {
-		case SW_DISCOVERY_BROWSE_INVALID:
+	case SW_DISCOVERY_BROWSE_INVALID:
 		{
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "browse reply: Invalid\n");
 		}
 		break;
 
-		case SW_DISCOVERY_BROWSE_RELEASE:
+	case SW_DISCOVERY_BROWSE_RELEASE:
 		{
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "browse reply: Release\n");
 		}
 		break;
 
-		case SW_DISCOVERY_BROWSE_ADD_DOMAIN:
+	case SW_DISCOVERY_BROWSE_ADD_DOMAIN:
 		{
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "browse reply: Add Domain\n");
 		}
 		break;
 
-		case SW_DISCOVERY_BROWSE_ADD_DEFAULT_DOMAIN:
+	case SW_DISCOVERY_BROWSE_ADD_DEFAULT_DOMAIN:
 		{
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "browse reply: Add Default Domain\n");
 		}
 		break;
 
-		case SW_DISCOVERY_BROWSE_REMOVE_DOMAIN:
+	case SW_DISCOVERY_BROWSE_REMOVE_DOMAIN:
 		{
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "browse reply: Remove Domain\n");
 		}
 		break;
 
-		case SW_DISCOVERY_BROWSE_REMOVE_SERVICE:
+	case SW_DISCOVERY_BROWSE_REMOVE_SERVICE:
 		{
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "browse reply: Remove Service\n");
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "remove service: 0x%x %s %s %s\n", interface_index, name, type, domain);
 		}
 		break;
 
-		case SW_DISCOVERY_BROWSE_RESOLVED:
+	case SW_DISCOVERY_BROWSE_RESOLVED:
 		{
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "browse reply: Resolved\n");
 		}
 		break;
-		case SW_DISCOVERY_BROWSE_ADD_SERVICE:
+	case SW_DISCOVERY_BROWSE_ADD_SERVICE:
 		break;
 	}
 
@@ -108,17 +105,15 @@
 }
 
 
-static sw_result HOWL_API my_service_reply(sw_discovery	discovery,
-   sw_discovery_oid	oid,
-   sw_discovery_publish_status status,
-   sw_opaque extra) {
+static sw_result HOWL_API my_service_reply(sw_discovery discovery, sw_discovery_oid oid, sw_discovery_publish_status status, sw_opaque extra)
+{
 	static sw_string status_text[] = {
 		"Started",
 		"Stopped",
 		"Name Collision",
 		"Invalid"
 	};
-	
+
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "publish reply: %s\n", status_text[status]);
 	return SW_OKAY;
 }
@@ -126,7 +121,7 @@
 
 static void event_handler(switch_event_t *event)
 {
-	sw_text_record text_record;	
+	sw_text_record text_record;
 	sw_result result;
 
 	switch (event->event_id) {
@@ -159,10 +154,10 @@
 				service = "_freeswitch._tcp";
 			}
 			if (port) {
-				porti = (sw_port)atoi(port);				
+				porti = (sw_port) atoi(port);
 			}
 
-			switch_mutex_lock(globals.zc_lock);			
+			switch_mutex_lock(globals.zc_lock);
 			if ((result = sw_discovery_publish(globals.discovery,
 											   0,
 											   "freeswitch",
@@ -171,10 +166,7 @@
 											   NULL,
 											   porti,
 											   sw_text_record_bytes(text_record),
-											   sw_text_record_len(text_record),
-											   my_service_reply,
-											   NULL,
-											   &globals.disc_id)) != SW_OKAY) {
+											   sw_text_record_len(text_record), my_service_reply, NULL, &globals.disc_id)) != SW_OKAY) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "publish failed: %u\n", result);
 				sw_text_record_fina(text_record);
 				switch_mutex_unlock(globals.zc_lock);
@@ -183,7 +175,7 @@
 			switch_mutex_unlock(globals.zc_lock);
 			sw_text_record_fina(text_record);
 		}
-		
+
 		break;
 	case SWITCH_EVENT_UNPUBLISH:
 
@@ -211,11 +203,11 @@
 		for (param = switch_xml_child(settings, "param"); param; param = param->next) {
 			char *var = (char *) switch_xml_attr_soft(param, "name");
 			char *val = (char *) switch_xml_attr_soft(param, "value");
-			
+
 			if (!strcmp(var, "browse")) {
 				if ((oid = switch_core_alloc(module_pool, sizeof(*oid))) != 0) {
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Bind browser to to %s\n", val);
-					switch_mutex_lock(globals.zc_lock);	
+					switch_mutex_lock(globals.zc_lock);
 					sw_discovery_browse(globals.discovery, 0, val, NULL, my_browser, NULL, oid);
 					switch_mutex_unlock(globals.zc_lock);
 					count++;
@@ -223,14 +215,12 @@
 					return SWITCH_STATUS_MEMERR;
 				}
 			} else if (!strcasecmp(var, "publish") && !strcasecmp(val, "yes")) {
-				if (switch_event_bind((char *) modname, SWITCH_EVENT_PUBLISH, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) !=
-					SWITCH_STATUS_SUCCESS) {
+				if (switch_event_bind((char *) modname, SWITCH_EVENT_PUBLISH, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 					return SWITCH_STATUS_GENERR;
 				}
-				
-				if (switch_event_bind((char *) modname, SWITCH_EVENT_UNPUBLISH, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) !=
-					SWITCH_STATUS_SUCCESS) {
+
+				if (switch_event_bind((char *) modname, SWITCH_EVENT_UNPUBLISH, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
 					return SWITCH_STATUS_GENERR;
 				}
@@ -289,7 +279,7 @@
 	if (load_config() != SWITCH_STATUS_SUCCESS) {
 		return SWITCH_STATUS_TERM;
 	}
-	
+
 	if (switch_event_reserve_subclass(MY_EVENT_PUBLISH) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass!");
 		return SWITCH_STATUS_GENERR;
@@ -312,7 +302,7 @@
 {
 
 	RUNNING = 1;
-	while(RUNNING == 1) {
+	while (RUNNING == 1) {
 		sw_uint32 ms;
 		ms = 100;
 		sw_discovery_step(globals.discovery, &ms);

Modified: freeswitch/branches/cparker/src/mod/formats/mod_native_file/mod_native_file.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/formats/mod_native_file/mod_native_file.c	(original)
+++ freeswitch/branches/cparker/src/mod/formats/mod_native_file/mod_native_file.c	Tue Apr 24 10:14:28 2007
@@ -63,7 +63,7 @@
 		flags |= SWITCH_FOPEN_READ;
 	}
 
-	if (switch_file_open(&context->fd, path, flags, SWITCH_FPROT_UREAD|SWITCH_FPROT_UWRITE, handle->memory_pool) != SWITCH_STATUS_SUCCESS) {
+	if (switch_file_open(&context->fd, path, flags, SWITCH_FPROT_UREAD | SWITCH_FPROT_UWRITE, handle->memory_pool) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error opening %s\n", path);
 		return SWITCH_STATUS_GENERR;
 	}
@@ -78,7 +78,7 @@
 	handle->seekable = 1;
 	handle->speed = 0;
 	handle->private_info = context;
-	handle->flags |=  SWITCH_FILE_NATIVE;
+	handle->flags |= SWITCH_FILE_NATIVE;
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Opening File [%s] %dhz\n", path, handle->samplerate);
 
 
@@ -88,7 +88,7 @@
 static switch_status_t native_file_file_close(switch_file_handle_t *handle)
 {
 	native_file_context *context = handle->private_info;
-	
+
 	if (context->fd) {
 		switch_file_close(context->fd);
 		context->fd = NULL;
@@ -100,9 +100,9 @@
 static switch_status_t native_file_file_seek(switch_file_handle_t *handle, unsigned int *cur_sample, int64_t samples, int whence)
 {
 	native_file_context *context = handle->private_info;
-	
+
 	switch_file_seek(context->fd, whence, &samples);
-	
+
 	return SWITCH_STATUS_FALSE;
 
 }
@@ -135,7 +135,7 @@
 
 /* Registration */
 
-static char *supported_formats[SWITCH_MAX_CODECS] = {0};
+static char *supported_formats[SWITCH_MAX_CODECS] = { 0 };
 
 static switch_file_interface_t native_file_file_interface = {
 	/*.interface_name */ modname,
@@ -170,7 +170,7 @@
 	uint32_t num_codecs = switch_loadable_module_get_codecs(NULL, codecs, sizeof(codecs) / sizeof(codecs[0]));
 	uint32_t x;
 
-	for (x = 0 ; x < num_codecs; x++) {
+	for (x = 0; x < num_codecs; x++) {
 		supported_formats[x] = codecs[x]->iananame;
 	}
 

Modified: freeswitch/branches/cparker/src/mod/formats/mod_sndfile/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/formats/mod_sndfile/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/formats/mod_sndfile/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,19 +1,14 @@
-LDFLAGS += -lsndfile -L/usr/local/lib
+BASE=../../../..
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+SNDFILE_DIR=$(BASE)/libs/libsndfile
+SNDFILELA=$(SNDFILE_DIR)/src/libsndfile.la
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install libsndfile --prefix=$(PREFIX) --disable-sqlite
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
-
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+LOCAL_CFLAGS=-I$(SNDFILE_DIR)/src
+LOCAL_LIBADD=$(SNDFILELA)
+LOCAL_OBJS=
 
+include $(BASE)/build/modmake.rules
 
+$(SNDFILELA): $(SNDFILE_DIR) $(SNDFILE_DIR)/.update
+	cd $(SNDFILE_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/formats/mod_sndfile/mod_sndfile.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/formats/mod_sndfile/mod_sndfile.c	(original)
+++ freeswitch/branches/cparker/src/mod/formats/mod_sndfile/mod_sndfile.c	Tue Apr 24 10:14:28 2007
@@ -87,8 +87,8 @@
 	map = switch_core_hash_find(globals.format_hash, ext);
 
 	if (mode & SFM_WRITE) {
-		sf_count_t  frames = 0 ;
-		
+		sf_count_t frames = 0;
+
 		context->sfinfo.channels = handle->channels;
 		context->sfinfo.samplerate = handle->samplerate;
 		if (handle->samplerate == 8000 || handle->samplerate == 16000) {
@@ -99,9 +99,9 @@
 			context->sfinfo.format |= SF_FORMAT_PCM_32;
 		}
 
-        sf_command (context->handle, SFC_FILE_TRUNCATE, &frames, sizeof (frames));
-	} 
-	
+		sf_command(context->handle, SFC_FILE_TRUNCATE, &frames, sizeof(frames));
+	}
+
 	if (map) {
 		context->sfinfo.format |= map->format;
 	}
@@ -134,23 +134,22 @@
 		context->sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_ALAW;
 		context->sfinfo.channels = 1;
 		context->sfinfo.samplerate = 8000;
-	} 
-	
-	if ((mode & SFM_WRITE) && sf_format_check (&context->sfinfo) == 0) {
+	}
+
+	if ((mode & SFM_WRITE) && sf_format_check(&context->sfinfo) == 0) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error : file format is invalid (0x%08X).\n", context->sfinfo.format);
 		return SWITCH_STATUS_GENERR;
 	};
-	
+
 	if ((context->handle = sf_open(path, mode, &context->sfinfo)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening File [%s] [%s]\n", path,
-							  sf_strerror(context->handle));
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening File [%s] [%s]\n", path, sf_strerror(context->handle));
 		return SWITCH_STATUS_GENERR;
 	}
 
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Opening File [%s] %dhz\n", path, context->sfinfo.samplerate);
 	handle->samples = (unsigned int) context->sfinfo.frames;
 	handle->samplerate = context->sfinfo.samplerate;
-	handle->channels = (uint8_t)context->sfinfo.channels;
+	handle->channels = (uint8_t) context->sfinfo.channels;
 	handle->format = context->sfinfo.format;
 	handle->sections = context->sfinfo.sections;
 	handle->seekable = context->sfinfo.seekable;
@@ -233,7 +232,7 @@
 {
 	sndfile_context *context = handle->private_info;
 
-	return sf_set_string(context->handle, (int)col, string) ? SWITCH_STATUS_FALSE : SWITCH_STATUS_SUCCESS;
+	return sf_set_string(context->handle, (int) col, string) ? SWITCH_STATUS_FALSE : SWITCH_STATUS_SUCCESS;
 }
 
 static switch_status_t sndfile_file_get_string(switch_file_handle_t *handle, switch_audio_col_t col, const char **string)
@@ -241,7 +240,7 @@
 	sndfile_context *context = handle->private_info;
 	const char *s;
 
-	if ((s = sf_get_string(context->handle, (int)col))) {
+	if ((s = sf_get_string(context->handle, (int) col))) {
 		*string = s;
 		return SWITCH_STATUS_SUCCESS;
 	}
@@ -287,7 +286,7 @@
 	char *extras[] = { "r8", "r16", "r24", "r32", "gsm", "ul", "al", NULL };
 	int exlen = (sizeof(extras) / sizeof(extras[0]));
 	buffer[0] = 0;
-	
+
 	sf_command(NULL, SFC_GET_LIB_VERSION, buffer, sizeof(buffer));
 	if (strlen(buffer) < 1) {
 		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_ERROR, "Line %d: could not retrieve lib version.\n", __LINE__);
@@ -296,8 +295,7 @@
 
 
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "\nLibSndFile Version : %s Supported Formats\n", buffer);
-	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO,
-						  "================================================================================\n");
+	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_INFO, "================================================================================\n");
 	sf_command(NULL, SFC_GET_FORMAT_MAJOR_COUNT, &major_count, sizeof(int));
 	sf_command(NULL, SFC_GET_FORMAT_SUBTYPE_COUNT, &subtype_count, sizeof(int));
 
@@ -327,11 +325,11 @@
 			map->ext = switch_core_permanent_strdup(info.extension);
 			map->uext = switch_core_permanent_strdup(info.extension);
 			map->format = info.format;
-			for(p = map->ext; *p; p++) {
-				*p = (char)tolower(*p);
+			for (p = map->ext; *p; p++) {
+				*p = (char) tolower(*p);
 			}
-			for(p = map->uext; *p; p++) {
-				*p = (char)toupper(*p);
+			for (p = map->uext; *p; p++) {
+				*p = (char) toupper(*p);
 			}
 			switch_core_hash_insert(globals.format_hash, map->ext, map);
 			switch_core_hash_insert(globals.format_hash, map->uext, map);
@@ -339,16 +337,16 @@
 		}
 		format = info.format;
 
-		for (s = 0; s < subtype_count; s++) {			
+		for (s = 0; s < subtype_count; s++) {
 			info.format = s;
 			sf_command(NULL, SFC_GET_FORMAT_SUBTYPE, &info, sizeof(info));
 			format = (format & SF_FORMAT_TYPEMASK) | info.format;
 			sfinfo.format = format;
 			/*
-			if (sf_format_check(&sfinfo)) {
-				switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_DEBUG, "   %s\n", info.name);
-			}
-			*/
+			   if (sf_format_check(&sfinfo)) {
+			   switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_DEBUG, "   %s\n", info.name);
+			   }
+			 */
 		}
 
 	}
@@ -358,9 +356,8 @@
 
 
 
-	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_NOTICE,
-						  "================================================================================\n");
-	
+	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_NOTICE, "================================================================================\n");
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -373,7 +370,7 @@
 	}
 
 	switch_core_hash_init(&globals.format_hash, module_pool);
-	
+
 	if (setup_formats() != SWITCH_STATUS_SUCCESS) {
 		return SWITCH_STATUS_FALSE;
 	}

Modified: freeswitch/branches/cparker/src/mod/languages/mod_mono/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_mono/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_mono/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,28 +1,17 @@
+
 VERSION = mono-1.1.13.8
 TARBALL = mono-1.1.13.8.tar.gz
 GLIB_TARBALL = glib-2.12.3.tar.gz
 GETTEXT_TARBALL = gettext-0.15.tar.gz
 PKGCONFIG_TARBALL = pkg-config-0.21.tar.gz
-CFLAGS += `$(PREFIX)/bin/pkg-config --cflags mono`
-LDFLAGS += `$(PREFIX)/bin/pkg-config --libs mono` 
-
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install $(GETTEXT_TARBALL) --prefix=$(PREFIX) --with-pic
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install $(PKGCONFIG_TARBALL) --prefix=$(PREFIX) --with-pic
-	export PKG_CONFIG=$(PREFIX)/bin/pkg-config; export MSGFMT=$(PREFIX)/bin/; MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install $(GLIB_TARBALL) --prefix=$(PREFIX) --with-pic
-	export PATH=$(PATH):$(PREFIX)/bin/; MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install $(TARBALL) --prefix=$(PREFIX) --with-pic --with-gc=boehm --with-preview=yes --without-sigaltstack
-
-%.o:  %.c
-	$(CC) -fPIC $(CFLAGS) -c -o $@ $<
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) $(MODNAME).o -o $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(LDFLAGS)
 
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+LOCAL_CFLAGS=`$(PREFIX)/bin/pkg-config --cflags mono`
+LOCAL_LDFLAGS=`$(PREFIX)/bin/pkg-config --libs mono`
+include ../../../../build/modmake.rules
+
+local_depend:
+	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) configure install $(GETTEXT_TARBALL) --prefix=$(PREFIX) --with-pic
+	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) configure install $(PKGCONFIG_TARBALL) --prefix=$(PREFIX) --with-pic
+	export PKG_CONFIG=$(PREFIX)/bin/pkg-config; export MSGFMT=$(PREFIX)/bin/; MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) configure install $(GLIB_TARBALL) --prefix=$(PREFIX) --with-pic
+	export PATH=$(PATH):$(PREFIX)/bin/; MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) configure install $(TARBALL) --prefix=$(PREFIX) --with-pic --with-gc=boehm --with-preview=yes --without-sigaltstack
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/languages/mod_mono/mod_mono.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_mono/mod_mono.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_mono/mod_mono.c	Tue Apr 24 10:14:28 2007
@@ -39,13 +39,13 @@
 //#include <gc/gc.h>
 #include <switch.h>
 
-#define SWITCH_MONO_MODULES  "mono/" 
+#define SWITCH_MONO_MODULES  "mono/"
 #define SWITCH_MONO_LIBDIR   "lib/"
 #define SWITCH_MONO_ASSEMBLY "FreeSwitch.dll"
 
 /* Module functions */
 switch_status_t mod_mono_load_modules(const char *module_dir);
-MonoClass* mod_mono_find_assembly_class(MonoImage *image);
+MonoClass *mod_mono_find_assembly_class(MonoImage * image);
 
 /* Managed functions */
 void mod_mono_switch_console_printf(switch_text_channel_t channel, char *file, const char *func, int line, char *fmt, char *msg);
@@ -61,7 +61,7 @@
 typedef struct {
 	MonoAssembly *assembly;
 	MonoClass *class;
-	MonoObject *object;	
+	MonoObject *object;
 } mono_plugin;
 
 static switch_loadable_module_interface_t mono_module_interface = {
@@ -83,17 +83,17 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate memory pool\n");
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	/* Initialise plugin hash */
 	if (switch_core_hash_init(&globals.plugins, mono_pool) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not initialise plugins hash\n");
 		return SWITCH_STATUS_FALSE;
-	}		
-	
+	}
+
 	/* Construct the path to the FreeSwitch assembly, then check to make sure it exists */
-	switch_size_t assembly_dir_len  = strlen(SWITCH_GLOBAL_dirs.base_dir) + strlen(SWITCH_MONO_LIBDIR) + 2; /* Account for / and \0 */
+	switch_size_t assembly_dir_len = strlen(SWITCH_GLOBAL_dirs.base_dir) + strlen(SWITCH_MONO_LIBDIR) + 2;	/* Account for / and \0 */
 	switch_size_t assembly_file_len = assembly_dir_len + strlen(SWITCH_MONO_ASSEMBLY);
-	char *assembly_dir  = (char *) switch_core_alloc(mono_pool, assembly_dir_len);
+	char *assembly_dir = (char *) switch_core_alloc(mono_pool, assembly_dir_len);
 	char *assembly_file = (char *) switch_core_alloc(mono_pool, assembly_file_len);
 
 	apr_finfo_t *assembly_finfo = (apr_finfo_t *) switch_core_alloc(mono_pool, sizeof(*assembly_finfo));
@@ -108,22 +108,21 @@
 
 	/* Mono wants to know where it will be able to find the FreeSwitch assembly if it's not in the GAC */
 	if (getenv("MONO_PATH") != NULL) {
-		switch_size_t mono_path_len = strlen(getenv("MONO_PATH")) + strlen(assembly_dir) + 2; /* Account for : and \0 */ 
+		switch_size_t mono_path_len = strlen(getenv("MONO_PATH")) + strlen(assembly_dir) + 2;	/* Account for : and \0 */
 		char *mono_path = (char *) switch_core_alloc(mono_pool, mono_path_len);
-	
+
 		snprintf(mono_path, mono_path_len, "%s:%s", getenv("MONO_PATH"), assembly_dir);
 
 		setenv("MONO_PATH", mono_path, 1);
-	}
-	else
+	} else
 		setenv("MONO_PATH", assembly_dir, 1);
 
 	/* Now find where our managed modules are */
-	switch_size_t module_dir_len = strlen(SWITCH_GLOBAL_dirs.mod_dir) + strlen(SWITCH_MONO_MODULES) + 2; /* Account for / and \0 */
+	switch_size_t module_dir_len = strlen(SWITCH_GLOBAL_dirs.mod_dir) + strlen(SWITCH_MONO_MODULES) + 2;	/* Account for / and \0 */
 	char *module_dir = (char *) switch_core_alloc(mono_pool, module_dir_len);
 
 	snprintf(module_dir, module_dir_len, "%s/%s", SWITCH_GLOBAL_dirs.mod_dir, SWITCH_MONO_MODULES);
-	
+
 	/* Initialise the mono domain */
 	if (!(globals.domain = mono_jit_init("freeswitch"))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error initialising mono runtime\n");
@@ -139,7 +138,7 @@
 		return SWITCH_STATUS_FALSE;
 	}
 
-	/* Finally, go through and initialise each plugin before returning SUCCESS */ 
+	/* Finally, go through and initialise each plugin before returning SUCCESS */
 	switch_hash_index_t *p = NULL;
 
 	for (p = switch_hash_first(mono_pool, globals.plugins); p; p = switch_hash_next(p)) {
@@ -150,10 +149,10 @@
 
 		switch_hash_this(p, &key, key_length, &value);
 		plugin = (mono_plugin *) value;
-		
+
 		mono_runtime_object_init(plugin->object);
 	}
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -175,16 +174,16 @@
 /*
  * This function will load the managed modules
  *
- */ 
+ */
 switch_status_t mod_mono_load_modules(const char *module_dir)
 {
 	apr_finfo_t *module_finfo = (apr_finfo_t *) switch_core_alloc(mono_pool, sizeof(*module_finfo));
-	
+
 	if (apr_stat(module_finfo, module_dir, 0, mono_pool) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not access module dir!.\n");
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	apr_dir_t *module_dir_handle;
 	char *file;
 	size_t len;
@@ -196,22 +195,21 @@
 	MonoAssembly *assembly;
 	MonoImage *image;
 	gpointer iter;
-	iter=NULL;
-	mono_plugin *plugin=NULL;
+	iter = NULL;
+	mono_plugin *plugin = NULL;
 
 	if (apr_dir_open(&module_dir_handle, module_dir, mono_pool) != SWITCH_STATUS_SUCCESS)
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Could not open directory: %s\n", module_dir);
 
 	/* Read the modules directory */
-	while (apr_dir_read(&finfo, finfo_flags, module_dir_handle) == SWITCH_STATUS_SUCCESS)
-	{
+	while (apr_dir_read(&finfo, finfo_flags, module_dir_handle) == SWITCH_STATUS_SUCCESS) {
 		assembly = (MonoAssembly *) switch_core_alloc(mono_pool, sizeof(assembly));
 		image = (MonoImage *) switch_core_alloc(mono_pool, sizeof(image));
 		const char *fname = finfo.fname;
 
 		if (finfo.filetype != APR_REG)
 			continue;
-                        
+
 		if (!fname)
 			fname = finfo.name;
 
@@ -222,7 +220,7 @@
 			continue;
 
 		len = strlen(module_dir) + strlen(fname) + 2;
-		file = (char *)switch_core_alloc(mono_pool, len);
+		file = (char *) switch_core_alloc(mono_pool, len);
 		snprintf(file, len, "%s%s", module_dir, fname);
 
 		/* Attempt to open the assembly */
@@ -233,13 +231,13 @@
 			continue;
 		}
 
-		/* Get the image from assembly */	
+		/* Get the image from assembly */
 		image = mono_assembly_get_image(assembly);
-	
-		plugin = (mono_plugin *)switch_core_alloc(mono_pool, sizeof(*plugin));
+
+		plugin = (mono_plugin *) switch_core_alloc(mono_pool, sizeof(*plugin));
 
 		plugin->assembly = assembly;
-		plugin->class    = mod_mono_find_assembly_class(mono_assembly_get_image(plugin->assembly));
+		plugin->class = mod_mono_find_assembly_class(mono_assembly_get_image(plugin->assembly));
 
 		if (!plugin->class)
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "No plugin class\n");
@@ -249,30 +247,29 @@
 		switch_core_hash_insert(globals.plugins, (char *) mono_image_get_name(mono_assembly_get_image(assembly)), plugin);
 
 		plugin = NULL;
-	}	
+	}
 	return SWITCH_STATUS_SUCCESS;
 }
 
 /*
  *
- */ 
-MonoClass* mod_mono_find_assembly_class(MonoImage *image)
+ */
+MonoClass *mod_mono_find_assembly_class(MonoImage * image)
 {
 	MonoClass *class, *parent_class = NULL;
 	int i, total;
 
 	total = mono_image_get_table_rows(image, MONO_TABLE_TYPEDEF);
-	
-	for (i = 1; i <= total; ++i)
-	{
+
+	for (i = 1; i <= total; ++i) {
 		class = mono_class_get(image, MONO_TOKEN_TYPE_DEF | i);
 		parent_class = mono_class_get_parent(class);
-		
-		if (parent_class) 
+
+		if (parent_class)
 			if (!strcmp("Module", mono_class_get_name(parent_class)))
 				return class;
 	}
-						
+
 	return NULL;
 }
 

Modified: freeswitch/branches/cparker/src/mod/languages/mod_perl/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_perl/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_perl/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,50 +1,47 @@
-PERL        = $(shell which perl)
+# define these targets in your makefile if you wish
+# local_all local_depend local_clean depend_install local_install local_distclean local_extraclean:
+
+# and define these variables to impact your build
+
+PERL        = `which perl`
 PERL_LIBDIR =-L$(shell perl -MConfig -e 'print $$Config{archlib}')/CORE
 PERL_LIBS   =$(shell perl -MConfig -e 'print $$Config{libs}')
-CFLAGS  +=  -DMULTIPLICITY $(shell $(PERL) -MExtUtils::Embed -e ccopts)
-CFLAGS  += -DEMBED_PERL
-LDFLAGS +=  $(shell $(PERL) -MExtUtils::Embed -e ldopts)
-LDFLAGS +=  $(shell $(PERL) -MConfig -e 'print $$Config{libs}')  
-OBJS += perlxsi.o
+
+LOCAL_CFLAGS=-w -DMULTIPLICITY $(shell $(PERL) -MExtUtils::Embed -e ccopts) -DEMBED_PERL
+LOCAL_LDFLAGS=$(shell $(PERL) -MExtUtils::Embed -e ldopts) $(shell $(PERL) -MConfig -e 'print $$Config{libs}')
+LOCAL_OBJS=perlxsi.o
+include ../../../../build/modmake.rules
+
+
 SWIGCFILE=../../../switch_swig.c
 SWIGIFILE=../../../switch_swig.i
 
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN) fs_perl.$(DYNAMIC_LIB_EXTEN)
+
+local_all: fs_perl.$(DYNAMIC_LIB_EXTEN)
 
 .perlok:
 	@(${PERL} -V | grep -i usemultiplicity=define >/dev/null && echo Phew, You have the right perl.) \
 	|| ((echo Sorry, you need to compile perl with threads and multiplicity.&& exit 1))
 	@touch .perlok
 
-depends:
-
-%.o:  %.c
-	$(CC) -fPIC $(CFLAGS) -c $< -o $@
-
 reswig: 
 	rm switch_swig_wrap.c
 	swig -o switch_swig_wrap.c -l$(SWIGIFILE) -ignoremissing -DMULTIPLICITY -perl5 -module fs_perl $(SWIGCFILE)
 
 switch_swig.o: $(SWIGCFILE) Makefile
-	$(CC)  -w $(CFLAGS) -c $< -o $@
+	$(CC)  -w $(ALL_CFLAGS) -c $< -o $@
 
 switch_swig_wrap.o: switch_swig_wrap.c
-	$(CC) -w $(CFLAGS) -c $< -o $@
-
+	$(CC) -w $(ALL_CFLAGS) -c $< -o $@
 
 fs_perl.$(DYNAMIC_LIB_EXTEN): $(MODNAME).$(DYNAMIC_LIB_EXTEN) switch_swig_wrap.o switch_swig.o
-	$(CC) $(SOLINK) -o fs_perl.$(DYNAMIC_LIB_EXTEN) switch_swig_wrap.o switch_swig.o $(LDFLAGS)
-
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c $(MODNAME).o $(OBJS)
-	$(CC) -fPIC $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(OBJS) $(LDFLAGS)
+	$(LINK) $(SOLINK) -o fs_perl.$(DYNAMIC_LIB_EXTEN) switch_swig_wrap.o switch_swig.o $(LDFLAGS)
 
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~ .perlok
+local_clean:
+	rm -fr *~ .perlok
 
-install:
+depend_install:
 	mkdir -p $(PREFIX)/perl
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
-	cp -f fs_perl.$(DYNAMIC_LIB_EXTEN) fs_perl.pm $(PREFIX)/perl
-	if [ ! -f $(PREFIX)/perl/freeswitch.pm ] ; then cp -f freeswitch.pm $(PREFIX)/perl ; fi
+	$(LTINSTALL) fs_perl.$(DYNAMIC_LIB_EXTEN) fs_perl.pm $(PREFIX)/perl
+	if [ ! -f $(PREFIX)/perl/freeswitch.pm ] ; then $(LTINSTALL) freeswitch.pm $(PREFIX)/perl ; fi

Modified: freeswitch/branches/cparker/src/mod/languages/mod_perl/fs_perl.pm
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_perl/fs_perl.pm	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_perl/fs_perl.pm	Tue Apr 24 10:14:28 2007
@@ -76,4 +76,8 @@
 
 package fs_perl;
 
+*FREESWITCH_PEN = *fs_perlc::FREESWITCH_PEN;
+*FREESWITCH_OID_PREFIX = *fs_perlc::FREESWITCH_OID_PREFIX;
+*FREESWITCH_ITAD = *fs_perlc::FREESWITCH_ITAD;
+*__EXTENSIONS__ = *fs_perlc::__EXTENSIONS__;
 1;

Modified: freeswitch/branches/cparker/src/mod/languages/mod_perl/mod_perl.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_perl/mod_perl.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_perl/mod_perl.c	Tue Apr 24 10:14:28 2007
@@ -50,7 +50,7 @@
 } globals;
 
 
-static void destroy_perl(PerlInterpreter **to_destroy)
+static void destroy_perl(PerlInterpreter ** to_destroy)
 {
 	perl_destruct(*to_destroy);
 	perl_free(*to_destroy);
@@ -59,7 +59,7 @@
 
 static PerlInterpreter *clone_perl(void)
 {
-	return perl_clone(globals.my_perl, CLONEf_COPY_STACKS|CLONEf_KEEP_PTR_TABLE);
+	return perl_clone(globals.my_perl, CLONEf_COPY_STACKS | CLONEf_KEEP_PTR_TABLE);
 }
 
 
@@ -68,10 +68,7 @@
 	char *uuid = switch_core_session_get_uuid(session);
 	char code[1024];
 	PerlInterpreter *my_perl = clone_perl();
-	sprintf(code, "package fs_perl;\n"
-			"$SWITCH_ENV{UUID} = \"%s\";\n"
-			"chdir(\"%s/perl\");\n",
-			uuid, SWITCH_GLOBAL_dirs.base_dir);
+	sprintf(code, "package fs_perl;\n" "$SWITCH_ENV{UUID} = \"%s\";\n" "chdir(\"%s/perl\");\n", uuid, SWITCH_GLOBAL_dirs.base_dir);
 
 	Perl_eval_pv(my_perl, code, TRUE);
 
@@ -84,8 +81,9 @@
 	/*.interface_name */ "perl",
 	/*.application_function */ perl_function,
 	NULL, NULL, NULL,
-	/* flags */ SAF_NONE, /* should we support no media mode here?  If so, we need to detect the mode, and either disable the media functions or indicate media if/when we need */
-	/*.next*/ NULL
+	/* flags */ SAF_NONE,
+	/* should we support no media mode here?  If so, we need to detect the mode, and either disable the media functions or indicate media if/when we need */
+	/*.next */ NULL
 };
 
 static switch_loadable_module_interface_t perl_module_interface = {
@@ -102,7 +100,7 @@
 };
 
 
-SWITCH_MOD_DECLARE(switch_status_t) switch_module_shutdown(void) 
+SWITCH_MOD_DECLARE(switch_status_t) switch_module_shutdown(void)
 {
 	if (globals.my_perl) {
 		perl_destruct(globals.my_perl);
@@ -118,7 +116,7 @@
 
 	PerlInterpreter *my_perl;
 	char code[1024];
-	
+
 	if (!(my_perl = perl_alloc())) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate perl intrepreter\n");
 		return SWITCH_STATUS_MEMERR;
@@ -131,7 +129,7 @@
 	perl_run(my_perl);
 	globals.my_perl = my_perl;
 	sprintf(code, "use lib '%s/perl';use fs_perl;use freeswitch\n", SWITCH_GLOBAL_dirs.base_dir);
-    Perl_eval_pv(my_perl, code, TRUE);
+	Perl_eval_pv(my_perl, code, TRUE);
 
 
 	/* connect my internal structure to the blank pointer passed to me */

Modified: freeswitch/branches/cparker/src/mod/languages/mod_perl/perlxsi.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_perl/perlxsi.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_perl/perlxsi.c	Tue Apr 24 10:14:28 2007
@@ -4,12 +4,11 @@
 #include <EXTERN.h>
 #include <perl.h>
 
-EXTERN_C void xs_init (pTHX);
+EXTERN_C void xs_init(pTHX);
 
-EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);
+EXTERN_C void boot_DynaLoader(pTHX_ CV * cv);
 
-EXTERN_C void
-xs_init(pTHX)
+EXTERN_C void xs_init(pTHX)
 {
 	char *file = __FILE__;
 	dXSUB_SYS;

Modified: freeswitch/branches/cparker/src/mod/languages/mod_perl/switch_swig_wrap.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_perl/switch_swig_wrap.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_perl/switch_swig_wrap.c	Tue Apr 24 10:14:28 2007
@@ -15,8 +15,7 @@
  * clashes if multiple interpreters are included
  *
  ************************************************************************/
-#include <switch.h>
-
+#include "switch.h"
 #define SWIG_TypeRegister    SWIG_Perl_TypeRegister
 #define SWIG_TypeCheck       SWIG_Perl_TypeCheck
 #define SWIG_TypeCast        SWIG_Perl_TypeCast
@@ -769,7 +768,7 @@
 #define  SWIGTYPE_p_switch_core_session_t swig_types[2] 
 #define  SWIGTYPE_p_p_switch_core_session_t swig_types[3] 
 #define  SWIGTYPE_p_uint32_t swig_types[4] 
-#define  SWIGTYPE_p_switch_input_callback_function_t swig_types[5] 
+#define  SWIGTYPE_p_switch_input_args_t swig_types[5] 
 static swig_type_info *swig_types[7];
 
 /* -------- TYPES TABLE (END) -------- */
@@ -807,11 +806,11 @@
 extern void fs_channel_set_variable(switch_core_session_t *,char *,char *);
 extern void fs_channel_get_variable(switch_core_session_t *,char *);
 extern void fs_channel_set_state(switch_core_session_t *,char *);
-extern int fs_ivr_play_file(switch_core_session_t *,char *);
-extern int fs_switch_ivr_record_file(switch_core_session_t *,switch_file_handle_t *,char *,switch_input_callback_function_t,void *,unsigned int,unsigned int);
+extern int fs_ivr_play_file(switch_core_session_t *,switch_file_handle_t *,char *,switch_input_args_t *);
+extern int fs_switch_ivr_record_file(switch_core_session_t *,switch_file_handle_t *,char *,switch_input_args_t *,unsigned int);
 extern int fs_switch_ivr_sleep(switch_core_session_t *,uint32_t);
 extern int fs_ivr_play_file2(switch_core_session_t *,char *);
-extern int fs_switch_ivr_collect_digits_callback(switch_core_session_t *,switch_input_callback_function_t,void *,unsigned int,unsigned int);
+extern int fs_switch_ivr_collect_digits_callback(switch_core_session_t *,switch_input_args_t *,unsigned int);
 extern int fs_switch_ivr_collect_digits_count(switch_core_session_t *,char *,unsigned int,unsigned int,char const *,char *,unsigned int);
 extern int fs_switch_ivr_originate(switch_core_session_t *,switch_core_session_t **,char *,uint32_t);
 extern int fs_switch_ivr_session_transfer(switch_core_session_t *,char *,char *,char *);
@@ -819,7 +818,7 @@
 extern char *fs_switch_channel_get_variable(switch_channel_t *,char *);
 extern int fs_switch_channel_set_variable(switch_channel_t *,char *,char *);
 
-#include "switch.h"
+
 
 #ifdef PERL_OBJECT
 #define MAGIC_CLASS _wrap_fs_perl_var::
@@ -1209,22 +1208,34 @@
 XS(_wrap_fs_ivr_play_file) {
     {
         switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-        char *arg2 ;
+        switch_file_handle_t *arg2 = (switch_file_handle_t *) 0 ;
+        char *arg3 ;
+        switch_input_args_t *arg4 = (switch_input_args_t *) 0 ;
         int result;
         int argvi = 0;
         dXSARGS;
         
-        if ((items < 2) || (items > 2)) {
-            SWIG_croak("Usage: fs_ivr_play_file(session,file);");
+        if ((items < 4) || (items > 4)) {
+            SWIG_croak("Usage: fs_ivr_play_file(session,fh,file,args);");
         }
         {
             if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_switch_core_session_t,0) < 0) {
                 SWIG_croak("Type error in argument 1 of fs_ivr_play_file. Expected _p_switch_core_session_t");
             }
         }
-        if (!SvOK((SV*) ST(1))) arg2 = 0;
-        else arg2 = (char *) SvPV(ST(1), PL_na);
-        result = (int)fs_ivr_play_file(arg1,arg2);
+        {
+            if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_switch_file_handle_t,0) < 0) {
+                SWIG_croak("Type error in argument 2 of fs_ivr_play_file. Expected _p_switch_file_handle_t");
+            }
+        }
+        if (!SvOK((SV*) ST(2))) arg3 = 0;
+        else arg3 = (char *) SvPV(ST(2), PL_na);
+        {
+            if (SWIG_ConvertPtr(ST(3), (void **) &arg4, SWIGTYPE_p_switch_input_args_t,0) < 0) {
+                SWIG_croak("Type error in argument 4 of fs_ivr_play_file. Expected _p_switch_input_args_t");
+            }
+        }
+        result = (int)fs_ivr_play_file(arg1,arg2,arg3,arg4);
         
         ST(argvi) = sv_newmortal();
         sv_setiv(ST(argvi++), (IV) result);
@@ -1241,16 +1252,14 @@
         switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
         switch_file_handle_t *arg2 = (switch_file_handle_t *) 0 ;
         char *arg3 ;
-        switch_input_callback_function_t arg4 ;
-        void *arg5 = (void *) 0 ;
-        unsigned int arg6 ;
-        unsigned int arg7 ;
+        switch_input_args_t *arg4 = (switch_input_args_t *) 0 ;
+        unsigned int arg5 ;
         int result;
         int argvi = 0;
         dXSARGS;
         
-        if ((items < 7) || (items > 7)) {
-            SWIG_croak("Usage: fs_switch_ivr_record_file(session,fh,file,dtmf_callback,buf,buflen,limit);");
+        if ((items < 5) || (items > 5)) {
+            SWIG_croak("Usage: fs_switch_ivr_record_file(session,fh,file,args,limit);");
         }
         {
             if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_switch_core_session_t,0) < 0) {
@@ -1265,20 +1274,12 @@
         if (!SvOK((SV*) ST(2))) arg3 = 0;
         else arg3 = (char *) SvPV(ST(2), PL_na);
         {
-            switch_input_callback_function_t * argp;
-            if (SWIG_ConvertPtr(ST(3),(void **) &argp, SWIGTYPE_p_switch_input_callback_function_t,0) < 0) {
-                SWIG_croak("Type error in argument 4 of fs_switch_ivr_record_file. Expected _p_switch_input_callback_function_t");
+            if (SWIG_ConvertPtr(ST(3), (void **) &arg4, SWIGTYPE_p_switch_input_args_t,0) < 0) {
+                SWIG_croak("Type error in argument 4 of fs_switch_ivr_record_file. Expected _p_switch_input_args_t");
             }
-            arg4 = *argp;
         }
-        {
-            if (SWIG_ConvertPtr(ST(4), (void **) &arg5, 0,0) < 0) {
-                SWIG_croak("Type error in argument 5 of fs_switch_ivr_record_file. Expected _p_void");
-            }
-        }
-        arg6 = (unsigned int) SvUV(ST(5));
-        arg7 = (unsigned int) SvUV(ST(6));
-        result = (int)fs_switch_ivr_record_file(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
+        arg5 = (unsigned int) SvUV(ST(4));
+        result = (int)fs_switch_ivr_record_file(arg1,arg2,arg3,arg4,arg5);
         
         ST(argvi) = sv_newmortal();
         sv_setiv(ST(argvi++), (IV) result);
@@ -1358,16 +1359,14 @@
 XS(_wrap_fs_switch_ivr_collect_digits_callback) {
     {
         switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-        switch_input_callback_function_t arg2 ;
-        void *arg3 = (void *) 0 ;
-        unsigned int arg4 ;
-        unsigned int arg5 ;
+        switch_input_args_t *arg2 = (switch_input_args_t *) 0 ;
+        unsigned int arg3 ;
         int result;
         int argvi = 0;
         dXSARGS;
         
-        if ((items < 5) || (items > 5)) {
-            SWIG_croak("Usage: fs_switch_ivr_collect_digits_callback(session,dtmf_callback,buf,buflen,timeout);");
+        if ((items < 3) || (items > 3)) {
+            SWIG_croak("Usage: fs_switch_ivr_collect_digits_callback(session,args,timeout);");
         }
         {
             if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_switch_core_session_t,0) < 0) {
@@ -1375,20 +1374,12 @@
             }
         }
         {
-            switch_input_callback_function_t * argp;
-            if (SWIG_ConvertPtr(ST(1),(void **) &argp, SWIGTYPE_p_switch_input_callback_function_t,0) < 0) {
-                SWIG_croak("Type error in argument 2 of fs_switch_ivr_collect_digits_callback. Expected _p_switch_input_callback_function_t");
-            }
-            arg2 = *argp;
-        }
-        {
-            if (SWIG_ConvertPtr(ST(2), (void **) &arg3, 0,0) < 0) {
-                SWIG_croak("Type error in argument 3 of fs_switch_ivr_collect_digits_callback. Expected _p_void");
+            if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_switch_input_args_t,0) < 0) {
+                SWIG_croak("Type error in argument 2 of fs_switch_ivr_collect_digits_callback. Expected _p_switch_input_args_t");
             }
         }
-        arg4 = (unsigned int) SvUV(ST(3));
-        arg5 = (unsigned int) SvUV(ST(4));
-        result = (int)fs_switch_ivr_collect_digits_callback(arg1,arg2,arg3,arg4,arg5);
+        arg3 = (unsigned int) SvUV(ST(2));
+        result = (int)fs_switch_ivr_collect_digits_callback(arg1,arg2,arg3);
         
         ST(argvi) = sv_newmortal();
         sv_setiv(ST(argvi++), (IV) result);
@@ -1641,7 +1632,7 @@
 static swig_type_info _swigt__p_switch_core_session_t[] = {{"_p_switch_core_session_t", 0, "switch_core_session_t *", 0},{"_p_switch_core_session_t"},{0}};
 static swig_type_info _swigt__p_p_switch_core_session_t[] = {{"_p_p_switch_core_session_t", 0, "switch_core_session_t **", 0},{"_p_p_switch_core_session_t"},{0}};
 static swig_type_info _swigt__p_uint32_t[] = {{"_p_uint32_t", 0, "uint32_t *", 0},{"_p_uint32_t"},{0}};
-static swig_type_info _swigt__p_switch_input_callback_function_t[] = {{"_p_switch_input_callback_function_t", 0, "switch_input_callback_function_t *", 0},{"_p_switch_input_callback_function_t"},{0}};
+static swig_type_info _swigt__p_switch_input_args_t[] = {{"_p_switch_input_args_t", 0, "switch_input_args_t *", 0},{"_p_switch_input_args_t"},{0}};
 
 static swig_type_info *swig_types_initial[] = {
 _swigt__p_switch_channel_t, 
@@ -1649,7 +1640,7 @@
 _swigt__p_switch_core_session_t, 
 _swigt__p_p_switch_core_session_t, 
 _swigt__p_uint32_t, 
-_swigt__p_switch_input_callback_function_t, 
+_swigt__p_switch_input_args_t, 
 0
 };
 
@@ -1657,6 +1648,10 @@
 /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */
 
 static swig_constant_info swig_constants[] = {
+{ SWIG_STRING,  (char *) SWIG_prefix "FREESWITCH_PEN", 0, 0, (void *)"27880", 0},
+{ SWIG_STRING,  (char *) SWIG_prefix "FREESWITCH_OID_PREFIX", 0, 0, (void *)".1.3.6.1.4.1.27880", 0},
+{ SWIG_STRING,  (char *) SWIG_prefix "FREESWITCH_ITAD", 0, 0, (void *)"543", 0},
+{ SWIG_INT,     (char *) SWIG_prefix "__EXTENSIONS__", (long) 1, 0, 0, 0},
 {0}
 };
 #ifdef __cplusplus

Modified: freeswitch/branches/cparker/src/mod/languages/mod_python/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_python/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_python/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,32 +1,23 @@
-LCFLAGS=-fPIC
-CFLAGS += -fPIC -I$(PREFIX)/include/python2.4/
-PYMOD=freeswitch
-LDFLAGS=-lpython2.4 -Xlinker -export-dynamic -L$(PREFIX)/lib/python2.4/config/  -lutil -lstdc++
-SWIGCFILE=../../../switch_swig.c
-SWIGIFILE=../../../switch_swig.i
-CPPCC = g++
-OBJS=freeswitch_python.o mod_python_wrap.o
+# define these targets in your makefile if you wish
+# local_all local_depend local_clean depend_install local_install local_distclean local_extraclean:
 
-#all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PYMOD).$(DYNAMIC_LIB_EXTEN)
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(OBJS) 
+# and define these variables to impact your build
 
-depends:
-	MAKE=$(MAKE) PY_CFLAGS=-fPIC $(BASE)/build/buildlib.sh $(BASE) install Python-2.4.3.tgz --prefix=$(PREFIX) --enable-threads
+LOCAL_CFLAGS=-I$(PREFIX)/include/python2.4/
+LOCAL_LDFLAGS=-lpython2.4 -L$(PREFIX)/lib/python2.4/config/  -lutil -lstdc++
+LOCAL_OBJS=freeswitch_python.o mod_python_wrap.o
+include ../../../../build/modmake.rules
 
-%.o: %.cpp
-	$(CPPCC) -Wall -Werror -fPIC $(CFLAGS) -c -o $@ $<
+PYMOD=freeswitch
 
-%.o:  %.c
-	$(CC) $(LCFLAGS) $(CFLAGS) -c $< -o $@
+SWIGCFILE=../../../switch_swig.c
+SWIGIFILE=../../../switch_swig.i
 
-od_python.c:
-	$(CC) $(LCFLAGS) $(CFLAGS) -c  mod_python.c -o mod_python.o
+local_depend:
+	MAKE=$(MAKE) PY_CFLAGS=-fPIC $(BASE)/build/buildlib.sh $(BASE) install Python-2.4.3.tgz --prefix=$(PREFIX) --enable-threads
 
 reswig: 
-	# rm -f switch_swig_wrap.c config.m4 CREDITS *${PYMOD}*
-	# swig -o switch_swig_wrap.c -l$(SWIGIFILE) -ignoremissing -DMULTIPLICITY -python -module $(PYMOD) $(SWIGCFILE)
 	swig -python -shadow -c++ -o mod_python_wrap.cpp mod_python.i
-	# patch -p0 -i fix.diff
 
 switch_swig_wrap.o: switch_swig_wrap.c Makefile
 	$(CC)  -w $(CFLAGS) -c $< -o $@
@@ -34,21 +25,6 @@
 switch_swig.o: $(SWIGCFILE) Makefile
 	$(CC)  -w $(CFLAGS) -c $< -o $@
 
-
-# $(PYMOD).$(DYNAMIC_LIB_EXTEN): $(MODNAME).$(DYNAMIC_LIB_EXTEN) switch_swig_wrap.o switch_swig.o Makefile
-#	$(CC) $(SOLINK) -o py_$(PYMOD).$(DYNAMIC_LIB_EXTEN) switch_swig_wrap.o switch_swig.o $(LDFLAGS)
-
-# $(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c $(MODNAME).o $(OBJS) switch_swig_wrap.o switch_swig.o Makefile
-#	$(CC) $(LCFLAGS) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o switch_swig_wrap.o switch_swig.o $(OBJS) $(LDFLAGS)
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c $(MODNAME).o $(OBJS) Makefile
-	$(CC) $(LCFLAGS) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(OBJS) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	# cp -f py_$(PYMOD).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+local_install:
 	cp -f freeswitch.py $(PREFIX)/lib/python2.4/site-packages/
 

Modified: freeswitch/branches/cparker/src/mod/languages/mod_python/freeswitch_python.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_python/freeswitch_python.h	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_python/freeswitch_python.h	Tue Apr 24 10:14:28 2007
@@ -1,4 +1,4 @@
-#ifndef FREESWITCH_PYTHON_H 
+#ifndef FREESWITCH_PYTHON_H
 #define FREESWITCH_PYTHON_H
 
 #include <Python.h>
@@ -9,45 +9,40 @@
 
 #include <switch.h>
 
-extern void *globalDTMFCallbackFunction;
-extern switch_status_t PythonDTMFCallback(switch_core_session *session, 
-                                    void *input, 
-                                    switch_input_type_t itype,
-                                    void *buf,
-                                    unsigned int buflen);
-
-class SessionContainer {
-    private:
-        switch_core_session_t *session;
-        switch_channel_t *channel;
-        char *uuid;
-        PyObject *dtmfCallbackFunction;
-        char *tts_name;
-        char *voice_name;
-    public:
-        SessionContainer(char *uuid);
-        ~SessionContainer();
-        void console_log(char *level_str, char *msg);
-        void console_clean_log(char *msg);
-        int  answer();
-        int  pre_answer();
-        void hangup(char *cause);
-        void set_variable(char *var, char *val);
-        void get_variable(char *var, char *val);
-        void set_state(char *state);
-        int  play_file(char *file, char *timer_name);
-        void set_dtmf_callback(PyObject *pyfunc);
-        int  speak_text(char *text);
-        void set_tts_parms(char *tts_name, char *voice_name);
-        int  get_digits(char *dtmf_buf, int len, char *terminators, char *terminator, int timeout);
-        int  transfer(char *extensions, char *dialplan, char *context);
-        int  play_and_get_digits(int min_digits, int max_digits, int max_tries, int timeout, char *terminators, 
-                char *audio_files, char *bad_input_audio_files, char *dtmf_buf, char *digits_regex);
-    protected:
-};
+	extern void *globalDTMFCallbackFunction;
+	extern switch_status_t PythonDTMFCallback(switch_core_session * session, void *input, switch_input_type_t itype, void *buf, unsigned int buflen);
+
+	class SessionContainer {
+	  private:
+		switch_core_session_t *session;
+		switch_channel_t *channel;
+		char *uuid;
+		PyObject *dtmfCallbackFunction;
+		char *tts_name;
+		char *voice_name;
+	  public:
+		     SessionContainer(char *uuid);
+		    ~SessionContainer();
+		void console_log(char *level_str, char *msg);
+		void console_clean_log(char *msg);
+		int answer();
+		int pre_answer();
+		void hangup(char *cause);
+		void set_variable(char *var, char *val);
+		void get_variable(char *var, char *val);
+		void set_state(char *state);
+		int play_file(char *file, char *timer_name);
+		void set_dtmf_callback(PyObject * pyfunc);
+		int speak_text(char *text);
+		void set_tts_parms(char *tts_name, char *voice_name);
+		int get_digits(char *dtmf_buf, int len, char *terminators, char *terminator, int timeout);
+		int transfer(char *extensions, char *dialplan, char *context);
+		int play_and_get_digits(int min_digits, int max_digits, int max_tries, int timeout, char *terminators,
+								char *audio_files, char *bad_input_audio_files, char *dtmf_buf, char *digits_regex);
+	  protected:
+	};
 
 #ifdef __cplusplus
 }
 #endif
-
 #endif

Modified: freeswitch/branches/cparker/src/mod/languages/mod_python/mod_python.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_python/mod_python.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_python/mod_python.c	Tue Apr 24 10:14:28 2007
@@ -50,54 +50,55 @@
 static void python_function(switch_core_session_t *session, char *data)
 {
 	char *uuid = switch_core_session_get_uuid(session);
-    char *argv[1];
-    FILE* pythonfile;
+	char *argv[1];
+	FILE *pythonfile;
 
-    argv[0] = uuid;
-    pythonfile = fopen(data, "r");
+	argv[0] = uuid;
+	pythonfile = fopen(data, "r");
 
-    Py_Initialize();
-    PySys_SetArgv(1, argv);
-    init_freeswitch();
-    PyRun_SimpleFile(pythonfile, "");
-    Py_Finalize();
+	Py_Initialize();
+	PySys_SetArgv(1, argv);
+	init_freeswitch();
+	PyRun_SimpleFile(pythonfile, "");
+	Py_Finalize();
 
 }
 
 static switch_status_t launch_python(char *text, switch_core_session_t *session, switch_stream_handle_t *stream)
 {
-    FILE* pythonfile;
+	FILE *pythonfile;
 
-    if (switch_strlen_zero(text)) {
-        stream->write_function(stream, "USAGE: %s\n", python_run_interface.syntax);
-        return SWITCH_STATUS_SUCCESS;
-    }
-
-    pythonfile = fopen(text, "r");
-
-    Py_Initialize();
-    init_freeswitch();
-    PyRun_SimpleFile(pythonfile, "");
-    Py_Finalize();
+	if (switch_strlen_zero(text)) {
+		stream->write_function(stream, "USAGE: %s\n", python_run_interface.syntax);
+		return SWITCH_STATUS_SUCCESS;
+	}
 
-    stream->write_function(stream, "OK\n");
-    return SWITCH_STATUS_SUCCESS;
+	pythonfile = fopen(text, "r");
+
+	Py_Initialize();
+	init_freeswitch();
+	PyRun_SimpleFile(pythonfile, "");
+	Py_Finalize();
+
+	stream->write_function(stream, "OK\n");
+	return SWITCH_STATUS_SUCCESS;
 }
 
 static const switch_application_interface_t python_application_interface = {
 	/*.interface_name */ "python",
 	/*.application_function */ python_function,
 	NULL, NULL, NULL,
-	/* flags */ SAF_NONE, /* should we support no media mode here?  If so, we need to detect the mode, and either disable the media functions or indicate media if/when we need */
-	/*.next*/ NULL
+	/* flags */ SAF_NONE,
+	/* should we support no media mode here?  If so, we need to detect the mode, and either disable the media functions or indicate media if/when we need */
+	/*.next */ NULL
 };
 
 static switch_api_interface_t python_run_interface = {
-    /*.interface_name */ "python",
-    /*.desc */ "run a python script",
-    /*.function */ launch_python,
-    /*.syntax */ "python </path/to/script>",
-    /*.next */ NULL
+	/*.interface_name */ "python",
+	/*.desc */ "run a python script",
+	/*.function */ launch_python,
+	/*.syntax */ "python </path/to/script>",
+	/*.next */ NULL
 };
 
 static switch_loadable_module_interface_t python_module_interface = {

Modified: freeswitch/branches/cparker/src/mod/languages/mod_python/switch_swig_wrap.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_python/switch_swig_wrap.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_python/switch_swig_wrap.c	Tue Apr 24 10:14:28 2007
@@ -21,7 +21,7 @@
 #  if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
 #    define SWIGTEMPLATEDISAMBIGUATOR template
 #  else
-#    define SWIGTEMPLATEDISAMBIGUATOR 
+#    define SWIGTEMPLATEDISAMBIGUATOR
 #  endif
 #endif
 
@@ -37,9 +37,9 @@
 /* attribute recognised by some compilers to avoid 'unused' warnings */
 #ifndef SWIGUNUSED
 # if defined(__GNUC__) || defined(__ICC)
-#   define SWIGUNUSED __attribute__ ((unused)) 
+#   define SWIGUNUSED __attribute__ ((unused))
 # else
-#   define SWIGUNUSED 
+#   define SWIGUNUSED
 # endif
 #endif
 
@@ -72,7 +72,7 @@
 #   define SWIGSTDCALL __stdcall
 # else
 #   define SWIGSTDCALL
-# endif 
+# endif
 #endif
 
 
@@ -123,37 +123,37 @@
 extern "C" {
 #endif
 
-typedef void *(*swig_converter_func)(void *);
-typedef struct swig_type_info *(*swig_dycast_func)(void **);
+	typedef void *(*swig_converter_func) (void *);
+	typedef struct swig_type_info *(*swig_dycast_func) (void **);
 
 /* Structure to store inforomation on one type */
-typedef struct swig_type_info {
-  const char             *name;			/* mangled name of this type */
-  const char             *str;			/* human readable name of this type */
-  swig_dycast_func        dcast;		/* dynamic cast function down a hierarchy */
-  struct swig_cast_info  *cast;			/* linked list of types that can cast into this type */
-  void                   *clientdata;		/* language specific type data */
-} swig_type_info;
+	typedef struct swig_type_info {
+		const char *name;		/* mangled name of this type */
+		const char *str;		/* human readable name of this type */
+		swig_dycast_func dcast;	/* dynamic cast function down a hierarchy */
+		struct swig_cast_info *cast;	/* linked list of types that can cast into this type */
+		void *clientdata;		/* language specific type data */
+	} swig_type_info;
 
 /* Structure to store a type and conversion function used for casting */
-typedef struct swig_cast_info {
-  swig_type_info         *type;			/* pointer to type that is equivalent to this type */
-  swig_converter_func     converter;		/* function to cast the void pointers */
-  struct swig_cast_info  *next;			/* pointer to next cast in linked list */
-  struct swig_cast_info  *prev;			/* pointer to the previous cast */
-} swig_cast_info;
+	typedef struct swig_cast_info {
+		swig_type_info *type;	/* pointer to type that is equivalent to this type */
+		swig_converter_func converter;	/* function to cast the void pointers */
+		struct swig_cast_info *next;	/* pointer to next cast in linked list */
+		struct swig_cast_info *prev;	/* pointer to the previous cast */
+	} swig_cast_info;
 
 /* Structure used to store module information
  * Each module generates one structure like this, and the runtime collects
  * all of these structures and stores them in a circularly linked list.*/
-typedef struct swig_module_info {
-  swig_type_info         **types;		/* Array of pointers to swig_type_info structures that are in this module */
-  size_t                 size;		        /* Number of types in this module */
-  struct swig_module_info *next;		/* Pointer to next element in circularly linked list */
-  swig_type_info         **type_initial;	/* Array of initially generated type structures */
-  swig_cast_info         **cast_initial;	/* Array of initially generated casting structures */
-  void                    *clientdata;		/* Language specific module data */
-} swig_module_info;
+	typedef struct swig_module_info {
+		swig_type_info **types;	/* Array of pointers to swig_type_info structures that are in this module */
+		size_t size;			/* Number of types in this module */
+		struct swig_module_info *next;	/* Pointer to next element in circularly linked list */
+		swig_type_info **type_initial;	/* Array of initially generated type structures */
+		swig_cast_info **cast_initial;	/* Array of initially generated casting structures */
+		void *clientdata;		/* Language specific module data */
+	} swig_module_info;
 
 
 /* 
@@ -163,54 +163,59 @@
   Return 0 when the two name types are equivalent, as in
   strncmp, but skipping ' '.
 */
-SWIGRUNTIME int
-SWIG_TypeNameComp(const char *f1, const char *l1,
-		  const char *f2, const char *l2) {
-  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
-    while ((*f1 == ' ') && (f1 != l1)) ++f1;
-    while ((*f2 == ' ') && (f2 != l2)) ++f2;
-    if (*f1 != *f2) return (int)(*f1 - *f2);
-  }
-  return (l1 - f1) - (l2 - f2);
-}
+	SWIGRUNTIME int
+	    SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) {
+		for (; (f1 != l1) && (f2 != l2); ++f1, ++f2) {
+			while ((*f1 == ' ') && (f1 != l1))
+				++f1;
+			while ((*f2 == ' ') && (f2 != l2))
+				++f2;
+			if (*f1 != *f2)
+				return (int) (*f1 - *f2);
+		} return (l1 - f1) - (l2 - f2);
+	}
 
 /*
   Check type equivalence in a name list like <name1>|<name2>|...
   Return 0 if not equal, 1 if equal
 */
-SWIGRUNTIME int
-SWIG_TypeEquiv(const char *nb, const char *tb) {
-  int equiv = 0;
-  const char* te = tb + strlen(tb);
-  const char* ne = nb;
-  while (!equiv && *ne) {
-    for (nb = ne; *ne; ++ne) {
-      if (*ne == '|') break;
-    }
-    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
-    if (*ne) ++ne;
-  }
-  return equiv;
-}
+	SWIGRUNTIME int
+	    SWIG_TypeEquiv(const char *nb, const char *tb) {
+		int equiv = 0;
+		const char *te = tb + strlen(tb);
+		const char *ne = nb;
+		while (!equiv && *ne) {
+			for (nb = ne; *ne; ++ne) {
+				if (*ne == '|')
+					break;
+			}
+			equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
+			if (*ne)
+				++ne;
+		}
+		return equiv;
+	}
 
 /*
   Check type equivalence in a name list like <name1>|<name2>|...
   Return 0 if equal, -1 if nb < tb, 1 if nb > tb
 */
-SWIGRUNTIME int
-SWIG_TypeCompare(const char *nb, const char *tb) {
-  int equiv = 0;
-  const char* te = tb + strlen(tb);
-  const char* ne = nb;
-  while (!equiv && *ne) {
-    for (nb = ne; *ne; ++ne) {
-      if (*ne == '|') break;
-    }
-    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
-    if (*ne) ++ne;
-  }
-  return equiv;
-}
+	SWIGRUNTIME int
+	    SWIG_TypeCompare(const char *nb, const char *tb) {
+		int equiv = 0;
+		const char *te = tb + strlen(tb);
+		const char *ne = nb;
+		while (!equiv && *ne) {
+			for (nb = ne; *ne; ++ne) {
+				if (*ne == '|')
+					break;
+			}
+			equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
+			if (*ne)
+				++ne;
+		}
+		return equiv;
+	}
 
 
 /* think of this as a c++ template<> or a scheme macro */
@@ -238,87 +243,83 @@
 /*
   Check the typename
 */
-SWIGRUNTIME swig_cast_info *
-SWIG_TypeCheck(const char *c, swig_type_info *ty) {
-  SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty);
-}
+	SWIGRUNTIME swig_cast_info *SWIG_TypeCheck(const char *c, swig_type_info * ty) {
+		SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty);
+	}
 
 /* Same as previous function, except strcmp is replaced with a pointer comparison */
-SWIGRUNTIME swig_cast_info *
-SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) {
-  SWIG_TypeCheck_Template(iter->type == from, into);
-}
+	SWIGRUNTIME swig_cast_info *SWIG_TypeCheckStruct(swig_type_info * from, swig_type_info * into) {
+		SWIG_TypeCheck_Template(iter->type == from, into);
+	}
 
 /*
   Cast a pointer up an inheritance hierarchy
 */
-SWIGRUNTIMEINLINE void *
-SWIG_TypeCast(swig_cast_info *ty, void *ptr) {
-  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr);
-}
+	SWIGRUNTIMEINLINE void *SWIG_TypeCast(swig_cast_info * ty, void *ptr) {
+		return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter) (ptr);
+	}
 
 /* 
    Dynamic pointer casting. Down an inheritance hierarchy
 */
-SWIGRUNTIME swig_type_info *
-SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
-  swig_type_info *lastty = ty;
-  if (!ty || !ty->dcast) return ty;
-  while (ty && (ty->dcast)) {
-    ty = (*ty->dcast)(ptr);
-    if (ty) lastty = ty;
-  }
-  return lastty;
-}
+	SWIGRUNTIME swig_type_info *SWIG_TypeDynamicCast(swig_type_info * ty, void **ptr) {
+		swig_type_info *lastty = ty;
+		if (!ty || !ty->dcast)
+			return ty;
+		while (ty && (ty->dcast)) {
+			ty = (*ty->dcast) (ptr);
+			if (ty)
+				lastty = ty;
+		}
+		return lastty;
+	}
 
 /*
   Return the name associated with this type
 */
-SWIGRUNTIMEINLINE const char *
-SWIG_TypeName(const swig_type_info *ty) {
-  return ty->name;
-}
+	SWIGRUNTIMEINLINE const char *SWIG_TypeName(const swig_type_info * ty) {
+		return ty->name;
+	}
 
 /*
   Return the pretty name associated with this type,
   that is an unmangled type name in a form presentable to the user.
 */
-SWIGRUNTIME const char *
-SWIG_TypePrettyName(const swig_type_info *type) {
-  /* The "str" field contains the equivalent pretty names of the
-     type, separated by vertical-bar characters.  We choose
-     to print the last name, as it is often (?) the most
-     specific. */
-  if (type->str != NULL) {
-    const char *last_name = type->str;
-    const char *s;
-    for (s = type->str; *s; s++)
-      if (*s == '|') last_name = s+1;
-    return last_name;
-  }
-  else
-    return type->name;
-}
+	SWIGRUNTIME const char *SWIG_TypePrettyName(const swig_type_info * type) {
+		/* The "str" field contains the equivalent pretty names of the
+		   type, separated by vertical-bar characters.  We choose
+		   to print the last name, as it is often (?) the most
+		   specific. */
+		if (type->str != NULL) {
+			const char *last_name = type->str;
+			const char *s;
+			for (s = type->str; *s; s++)
+				if (*s == '|')
+					last_name = s + 1;
+			return last_name;
+		} else
+			return type->name;
+	}
 
 /* 
    Set the clientdata field for a type
 */
-SWIGRUNTIME void
-SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
-  swig_cast_info *cast = ti->cast;
-  /* if (ti->clientdata == clientdata) return; */
-  ti->clientdata = clientdata;
-  
-  while (cast) {
-    if (!cast->converter) {
-      swig_type_info *tc = cast->type;
-      if (!tc->clientdata) {
-	SWIG_TypeClientData(tc, clientdata);
-      }
-    }    
-    cast = cast->next;
-  }
-}
+	SWIGRUNTIME void
+	     SWIG_TypeClientData(swig_type_info * ti, void *clientdata) {
+		swig_cast_info *cast = ti->cast;
+		/* if (ti->clientdata == clientdata) return; */
+		ti->clientdata = clientdata;
+
+		while (cast) {
+			if (!cast->converter) {
+				swig_type_info *tc = cast->type;
+				if (!tc->clientdata) {
+					SWIG_TypeClientData(tc, clientdata);
+				}
+			}
+			cast = cast->next;
+		}
+	}
 
 /*
   Search for a swig_type_info structure only by mangled name
@@ -328,41 +329,38 @@
   Note: if start == end at the beginning of the function, we go all the way around
   the circular list.
 */
-SWIGRUNTIME swig_type_info *
-SWIG_MangledTypeQueryModule(swig_module_info *start, 
-                            swig_module_info *end, 
-		            const char *name) {
-  swig_module_info *iter = start;
-  do {
-    if (iter->size) {
-      register size_t l = 0;
-      register size_t r = iter->size - 1;
-      do {
-	/* since l+r >= 0, we can (>> 1) instead (/ 2) */
-	register size_t i = (l + r) >> 1; 
-	const char *iname = iter->types[i]->name;
-	if (iname) {
-	  register int compare = strcmp(name, iname);
-	  if (compare == 0) {	    
-	    return iter->types[i];
-	  } else if (compare < 0) {
-	    if (i) {
-	      r = i - 1;
-	    } else {
-	      break;
-	    }
-	  } else if (compare > 0) {
-	    l = i + 1;
-	  }
-	} else {
-	  break; /* should never happen */
+	SWIGRUNTIME swig_type_info *SWIG_MangledTypeQueryModule(swig_module_info * start, swig_module_info * end, const char *name) {
+		swig_module_info *iter = start;
+		do {
+			if (iter->size) {
+				register size_t l = 0;
+				register size_t r = iter->size - 1;
+				do {
+					/* since l+r >= 0, we can (>> 1) instead (/ 2) */
+					register size_t i = (l + r) >> 1;
+					const char *iname = iter->types[i]->name;
+					if (iname) {
+						register int compare = strcmp(name, iname);
+						if (compare == 0) {
+							return iter->types[i];
+						} else if (compare < 0) {
+							if (i) {
+								r = i - 1;
+							} else {
+								break;
+							}
+						} else if (compare > 0) {
+							l = i + 1;
+						}
+					} else {
+						break;	/* should never happen */
+					}
+				} while (l <= r);
+			}
+			iter = iter->next;
+		} while (iter != end);
+		return 0;
 	}
-      } while (l <= r);
-    }
-    iter = iter->next;
-  } while (iter != end);
-  return 0;
-}
 
 /*
   Search for a swig_type_info structure for either a mangled name or a human readable name.
@@ -373,131 +371,125 @@
   Note: if start == end at the beginning of the function, we go all the way around
   the circular list.
 */
-SWIGRUNTIME swig_type_info *
-SWIG_TypeQueryModule(swig_module_info *start, 
-                     swig_module_info *end, 
-		     const char *name) {
-  /* STEP 1: Search the name field using binary search */
-  swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
-  if (ret) {
-    return ret;
-  } else {
-    /* STEP 2: If the type hasn't been found, do a complete search
-       of the str field (the human readable name) */
-    swig_module_info *iter = start;
-    do {
-      register size_t i = 0;
-      for (; i < iter->size; ++i) {
-	if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
-	  return iter->types[i];
-      }
-      iter = iter->next;
-    } while (iter != end);
-  }
-  
-  /* neither found a match */
-  return 0;
-}
+	SWIGRUNTIME swig_type_info *SWIG_TypeQueryModule(swig_module_info * start, swig_module_info * end, const char *name) {
+		/* STEP 1: Search the name field using binary search */
+		swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
+		if (ret) {
+			return ret;
+		} else {
+			/* STEP 2: If the type hasn't been found, do a complete search
+			   of the str field (the human readable name) */
+			swig_module_info *iter = start;
+			do {
+				register size_t i = 0;
+				for (; i < iter->size; ++i) {
+					if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
+						return iter->types[i];
+				}
+				iter = iter->next;
+			} while (iter != end);
+		}
+
+		/* neither found a match */
+		return 0;
+	}
 
 
 /* 
    Pack binary data into a string
 */
-SWIGRUNTIME char *
-SWIG_PackData(char *c, void *ptr, size_t sz) {
-  static const char hex[17] = "0123456789abcdef";
-  register const unsigned char *u = (unsigned char *) ptr;
-  register const unsigned char *eu =  u + sz;
-  for (; u != eu; ++u) {
-    register unsigned char uu = *u;
-    *(c++) = hex[(uu & 0xf0) >> 4];
-    *(c++) = hex[uu & 0xf];
-  }
-  return c;
-}
+	SWIGRUNTIME char *SWIG_PackData(char *c, void *ptr, size_t sz) {
+		static const char hex[17] = "0123456789abcdef";
+		register const unsigned char *u = (unsigned char *) ptr;
+		register const unsigned char *eu = u + sz;
+		for (; u != eu; ++u) {
+			register unsigned char uu = *u;
+			*(c++) = hex[(uu & 0xf0) >> 4];
+			*(c++) = hex[uu & 0xf];
+		}
+		return c;
+	}
 
 /* 
    Unpack binary data from a string
 */
-SWIGRUNTIME const char *
-SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
-  register unsigned char *u = (unsigned char *) ptr;
-  register const unsigned char *eu = u + sz;
-  for (; u != eu; ++u) {
-    register char d = *(c++);
-    register unsigned char uu = 0;
-    if ((d >= '0') && (d <= '9'))
-      uu = ((d - '0') << 4);
-    else if ((d >= 'a') && (d <= 'f'))
-      uu = ((d - ('a'-10)) << 4);
-    else 
-      return (char *) 0;
-    d = *(c++);
-    if ((d >= '0') && (d <= '9'))
-      uu |= (d - '0');
-    else if ((d >= 'a') && (d <= 'f'))
-      uu |= (d - ('a'-10));
-    else 
-      return (char *) 0;
-    *u = uu;
-  }
-  return c;
-}
+	SWIGRUNTIME const char *SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
+		register unsigned char *u = (unsigned char *) ptr;
+		register const unsigned char *eu = u + sz;
+		for (; u != eu; ++u) {
+			register char d = *(c++);
+			register unsigned char uu = 0;
+			if ((d >= '0') && (d <= '9'))
+				uu = ((d - '0') << 4);
+			else if ((d >= 'a') && (d <= 'f'))
+				uu = ((d - ('a' - 10)) << 4);
+			else
+				return (char *) 0;
+			d = *(c++);
+			if ((d >= '0') && (d <= '9'))
+				uu |= (d - '0');
+			else if ((d >= 'a') && (d <= 'f'))
+				uu |= (d - ('a' - 10));
+			else
+				return (char *) 0;
+			*u = uu;
+		}
+		return c;
+	}
 
 /* 
    Pack 'void *' into a string buffer.
 */
-SWIGRUNTIME char *
-SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
-  char *r = buff;
-  if ((2*sizeof(void *) + 2) > bsz) return 0;
-  *(r++) = '_';
-  r = SWIG_PackData(r,&ptr,sizeof(void *));
-  if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
-  strcpy(r,name);
-  return buff;
-}
+	SWIGRUNTIME char *SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
+		char *r = buff;
+		if ((2 * sizeof(void *) + 2) > bsz)
+			return 0;
+		*(r++) = '_';
+		r = SWIG_PackData(r, &ptr, sizeof(void *));
+		if (strlen(name) + 1 > (bsz - (r - buff)))
+			return 0;
+		strcpy(r, name);
+		return buff;
+	}
 
-SWIGRUNTIME const char *
-SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
-  if (*c != '_') {
-    if (strcmp(c,"NULL") == 0) {
-      *ptr = (void *) 0;
-      return name;
-    } else {
-      return 0;
-    }
-  }
-  return SWIG_UnpackData(++c,ptr,sizeof(void *));
-}
+	SWIGRUNTIME const char *SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
+		if (*c != '_') {
+			if (strcmp(c, "NULL") == 0) {
+				*ptr = (void *) 0;
+				return name;
+			} else {
+				return 0;
+			}
+		}
+		return SWIG_UnpackData(++c, ptr, sizeof(void *));
+	}
 
-SWIGRUNTIME char *
-SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
-  char *r = buff;
-  size_t lname = (name ? strlen(name) : 0);
-  if ((2*sz + 2 + lname) > bsz) return 0;
-  *(r++) = '_';
-  r = SWIG_PackData(r,ptr,sz);
-  if (lname) {
-    strncpy(r,name,lname+1);
-  } else {
-    *r = 0;
-  }
-  return buff;
-}
+	SWIGRUNTIME char *SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
+		char *r = buff;
+		size_t lname = (name ? strlen(name) : 0);
+		if ((2 * sz + 2 + lname) > bsz)
+			return 0;
+		*(r++) = '_';
+		r = SWIG_PackData(r, ptr, sz);
+		if (lname) {
+			strncpy(r, name, lname + 1);
+		} else {
+			*r = 0;
+		}
+		return buff;
+	}
 
-SWIGRUNTIME const char *
-SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
-  if (*c != '_') {
-    if (strcmp(c,"NULL") == 0) {
-      memset(ptr,0,sz);
-      return name;
-    } else {
-      return 0;
-    }
-  }
-  return SWIG_UnpackData(++c,ptr,sz);
-}
+	SWIGRUNTIME const char *SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
+		if (*c != '_') {
+			if (strcmp(c, "NULL") == 0) {
+				memset(ptr, 0, sz);
+				return name;
+			} else {
+				return 0;
+			}
+		}
+		return SWIG_UnpackData(++c, ptr, sz);
+	}
 
 #ifdef __cplusplus
 }
@@ -551,14 +543,14 @@
 #define SWIG_PY_BINARY  5
 
 /* Constant information structure */
-typedef struct swig_const_info {
-    int type;
-    char *name;
-    long lvalue;
-    double dvalue;
-    void   *pvalue;
-    swig_type_info **ptype;
-} swig_const_info;
+	typedef struct swig_const_info {
+		int type;
+		char *name;
+		long lvalue;
+		double dvalue;
+		void *pvalue;
+		swig_type_info **ptype;
+	} swig_const_info;
 
 
 /* -----------------------------------------------------------------------------
@@ -571,8 +563,6 @@
 #ifdef __cplusplus
 }
 #endif
-
-
 /***********************************************************************
  * pyrun.swg
  *
@@ -581,44 +571,33 @@
  *     type checking.
  *
  * Author : David Beazley (beazley at cs.uchicago.edu)
- ************************************************************************/
-
-/* Common SWIG API */
+																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																													   ************************************************************************//* Common SWIG API */
 #define SWIG_ConvertPtr(obj, pp, type, flags)    SWIG_Python_ConvertPtr(obj, pp, type, flags)
 #define SWIG_NewPointerObj(p, type, flags)       SWIG_Python_NewPointerObj(p, type, flags)
 #define SWIG_MustGetPtr(p, type, argnum, flags)  SWIG_Python_MustGetPtr(p, type, argnum, flags)
- 
-
 /* Python-specific SWIG API */
 #define SWIG_ConvertPacked(obj, ptr, sz, ty, flags)   SWIG_Python_ConvertPacked(obj, ptr, sz, ty, flags)
 #define SWIG_NewPackedObj(ptr, sz, type)              SWIG_Python_NewPackedObj(ptr, sz, type)
-
 /* Runtime API */
 #define SWIG_GetModule(clientdata) SWIG_Python_GetModule()
 #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer)
-
 /* -----------------------------------------------------------------------------
  * Pointer declarations
- * ----------------------------------------------------------------------------- */
-/*
-  Use SWIG_NO_COBJECT_TYPES to force the use of strings to represent
-  C/C++ pointers in the python side. Very useful for debugging, but
-  not always safe.
-*/
+																																																																																																																																																																																																																																																																																																																																								  																																																																																																																																																																				  																																																																																		  																																									  																				    * ----------------------------------------------------------------------------- *//*
+																																																																																																																																																																																																																																																																																																																																								     Use SWIG_NO_COBJECT_TYPES to force the use of strings to represent
+																																																																																																																																																																																																																																																																																																																																								     C/C++ pointers in the python side. Very useful for debugging, but
+																																																																																																																																																																																																																																																																																																																																								     not always safe.
+																																																																																																																																																																																																																																																																																																																																								   */
 #if !defined(SWIG_NO_COBJECT_TYPES) && !defined(SWIG_COBJECT_TYPES)
 #  define SWIG_COBJECT_TYPES
 #endif
-
 /* Flags for pointer conversion */
 #define SWIG_POINTER_EXCEPTION     0x1
 #define SWIG_POINTER_DISOWN        0x2
-
-
 /* Add PyOS_snprintf for old Pythons */
 #if PY_VERSION_HEX < 0x02020000
 #define PyOS_snprintf snprintf
 #endif
-
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -632,507 +611,450 @@
 
 /* A crude PyString_FromFormat implementation for old Pythons */
 #if PY_VERSION_HEX < 0x02020000
-static PyObject *
-PyString_FromFormat(const char *fmt, ...) {
-  va_list ap;
-  char buf[SWIG_BUFFER_SIZE * 2];
-  int res;
-  va_start(ap, fmt);
-  res = vsnprintf(buf, sizeof(buf), fmt, ap);
-  va_end(ap);
-  return (res < 0 || res >= sizeof(buf)) ? 0 : PyString_FromString(buf);
-}
+	static PyObject *PyString_FromFormat(const char *fmt, ...) {
+		va_list ap;
+		char buf[SWIG_BUFFER_SIZE * 2];
+		int res;
+		    va_start(ap, fmt);
+		    res = vsnprintf(buf, sizeof(buf), fmt, ap);
+		    va_end(ap);
+		    return (res < 0 || res >= sizeof(buf)) ? 0 : PyString_FromString(buf);
+	}
 #endif
-
 #if PY_VERSION_HEX < 0x01060000
 #define PyObject_Del(op) PyMem_DEL((op))
 #endif
-
 #if defined(SWIG_COBJECT_TYPES)
 #if !defined(SWIG_COBJECT_PYTHON)
 /* -----------------------------------------------------------------------------
  * Implements a simple Swig Object type, and use it instead of PyCObject
- * ----------------------------------------------------------------------------- */
-
-typedef struct {
-  PyObject_HEAD
-  void *ptr;
-  const char *desc;
-} PySwigObject;
+ * ----------------------------------------------------------------------------- */ typedef struct {
+		PyObject_HEAD void *ptr;
+		const char *desc;
+	} PySwigObject;
 
 /* Declarations for objects of type PySwigObject */
 
-SWIGRUNTIME int
-PySwigObject_print(PySwigObject *v, FILE *fp, int flags)
-{
-  char result[SWIG_BUFFER_SIZE];
-  flags = flags;
-  if (SWIG_PackVoidPtr(result, v->ptr, v->desc, sizeof(result))) {
-    fputs("<Swig Object at ", fp); fputs(result, fp); fputs(">", fp);
-    return 0; 
-  } else {
-    return 1; 
-  }
-}
-  
-SWIGRUNTIME PyObject *
-PySwigObject_repr(PySwigObject *v)
-{
-  char result[SWIG_BUFFER_SIZE];
-  return SWIG_PackVoidPtr(result, v->ptr, v->desc, sizeof(result)) ?
-    PyString_FromFormat("<Swig Object at %s>", result) : 0;
-}
+	SWIGRUNTIME int
+	    PySwigObject_print(PySwigObject * v, FILE * fp, int flags) {
+		char result[SWIG_BUFFER_SIZE];
+		flags = flags;
+		if (SWIG_PackVoidPtr(result, v->ptr, v->desc, sizeof(result))) {
+			fputs("<Swig Object at ", fp);
+			fputs(result, fp);
+			fputs(">", fp);
+			return 0;
+		} else {
+			return 1;
+		}
+	}
 
-SWIGRUNTIME PyObject *
-PySwigObject_str(PySwigObject *v)
-{
-  char result[SWIG_BUFFER_SIZE];
-  return SWIG_PackVoidPtr(result, v->ptr, v->desc, sizeof(result)) ?
-    PyString_FromString(result) : 0;
-}
+	SWIGRUNTIME PyObject *PySwigObject_repr(PySwigObject * v) {
+		char result[SWIG_BUFFER_SIZE];
+		return SWIG_PackVoidPtr(result, v->ptr, v->desc, sizeof(result)) ? PyString_FromFormat("<Swig Object at %s>", result) : 0;
+	}
 
-SWIGRUNTIME PyObject *
-PySwigObject_long(PySwigObject *v)
-{
-  return PyLong_FromVoidPtr(v->ptr);
-}
+	SWIGRUNTIME PyObject *PySwigObject_str(PySwigObject * v) {
+		char result[SWIG_BUFFER_SIZE];
+		return SWIG_PackVoidPtr(result, v->ptr, v->desc, sizeof(result)) ? PyString_FromString(result) : 0;
+	}
 
-SWIGRUNTIME PyObject *
-PySwigObject_format(const char* fmt, PySwigObject *v)
-{
-  PyObject *res = NULL;
-  PyObject *args = PyTuple_New(1);
-  if (args && (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0)) {
-    PyObject *ofmt = PyString_FromString(fmt);
-    if (ofmt) {
-      res = PyString_Format(ofmt,args);
-      Py_DECREF(ofmt);
-    }
-    Py_DECREF(args);
-  }  
-  return res;
-}
+	SWIGRUNTIME PyObject *PySwigObject_long(PySwigObject * v) {
+		return PyLong_FromVoidPtr(v->ptr);
+	}
 
-SWIGRUNTIME PyObject *
-PySwigObject_oct(PySwigObject *v)
-{
-  return PySwigObject_format("%o",v);
-}
+	SWIGRUNTIME PyObject *PySwigObject_format(const char *fmt, PySwigObject * v) {
+		PyObject *res = NULL;
+		PyObject *args = PyTuple_New(1);
+		if (args && (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0)) {
+			PyObject *ofmt = PyString_FromString(fmt);
+			if (ofmt) {
+				res = PyString_Format(ofmt, args);
+				Py_DECREF(ofmt);
+			}
+			Py_DECREF(args);
+		}
+		return res;
+	}
 
-SWIGRUNTIME PyObject *
-PySwigObject_hex(PySwigObject *v)
-{
-  return PySwigObject_format("%x",v);
-}
+	SWIGRUNTIME PyObject *PySwigObject_oct(PySwigObject * v) {
+		return PySwigObject_format("%o", v);
+	}
 
-SWIGRUNTIME int
-PySwigObject_compare(PySwigObject *v, PySwigObject *w)
-{
-  int c = strcmp(v->desc, w->desc);
-  if (c) {
-    return (c > 0) ? 1 : -1;
-  } else {
-    void *i = v->ptr;
-    void *j = w->ptr;
-    return (i < j) ? -1 : ((i > j) ? 1 : 0);
-  }
-}
+	SWIGRUNTIME PyObject *PySwigObject_hex(PySwigObject * v) {
+		return PySwigObject_format("%x", v);
+	}
 
-SWIGRUNTIME void
-PySwigObject_dealloc(PySwigObject *self)
-{
-  PyObject_Del(self);
-}
+	SWIGRUNTIME int
+	    PySwigObject_compare(PySwigObject * v, PySwigObject * w) {
+		int c = strcmp(v->desc, w->desc);
+		if (c) {
+			return (c > 0) ? 1 : -1;
+		} else {
+			void *i = v->ptr;
+			void *j = w->ptr;
+			return (i < j) ? -1 : ((i > j) ? 1 : 0);
+		}
+	}
 
-SWIGRUNTIME PyTypeObject*
-PySwigObject_type(void) {
-  static char pyswigobject_type__doc__[] = 
-    "Swig object carries a C/C++ instance pointer";
-  
-  static PyNumberMethods PySwigObject_as_number = {
-    (binaryfunc)0, /*nb_add*/
-    (binaryfunc)0, /*nb_subtract*/
-    (binaryfunc)0, /*nb_multiply*/
-    (binaryfunc)0, /*nb_divide*/
-    (binaryfunc)0, /*nb_remainder*/
-    (binaryfunc)0, /*nb_divmod*/
-    (ternaryfunc)0,/*nb_power*/
-    (unaryfunc)0,  /*nb_negative*/
-    (unaryfunc)0,  /*nb_positive*/
-    (unaryfunc)0,  /*nb_absolute*/
-    (inquiry)0,    /*nb_nonzero*/
-    0,		   /*nb_invert*/
-    0,		   /*nb_lshift*/
-    0,		   /*nb_rshift*/
-    0,		   /*nb_and*/
-    0,		   /*nb_xor*/
-    0,		   /*nb_or*/
-    (coercion)0,   /*nb_coerce*/
-    (unaryfunc)PySwigObject_long, /*nb_int*/
-    (unaryfunc)PySwigObject_long, /*nb_long*/
-    (unaryfunc)0,                 /*nb_float*/
-    (unaryfunc)PySwigObject_oct,  /*nb_oct*/
-    (unaryfunc)PySwigObject_hex,  /*nb_hex*/
+	SWIGRUNTIME void
+	     PySwigObject_dealloc(PySwigObject * self) {
+		PyObject_Del(self);
+	}
+
+	SWIGRUNTIME PyTypeObject *PySwigObject_type(void) {
+		static char pyswigobject_type__doc__[] = "Swig object carries a C/C++ instance pointer";
+
+		static PyNumberMethods PySwigObject_as_number = {
+			(binaryfunc) 0,		/*nb_add */
+			(binaryfunc) 0,		/*nb_subtract */
+			(binaryfunc) 0,		/*nb_multiply */
+			(binaryfunc) 0,		/*nb_divide */
+			(binaryfunc) 0,		/*nb_remainder */
+			(binaryfunc) 0,		/*nb_divmod */
+			(ternaryfunc) 0,	/*nb_power */
+			(unaryfunc) 0,		/*nb_negative */
+			(unaryfunc) 0,		/*nb_positive */
+			(unaryfunc) 0,		/*nb_absolute */
+			(inquiry) 0,		/*nb_nonzero */
+			0,					/*nb_invert */
+			0,					/*nb_lshift */
+			0,					/*nb_rshift */
+			0,					/*nb_and */
+			0,					/*nb_xor */
+			0,					/*nb_or */
+			(coercion) 0,		/*nb_coerce */
+			(unaryfunc) PySwigObject_long,	/*nb_int */
+			(unaryfunc) PySwigObject_long,	/*nb_long */
+			(unaryfunc) 0,		/*nb_float */
+			(unaryfunc) PySwigObject_oct,	/*nb_oct */
+			(unaryfunc) PySwigObject_hex,	/*nb_hex */
 #if PY_VERSION_HEX >= 0x02020000
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ 
+			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0	/* nb_inplace_add -> nb_inplace_true_divide */
 #elif PY_VERSION_HEX >= 0x02000000
-    0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */
+			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0	/* nb_inplace_add -> nb_inplace_or */
 #endif
-  };
+		};
 
-  static PyTypeObject pyswigobject_type
+		static PyTypeObject pyswigobject_type
 #if !defined(__cplusplus)
-  ;  
-  static int type_init = 0;
-  if (!type_init) {
-    PyTypeObject tmp
-#endif
-    = {
-    PyObject_HEAD_INIT(&PyType_Type)
-    0,					/*ob_size*/
-    (char *)"PySwigObject",		/*tp_name*/
-    sizeof(PySwigObject),		/*tp_basicsize*/
-    0,					/*tp_itemsize*/
-    /* methods */
-    (destructor)PySwigObject_dealloc,	/*tp_dealloc*/
-    (printfunc)PySwigObject_print,	/*tp_print*/
-    (getattrfunc)0,			/*tp_getattr*/
-    (setattrfunc)0,			/*tp_setattr*/
-    (cmpfunc)PySwigObject_compare,	/*tp_compare*/
-    (reprfunc)PySwigObject_repr,	/*tp_repr*/
-    &PySwigObject_as_number,	        /*tp_as_number*/
-    0,					/*tp_as_sequence*/
-    0,					/*tp_as_mapping*/
-    (hashfunc)0,			/*tp_hash*/
-    (ternaryfunc)0,			/*tp_call*/
-    (reprfunc)PySwigObject_str,		/*tp_str*/
-    /* Space for future expansion */
-    0,0,0,0,
-    pyswigobject_type__doc__, 	        /* Documentation string */
+		            ;
+		static int type_init = 0;
+		if (!type_init) {
+			PyTypeObject tmp
+#endif
+				= {
+				PyObject_HEAD_INIT(&PyType_Type)
+					0,			/*ob_size */
+				(char *) "PySwigObject",	/*tp_name */
+				sizeof(PySwigObject),	/*tp_basicsize */
+				0,				/*tp_itemsize */
+				/* methods */
+				(destructor) PySwigObject_dealloc,	/*tp_dealloc */
+				(printfunc) PySwigObject_print,	/*tp_print */
+				(getattrfunc) 0,	/*tp_getattr */
+				(setattrfunc) 0,	/*tp_setattr */
+				(cmpfunc) PySwigObject_compare,	/*tp_compare */
+				(reprfunc) PySwigObject_repr,	/*tp_repr */
+				&PySwigObject_as_number,	/*tp_as_number */
+				0,				/*tp_as_sequence */
+				0,				/*tp_as_mapping */
+				(hashfunc) 0,	/*tp_hash */
+				(ternaryfunc) 0,	/*tp_call */
+				(reprfunc) PySwigObject_str,	/*tp_str */
+				/* Space for future expansion */
+				0, 0, 0, 0,
+				pyswigobject_type__doc__,	/* Documentation string */
 #if PY_VERSION_HEX >= 0x02000000
-    0,                                  /* tp_traverse */
-    0,                                  /* tp_clear */
+				0,				/* tp_traverse */
+				0,				/* tp_clear */
 #endif
 #if PY_VERSION_HEX >= 0x02010000
-    0,                                  /* tp_richcompare */
-    0,                                  /* tp_weaklistoffset */
+				0,				/* tp_richcompare */
+				0,				/* tp_weaklistoffset */
 #endif
 #if PY_VERSION_HEX >= 0x02020000
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */
+				0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,	/* tp_iter -> tp_weaklist */
 #endif
 #if PY_VERSION_HEX >= 0x02030000
-    0,                                  /* tp_del */
+				0,				/* tp_del */
 #endif
 #ifdef COUNT_ALLOCS
-    0,0,0,0                             /* tp_alloc -> tp_next */
+				0, 0, 0, 0		/* tp_alloc -> tp_next */
 #endif
-    };
+			};
 #if !defined(__cplusplus)
-    pyswigobject_type = tmp;
-    type_init = 1;
-  }
+			pyswigobject_type = tmp;
+			type_init = 1;
+		}
 #endif
-  return &pyswigobject_type;
-}
+		return &pyswigobject_type;
+	}
 
-SWIGRUNTIME PyObject *
-PySwigObject_FromVoidPtrAndDesc(void *ptr, const char *desc)
-{
-  PySwigObject *self = PyObject_NEW(PySwigObject, PySwigObject_type());
-  if (self) {
-    self->ptr = ptr;
-    self->desc = desc;
-  }
-  return (PyObject *)self;
-}
+	SWIGRUNTIME PyObject *PySwigObject_FromVoidPtrAndDesc(void *ptr, const char *desc) {
+		PySwigObject *self = PyObject_NEW(PySwigObject, PySwigObject_type());
+		if (self) {
+			self->ptr = ptr;
+			self->desc = desc;
+		}
+		return (PyObject *) self;
+	}
 
-SWIGRUNTIMEINLINE void *
-PySwigObject_AsVoidPtr(PyObject *self)
-{
-  return ((PySwigObject *)self)->ptr;
-}
+	SWIGRUNTIMEINLINE void *PySwigObject_AsVoidPtr(PyObject * self) {
+		return ((PySwigObject *) self)->ptr;
+	}
 
-SWIGRUNTIMEINLINE const char *
-PySwigObject_GetDesc(PyObject *self)
-{
-  return ((PySwigObject *)self)->desc;
-}
+	SWIGRUNTIMEINLINE const char *PySwigObject_GetDesc(PyObject * self) {
+		return ((PySwigObject *) self)->desc;
+	}
 
-SWIGRUNTIMEINLINE int
-PySwigObject_Check(PyObject *op) {
-  return ((op)->ob_type == PySwigObject_type()) 
-    || (strcmp((op)->ob_type->tp_name,"PySwigObject") == 0);
-}
+	SWIGRUNTIMEINLINE int
+	    PySwigObject_Check(PyObject * op) {
+		return ((op)->ob_type == PySwigObject_type())
+			|| (strcmp((op)->ob_type->tp_name, "PySwigObject") == 0);
+	}
 
 /* -----------------------------------------------------------------------------
  * Implements a simple Swig Packed type, and use it instead of string
  * ----------------------------------------------------------------------------- */
 
-typedef struct {
-  PyObject_HEAD
-  void *pack;
-  const char *desc;
-  size_t size;
-} PySwigPacked;
+	typedef struct {
+		PyObject_HEAD void *pack;
+		const char *desc;
+		size_t size;
+	} PySwigPacked;
+
+	SWIGRUNTIME int
+	    PySwigPacked_print(PySwigPacked * v, FILE * fp, int flags) {
+		char result[SWIG_BUFFER_SIZE];
+		flags = flags;
+		fputs("<Swig Packed ", fp);
+		if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+			fputs("at ", fp);
+			fputs(result, fp);
+		}
+		fputs(v->desc, fp);
+		fputs(">", fp);
+		return 0;
+	}
 
-SWIGRUNTIME int
-PySwigPacked_print(PySwigPacked *v, FILE *fp, int flags)
-{
-  char result[SWIG_BUFFER_SIZE];
-  flags = flags;
-  fputs("<Swig Packed ", fp); 
-  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
-    fputs("at ", fp); 
-    fputs(result, fp); 
-  }
-  fputs(v->desc,fp); 
-  fputs(">", fp);
-  return 0; 
-}
-  
-SWIGRUNTIME PyObject *
-PySwigPacked_repr(PySwigPacked *v)
-{
-  char result[SWIG_BUFFER_SIZE];
-  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
-    return PyString_FromFormat("<Swig Packed at %s%s>", result, v->desc);
-  } else {
-    return PyString_FromFormat("<Swig Packed %s>", v->desc);
-  }  
-}
+	SWIGRUNTIME PyObject *PySwigPacked_repr(PySwigPacked * v) {
+		char result[SWIG_BUFFER_SIZE];
+		if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+			return PyString_FromFormat("<Swig Packed at %s%s>", result, v->desc);
+		} else {
+			return PyString_FromFormat("<Swig Packed %s>", v->desc);
+		}
+	}
 
-SWIGRUNTIME PyObject *
-PySwigPacked_str(PySwigPacked *v)
-{
-  char result[SWIG_BUFFER_SIZE];
-  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){
-    return PyString_FromFormat("%s%s", result, v->desc);
-  } else {
-    return PyString_FromString(v->desc);
-  }  
-}
+	SWIGRUNTIME PyObject *PySwigPacked_str(PySwigPacked * v) {
+		char result[SWIG_BUFFER_SIZE];
+		if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+			return PyString_FromFormat("%s%s", result, v->desc);
+		} else {
+			return PyString_FromString(v->desc);
+		}
+	}
 
-SWIGRUNTIME int
-PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w)
-{
-  int c = strcmp(v->desc, w->desc);
-  if (c) {
-    return (c > 0) ? 1 : -1;
-  } else {
-    size_t i = v->size;
-    size_t j = w->size;
-    int s = (i < j) ? -1 : ((i > j) ? 1 : 0);
-    return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size);
-  }
-}
+	SWIGRUNTIME int
+	    PySwigPacked_compare(PySwigPacked * v, PySwigPacked * w) {
+		int c = strcmp(v->desc, w->desc);
+		if (c) {
+			return (c > 0) ? 1 : -1;
+		} else {
+			size_t i = v->size;
+			size_t j = w->size;
+			int s = (i < j) ? -1 : ((i > j) ? 1 : 0);
+			return s ? s : strncmp((char *) v->pack, (char *) w->pack, 2 * v->size);
+		}
+	}
 
-SWIGRUNTIME void
-PySwigPacked_dealloc(PySwigPacked *self)
-{
-  free(self->pack);
-  PyObject_Del(self);
-}
+	SWIGRUNTIME void
+	     PySwigPacked_dealloc(PySwigPacked * self) {
+		free(self->pack);
+		PyObject_Del(self);
+	}
 
-SWIGRUNTIME PyTypeObject*
-PySwigPacked_type(void) {
-  static char pyswigpacked_type__doc__[] = 
-    "Swig object carries a C/C++ instance pointer";
-  static PyTypeObject pyswigpacked_type
+	SWIGRUNTIME PyTypeObject *PySwigPacked_type(void) {
+		static char pyswigpacked_type__doc__[] = "Swig object carries a C/C++ instance pointer";
+		static PyTypeObject pyswigpacked_type
 #if !defined(__cplusplus)
-  ;
-  static int type_init = 0;  
-  if (!type_init) {
-    PyTypeObject tmp
-#endif
-    = {
-    PyObject_HEAD_INIT(&PyType_Type)
-    0,					/*ob_size*/
-    (char *)"PySwigPacked",		/*tp_name*/
-    sizeof(PySwigPacked),		/*tp_basicsize*/
-    0,					/*tp_itemsize*/
-    /* methods */
-    (destructor)PySwigPacked_dealloc,	/*tp_dealloc*/
-    (printfunc)PySwigPacked_print,	/*tp_print*/
-    (getattrfunc)0,			/*tp_getattr*/
-    (setattrfunc)0,			/*tp_setattr*/
-    (cmpfunc)PySwigPacked_compare,	/*tp_compare*/
-    (reprfunc)PySwigPacked_repr,	/*tp_repr*/
-    0,	                                /*tp_as_number*/
-    0,					/*tp_as_sequence*/
-    0,					/*tp_as_mapping*/
-    (hashfunc)0,			/*tp_hash*/
-    (ternaryfunc)0,			/*tp_call*/
-    (reprfunc)PySwigPacked_str,		/*tp_str*/
-    /* Space for future expansion */
-    0,0,0,0,
-    pyswigpacked_type__doc__, 	        /* Documentation string */
+		            ;
+		static int type_init = 0;
+		if (!type_init) {
+			PyTypeObject tmp
+#endif
+				= {
+				PyObject_HEAD_INIT(&PyType_Type)
+					0,			/*ob_size */
+				(char *) "PySwigPacked",	/*tp_name */
+				sizeof(PySwigPacked),	/*tp_basicsize */
+				0,				/*tp_itemsize */
+				/* methods */
+				(destructor) PySwigPacked_dealloc,	/*tp_dealloc */
+				(printfunc) PySwigPacked_print,	/*tp_print */
+				(getattrfunc) 0,	/*tp_getattr */
+				(setattrfunc) 0,	/*tp_setattr */
+				(cmpfunc) PySwigPacked_compare,	/*tp_compare */
+				(reprfunc) PySwigPacked_repr,	/*tp_repr */
+				0,				/*tp_as_number */
+				0,				/*tp_as_sequence */
+				0,				/*tp_as_mapping */
+				(hashfunc) 0,	/*tp_hash */
+				(ternaryfunc) 0,	/*tp_call */
+				(reprfunc) PySwigPacked_str,	/*tp_str */
+				/* Space for future expansion */
+				0, 0, 0, 0,
+				pyswigpacked_type__doc__,	/* Documentation string */
 #if PY_VERSION_HEX >= 0x02000000
-    0,                                  /* tp_traverse */
-    0,                                  /* tp_clear */
+				0,				/* tp_traverse */
+				0,				/* tp_clear */
 #endif
 #if PY_VERSION_HEX >= 0x02010000
-    0,                                  /* tp_richcompare */
-    0,                                  /* tp_weaklistoffset */
+				0,				/* tp_richcompare */
+				0,				/* tp_weaklistoffset */
 #endif
-#if PY_VERSION_HEX >= 0x02020000         
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */
+#if PY_VERSION_HEX >= 0x02020000
+				0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,	/* tp_iter -> tp_weaklist */
 #endif
 #if PY_VERSION_HEX >= 0x02030000
-    0,                                  /* tp_del */
+				0,				/* tp_del */
 #endif
 #ifdef COUNT_ALLOCS
-    0,0,0,0                             /* tp_alloc -> tp_next */
+				0, 0, 0, 0		/* tp_alloc -> tp_next */
 #endif
-    };
+			};
 #if !defined(__cplusplus)
-    pyswigpacked_type = tmp;
-    type_init = 1;
-  }
+			pyswigpacked_type = tmp;
+			type_init = 1;
+		}
 #endif
-  return &pyswigpacked_type;
-}
+		return &pyswigpacked_type;
+	}
 
-SWIGRUNTIME PyObject *
-PySwigPacked_FromDataAndDesc(void *ptr, size_t size, const char *desc)
-{
-  PySwigPacked *self = PyObject_NEW(PySwigPacked, PySwigPacked_type());
-  if (self == NULL) {
-    return NULL;
-  } else {
-    void *pack = malloc(size);
-    if (pack) {
-      memcpy(pack, ptr, size);
-      self->pack = pack;
-      self->desc = desc;
-      self->size = size;
-      return (PyObject *) self;
-    }
-    return NULL;
-  }
-}
+	SWIGRUNTIME PyObject *PySwigPacked_FromDataAndDesc(void *ptr, size_t size, const char *desc) {
+		PySwigPacked *self = PyObject_NEW(PySwigPacked, PySwigPacked_type());
+		if (self == NULL) {
+			return NULL;
+		} else {
+			void *pack = malloc(size);
+			if (pack) {
+				memcpy(pack, ptr, size);
+				self->pack = pack;
+				self->desc = desc;
+				self->size = size;
+				return (PyObject *) self;
+			}
+			return NULL;
+		}
+	}
 
-SWIGRUNTIMEINLINE const char *
-PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size)
-{
-  PySwigPacked *self = (PySwigPacked *)obj;
-  if (self->size != size) return 0;
-  memcpy(ptr, self->pack, size);
-  return self->desc;
-}
+	SWIGRUNTIMEINLINE const char *PySwigPacked_UnpackData(PyObject * obj, void *ptr, size_t size) {
+		PySwigPacked *self = (PySwigPacked *) obj;
+		if (self->size != size)
+			return 0;
+		memcpy(ptr, self->pack, size);
+		return self->desc;
+	}
 
-SWIGRUNTIMEINLINE const char *
-PySwigPacked_GetDesc(PyObject *self)
-{
-  return ((PySwigPacked *)self)->desc;
-}
+	SWIGRUNTIMEINLINE const char *PySwigPacked_GetDesc(PyObject * self) {
+		return ((PySwigPacked *) self)->desc;
+	}
 
-SWIGRUNTIMEINLINE int
-PySwigPacked_Check(PyObject *op) {
-  return ((op)->ob_type == PySwigPacked_type()) 
-    || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0);
-}
+	SWIGRUNTIMEINLINE int
+	    PySwigPacked_Check(PyObject * op) {
+		return ((op)->ob_type == PySwigPacked_type())
+			|| (strcmp((op)->ob_type->tp_name, "PySwigPacked") == 0);
+	}
 
 #else
 /* -----------------------------------------------------------------------------
  * Use the old Python PyCObject instead of PySwigObject
  * ----------------------------------------------------------------------------- */
-
 #define PySwigObject_GetDesc(obj)	           PyCObject_GetDesc(obj)
 #define PySwigObject_Check(obj)	           PyCObject_Check(obj)
 #define PySwigObject_AsVoidPtr(obj)	   PyCObject_AsVoidPtr(obj)
 #define PySwigObject_FromVoidPtrAndDesc(p, d)  PyCObject_FromVoidPtrAndDesc(p, d, NULL)
-
 #endif
-
 #endif
-
 /* -----------------------------------------------------------------------------
  * errors manipulation
- * ----------------------------------------------------------------------------- */
-
-SWIGRUNTIME void
-SWIG_Python_TypeError(const char *type, PyObject *obj)
-{
-  if (type) {
+ * ----------------------------------------------------------------------------- */ SWIGRUNTIME void
+	     SWIG_Python_TypeError(const char *type, PyObject * obj) {
+		if (type) {
 #if defined(SWIG_COBJECT_TYPES)
-    if (obj && PySwigObject_Check(obj)) {
-      const char *otype = (const char *) PySwigObject_GetDesc(obj);
-      if (otype) {
-	PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PySwigObject(%s)' is received",
-		     type, otype);
-	return;
-      }
-    } else 
-#endif      
-    {
-      const char *otype = (obj ? obj->ob_type->tp_name : 0); 
-      if (otype) {
-	PyObject *str = PyObject_Str(obj);
-	const char *cstr = str ? PyString_AsString(str) : 0;
-	if (cstr) {
-	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received",
-		       type, otype, cstr);
-	} else {
-	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received",
-		       type, otype);
+			if (obj && PySwigObject_Check(obj)) {
+				const char *otype = (const char *) PySwigObject_GetDesc(obj);
+				if (otype) {
+					PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PySwigObject(%s)' is received", type, otype);
+					return;
+				}
+			} else
+#endif
+			{
+				const char *otype = (obj ? obj->ob_type->tp_name : 0);
+				if (otype) {
+					PyObject *str = PyObject_Str(obj);
+					const char *cstr = str ? PyString_AsString(str) : 0;
+					if (cstr) {
+						PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", type, otype, cstr);
+					} else {
+						PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", type, otype);
+					}
+					Py_XDECREF(str);
+					return;
+				}
+			}
+			PyErr_Format(PyExc_TypeError, "a '%s' is expected", type);
+		} else {
+			PyErr_Format(PyExc_TypeError, "unexpected type is received");
+		}
 	}
-	Py_XDECREF(str);
-	return;
-      }
-    }   
-    PyErr_Format(PyExc_TypeError, "a '%s' is expected", type);
-  } else {
-    PyErr_Format(PyExc_TypeError, "unexpected type is received");
-  }
-}
 
-SWIGRUNTIMEINLINE void
-SWIG_Python_NullRef(const char *type)
-{
-  if (type) {
-    PyErr_Format(PyExc_TypeError, "null reference of type '%s' was received",type);
-  } else {
-    PyErr_Format(PyExc_TypeError, "null reference was received");
-  }
-}
+	SWIGRUNTIMEINLINE void
+	     SWIG_Python_NullRef(const char *type) {
+		if (type) {
+			PyErr_Format(PyExc_TypeError, "null reference of type '%s' was received", type);
+		} else {
+			PyErr_Format(PyExc_TypeError, "null reference was received");
+		}
+	}
 
-SWIGRUNTIME int
-SWIG_Python_AddErrMesg(const char* mesg, int infront)
-{
-  if (PyErr_Occurred()) {
-    PyObject *type = 0;
-    PyObject *value = 0;
-    PyObject *traceback = 0;
-    PyErr_Fetch(&type, &value, &traceback);
-    if (value) {
-      PyObject *old_str = PyObject_Str(value);
-      Py_XINCREF(type);
-      PyErr_Clear();
-      if (infront) {
-	PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str));
-      } else {
-	PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
-      }
-      Py_DECREF(old_str);
-    }
-    return 1;
-  } else {
-    return 0;
-  }
-}
+	SWIGRUNTIME int
+	    SWIG_Python_AddErrMesg(const char *mesg, int infront) {
+		if (PyErr_Occurred()) {
+			PyObject *type = 0;
+			PyObject *value = 0;
+			PyObject *traceback = 0;
+			PyErr_Fetch(&type, &value, &traceback);
+			if (value) {
+				PyObject *old_str = PyObject_Str(value);
+				Py_XINCREF(type);
+				PyErr_Clear();
+				if (infront) {
+					PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str));
+				} else {
+					PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
+				}
+				Py_DECREF(old_str);
+			}
+			return 1;
+		} else {
+			return 0;
+		}
+	}
 
-SWIGRUNTIME int
-SWIG_Python_ArgFail(int argnum)
-{
-  if (PyErr_Occurred()) {
-    /* add information about failing argument */
-    char mesg[256];
-    PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum);
-    return SWIG_Python_AddErrMesg(mesg, 1);
-  } else {
-    return 0;
-  }
-}
+	SWIGRUNTIME int
+	    SWIG_Python_ArgFail(int argnum) {
+		if (PyErr_Occurred()) {
+			/* add information about failing argument */
+			char mesg[256];
+			PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum);
+			return SWIG_Python_AddErrMesg(mesg, 1);
+		} else {
+			return 0;
+		}
+	}
 
 
 /* -----------------------------------------------------------------------------
@@ -1140,272 +1062,274 @@
  * ----------------------------------------------------------------------------- */
 
 /* Convert a pointer value */
-SWIGRUNTIME int
-SWIG_Python_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) {
-  swig_cast_info *tc;
-  const char *c = 0;
-  static PyObject *SWIG_this = 0;
-  int    newref = 0;
-  PyObject  *pyobj = 0;
-  void *vptr;
-  
-  if (!obj) return 0;
-  if (obj == Py_None) {
-    *ptr = 0;
-    return 0;
-  }
-
+	SWIGRUNTIME int
+	    SWIG_Python_ConvertPtr(PyObject * obj, void **ptr, swig_type_info * ty, int flags) {
+		swig_cast_info *tc;
+		const char *c = 0;
+		static PyObject *SWIG_this = 0;
+		int newref = 0;
+		PyObject *pyobj = 0;
+		void *vptr;
+
+		if (!obj)
+			return 0;
+		if (obj == Py_None) {
+			*ptr = 0;
+			return 0;
+		}
 #ifdef SWIG_COBJECT_TYPES
-  if (!(PySwigObject_Check(obj))) {
-    if (!SWIG_this)
-      SWIG_this = PyString_FromString("this");
-    pyobj = obj;
-    obj = PyObject_GetAttr(obj,SWIG_this);
-    newref = 1;
-    if (!obj) goto type_error;
-    if (!PySwigObject_Check(obj)) {
-      Py_DECREF(obj);
-      goto type_error;
-    }
-  }  
-  vptr = PySwigObject_AsVoidPtr(obj);
-  c = (const char *) PySwigObject_GetDesc(obj);
-  if (newref) { Py_DECREF(obj); }
-  goto type_check;
+		if (!(PySwigObject_Check(obj))) {
+			if (!SWIG_this)
+				SWIG_this = PyString_FromString("this");
+			pyobj = obj;
+			obj = PyObject_GetAttr(obj, SWIG_this);
+			newref = 1;
+			if (!obj)
+				goto type_error;
+			if (!PySwigObject_Check(obj)) {
+				Py_DECREF(obj);
+				goto type_error;
+			}
+		}
+		vptr = PySwigObject_AsVoidPtr(obj);
+		c = (const char *) PySwigObject_GetDesc(obj);
+		if (newref) {
+			Py_DECREF(obj);
+		}
+		goto type_check;
 #else
-  if (!(PyString_Check(obj))) {
-    if (!SWIG_this)
-      SWIG_this = PyString_FromString("this");
-    pyobj = obj;
-    obj = PyObject_GetAttr(obj,SWIG_this);
-    newref = 1;
-    if (!obj) goto type_error;
-    if (!PyString_Check(obj)) {
-      Py_DECREF(obj);
-      goto type_error;
-    }
-  } 
-  c = PyString_AsString(obj);
-  /* Pointer values must start with leading underscore */
-  c = SWIG_UnpackVoidPtr(c, &vptr, ty->name);
-  if (newref) { Py_DECREF(obj); }
-  if (!c) goto type_error;
-#endif
-
-type_check:
-  if (ty) {
-    tc = SWIG_TypeCheck(c,ty);
-    if (!tc) goto type_error;
-    *ptr = SWIG_TypeCast(tc,vptr);
-  } else {
-    *ptr = vptr;
-  }
-  if ((pyobj) && (flags & SWIG_POINTER_DISOWN)) {
-    PyObject_SetAttrString(pyobj,(char*)"thisown",Py_False);
-  }
-  return 0;
-
-type_error:
-  PyErr_Clear();
-  if (pyobj && !obj) {    
-    obj = pyobj;
-    if (PyCFunction_Check(obj)) {
-      /* here we get the method pointer for callbacks */
-      char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
-      c = doc ? strstr(doc, "swig_ptr: ") : 0;
-      if (c) {
-	c = ty ? SWIG_UnpackVoidPtr(c + 10, &vptr, ty->name) : 0;
-	if (!c) goto type_error;
-	goto type_check;
-      }
-    }
-  }
-  if (flags & SWIG_POINTER_EXCEPTION) {
-    if (ty) {
-      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
-    } else {
-      SWIG_Python_TypeError("C/C++ pointer", obj);
-    }
-  }
-  return -1;
-}
+		if (!(PyString_Check(obj))) {
+			if (!SWIG_this)
+				SWIG_this = PyString_FromString("this");
+			pyobj = obj;
+			obj = PyObject_GetAttr(obj, SWIG_this);
+			newref = 1;
+			if (!obj)
+				goto type_error;
+			if (!PyString_Check(obj)) {
+				Py_DECREF(obj);
+				goto type_error;
+			}
+		}
+		c = PyString_AsString(obj);
+		/* Pointer values must start with leading underscore */
+		c = SWIG_UnpackVoidPtr(c, &vptr, ty->name);
+		if (newref) {
+			Py_DECREF(obj);
+		}
+		if (!c)
+			goto type_error;
+#endif
+
+	  type_check:
+		if (ty) {
+			tc = SWIG_TypeCheck(c, ty);
+			if (!tc)
+				goto type_error;
+			*ptr = SWIG_TypeCast(tc, vptr);
+		} else {
+			*ptr = vptr;
+		}
+		if ((pyobj) && (flags & SWIG_POINTER_DISOWN)) {
+			PyObject_SetAttrString(pyobj, (char *) "thisown", Py_False);
+		}
+		return 0;
+
+	  type_error:
+		PyErr_Clear();
+		if (pyobj && !obj) {
+			obj = pyobj;
+			if (PyCFunction_Check(obj)) {
+				/* here we get the method pointer for callbacks */
+				char *doc = (((PyCFunctionObject *) obj)->m_ml->ml_doc);
+				c = doc ? strstr(doc, "swig_ptr: ") : 0;
+				if (c) {
+					c = ty ? SWIG_UnpackVoidPtr(c + 10, &vptr, ty->name) : 0;
+					if (!c)
+						goto type_error;
+					goto type_check;
+				}
+			}
+		}
+		if (flags & SWIG_POINTER_EXCEPTION) {
+			if (ty) {
+				SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
+			} else {
+				SWIG_Python_TypeError("C/C++ pointer", obj);
+			}
+		}
+		return -1;
+	}
 
 /* Convert a pointer value, signal an exception on a type mismatch */
-SWIGRUNTIME void *
-SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) {
-  void *result;
-  if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {
-    PyErr_Clear();
-    if (flags & SWIG_POINTER_EXCEPTION) {
-      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
-      SWIG_Python_ArgFail(argnum);
-    }
-  }
-  return result;
-}
+	SWIGRUNTIME void *SWIG_Python_MustGetPtr(PyObject * obj, swig_type_info * ty, int argnum, int flags) {
+		void *result;
+		if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {
+			PyErr_Clear();
+			if (flags & SWIG_POINTER_EXCEPTION) {
+				SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
+				SWIG_Python_ArgFail(argnum);
+			}
+		}
+		return result;
+	}
 
 /* Convert a packed value value */
-SWIGRUNTIME int
-SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty, int flags) {
-  swig_cast_info *tc;
-  const char *c = 0;
+	SWIGRUNTIME int
+	    SWIG_Python_ConvertPacked(PyObject * obj, void *ptr, size_t sz, swig_type_info * ty, int flags) {
+		swig_cast_info *tc;
+		const char *c = 0;
 
 #if defined(SWIG_COBJECT_TYPES) && !defined(SWIG_COBJECT_PYTHON)
-  c = PySwigPacked_UnpackData(obj, ptr, sz);
+		c = PySwigPacked_UnpackData(obj, ptr, sz);
 #else
-  if ((!obj) || (!PyString_Check(obj))) goto type_error;
-  c = PyString_AsString(obj);
-  /* Pointer values must start with leading underscore */
-  c = SWIG_UnpackDataName(c, ptr, sz, ty->name);
-#endif
-  if (!c) goto type_error;
-  if (ty) {
-    tc = SWIG_TypeCheck(c,ty);
-    if (!tc) goto type_error;
-  }
-  return 0;
-
-type_error:
-  PyErr_Clear();
-  if (flags & SWIG_POINTER_EXCEPTION) {
-    if (ty) {
-      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
-    } else {
-      SWIG_Python_TypeError("C/C++ packed data", obj);
-    }
-  }
-  return -1;
-}  
+		if ((!obj) || (!PyString_Check(obj)))
+			goto type_error;
+		c = PyString_AsString(obj);
+		/* Pointer values must start with leading underscore */
+		c = SWIG_UnpackDataName(c, ptr, sz, ty->name);
+#endif
+		if (!c)
+			goto type_error;
+		if (ty) {
+			tc = SWIG_TypeCheck(c, ty);
+			if (!tc)
+				goto type_error;
+		}
+		return 0;
+
+	  type_error:
+		PyErr_Clear();
+		if (flags & SWIG_POINTER_EXCEPTION) {
+			if (ty) {
+				SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
+			} else {
+				SWIG_Python_TypeError("C/C++ packed data", obj);
+			}
+		}
+		return -1;
+	}
 
 /* Create a new array object */
-SWIGRUNTIME PyObject *
-SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int own) {
-  PyObject *robj = 0;
-  if (!type) {
-    if (!PyErr_Occurred()) {
-      PyErr_Format(PyExc_TypeError, "Swig: null type passed to NewPointerObj");
-    }
-    return robj;
-  }
-  if (!ptr) {
-    Py_INCREF(Py_None);
-    return Py_None;
-  }
+	SWIGRUNTIME PyObject *SWIG_Python_NewPointerObj(void *ptr, swig_type_info * type, int own) {
+		PyObject *robj = 0;
+		if (!type) {
+			if (!PyErr_Occurred()) {
+				PyErr_Format(PyExc_TypeError, "Swig: null type passed to NewPointerObj");
+			}
+			return robj;
+		}
+		if (!ptr) {
+			Py_INCREF(Py_None);
+			return Py_None;
+		}
 #ifdef SWIG_COBJECT_TYPES
-  robj = PySwigObject_FromVoidPtrAndDesc((void *) ptr, (char *)type->name);
+		robj = PySwigObject_FromVoidPtrAndDesc((void *) ptr, (char *) type->name);
 #else
-  {
-    char result[SWIG_BUFFER_SIZE];
-    robj = SWIG_PackVoidPtr(result, ptr, type->name, sizeof(result)) ?
-      PyString_FromString(result) : 0;
-  }
-#endif
-  if (!robj || (robj == Py_None)) return robj;
-  if (type->clientdata) {
-    PyObject *inst;
-    PyObject *args = Py_BuildValue((char*)"(O)", robj);
-    Py_DECREF(robj);
-    inst = PyObject_CallObject((PyObject *) type->clientdata, args);
-    Py_DECREF(args);
-    if (inst) {
-      if (own) {
-        PyObject_SetAttrString(inst,(char*)"thisown",Py_True);
-      }
-      robj = inst;
-    }
-  }
-  return robj;
-}
+		{
+			char result[SWIG_BUFFER_SIZE];
+			robj = SWIG_PackVoidPtr(result, ptr, type->name, sizeof(result)) ? PyString_FromString(result) : 0;
+		}
+#endif
+		if (!robj || (robj == Py_None))
+			return robj;
+		if (type->clientdata) {
+			PyObject *inst;
+			PyObject *args = Py_BuildValue((char *) "(O)", robj);
+			Py_DECREF(robj);
+			inst = PyObject_CallObject((PyObject *) type->clientdata, args);
+			Py_DECREF(args);
+			if (inst) {
+				if (own) {
+					PyObject_SetAttrString(inst, (char *) "thisown", Py_True);
+				}
+				robj = inst;
+			}
+		}
+		return robj;
+	}
 
-SWIGRUNTIME PyObject *
-SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
-  PyObject *robj = 0;
-  if (!ptr) {
-    Py_INCREF(Py_None);
-    return Py_None;
-  }
+	SWIGRUNTIME PyObject *SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info * type) {
+		PyObject *robj = 0;
+		if (!ptr) {
+			Py_INCREF(Py_None);
+			return Py_None;
+		}
 #if defined(SWIG_COBJECT_TYPES) && !defined(SWIG_COBJECT_PYTHON)
-  robj = PySwigPacked_FromDataAndDesc((void *) ptr, sz, (char *)type->name);
+		robj = PySwigPacked_FromDataAndDesc((void *) ptr, sz, (char *) type->name);
 #else
-  {
-    char result[SWIG_BUFFER_SIZE];
-    robj = SWIG_PackDataName(result, ptr, sz, type->name, sizeof(result)) ?
-      PyString_FromString(result) : 0;
-  }
+		{
+			char result[SWIG_BUFFER_SIZE];
+			robj = SWIG_PackDataName(result, ptr, sz, type->name, sizeof(result)) ? PyString_FromString(result) : 0;
+		}
 #endif
-  return robj;
-}
+		return robj;
+	}
 
 /* -----------------------------------------------------------------------------*
  *  Get type list 
  * -----------------------------------------------------------------------------*/
 
 #ifdef SWIG_LINK_RUNTIME
-void *SWIG_ReturnGlobalTypeList(void *);
+	void *SWIG_ReturnGlobalTypeList(void *);
 #endif
 
-SWIGRUNTIME swig_module_info *
-SWIG_Python_GetModule(void) {
-  static void *type_pointer = (void *)0;
-  /* first check if module already created */
-  if (!type_pointer) {
+	SWIGRUNTIME swig_module_info *SWIG_Python_GetModule(void) {
+		static void *type_pointer = (void *) 0;
+		/* first check if module already created */
+		if (!type_pointer) {
 #ifdef SWIG_LINK_RUNTIME
-    type_pointer = SWIG_ReturnGlobalTypeList((void *)0);
+			type_pointer = SWIG_ReturnGlobalTypeList((void *) 0);
 #else
-    type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION,
-				    (char*)"type_pointer" SWIG_TYPE_TABLE_NAME);
-    if (PyErr_Occurred()) {
-      PyErr_Clear();
-      type_pointer = (void *)0;
-    }
+			type_pointer = PyCObject_Import((char *) "swig_runtime_data" SWIG_RUNTIME_VERSION, (char *) "type_pointer" SWIG_TYPE_TABLE_NAME);
+			if (PyErr_Occurred()) {
+				PyErr_Clear();
+				type_pointer = (void *) 0;
+			}
 #endif
-  }
-  return (swig_module_info *) type_pointer;
-}
+		}
+		return (swig_module_info *) type_pointer;
+	}
 
 #if PY_MAJOR_VERSION < 2
 /* PyModule_AddObject function was introduced in Python 2.0.  The following function
 is copied out of Python/modsupport.c in python version 2.3.4 */
-SWIGINTERN int
-PyModule_AddObject(PyObject *m, char *name, PyObject *o)
-{
-  PyObject *dict;
-  if (!PyModule_Check(m)) {
-    PyErr_SetString(PyExc_TypeError,
-		    "PyModule_AddObject() needs module as first arg");
-    return -1;
-  }
-  if (!o) {
-    PyErr_SetString(PyExc_TypeError,
-		    "PyModule_AddObject() needs non-NULL value");
-    return -1;
-  }
-  
-  dict = PyModule_GetDict(m);
-  if (dict == NULL) {
-    /* Internal error -- modules must have a dict! */
-    PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
-		 PyModule_GetName(m));
-    return -1;
-  }
-  if (PyDict_SetItemString(dict, name, o))
-    return -1;
-  Py_DECREF(o);
-  return 0;
-}
+	SWIGINTERN int
+	    PyModule_AddObject(PyObject * m, char *name, PyObject * o) {
+		PyObject *dict;
+		if (!PyModule_Check(m)) {
+			PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg");
+			return -1;
+		}
+		if (!o) {
+			PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value");
+			return -1;
+		}
+
+		dict = PyModule_GetDict(m);
+		if (dict == NULL) {
+			/* Internal error -- modules must have a dict! */
+			PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", PyModule_GetName(m));
+			return -1;
+		}
+		if (PyDict_SetItemString(dict, name, o))
+			return -1;
+		Py_DECREF(o);
+		return 0;
+	}
 #endif
 
-SWIGRUNTIME void
-SWIG_Python_SetModule(swig_module_info *swig_module) {
-  static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */
-
-  PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION,
-				   swig_empty_runtime_method_table);
-  PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, NULL);
-  if (pointer && module) {
-    PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer);
-  }
-}
+	SWIGRUNTIME void
+	     SWIG_Python_SetModule(swig_module_info * swig_module) {
+		static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };	/* Sentinel */
+
+		PyObject *module = Py_InitModule((char *) "swig_runtime_data" SWIG_RUNTIME_VERSION,
+										 swig_empty_runtime_method_table);
+		PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, NULL);
+		if (pointer && module) {
+			PyModule_AddObject(module, (char *) "type_pointer" SWIG_TYPE_TABLE_NAME, pointer);
+		}
+	}
 
 #ifdef __cplusplus
 }
@@ -1424,7 +1348,8 @@
 #define SWIGTYPE_ptrdiff_t swig_types[7]
 #define SWIGTYPE_size_t swig_types[8]
 static swig_type_info *swig_types[10];
-static swig_module_info swig_module = {swig_types, 9, 0, 0, 0, 0};
+static swig_module_info swig_module = { swig_types, 9, 0, 0, 0, 0 };
+
 #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
 #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
 
@@ -1439,50 +1364,51 @@
 #define SWIG_name    "_freeswitch"
 
 /* returns SWIG_OLDOBJ if the input is a raw char*, SWIG_PYSTR if is a PyString */
-SWIGINTERN int
-SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize)
+SWIGINTERN int SWIG_AsCharPtrAndSize(PyObject * obj, char **cptr, size_t *psize)
 {
-  static swig_type_info* pchar_info = 0;
-  char* vptr = 0;
-  if (!pchar_info) pchar_info = SWIG_TypeQuery("char *");
-  if (SWIG_ConvertPtr(obj, (void**)&vptr, pchar_info, 0) != -1) {
-    if (cptr) *cptr = vptr;
-    if (psize) *psize = vptr ? (strlen(vptr) + 1) : 0;
-    return SWIG_OLDOBJ;
-  } else {
-    PyErr_Clear();
-    if (PyString_Check(obj)) {
-      if (cptr) {
-	*cptr = PyString_AS_STRING(obj);
-	if (psize) {
-	  *psize = PyString_GET_SIZE(obj) + 1;
-	}
-      }
-      return SWIG_PYSTR;
-    }
-  }
-  if (cptr) {
-    SWIG_type_error("char *", obj);
-  }
-  return 0;
+	static swig_type_info *pchar_info = 0;
+	char *vptr = 0;
+	if (!pchar_info)
+		pchar_info = SWIG_TypeQuery("char *");
+	if (SWIG_ConvertPtr(obj, (void **) &vptr, pchar_info, 0) != -1) {
+		if (cptr)
+			*cptr = vptr;
+		if (psize)
+			*psize = vptr ? (strlen(vptr) + 1) : 0;
+		return SWIG_OLDOBJ;
+	} else {
+		PyErr_Clear();
+		if (PyString_Check(obj)) {
+			if (cptr) {
+				*cptr = PyString_AS_STRING(obj);
+				if (psize) {
+					*psize = PyString_GET_SIZE(obj) + 1;
+				}
+			}
+			return SWIG_PYSTR;
+		}
+	}
+	if (cptr) {
+		SWIG_type_error("char *", obj);
+	}
+	return 0;
 }
 
 
-SWIGINTERNINLINE int
-SWIG_AsCharPtr(PyObject *obj, char **val)
+SWIGINTERNINLINE int SWIG_AsCharPtr(PyObject * obj, char **val)
 {
-  if (SWIG_AsCharPtrAndSize(obj, val, (size_t*)(0))) {
-    return 1;
-  }
-  if (val) {
-    PyErr_Clear();
-    SWIG_type_error("char *", obj);
-  }
-  return 0;
+	if (SWIG_AsCharPtrAndSize(obj, val, (size_t *) (0))) {
+		return 1;
+	}
+	if (val) {
+		PyErr_Clear();
+		SWIG_type_error("char *", obj);
+	}
+	return 0;
 }
 
 
-  /*@/usr/share/swig1.3/python/pymacros.swg,72,SWIG_define@*/
+  /*@/usr/share/swig1.3/python/pymacros.swg,72,SWIG_define@ */
 #define SWIG_From_int PyInt_FromLong
 /*@@*/
 
@@ -1490,117 +1416,109 @@
 #include <limits.h>
 
 
-SWIGINTERNINLINE int
-  SWIG_CheckUnsignedLongInRange(unsigned long value,
-				unsigned long max_value,
-				const char *errmsg) 
+SWIGINTERNINLINE int SWIG_CheckUnsignedLongInRange(unsigned long value, unsigned long max_value, const char *errmsg)
 {
-  if (value > max_value) {
-    if (errmsg) {
-      PyErr_Format(PyExc_OverflowError,
-		   "value %lu is greater than '%s' minimum %lu",
-		   value, errmsg, max_value);
-    }
-    return 0;
-  }
-  return 1;
- }
+	if (value > max_value) {
+		if (errmsg) {
+			PyErr_Format(PyExc_OverflowError, "value %lu is greater than '%s' minimum %lu", value, errmsg, max_value);
+		}
+		return 0;
+	}
+	return 1;
+}
 
 
-SWIGINTERN int
-  SWIG_AsVal_unsigned_SS_long(PyObject *obj, unsigned long *val) 
+SWIGINTERN int SWIG_AsVal_unsigned_SS_long(PyObject * obj, unsigned long *val)
 {
-  if (PyLong_Check(obj)) {
-    unsigned long v = PyLong_AsUnsignedLong(obj);
-    if (!PyErr_Occurred()) {
-      if (val) *val = v;
-      return 1;
-    } else {
-      if (!val) PyErr_Clear();
-      return 0;
-    }
-  } 
-  if (PyInt_Check(obj)) {
-    long v = PyInt_AsLong(obj);
-    if (v >= 0) {
-      if (val) *val = v;
-      return 1;
-    }   
-  }
-  if (val) {
-    SWIG_type_error("unsigned long", obj);
-  }
-  return 0;
+	if (PyLong_Check(obj)) {
+		unsigned long v = PyLong_AsUnsignedLong(obj);
+		if (!PyErr_Occurred()) {
+			if (val)
+				*val = v;
+			return 1;
+		} else {
+			if (!val)
+				PyErr_Clear();
+			return 0;
+		}
+	}
+	if (PyInt_Check(obj)) {
+		long v = PyInt_AsLong(obj);
+		if (v >= 0) {
+			if (val)
+				*val = v;
+			return 1;
+		}
+	}
+	if (val) {
+		SWIG_type_error("unsigned long", obj);
+	}
+	return 0;
 }
 
 
 #if UINT_MAX != ULONG_MAX
-SWIGINTERN int
-  SWIG_AsVal_unsigned_SS_int(PyObject *obj, unsigned int *val)
-{ 
-  const char* errmsg = val ? "unsigned int" : (char*)0;
-  unsigned long v;
-  if (SWIG_AsVal_unsigned_SS_long(obj, &v)) {
-    if (SWIG_CheckUnsignedLongInRange(v, INT_MAX, errmsg)) {
-      if (val) *val = (unsigned int)(v);
-      return 1;
-    }
-  } else {
-    PyErr_Clear();
-  }
-  if (val) {
-    SWIG_type_error(errmsg, obj);
-  }
-  return 0;    
+SWIGINTERN int SWIG_AsVal_unsigned_SS_int(PyObject * obj, unsigned int *val)
+{
+	const char *errmsg = val ? "unsigned int" : (char *) 0;
+	unsigned long v;
+	if (SWIG_AsVal_unsigned_SS_long(obj, &v)) {
+		if (SWIG_CheckUnsignedLongInRange(v, INT_MAX, errmsg)) {
+			if (val)
+				*val = (unsigned int) (v);
+			return 1;
+		}
+	} else {
+		PyErr_Clear();
+	}
+	if (val) {
+		SWIG_type_error(errmsg, obj);
+	}
+	return 0;
 }
 #else
-SWIGINTERNINLINE unsigned int
-  SWIG_AsVal_unsigned_SS_int(PyObject *obj, unsigned int *val)
+SWIGINTERNINLINE unsigned int SWIG_AsVal_unsigned_SS_int(PyObject * obj, unsigned int *val)
 {
-  return SWIG_AsVal_unsigned_SS_long(obj,(unsigned long *)val);
+	return SWIG_AsVal_unsigned_SS_long(obj, (unsigned long *) val);
 }
 #endif
 
 
-SWIGINTERNINLINE unsigned int
-SWIG_As_unsigned_SS_int(PyObject* obj)
+SWIGINTERNINLINE unsigned int SWIG_As_unsigned_SS_int(PyObject * obj)
 {
-  unsigned int v;
-  if (!SWIG_AsVal_unsigned_SS_int(obj, &v)) {
-    /*
-      this is needed to make valgrind/purify happier. 
-     */
-    memset((void*)&v, 0, sizeof(unsigned int));
-  }
-  return v;
+	unsigned int v;
+	if (!SWIG_AsVal_unsigned_SS_int(obj, &v)) {
+		/*
+		   this is needed to make valgrind/purify happier. 
+		 */
+		memset((void *) &v, 0, sizeof(unsigned int));
+	}
+	return v;
 }
 
-  
-SWIGINTERNINLINE int
-SWIG_Check_unsigned_SS_int(PyObject* obj)
+
+SWIGINTERNINLINE int SWIG_Check_unsigned_SS_int(PyObject * obj)
 {
-  return SWIG_AsVal_unsigned_SS_int(obj, (unsigned int*)0);
+	return SWIG_AsVal_unsigned_SS_int(obj, (unsigned int *) 0);
 }
 
 
-SWIGINTERN PyObject *
-SWIG_FromCharPtr(const char* cptr)
-{ 
-  if (cptr) {
-    size_t size = strlen(cptr);
-    if (size > INT_MAX) {
-      return SWIG_NewPointerObj((char*)(cptr), 
-				SWIG_TypeQuery("char *"), 0);
-    } else {
-      if (size != 0) {
-	return PyString_FromStringAndSize(cptr, size);
-      } else {
-	return PyString_FromString(cptr);
-      }
-    }
-  }
-  Py_INCREF(Py_None);
-  return Py_None;
+SWIGINTERN PyObject *SWIG_FromCharPtr(const char *cptr)
+{
+	if (cptr) {
+		size_t size = strlen(cptr);
+		if (size > INT_MAX) {
+			return SWIG_NewPointerObj((char *) (cptr), SWIG_TypeQuery("char *"), 0);
+		} else {
+			if (size != 0) {
+				return PyString_FromStringAndSize(cptr, size);
+			} else {
+				return PyString_FromString(cptr);
+			}
+		}
+	}
+	Py_INCREF(Py_None);
+	return Py_None;
 }
 
 
@@ -1609,867 +1527,978 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
-static PyObject *_wrap_fs_core_set_globals(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    
-    if(!PyArg_ParseTuple(args,(char *)":fs_core_set_globals")) goto fail;
-    fs_core_set_globals();
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_core_set_globals(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
 
-
-static PyObject *_wrap_fs_core_init(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    char *arg1 = (char *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:fs_core_init",&obj0)) goto fail;
-    if (!SWIG_AsCharPtr(obj0, (char**)&arg1)) {
-        SWIG_arg_fail(1);SWIG_fail;
-    }
-    result = (int)fs_core_init(arg1);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+		if       (!PyArg_ParseTuple(args, (char *) ":fs_core_set_globals"))
+			         goto fail;
+		         fs_core_set_globals();
+
+		         Py_INCREF(Py_None);
+		         resultobj = Py_None;
+		         return resultobj;
+		         fail:return NULL;
+	}
+	static PyObject *_wrap_fs_core_init(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		char *arg1 = (char *) 0;
+		int result;
+		PyObject *obj0 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "O:fs_core_init", &obj0))
+			goto fail;
+		if (!SWIG_AsCharPtr(obj0, (char **) &arg1)) {
+			SWIG_arg_fail(1);
+			SWIG_fail;
+		}
+		result = (int) fs_core_init(arg1);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_core_destroy(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    int result;
-    
-    if(!PyArg_ParseTuple(args,(char *)":fs_core_destroy")) goto fail;
-    result = (int)fs_core_destroy();
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_core_destroy(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		int result;
+
+		if (!PyArg_ParseTuple(args, (char *) ":fs_core_destroy"))
+			goto fail;
+		result = (int) fs_core_destroy();
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_loadable_module_init(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    int result;
-    
-    if(!PyArg_ParseTuple(args,(char *)":fs_loadable_module_init")) goto fail;
-    result = (int)fs_loadable_module_init();
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_loadable_module_init(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		int result;
+
+		if (!PyArg_ParseTuple(args, (char *) ":fs_loadable_module_init"))
+			goto fail;
+		result = (int) fs_loadable_module_init();
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_loadable_module_shutdown(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    int result;
-    
-    if(!PyArg_ParseTuple(args,(char *)":fs_loadable_module_shutdown")) goto fail;
-    result = (int)fs_loadable_module_shutdown();
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_loadable_module_shutdown(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		int result;
+
+		if (!PyArg_ParseTuple(args, (char *) ":fs_loadable_module_shutdown"))
+			goto fail;
+		result = (int) fs_loadable_module_shutdown();
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_console_loop(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    int result;
-    
-    if(!PyArg_ParseTuple(args,(char *)":fs_console_loop")) goto fail;
-    result = (int)fs_console_loop();
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_console_loop(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		int result;
+
+		if (!PyArg_ParseTuple(args, (char *) ":fs_console_loop"))
+			goto fail;
+		result = (int) fs_console_loop();
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_console_log(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    char *arg1 = (char *) 0 ;
-    char *arg2 = (char *) 0 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:fs_console_log",&obj0,&obj1)) goto fail;
-    if (!SWIG_AsCharPtr(obj0, (char**)&arg1)) {
-        SWIG_arg_fail(1);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    fs_console_log(arg1,arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_console_log(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		char *arg1 = (char *) 0;
+		char *arg2 = (char *) 0;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OO:fs_console_log", &obj0, &obj1))
+			goto fail;
+		if (!SWIG_AsCharPtr(obj0, (char **) &arg1)) {
+			SWIG_arg_fail(1);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		fs_console_log(arg1, arg2);
+
+		Py_INCREF(Py_None);
+		resultobj = Py_None;
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_console_clean(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    char *arg1 = (char *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:fs_console_clean",&obj0)) goto fail;
-    if (!SWIG_AsCharPtr(obj0, (char**)&arg1)) {
-        SWIG_arg_fail(1);SWIG_fail;
-    }
-    fs_console_clean(arg1);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_console_clean(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		char *arg1 = (char *) 0;
+		PyObject *obj0 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "O:fs_console_clean", &obj0))
+			goto fail;
+		if (!SWIG_AsCharPtr(obj0, (char **) &arg1)) {
+			SWIG_arg_fail(1);
+			SWIG_fail;
+		}
+		fs_console_clean(arg1);
+
+		Py_INCREF(Py_None);
+		resultobj = Py_None;
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_core_session_locate(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    char *arg1 = (char *) 0 ;
-    switch_core_session_t *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:fs_core_session_locate",&obj0)) goto fail;
-    if (!SWIG_AsCharPtr(obj0, (char**)&arg1)) {
-        SWIG_arg_fail(1);SWIG_fail;
-    }
-    result = (switch_core_session_t *)fs_core_session_locate(arg1);
-    
-    resultobj = SWIG_NewPointerObj((void*)(result), SWIGTYPE_p_switch_core_session_t, 0);
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_core_session_locate(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		char *arg1 = (char *) 0;
+		switch_core_session_t *result;
+		PyObject *obj0 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "O:fs_core_session_locate", &obj0))
+			goto fail;
+		if (!SWIG_AsCharPtr(obj0, (char **) &arg1)) {
+			SWIG_arg_fail(1);
+			SWIG_fail;
+		}
+		result = (switch_core_session_t *) fs_core_session_locate(arg1);
+
+		resultobj = SWIG_NewPointerObj((void *) (result), SWIGTYPE_p_switch_core_session_t, 0);
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_channel_answer(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:fs_channel_answer",&obj0)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    fs_channel_answer(arg1);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_channel_answer(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		PyObject *obj0 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "O:fs_channel_answer", &obj0))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		fs_channel_answer(arg1);
+
+		Py_INCREF(Py_None);
+		resultobj = Py_None;
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_channel_pre_answer(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:fs_channel_pre_answer",&obj0)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    fs_channel_pre_answer(arg1);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_channel_pre_answer(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		PyObject *obj0 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "O:fs_channel_pre_answer", &obj0))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		fs_channel_pre_answer(arg1);
+
+		Py_INCREF(Py_None);
+		resultobj = Py_None;
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_channel_hangup(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:fs_channel_hangup",&obj0,&obj1)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    fs_channel_hangup(arg1,arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_channel_hangup(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OO:fs_channel_hangup", &obj0, &obj1))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		fs_channel_hangup(arg1, arg2);
+
+		Py_INCREF(Py_None);
+		resultobj = Py_None;
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_channel_set_variable(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    char *arg3 = (char *) 0 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOO:fs_channel_set_variable",&obj0,&obj1,&obj2)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj2, (char**)&arg3)) {
-        SWIG_arg_fail(3);SWIG_fail;
-    }
-    fs_channel_set_variable(arg1,arg2,arg3);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_channel_set_variable(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		char *arg3 = (char *) 0;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOO:fs_channel_set_variable", &obj0, &obj1, &obj2))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj2, (char **) &arg3)) {
+			SWIG_arg_fail(3);
+			SWIG_fail;
+		}
+		fs_channel_set_variable(arg1, arg2, arg3);
+
+		Py_INCREF(Py_None);
+		resultobj = Py_None;
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_channel_get_variable(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:fs_channel_get_variable",&obj0,&obj1)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    fs_channel_get_variable(arg1,arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_channel_get_variable(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OO:fs_channel_get_variable", &obj0, &obj1))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		fs_channel_get_variable(arg1, arg2);
+
+		Py_INCREF(Py_None);
+		resultobj = Py_None;
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_channel_set_state(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:fs_channel_set_state",&obj0,&obj1)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    fs_channel_set_state(arg1,arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_channel_set_state(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OO:fs_channel_set_state", &obj0, &obj1))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		fs_channel_set_state(arg1, arg2);
+
+		Py_INCREF(Py_None);
+		resultobj = Py_None;
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_ivr_play_file(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    char *arg3 = (char *) 0 ;
-    switch_input_callback_function_t arg4 ;
-    void *arg5 = (void *) 0 ;
-    unsigned int arg6 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    PyObject * obj3 = 0 ;
-    PyObject * obj4 = 0 ;
-    PyObject * obj5 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOOOOO:fs_ivr_play_file",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj2, (char**)&arg3)) {
-        SWIG_arg_fail(3);SWIG_fail;
-    }
-    {
-        switch_input_callback_function_t * argp;
-        SWIG_Python_ConvertPtr(obj3, (void **)&argp, SWIGTYPE_p_switch_input_callback_function_t, SWIG_POINTER_EXCEPTION);
-        if (SWIG_arg_fail(4)) SWIG_fail;
-        if (argp == NULL) {
-            SWIG_null_ref("switch_input_callback_function_t");
-        }
-        if (SWIG_arg_fail(4)) SWIG_fail;
-        arg4 = *argp;
-    }
-    {
-        if ((SWIG_ConvertPtr(obj4,(void **)(&arg5),0,SWIG_POINTER_EXCEPTION|0))== -1) {
-            SWIG_arg_fail(5);SWIG_fail;
-        }
-    }
-    {
-        arg6 = (unsigned int)(SWIG_As_unsigned_SS_int(obj5)); 
-        if (SWIG_arg_fail(6)) SWIG_fail;
-    }
-    result = (int)fs_ivr_play_file(arg1,arg2,arg3,arg4,arg5,arg6);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_ivr_play_file(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		char *arg3 = (char *) 0;
+		switch_input_callback_function_t arg4;
+		void *arg5 = (void *) 0;
+		unsigned int arg6;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+		PyObject *obj3 = 0;
+		PyObject *obj4 = 0;
+		PyObject *obj5 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOOOOO:fs_ivr_play_file", &obj0, &obj1, &obj2, &obj3, &obj4, &obj5))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj2, (char **) &arg3)) {
+			SWIG_arg_fail(3);
+			SWIG_fail;
+		}
+		{
+			switch_input_callback_function_t *argp;
+			SWIG_Python_ConvertPtr(obj3, (void **) &argp, SWIGTYPE_p_switch_input_callback_function_t, SWIG_POINTER_EXCEPTION);
+			if (SWIG_arg_fail(4))
+				SWIG_fail;
+			if (argp == NULL) {
+				SWIG_null_ref("switch_input_callback_function_t");
+			}
+			if (SWIG_arg_fail(4))
+				SWIG_fail;
+			arg4 = *argp;
+		}
+		{
+			if ((SWIG_ConvertPtr(obj4, (void **) (&arg5), 0, SWIG_POINTER_EXCEPTION | 0)) == -1) {
+				SWIG_arg_fail(5);
+				SWIG_fail;
+			}
+		}
+		{
+			arg6 = (unsigned int) (SWIG_As_unsigned_SS_int(obj5));
+			if (SWIG_arg_fail(6))
+				SWIG_fail;
+		}
+		result = (int) fs_ivr_play_file(arg1, arg2, arg3, arg4, arg5, arg6);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_ivr_record_file(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    switch_file_handle_t *arg2 = (switch_file_handle_t *) 0 ;
-    char *arg3 = (char *) 0 ;
-    switch_input_callback_function_t arg4 ;
-    void *arg5 = (void *) 0 ;
-    unsigned int arg6 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    PyObject * obj3 = 0 ;
-    PyObject * obj4 = 0 ;
-    PyObject * obj5 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOOOOO:fs_switch_ivr_record_file",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    SWIG_Python_ConvertPtr(obj1, (void **)&arg2, SWIGTYPE_p_switch_file_handle_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(2)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj2, (char**)&arg3)) {
-        SWIG_arg_fail(3);SWIG_fail;
-    }
-    {
-        switch_input_callback_function_t * argp;
-        SWIG_Python_ConvertPtr(obj3, (void **)&argp, SWIGTYPE_p_switch_input_callback_function_t, SWIG_POINTER_EXCEPTION);
-        if (SWIG_arg_fail(4)) SWIG_fail;
-        if (argp == NULL) {
-            SWIG_null_ref("switch_input_callback_function_t");
-        }
-        if (SWIG_arg_fail(4)) SWIG_fail;
-        arg4 = *argp;
-    }
-    {
-        if ((SWIG_ConvertPtr(obj4,(void **)(&arg5),0,SWIG_POINTER_EXCEPTION|0))== -1) {
-            SWIG_arg_fail(5);SWIG_fail;
-        }
-    }
-    {
-        arg6 = (unsigned int)(SWIG_As_unsigned_SS_int(obj5)); 
-        if (SWIG_arg_fail(6)) SWIG_fail;
-    }
-    result = (int)fs_switch_ivr_record_file(arg1,arg2,arg3,arg4,arg5,arg6);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_ivr_record_file(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		switch_file_handle_t *arg2 = (switch_file_handle_t *) 0;
+		char *arg3 = (char *) 0;
+		switch_input_callback_function_t arg4;
+		void *arg5 = (void *) 0;
+		unsigned int arg6;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+		PyObject *obj3 = 0;
+		PyObject *obj4 = 0;
+		PyObject *obj5 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOOOOO:fs_switch_ivr_record_file", &obj0, &obj1, &obj2, &obj3, &obj4, &obj5))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		SWIG_Python_ConvertPtr(obj1, (void **) &arg2, SWIGTYPE_p_switch_file_handle_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(2))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj2, (char **) &arg3)) {
+			SWIG_arg_fail(3);
+			SWIG_fail;
+		}
+		{
+			switch_input_callback_function_t *argp;
+			SWIG_Python_ConvertPtr(obj3, (void **) &argp, SWIGTYPE_p_switch_input_callback_function_t, SWIG_POINTER_EXCEPTION);
+			if (SWIG_arg_fail(4))
+				SWIG_fail;
+			if (argp == NULL) {
+				SWIG_null_ref("switch_input_callback_function_t");
+			}
+			if (SWIG_arg_fail(4))
+				SWIG_fail;
+			arg4 = *argp;
+		}
+		{
+			if ((SWIG_ConvertPtr(obj4, (void **) (&arg5), 0, SWIG_POINTER_EXCEPTION | 0)) == -1) {
+				SWIG_arg_fail(5);
+				SWIG_fail;
+			}
+		}
+		{
+			arg6 = (unsigned int) (SWIG_As_unsigned_SS_int(obj5));
+			if (SWIG_arg_fail(6))
+				SWIG_fail;
+		}
+		result = (int) fs_switch_ivr_record_file(arg1, arg2, arg3, arg4, arg5, arg6);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_ivr_sleep(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    unsigned int arg2 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:fs_switch_ivr_sleep",&obj0,&obj1)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    {
-        arg2 = (unsigned int)(SWIG_As_unsigned_SS_int(obj1)); 
-        if (SWIG_arg_fail(2)) SWIG_fail;
-    }
-    result = (int)fs_switch_ivr_sleep(arg1,arg2);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_ivr_sleep(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		unsigned int arg2;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OO:fs_switch_ivr_sleep", &obj0, &obj1))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		{
+			arg2 = (unsigned int) (SWIG_As_unsigned_SS_int(obj1));
+			if (SWIG_arg_fail(2))
+				SWIG_fail;
+		}
+		result = (int) fs_switch_ivr_sleep(arg1, arg2);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_ivr_play_file2(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:fs_ivr_play_file2",&obj0,&obj1)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    result = (int)fs_ivr_play_file2(arg1,arg2);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_ivr_play_file2(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OO:fs_ivr_play_file2", &obj0, &obj1))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		result = (int) fs_ivr_play_file2(arg1, arg2);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_ivr_collect_digits_callback(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    switch_input_callback_function_t arg2 ;
-    void *arg3 = (void *) 0 ;
-    unsigned int arg4 ;
-    unsigned int arg5 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    PyObject * obj3 = 0 ;
-    PyObject * obj4 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOOOO:fs_switch_ivr_collect_digits_callback",&obj0,&obj1,&obj2,&obj3,&obj4)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    {
-        switch_input_callback_function_t * argp;
-        SWIG_Python_ConvertPtr(obj1, (void **)&argp, SWIGTYPE_p_switch_input_callback_function_t, SWIG_POINTER_EXCEPTION);
-        if (SWIG_arg_fail(2)) SWIG_fail;
-        if (argp == NULL) {
-            SWIG_null_ref("switch_input_callback_function_t");
-        }
-        if (SWIG_arg_fail(2)) SWIG_fail;
-        arg2 = *argp;
-    }
-    {
-        if ((SWIG_ConvertPtr(obj2,(void **)(&arg3),0,SWIG_POINTER_EXCEPTION|0))== -1) {
-            SWIG_arg_fail(3);SWIG_fail;
-        }
-    }
-    {
-        arg4 = (unsigned int)(SWIG_As_unsigned_SS_int(obj3)); 
-        if (SWIG_arg_fail(4)) SWIG_fail;
-    }
-    {
-        arg5 = (unsigned int)(SWIG_As_unsigned_SS_int(obj4)); 
-        if (SWIG_arg_fail(5)) SWIG_fail;
-    }
-    result = (int)fs_switch_ivr_collect_digits_callback(arg1,arg2,arg3,arg4,arg5);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_ivr_collect_digits_callback(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		switch_input_callback_function_t arg2;
+		void *arg3 = (void *) 0;
+		unsigned int arg4;
+		unsigned int arg5;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+		PyObject *obj3 = 0;
+		PyObject *obj4 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOOOO:fs_switch_ivr_collect_digits_callback", &obj0, &obj1, &obj2, &obj3, &obj4))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		{
+			switch_input_callback_function_t *argp;
+			SWIG_Python_ConvertPtr(obj1, (void **) &argp, SWIGTYPE_p_switch_input_callback_function_t, SWIG_POINTER_EXCEPTION);
+			if (SWIG_arg_fail(2))
+				SWIG_fail;
+			if (argp == NULL) {
+				SWIG_null_ref("switch_input_callback_function_t");
+			}
+			if (SWIG_arg_fail(2))
+				SWIG_fail;
+			arg2 = *argp;
+		}
+		{
+			if ((SWIG_ConvertPtr(obj2, (void **) (&arg3), 0, SWIG_POINTER_EXCEPTION | 0)) == -1) {
+				SWIG_arg_fail(3);
+				SWIG_fail;
+			}
+		}
+		{
+			arg4 = (unsigned int) (SWIG_As_unsigned_SS_int(obj3));
+			if (SWIG_arg_fail(4))
+				SWIG_fail;
+		}
+		{
+			arg5 = (unsigned int) (SWIG_As_unsigned_SS_int(obj4));
+			if (SWIG_arg_fail(5))
+				SWIG_fail;
+		}
+		result = (int) fs_switch_ivr_collect_digits_callback(arg1, arg2, arg3, arg4, arg5);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_ivr_collect_digits_count(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    unsigned int arg3 ;
-    unsigned int arg4 ;
-    char *arg5 = (char *) 0 ;
-    char *arg6 = (char *) 0 ;
-    unsigned int arg7 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    PyObject * obj3 = 0 ;
-    PyObject * obj4 = 0 ;
-    PyObject * obj5 = 0 ;
-    PyObject * obj6 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOOOOOO:fs_switch_ivr_collect_digits_count",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    {
-        arg3 = (unsigned int)(SWIG_As_unsigned_SS_int(obj2)); 
-        if (SWIG_arg_fail(3)) SWIG_fail;
-    }
-    {
-        arg4 = (unsigned int)(SWIG_As_unsigned_SS_int(obj3)); 
-        if (SWIG_arg_fail(4)) SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj4, (char**)&arg5)) {
-        SWIG_arg_fail(5);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj5, (char**)&arg6)) {
-        SWIG_arg_fail(6);SWIG_fail;
-    }
-    {
-        arg7 = (unsigned int)(SWIG_As_unsigned_SS_int(obj6)); 
-        if (SWIG_arg_fail(7)) SWIG_fail;
-    }
-    result = (int)fs_switch_ivr_collect_digits_count(arg1,arg2,arg3,arg4,(char const *)arg5,arg6,arg7);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_ivr_collect_digits_count(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		unsigned int arg3;
+		unsigned int arg4;
+		char *arg5 = (char *) 0;
+		char *arg6 = (char *) 0;
+		unsigned int arg7;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+		PyObject *obj3 = 0;
+		PyObject *obj4 = 0;
+		PyObject *obj5 = 0;
+		PyObject *obj6 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOOOOOO:fs_switch_ivr_collect_digits_count", &obj0, &obj1, &obj2, &obj3, &obj4, &obj5, &obj6))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		{
+			arg3 = (unsigned int) (SWIG_As_unsigned_SS_int(obj2));
+			if (SWIG_arg_fail(3))
+				SWIG_fail;
+		}
+		{
+			arg4 = (unsigned int) (SWIG_As_unsigned_SS_int(obj3));
+			if (SWIG_arg_fail(4))
+				SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj4, (char **) &arg5)) {
+			SWIG_arg_fail(5);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj5, (char **) &arg6)) {
+			SWIG_arg_fail(6);
+			SWIG_fail;
+		}
+		{
+			arg7 = (unsigned int) (SWIG_As_unsigned_SS_int(obj6));
+			if (SWIG_arg_fail(7))
+				SWIG_fail;
+		}
+		result = (int) fs_switch_ivr_collect_digits_count(arg1, arg2, arg3, arg4, (char const *) arg5, arg6, arg7);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_ivr_originate(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    switch_core_session_t **arg2 = (switch_core_session_t **) 0 ;
-    char *arg3 = (char *) 0 ;
-    unsigned int arg4 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    PyObject * obj3 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOOO:fs_switch_ivr_originate",&obj0,&obj1,&obj2,&obj3)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    SWIG_Python_ConvertPtr(obj1, (void **)&arg2, SWIGTYPE_p_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(2)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj2, (char**)&arg3)) {
-        SWIG_arg_fail(3);SWIG_fail;
-    }
-    {
-        arg4 = (unsigned int)(SWIG_As_unsigned_SS_int(obj3)); 
-        if (SWIG_arg_fail(4)) SWIG_fail;
-    }
-    result = (int)fs_switch_ivr_originate(arg1,arg2,arg3,arg4);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_ivr_originate(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		switch_core_session_t **arg2 = (switch_core_session_t **) 0;
+		char *arg3 = (char *) 0;
+		unsigned int arg4;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+		PyObject *obj3 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOOO:fs_switch_ivr_originate", &obj0, &obj1, &obj2, &obj3))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		SWIG_Python_ConvertPtr(obj1, (void **) &arg2, SWIGTYPE_p_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(2))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj2, (char **) &arg3)) {
+			SWIG_arg_fail(3);
+			SWIG_fail;
+		}
+		{
+			arg4 = (unsigned int) (SWIG_As_unsigned_SS_int(obj3));
+			if (SWIG_arg_fail(4))
+				SWIG_fail;
+		}
+		result = (int) fs_switch_ivr_originate(arg1, arg2, arg3, arg4);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_ivr_session_transfer(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    char *arg3 = (char *) 0 ;
-    char *arg4 = (char *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    PyObject * obj3 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOOO:fs_switch_ivr_session_transfer",&obj0,&obj1,&obj2,&obj3)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj2, (char**)&arg3)) {
-        SWIG_arg_fail(3);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj3, (char**)&arg4)) {
-        SWIG_arg_fail(4);SWIG_fail;
-    }
-    result = (int)fs_switch_ivr_session_transfer(arg1,arg2,arg3,arg4);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_ivr_session_transfer(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		char *arg3 = (char *) 0;
+		char *arg4 = (char *) 0;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+		PyObject *obj3 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOOO:fs_switch_ivr_session_transfer", &obj0, &obj1, &obj2, &obj3))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj2, (char **) &arg3)) {
+			SWIG_arg_fail(3);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj3, (char **) &arg4)) {
+			SWIG_arg_fail(4);
+			SWIG_fail;
+		}
+		result = (int) fs_switch_ivr_session_transfer(arg1, arg2, arg3, arg4);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_ivr_speak_text(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    char *arg3 = (char *) 0 ;
-    char *arg4 = (char *) 0 ;
-    unsigned int arg5 ;
-    switch_input_callback_function_t arg6 ;
-    char *arg7 = (char *) 0 ;
-    void *arg8 = (void *) 0 ;
-    unsigned int arg9 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    PyObject * obj3 = 0 ;
-    PyObject * obj4 = 0 ;
-    PyObject * obj5 = 0 ;
-    PyObject * obj6 = 0 ;
-    PyObject * obj7 = 0 ;
-    PyObject * obj8 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOOOOOOOO:fs_switch_ivr_speak_text",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj2, (char**)&arg3)) {
-        SWIG_arg_fail(3);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj3, (char**)&arg4)) {
-        SWIG_arg_fail(4);SWIG_fail;
-    }
-    {
-        arg5 = (unsigned int)(SWIG_As_unsigned_SS_int(obj4)); 
-        if (SWIG_arg_fail(5)) SWIG_fail;
-    }
-    {
-        switch_input_callback_function_t * argp;
-        SWIG_Python_ConvertPtr(obj5, (void **)&argp, SWIGTYPE_p_switch_input_callback_function_t, SWIG_POINTER_EXCEPTION);
-        if (SWIG_arg_fail(6)) SWIG_fail;
-        if (argp == NULL) {
-            SWIG_null_ref("switch_input_callback_function_t");
-        }
-        if (SWIG_arg_fail(6)) SWIG_fail;
-        arg6 = *argp;
-    }
-    if (!SWIG_AsCharPtr(obj6, (char**)&arg7)) {
-        SWIG_arg_fail(7);SWIG_fail;
-    }
-    {
-        if ((SWIG_ConvertPtr(obj7,(void **)(&arg8),0,SWIG_POINTER_EXCEPTION|0))== -1) {
-            SWIG_arg_fail(8);SWIG_fail;
-        }
-    }
-    {
-        arg9 = (unsigned int)(SWIG_As_unsigned_SS_int(obj8)); 
-        if (SWIG_arg_fail(9)) SWIG_fail;
-    }
-    result = (int)fs_switch_ivr_speak_text(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_ivr_speak_text(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		char *arg3 = (char *) 0;
+		char *arg4 = (char *) 0;
+		unsigned int arg5;
+		switch_input_callback_function_t arg6;
+		char *arg7 = (char *) 0;
+		void *arg8 = (void *) 0;
+		unsigned int arg9;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+		PyObject *obj3 = 0;
+		PyObject *obj4 = 0;
+		PyObject *obj5 = 0;
+		PyObject *obj6 = 0;
+		PyObject *obj7 = 0;
+		PyObject *obj8 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOOOOOOOO:fs_switch_ivr_speak_text", &obj0, &obj1, &obj2, &obj3, &obj4, &obj5, &obj6, &obj7, &obj8))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj2, (char **) &arg3)) {
+			SWIG_arg_fail(3);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj3, (char **) &arg4)) {
+			SWIG_arg_fail(4);
+			SWIG_fail;
+		}
+		{
+			arg5 = (unsigned int) (SWIG_As_unsigned_SS_int(obj4));
+			if (SWIG_arg_fail(5))
+				SWIG_fail;
+		}
+		{
+			switch_input_callback_function_t *argp;
+			SWIG_Python_ConvertPtr(obj5, (void **) &argp, SWIGTYPE_p_switch_input_callback_function_t, SWIG_POINTER_EXCEPTION);
+			if (SWIG_arg_fail(6))
+				SWIG_fail;
+			if (argp == NULL) {
+				SWIG_null_ref("switch_input_callback_function_t");
+			}
+			if (SWIG_arg_fail(6))
+				SWIG_fail;
+			arg6 = *argp;
+		}
+		if (!SWIG_AsCharPtr(obj6, (char **) &arg7)) {
+			SWIG_arg_fail(7);
+			SWIG_fail;
+		}
+		{
+			if ((SWIG_ConvertPtr(obj7, (void **) (&arg8), 0, SWIG_POINTER_EXCEPTION | 0)) == -1) {
+				SWIG_arg_fail(8);
+				SWIG_fail;
+			}
+		}
+		{
+			arg9 = (unsigned int) (SWIG_As_unsigned_SS_int(obj8));
+			if (SWIG_arg_fail(9))
+				SWIG_fail;
+		}
+		result = (int) fs_switch_ivr_speak_text(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_ivr_speak_text2(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_core_session_t *arg1 = (switch_core_session_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    char *arg3 = (char *) 0 ;
-    char *arg4 = (char *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    PyObject * obj3 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOOO:fs_switch_ivr_speak_text2",&obj0,&obj1,&obj2,&obj3)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj2, (char**)&arg3)) {
-        SWIG_arg_fail(3);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj3, (char**)&arg4)) {
-        SWIG_arg_fail(4);SWIG_fail;
-    }
-    result = (int)fs_switch_ivr_speak_text2(arg1,arg2,arg3,arg4);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_ivr_speak_text2(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_core_session_t *arg1 = (switch_core_session_t *) 0;
+		char *arg2 = (char *) 0;
+		char *arg3 = (char *) 0;
+		char *arg4 = (char *) 0;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+		PyObject *obj3 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOOO:fs_switch_ivr_speak_text2", &obj0, &obj1, &obj2, &obj3))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_core_session_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj2, (char **) &arg3)) {
+			SWIG_arg_fail(3);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj3, (char **) &arg4)) {
+			SWIG_arg_fail(4);
+			SWIG_fail;
+		}
+		result = (int) fs_switch_ivr_speak_text2(arg1, arg2, arg3, arg4);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_channel_get_variable(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_channel_t *arg1 = (switch_channel_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    char *result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:fs_switch_channel_get_variable",&obj0,&obj1)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_channel_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    result = (char *)fs_switch_channel_get_variable(arg1,arg2);
-    
-    resultobj = SWIG_FromCharPtr(result);
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_channel_get_variable(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_channel_t *arg1 = (switch_channel_t *) 0;
+		char *arg2 = (char *) 0;
+		char *result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OO:fs_switch_channel_get_variable", &obj0, &obj1))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_channel_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		result = (char *) fs_switch_channel_get_variable(arg1, arg2);
+
+		resultobj = SWIG_FromCharPtr(result);
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyObject *_wrap_fs_switch_channel_set_variable(PyObject *self, PyObject *args) {
-    PyObject *resultobj = NULL;
-    switch_channel_t *arg1 = (switch_channel_t *) 0 ;
-    char *arg2 = (char *) 0 ;
-    char *arg3 = (char *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    PyObject * obj2 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OOO:fs_switch_channel_set_variable",&obj0,&obj1,&obj2)) goto fail;
-    SWIG_Python_ConvertPtr(obj0, (void **)&arg1, SWIGTYPE_p_switch_channel_t, SWIG_POINTER_EXCEPTION | 0);
-    if (SWIG_arg_fail(1)) SWIG_fail;
-    if (!SWIG_AsCharPtr(obj1, (char**)&arg2)) {
-        SWIG_arg_fail(2);SWIG_fail;
-    }
-    if (!SWIG_AsCharPtr(obj2, (char**)&arg3)) {
-        SWIG_arg_fail(3);SWIG_fail;
-    }
-    result = (int)fs_switch_channel_set_variable(arg1,arg2,arg3);
-    
-    {
-        resultobj = SWIG_From_int((int)(result)); 
-    }
-    return resultobj;
-    fail:
-    return NULL;
-}
+	static PyObject *_wrap_fs_switch_channel_set_variable(PyObject * self, PyObject * args) {
+		PyObject *resultobj = NULL;
+		switch_channel_t *arg1 = (switch_channel_t *) 0;
+		char *arg2 = (char *) 0;
+		char *arg3 = (char *) 0;
+		int result;
+		PyObject *obj0 = 0;
+		PyObject *obj1 = 0;
+		PyObject *obj2 = 0;
+
+		if (!PyArg_ParseTuple(args, (char *) "OOO:fs_switch_channel_set_variable", &obj0, &obj1, &obj2))
+			goto fail;
+		SWIG_Python_ConvertPtr(obj0, (void **) &arg1, SWIGTYPE_p_switch_channel_t, SWIG_POINTER_EXCEPTION | 0);
+		if (SWIG_arg_fail(1))
+			SWIG_fail;
+		if (!SWIG_AsCharPtr(obj1, (char **) &arg2)) {
+			SWIG_arg_fail(2);
+			SWIG_fail;
+		}
+		if (!SWIG_AsCharPtr(obj2, (char **) &arg3)) {
+			SWIG_arg_fail(3);
+			SWIG_fail;
+		}
+		result = (int) fs_switch_channel_set_variable(arg1, arg2, arg3);
+
+		{
+			resultobj = SWIG_From_int((int) (result));
+		}
+		return resultobj;
+	  fail:
+		return NULL;
+	}
 
 
-static PyMethodDef SwigMethods[] = {
-	 { (char *)"fs_core_set_globals", _wrap_fs_core_set_globals, METH_VARARGS, NULL},
-	 { (char *)"fs_core_init", _wrap_fs_core_init, METH_VARARGS, NULL},
-	 { (char *)"fs_core_destroy", _wrap_fs_core_destroy, METH_VARARGS, NULL},
-	 { (char *)"fs_loadable_module_init", _wrap_fs_loadable_module_init, METH_VARARGS, NULL},
-	 { (char *)"fs_loadable_module_shutdown", _wrap_fs_loadable_module_shutdown, METH_VARARGS, NULL},
-	 { (char *)"fs_console_loop", _wrap_fs_console_loop, METH_VARARGS, NULL},
-	 { (char *)"fs_console_log", _wrap_fs_console_log, METH_VARARGS, NULL},
-	 { (char *)"fs_console_clean", _wrap_fs_console_clean, METH_VARARGS, NULL},
-	 { (char *)"fs_core_session_locate", _wrap_fs_core_session_locate, METH_VARARGS, NULL},
-	 { (char *)"fs_channel_answer", _wrap_fs_channel_answer, METH_VARARGS, NULL},
-	 { (char *)"fs_channel_pre_answer", _wrap_fs_channel_pre_answer, METH_VARARGS, NULL},
-	 { (char *)"fs_channel_hangup", _wrap_fs_channel_hangup, METH_VARARGS, NULL},
-	 { (char *)"fs_channel_set_variable", _wrap_fs_channel_set_variable, METH_VARARGS, NULL},
-	 { (char *)"fs_channel_get_variable", _wrap_fs_channel_get_variable, METH_VARARGS, NULL},
-	 { (char *)"fs_channel_set_state", _wrap_fs_channel_set_state, METH_VARARGS, NULL},
-	 { (char *)"fs_ivr_play_file", _wrap_fs_ivr_play_file, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_ivr_record_file", _wrap_fs_switch_ivr_record_file, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_ivr_sleep", _wrap_fs_switch_ivr_sleep, METH_VARARGS, NULL},
-	 { (char *)"fs_ivr_play_file2", _wrap_fs_ivr_play_file2, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_ivr_collect_digits_callback", _wrap_fs_switch_ivr_collect_digits_callback, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_ivr_collect_digits_count", _wrap_fs_switch_ivr_collect_digits_count, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_ivr_originate", _wrap_fs_switch_ivr_originate, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_ivr_session_transfer", _wrap_fs_switch_ivr_session_transfer, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_ivr_speak_text", _wrap_fs_switch_ivr_speak_text, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_ivr_speak_text2", _wrap_fs_switch_ivr_speak_text2, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_channel_get_variable", _wrap_fs_switch_channel_get_variable, METH_VARARGS, NULL},
-	 { (char *)"fs_switch_channel_set_variable", _wrap_fs_switch_channel_set_variable, METH_VARARGS, NULL},
-	 { NULL, NULL, 0, NULL }
-};
+	static PyMethodDef SwigMethods[] = {
+		{(char *) "fs_core_set_globals", _wrap_fs_core_set_globals, METH_VARARGS, NULL},
+		{(char *) "fs_core_init", _wrap_fs_core_init, METH_VARARGS, NULL},
+		{(char *) "fs_core_destroy", _wrap_fs_core_destroy, METH_VARARGS, NULL},
+		{(char *) "fs_loadable_module_init", _wrap_fs_loadable_module_init, METH_VARARGS, NULL},
+		{(char *) "fs_loadable_module_shutdown", _wrap_fs_loadable_module_shutdown, METH_VARARGS, NULL},
+		{(char *) "fs_console_loop", _wrap_fs_console_loop, METH_VARARGS, NULL},
+		{(char *) "fs_console_log", _wrap_fs_console_log, METH_VARARGS, NULL},
+		{(char *) "fs_console_clean", _wrap_fs_console_clean, METH_VARARGS, NULL},
+		{(char *) "fs_core_session_locate", _wrap_fs_core_session_locate, METH_VARARGS, NULL},
+		{(char *) "fs_channel_answer", _wrap_fs_channel_answer, METH_VARARGS, NULL},
+		{(char *) "fs_channel_pre_answer", _wrap_fs_channel_pre_answer, METH_VARARGS, NULL},
+		{(char *) "fs_channel_hangup", _wrap_fs_channel_hangup, METH_VARARGS, NULL},
+		{(char *) "fs_channel_set_variable", _wrap_fs_channel_set_variable, METH_VARARGS, NULL},
+		{(char *) "fs_channel_get_variable", _wrap_fs_channel_get_variable, METH_VARARGS, NULL},
+		{(char *) "fs_channel_set_state", _wrap_fs_channel_set_state, METH_VARARGS, NULL},
+		{(char *) "fs_ivr_play_file", _wrap_fs_ivr_play_file, METH_VARARGS, NULL},
+		{(char *) "fs_switch_ivr_record_file", _wrap_fs_switch_ivr_record_file, METH_VARARGS, NULL},
+		{(char *) "fs_switch_ivr_sleep", _wrap_fs_switch_ivr_sleep, METH_VARARGS, NULL},
+		{(char *) "fs_ivr_play_file2", _wrap_fs_ivr_play_file2, METH_VARARGS, NULL},
+		{(char *) "fs_switch_ivr_collect_digits_callback", _wrap_fs_switch_ivr_collect_digits_callback, METH_VARARGS,
+		 NULL},
+		{(char *) "fs_switch_ivr_collect_digits_count", _wrap_fs_switch_ivr_collect_digits_count, METH_VARARGS, NULL},
+		{(char *) "fs_switch_ivr_originate", _wrap_fs_switch_ivr_originate, METH_VARARGS, NULL},
+		{(char *) "fs_switch_ivr_session_transfer", _wrap_fs_switch_ivr_session_transfer, METH_VARARGS, NULL},
+		{(char *) "fs_switch_ivr_speak_text", _wrap_fs_switch_ivr_speak_text, METH_VARARGS, NULL},
+		{(char *) "fs_switch_ivr_speak_text2", _wrap_fs_switch_ivr_speak_text2, METH_VARARGS, NULL},
+		{(char *) "fs_switch_channel_get_variable", _wrap_fs_switch_channel_get_variable, METH_VARARGS, NULL},
+		{(char *) "fs_switch_channel_set_variable", _wrap_fs_switch_channel_set_variable, METH_VARARGS, NULL},
+		{NULL, NULL, 0, NULL}
+	};
 
 
 /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */
 
-static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, 0};
-static swig_type_info _swigt__p_p_switch_core_session_t = {"_p_p_switch_core_session_t", "switch_core_session_t **", 0, 0, 0};
-static swig_type_info _swigt__p_switch_channel_state_t = {"_p_switch_channel_state_t", "enum switch_channel_state_t *|switch_channel_state_t *", 0, 0, 0};
-static swig_type_info _swigt__p_switch_channel_t = {"_p_switch_channel_t", "switch_channel_t *", 0, 0, 0};
-static swig_type_info _swigt__p_switch_core_session_t = {"_p_switch_core_session_t", "switch_core_session_t *", 0, 0, 0};
-static swig_type_info _swigt__p_switch_file_handle_t = {"_p_switch_file_handle_t", "switch_file_handle_t *", 0, 0, 0};
-static swig_type_info _swigt__p_switch_input_callback_function_t = {"_p_switch_input_callback_function_t", "switch_input_callback_function_t *", 0, 0, 0};
-static swig_type_info _swigt__ptrdiff_t = {"_ptrdiff_t", "ptrdiff_t", 0, 0, 0};
-static swig_type_info _swigt__size_t = {"_size_t", "size_t", 0, 0, 0};
-
-static swig_type_info *swig_type_initial[] = {
-  &_swigt__p_char,
-  &_swigt__p_p_switch_core_session_t,
-  &_swigt__p_switch_channel_state_t,
-  &_swigt__p_switch_channel_t,
-  &_swigt__p_switch_core_session_t,
-  &_swigt__p_switch_file_handle_t,
-  &_swigt__p_switch_input_callback_function_t,
-  &_swigt__ptrdiff_t,
-  &_swigt__size_t,
-};
-
-static swig_cast_info _swigc__p_char[] = {  {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_p_switch_core_session_t[] = {  {&_swigt__p_p_switch_core_session_t, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_switch_channel_state_t[] = {  {&_swigt__p_switch_channel_state_t, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_switch_channel_t[] = {  {&_swigt__p_switch_channel_t, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_switch_core_session_t[] = {  {&_swigt__p_switch_core_session_t, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_switch_file_handle_t[] = {  {&_swigt__p_switch_file_handle_t, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__p_switch_input_callback_function_t[] = {  {&_swigt__p_switch_input_callback_function_t, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__ptrdiff_t[] = {  {&_swigt__ptrdiff_t, 0, 0, 0},{0, 0, 0, 0}};
-static swig_cast_info _swigc__size_t[] = {  {&_swigt__size_t, 0, 0, 0},{0, 0, 0, 0}};
-
-static swig_cast_info *swig_cast_initial[] = {
-  _swigc__p_char,
-  _swigc__p_p_switch_core_session_t,
-  _swigc__p_switch_channel_state_t,
-  _swigc__p_switch_channel_t,
-  _swigc__p_switch_core_session_t,
-  _swigc__p_switch_file_handle_t,
-  _swigc__p_switch_input_callback_function_t,
-  _swigc__ptrdiff_t,
-  _swigc__size_t,
-};
+	static swig_type_info _swigt__p_char = { "_p_char", "char *", 0, 0, 0 };
+	static swig_type_info _swigt__p_p_switch_core_session_t = { "_p_p_switch_core_session_t", "switch_core_session_t **", 0, 0, 0 };
+	static swig_type_info _swigt__p_switch_channel_state_t =
+		{ "_p_switch_channel_state_t", "enum switch_channel_state_t *|switch_channel_state_t *", 0, 0, 0 };
+	static swig_type_info _swigt__p_switch_channel_t = { "_p_switch_channel_t", "switch_channel_t *", 0, 0, 0 };
+	static swig_type_info _swigt__p_switch_core_session_t = { "_p_switch_core_session_t", "switch_core_session_t *", 0, 0, 0 };
+	static swig_type_info _swigt__p_switch_file_handle_t = { "_p_switch_file_handle_t", "switch_file_handle_t *", 0, 0, 0 };
+	static swig_type_info _swigt__p_switch_input_callback_function_t =
+		{ "_p_switch_input_callback_function_t", "switch_input_callback_function_t *", 0, 0, 0 };
+	static swig_type_info _swigt__ptrdiff_t = { "_ptrdiff_t", "ptrdiff_t", 0, 0, 0 };
+	static swig_type_info _swigt__size_t = { "_size_t", "size_t", 0, 0, 0 };
+
+	static swig_type_info *swig_type_initial[] = {
+		&_swigt__p_char,
+		&_swigt__p_p_switch_core_session_t,
+		&_swigt__p_switch_channel_state_t,
+		&_swigt__p_switch_channel_t,
+		&_swigt__p_switch_core_session_t,
+		&_swigt__p_switch_file_handle_t,
+		&_swigt__p_switch_input_callback_function_t,
+		&_swigt__ptrdiff_t,
+		&_swigt__size_t,
+	};
+
+	static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0}, {0, 0, 0, 0} };
+	static swig_cast_info _swigc__p_p_switch_core_session_t[] = { {&_swigt__p_p_switch_core_session_t, 0, 0, 0}, {0, 0, 0, 0} };
+	static swig_cast_info _swigc__p_switch_channel_state_t[] = { {&_swigt__p_switch_channel_state_t, 0, 0, 0}, {0, 0, 0, 0} };
+	static swig_cast_info _swigc__p_switch_channel_t[] = { {&_swigt__p_switch_channel_t, 0, 0, 0}, {0, 0, 0, 0} };
+	static swig_cast_info _swigc__p_switch_core_session_t[] = { {&_swigt__p_switch_core_session_t, 0, 0, 0}, {0, 0, 0, 0} };
+	static swig_cast_info _swigc__p_switch_file_handle_t[] = { {&_swigt__p_switch_file_handle_t, 0, 0, 0}, {0, 0, 0, 0} };
+	static swig_cast_info _swigc__p_switch_input_callback_function_t[] = { {&_swigt__p_switch_input_callback_function_t, 0, 0, 0}, {0, 0, 0, 0} };
+	static swig_cast_info _swigc__ptrdiff_t[] = { {&_swigt__ptrdiff_t, 0, 0, 0}, {0, 0, 0, 0} };
+	static swig_cast_info _swigc__size_t[] = { {&_swigt__size_t, 0, 0, 0}, {0, 0, 0, 0} };
+
+	static swig_cast_info *swig_cast_initial[] = {
+		_swigc__p_char,
+		_swigc__p_p_switch_core_session_t,
+		_swigc__p_switch_channel_state_t,
+		_swigc__p_switch_channel_t,
+		_swigc__p_switch_core_session_t,
+		_swigc__p_switch_file_handle_t,
+		_swigc__p_switch_input_callback_function_t,
+		_swigc__ptrdiff_t,
+		_swigc__size_t,
+	};
 
 
 /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */
 
-static swig_const_info swig_const_table[] = {
-{0, 0, 0, 0.0, 0, 0}};
+	static swig_const_info swig_const_table[] = {
+		{0, 0, 0, 0.0, 0, 0}
+	};
 
 #ifdef __cplusplus
 }
@@ -2518,108 +2547,109 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
-    
-    SWIGRUNTIME void
-    SWIG_InitializeModule(void *clientdata) {
-        swig_type_info *type, *ret;
-        swig_cast_info *cast;
-        size_t i;
-        swig_module_info *module_head;
-        static int init_run = 0;
-        
-        clientdata = clientdata;
-        
-        if (init_run) return;
-        init_run = 1;
-        
-        /* Initialize the swig_module */
-        swig_module.type_initial = swig_type_initial;
-        swig_module.cast_initial = swig_cast_initial;
-        
-        /* Try and load any already created modules */
-        module_head = SWIG_GetModule(clientdata);
-        if (module_head) {
-            swig_module.next = module_head->next;
-            module_head->next = &swig_module;
-        } else {
-            /* This is the first module loaded */
-            swig_module.next = &swig_module;
-            SWIG_SetModule(clientdata, &swig_module);
-        }
-        
-        /* Now work on filling in swig_module.types */
-        for (i = 0; i < swig_module.size; ++i) {
-            type = 0;
-            
-            /* if there is another module already loaded */
-            if (swig_module.next != &swig_module) {
-                type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);
-            }
-            if (type) {
-                /* Overwrite clientdata field */
-                if (swig_module.type_initial[i]->clientdata) type->clientdata = swig_module.type_initial[i]->clientdata;
-            } else {
-                type = swig_module.type_initial[i];
-            }
-            
-            /* Insert casting types */
-            cast = swig_module.cast_initial[i];
-            while (cast->type) {
-                /* Don't need to add information already in the list */
-                ret = 0;
-                if (swig_module.next != &swig_module) {
-                    ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);
-                }
-                if (ret && type == swig_module.type_initial[i]) {
-                    cast->type = ret;
-                    ret = 0;
-                }
-                
-                if (!ret) {
-                    if (type->cast) {
-                        type->cast->prev = cast;
-                        cast->next = type->cast;
-                    }
-                    type->cast = cast;
-                }
-                
-                cast++;
-            }
-            
-            /* Set entry in modules->types array equal to the type */
-            swig_module.types[i] = type;
-        }
-        swig_module.types[i] = 0;
-    }
-    
-    /* This function will propagate the clientdata field of type to
-    * any new swig_type_info structures that have been added into the list
-    * of equivalent types.  It is like calling
-    * SWIG_TypeClientData(type, clientdata) a second time.
-    */
-    SWIGRUNTIME void
-    SWIG_PropagateClientData(void) {
-        size_t i;
-        swig_cast_info *equiv;
-        static int init_run = 0;
-        
-        if (init_run) return;
-        init_run = 1;
-        
-        for (i = 0; i < swig_module.size; i++) {
-            if (swig_module.types[i]->clientdata) {
-                equiv = swig_module.types[i]->cast;
-                while (equiv) {
-                    if (!equiv->converter) {
-                        if (equiv->type && !equiv->type->clientdata)
-                        SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);
-                    }
-                    equiv = equiv->next;
-                }
-            }
-        }
-    }
-    
+
+	SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) {
+		swig_type_info *type, *ret;
+		swig_cast_info *cast;
+		size_t i;
+		swig_module_info *module_head;
+		static int init_run = 0;
+
+		    clientdata = clientdata;
+
+		if  (init_run)
+			    return;
+		    init_run = 1;
+
+		/* Initialize the swig_module */
+		    swig_module.type_initial = swig_type_initial;
+		    swig_module.cast_initial = swig_cast_initial;
+
+		/* Try and load any already created modules */
+		    module_head = SWIG_GetModule(clientdata);
+		if  (module_head) {
+			swig_module.next = module_head->next;
+			module_head->next = &swig_module;
+		} else {
+			/* This is the first module loaded */
+			swig_module.next = &swig_module;
+			SWIG_SetModule(clientdata, &swig_module);
+		}
+
+		/* Now work on filling in swig_module.types */
+		for (i = 0; i < swig_module.size; ++i) {
+			type = 0;
+
+			/* if there is another module already loaded */
+			if (swig_module.next != &swig_module) {
+				type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);
+			}
+			if (type) {
+				/* Overwrite clientdata field */
+				if (swig_module.type_initial[i]->clientdata)
+					type->clientdata = swig_module.type_initial[i]->clientdata;
+			} else {
+				type = swig_module.type_initial[i];
+			}
+
+			/* Insert casting types */
+			cast = swig_module.cast_initial[i];
+			while (cast->type) {
+				/* Don't need to add information already in the list */
+				ret = 0;
+				if (swig_module.next != &swig_module) {
+					ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);
+				}
+				if (ret && type == swig_module.type_initial[i]) {
+					cast->type = ret;
+					ret = 0;
+				}
+
+				if (!ret) {
+					if (type->cast) {
+						type->cast->prev = cast;
+						cast->next = type->cast;
+					}
+					type->cast = cast;
+				}
+
+				cast++;
+			}
+
+			/* Set entry in modules->types array equal to the type */
+			swig_module.types[i] = type;
+		}
+		swig_module.types[i] = 0;
+	}
+
+	/* This function will propagate the clientdata field of type to
+	 * any new swig_type_info structures that have been added into the list
+	 * of equivalent types.  It is like calling
+	 * SWIG_TypeClientData(type, clientdata) a second time.
+	 */
+	SWIGRUNTIME void SWIG_PropagateClientData(void) {
+		size_t i;
+		swig_cast_info *equiv;
+		static int init_run = 0;
+
+		if (init_run)
+			return;
+		init_run = 1;
+
+		for (i = 0; i < swig_module.size; i++) {
+			if (swig_module.types[i]->clientdata) {
+				equiv = swig_module.types[i]->cast;
+				while (equiv) {
+					if (!equiv->converter) {
+						if (equiv->type && !equiv->type->clientdata)
+							SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);
+					}
+					equiv = equiv->next;
+				}
+			}
+		}
+	}
+
 #ifdef __cplusplus
 }
 #endif
@@ -2629,251 +2659,237 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
-    
-    /* Python-specific SWIG API */
+
+	/* Python-specific SWIG API */
 #define SWIG_newvarlink()                             SWIG_Python_newvarlink()
 #define SWIG_addvarlink(p, name, get_attr, set_attr)  SWIG_Python_addvarlink(p, name, get_attr, set_attr)
 #define SWIG_InstallConstants(d, constants)           SWIG_Python_InstallConstants(d, constants)
-    
-    /* -----------------------------------------------------------------------------
-     * global variable support code.
-     * ----------------------------------------------------------------------------- */
-    
-    typedef struct swig_globalvar {
-        char       *name;                  /* Name of global variable */
-        PyObject *(*get_attr)(void);       /* Return the current value */
-        int       (*set_attr)(PyObject *); /* Set the value */
-        struct swig_globalvar *next;
-    } swig_globalvar;
-    
-    typedef struct swig_varlinkobject {
-        PyObject_HEAD
-        swig_globalvar *vars;
-    } swig_varlinkobject;
-    
-    SWIGINTERN PyObject *
-    swig_varlink_repr(swig_varlinkobject *v) {
-        v = v;
-        return PyString_FromString("<Swig global variables>");
-    }
-    
-    SWIGINTERN int
-    swig_varlink_print(swig_varlinkobject *v, FILE *fp, int flags) {
-        swig_globalvar  *var;
-        flags = flags;
-        fprintf(fp,"Swig global variables { ");
-        for (var = v->vars; var; var=var->next) {
-            fprintf(fp,"%s", var->name);
-            if (var->next) fprintf(fp,", ");
-        }
-        fprintf(fp," }\n");
-        return 0;
-    }
-    
-    SWIGINTERN PyObject *
-    swig_varlink_getattr(swig_varlinkobject *v, char *n) {
-        swig_globalvar *var = v->vars;
-        while (var) {
-            if (strcmp(var->name,n) == 0) {
-                return (*var->get_attr)();
-            }
-            var = var->next;
-        }
-        PyErr_SetString(PyExc_NameError,"Unknown C global variable");
-        return NULL;
-    }
-    
-    SWIGINTERN int
-    swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) {
-        swig_globalvar *var = v->vars;
-        while (var) {
-            if (strcmp(var->name,n) == 0) {
-                return (*var->set_attr)(p);
-            }
-            var = var->next;
-        }
-        PyErr_SetString(PyExc_NameError,"Unknown C global variable");
-        return 1;
-    }
-    
-    SWIGINTERN PyTypeObject*
-    swig_varlink_type(void) {
-        static char varlink__doc__[] = "Swig var link object";
-        static PyTypeObject varlink_type
+
+	/* -----------------------------------------------------------------------------
+	 * global variable support code.
+	 * ----------------------------------------------------------------------------- */
+
+	typedef struct swig_globalvar {
+		char *name;				/* Name of global variable */
+		PyObject *(*get_attr) (void);	/* Return the current value */
+		int (*set_attr) (PyObject *);	/* Set the value */
+		struct swig_globalvar *next;
+	} swig_globalvar;
+
+	typedef struct swig_varlinkobject {
+		PyObject_HEAD swig_globalvar *vars;
+	} swig_varlinkobject;
+
+	SWIGINTERN PyObject *swig_varlink_repr(swig_varlinkobject * v) {
+		v = v;
+		return PyString_FromString("<Swig global variables>");
+	}
+	SWIGINTERN int swig_varlink_print(swig_varlinkobject * v, FILE * fp, int flags) {
+		swig_globalvar *var;
+		flags = flags;
+		fprintf(fp, "Swig global variables { ");
+		for (var = v->vars; var; var = var->next) {
+			fprintf(fp, "%s", var->name);
+			if (var->next)
+				fprintf(fp, ", ");
+		}
+		fprintf(fp, " }\n");
+		return 0;
+	}
+
+	SWIGINTERN PyObject *swig_varlink_getattr(swig_varlinkobject * v, char *n) {
+		swig_globalvar *var = v->vars;
+		while (var) {
+			if (strcmp(var->name, n) == 0) {
+				return (*var->get_attr) ();
+			}
+			var = var->next;
+		}
+		PyErr_SetString(PyExc_NameError, "Unknown C global variable");
+		return NULL;
+	}
+
+	SWIGINTERN int swig_varlink_setattr(swig_varlinkobject * v, char *n, PyObject * p) {
+		swig_globalvar *var = v->vars;
+		while (var) {
+			if (strcmp(var->name, n) == 0) {
+				return (*var->set_attr) (p);
+			}
+			var = var->next;
+		}
+		PyErr_SetString(PyExc_NameError, "Unknown C global variable");
+		return 1;
+	}
+
+	SWIGINTERN PyTypeObject *swig_varlink_type(void) {
+		static char varlink__doc__[] = "Swig var link object";
+		static PyTypeObject varlink_type
 #if !defined(__cplusplus)
-        ;
-        static int type_init = 0;  
-        if (!type_init) {
-            PyTypeObject tmp
-#endif
-            = {
-                PyObject_HEAD_INIT(&PyType_Type)
-                0,                                  /* Number of items in variable part (ob_size) */
-                (char *)"swigvarlink",              /* Type name (tp_name) */
-                sizeof(swig_varlinkobject),         /* Basic size (tp_basicsize) */
-                0,                                  /* Itemsize (tp_itemsize) */
-                0,                                  /* Deallocator (tp_dealloc) */ 
-                (printfunc) swig_varlink_print,     /* Print (tp_print) */
-                (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */
-                (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */
-                0,                                  /* tp_compare */
-                (reprfunc) swig_varlink_repr,       /* tp_repr */
-                0,                                  /* tp_as_number */
-                0,                                  /* tp_as_sequence */
-                0,                                  /* tp_as_mapping */
-                0,                                  /* tp_hash */
-                0,                                  /* tp_call */
-                0,                                  /* tp_str */
-                0,                                  /* tp_getattro */
-                0,                                  /* tp_setattro */
-                0,                                  /* tp_as_buffer */
-                0,                                  /* tp_flags */
-                varlink__doc__,                     /* tp_doc */
+		            ;
+		static int type_init = 0;
+		if (!type_init) {
+			PyTypeObject tmp
+#endif
+				= {
+				PyObject_HEAD_INIT(&PyType_Type)
+					0,			/* Number of items in variable part (ob_size) */
+				(char *) "swigvarlink",	/* Type name (tp_name) */
+				sizeof(swig_varlinkobject),	/* Basic size (tp_basicsize) */
+				0,				/* Itemsize (tp_itemsize) */
+				0,				/* Deallocator (tp_dealloc) */
+				(printfunc) swig_varlink_print,	/* Print (tp_print) */
+				(getattrfunc) swig_varlink_getattr,	/* get attr (tp_getattr) */
+				(setattrfunc) swig_varlink_setattr,	/* Set attr (tp_setattr) */
+				0,				/* tp_compare */
+				(reprfunc) swig_varlink_repr,	/* tp_repr */
+				0,				/* tp_as_number */
+				0,				/* tp_as_sequence */
+				0,				/* tp_as_mapping */
+				0,				/* tp_hash */
+				0,				/* tp_call */
+				0,				/* tp_str */
+				0,				/* tp_getattro */
+				0,				/* tp_setattro */
+				0,				/* tp_as_buffer */
+				0,				/* tp_flags */
+				varlink__doc__,	/* tp_doc */
 #if PY_VERSION_HEX >= 0x02000000
-                0,                                  /* tp_traverse */
-                0,                                  /* tp_clear */
+				0,				/* tp_traverse */
+				0,				/* tp_clear */
 #endif
 #if PY_VERSION_HEX >= 0x02010000
-                0,                                  /* tp_richcompare */
-                0,                                  /* tp_weaklistoffset */
+				0,				/* tp_richcompare */
+				0,				/* tp_weaklistoffset */
 #endif
 #if PY_VERSION_HEX >= 0x02020000
-                0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */
+				0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,	/* tp_iter -> tp_weaklist */
 #endif
 #if PY_VERSION_HEX >= 0x02030000
-                0,                                  /* tp_del */
+				0,				/* tp_del */
 #endif
 #ifdef COUNT_ALLOCS
-                0,0,0,0                             /* tp_alloc -> tp_next */
+				0, 0, 0, 0		/* tp_alloc -> tp_next */
 #endif
-            };
+			};
 #if !defined(__cplusplus)
-            varlink_type = tmp;
-            type_init = 1;
-        }
-#endif
-        return &varlink_type;
-    }
-    
-    /* Create a variable linking object for use later */
-    SWIGINTERN PyObject *
-    SWIG_Python_newvarlink(void) {
-        swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type());
-        if (result) {
-            result->vars = 0;
-        }
-        return ((PyObject*) result);
-    }
-    
-    SWIGINTERN void 
-    SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {
-        swig_varlinkobject *v = (swig_varlinkobject *) p;
-        swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));
-        if (gv) {
-            size_t size = strlen(name)+1;
-            gv->name = (char *)malloc(size);
-            if (gv->name) {
-                strncpy(gv->name,name,size);
-                gv->get_attr = get_attr;
-                gv->set_attr = set_attr;
-                gv->next = v->vars;
-            }
-        }
-        v->vars = gv;
-    }
-    
-    /* -----------------------------------------------------------------------------
-     * constants/methods manipulation
-     * ----------------------------------------------------------------------------- */
-    
-    /* Install Constants */
-    SWIGINTERN void
-    SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) {
-        PyObject *obj = 0;
-        size_t i;
-        for (i = 0; constants[i].type; ++i) {
-            switch(constants[i].type) {
-                case SWIG_PY_INT:
-                obj = PyInt_FromLong(constants[i].lvalue);
-                break;
-                case SWIG_PY_FLOAT:
-                obj = PyFloat_FromDouble(constants[i].dvalue);
-                break;
-                case SWIG_PY_STRING:
-                if (constants[i].pvalue) {
-                    obj = PyString_FromString((char *) constants[i].pvalue);
-                } else {
-                    Py_INCREF(Py_None);
-                    obj = Py_None;
-                }
-                break;
-                case SWIG_PY_POINTER:
-                obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);
-                break;
-                case SWIG_PY_BINARY:
-                obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));
-                break;
-                default:
-                obj = 0;
-                break;
-            }
-            if (obj) {
-                PyDict_SetItemString(d,constants[i].name,obj);
-                Py_DECREF(obj);
-            }
-        }
-    }
-    
-    /* -----------------------------------------------------------------------------*/
-    /* Fix SwigMethods to carry the callback ptrs when needed */
-    /* -----------------------------------------------------------------------------*/
-    
-    SWIGINTERN void
-    SWIG_Python_FixMethods(PyMethodDef *methods,
-    swig_const_info *const_table,
-    swig_type_info **types,
-    swig_type_info **types_initial) {
-        size_t i;
-        for (i = 0; methods[i].ml_name; ++i) {
-            char *c = methods[i].ml_doc;
-            if (c && (c = strstr(c, "swig_ptr: "))) {
-                int j;
-                swig_const_info *ci = 0;
-                char *name = c + 10;
-                for (j = 0; const_table[j].type; ++j) {
-                    if (strncmp(const_table[j].name, name, 
-                    strlen(const_table[j].name)) == 0) {
-                        ci = &(const_table[j]);
-                        break;
-                    }
-                }
-                if (ci) {
-                    size_t shift = (ci->ptype) - types;
-                    swig_type_info *ty = types_initial[shift];
-                    size_t ldoc = (c - methods[i].ml_doc);
-                    size_t lptr = strlen(ty->name)+2*sizeof(void*)+2;
-                    char *ndoc = (char*)malloc(ldoc + lptr + 10);
-                    if (ndoc) {
-                        char *buff = ndoc;
-                        void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0;
-                        if (ptr) {
-                            strncpy(buff, methods[i].ml_doc, ldoc);
-                            buff += ldoc;
-                            strncpy(buff, "swig_ptr: ", 10);
-                            buff += 10;
-                            SWIG_PackVoidPtr(buff, ptr, ty->name, lptr);
-                            methods[i].ml_doc = ndoc;
-                        }
-                    }
-                }
-            }
-        }
-    }
-    
-    /* -----------------------------------------------------------------------------*
-     *  Initialize type list
-     * -----------------------------------------------------------------------------*/
-    
+			varlink_type = tmp;
+			type_init = 1;
+		}
+#endif
+		return &varlink_type;
+	}
+
+	/* Create a variable linking object for use later */
+	SWIGINTERN PyObject *SWIG_Python_newvarlink(void) {
+		swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type());
+		if (result) {
+			result->vars = 0;
+		}
+		return ((PyObject *) result);
+	}
+
+	SWIGINTERN void SWIG_Python_addvarlink(PyObject * p, char *name, PyObject * (*get_attr) (void), int (*set_attr) (PyObject * p)) {
+		swig_varlinkobject *v = (swig_varlinkobject *) p;
+		swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));
+		if (gv) {
+			size_t size = strlen(name) + 1;
+			gv->name = (char *) malloc(size);
+			if (gv->name) {
+				strncpy(gv->name, name, size);
+				gv->get_attr = get_attr;
+				gv->set_attr = set_attr;
+				gv->next = v->vars;
+			}
+		}
+		v->vars = gv;
+	}
+
+	/* -----------------------------------------------------------------------------
+	 * constants/methods manipulation
+	 * ----------------------------------------------------------------------------- */
+
+	/* Install Constants */
+	SWIGINTERN void SWIG_Python_InstallConstants(PyObject * d, swig_const_info constants[]) {
+		PyObject *obj = 0;
+		size_t i;
+		for (i = 0; constants[i].type; ++i) {
+			switch (constants[i].type) {
+			case SWIG_PY_INT:
+				obj = PyInt_FromLong(constants[i].lvalue);
+				break;
+			case SWIG_PY_FLOAT:
+				obj = PyFloat_FromDouble(constants[i].dvalue);
+				break;
+			case SWIG_PY_STRING:
+				if (constants[i].pvalue) {
+					obj = PyString_FromString((char *) constants[i].pvalue);
+				} else {
+					Py_INCREF(Py_None);
+					obj = Py_None;
+				}
+				break;
+			case SWIG_PY_POINTER:
+				obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype, 0);
+				break;
+			case SWIG_PY_BINARY:
+				obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));
+				break;
+			default:
+				obj = 0;
+				break;
+			}
+			if (obj) {
+				PyDict_SetItemString(d, constants[i].name, obj);
+				Py_DECREF(obj);
+			}
+		}
+	}
+
+	/* ----------------------------------------------------------------------------- */
+	/* Fix SwigMethods to carry the callback ptrs when needed */
+	/* ----------------------------------------------------------------------------- */
+
+	SWIGINTERN void SWIG_Python_FixMethods(PyMethodDef * methods, swig_const_info * const_table, swig_type_info ** types, swig_type_info ** types_initial) {
+		size_t i;
+		for (i = 0; methods[i].ml_name; ++i) {
+			char *c = methods[i].ml_doc;
+			if (c && (c = strstr(c, "swig_ptr: "))) {
+				int j;
+				swig_const_info *ci = 0;
+				char *name = c + 10;
+				for (j = 0; const_table[j].type; ++j) {
+					if (strncmp(const_table[j].name, name, strlen(const_table[j].name)) == 0) {
+						ci = &(const_table[j]);
+						break;
+					}
+				}
+				if (ci) {
+					size_t shift = (ci->ptype) - types;
+					swig_type_info *ty = types_initial[shift];
+					size_t ldoc = (c - methods[i].ml_doc);
+					size_t lptr = strlen(ty->name) + 2 * sizeof(void *) + 2;
+					char *ndoc = (char *) malloc(ldoc + lptr + 10);
+					if (ndoc) {
+						char *buff = ndoc;
+						void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0;
+						if (ptr) {
+							strncpy(buff, methods[i].ml_doc, ldoc);
+							buff += ldoc;
+							strncpy(buff, "swig_ptr: ", 10);
+							buff += 10;
+							SWIG_PackVoidPtr(buff, ptr, ty->name, lptr);
+							methods[i].ml_doc = ndoc;
+						}
+					}
+				}
+			}
+		}
+	}
+
+	/* -----------------------------------------------------------------------------*
+	 *  Initialize type list
+	 * -----------------------------------------------------------------------------*/
+
 #ifdef __cplusplus
 }
 #endif
@@ -2885,49 +2901,50 @@
 #ifdef __cplusplus
 extern "C"
 #endif
-SWIGEXPORT void SWIG_init(void) {
-    static PyObject *SWIG_globals = 0; 
-    PyObject *m, *d;
-    if (!SWIG_globals) SWIG_globals = SWIG_newvarlink();
-    
-    /* Fix SwigMethods to carry the callback ptrs when needed */
-    SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial);
-    
-    m = Py_InitModule((char *) SWIG_name, SwigMethods);
-    d = PyModule_GetDict(m);
-    
-    SWIG_InitializeModule(0);
-    SWIG_InstallConstants(d,swig_const_table);
-    
-    {
-        PyDict_SetItemString(d,"CS_NEW", SWIG_From_int((int)(CS_NEW))); 
-    }
-    {
-        PyDict_SetItemString(d,"CS_INIT", SWIG_From_int((int)(CS_INIT))); 
-    }
-    {
-        PyDict_SetItemString(d,"CS_RING", SWIG_From_int((int)(CS_RING))); 
-    }
-    {
-        PyDict_SetItemString(d,"CS_TRANSMIT", SWIG_From_int((int)(CS_TRANSMIT))); 
-    }
-    {
-        PyDict_SetItemString(d,"CS_EXECUTE", SWIG_From_int((int)(CS_EXECUTE))); 
-    }
-    {
-        PyDict_SetItemString(d,"CS_LOOPBACK", SWIG_From_int((int)(CS_LOOPBACK))); 
-    }
-    {
-        PyDict_SetItemString(d,"CS_HOLD", SWIG_From_int((int)(CS_HOLD))); 
-    }
-    {
-        PyDict_SetItemString(d,"CS_HIBERNATE", SWIG_From_int((int)(CS_HIBERNATE))); 
-    }
-    {
-        PyDict_SetItemString(d,"CS_HANGUP", SWIG_From_int((int)(CS_HANGUP))); 
-    }
-    {
-        PyDict_SetItemString(d,"CS_DONE", SWIG_From_int((int)(CS_DONE))); 
-    }
-}
+       SWIGEXPORT void SWIG_init(void)
+{
+	static PyObject *SWIG_globals = 0;
+	PyObject *m, *d;
+	if (!SWIG_globals)
+		SWIG_globals = SWIG_newvarlink();
+
+	/* Fix SwigMethods to carry the callback ptrs when needed */
+	SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial);
 
+	m = Py_InitModule((char *) SWIG_name, SwigMethods);
+	d = PyModule_GetDict(m);
+
+	SWIG_InitializeModule(0);
+	SWIG_InstallConstants(d, swig_const_table);
+
+	{
+		PyDict_SetItemString(d, "CS_NEW", SWIG_From_int((int) (CS_NEW)));
+	}
+	{
+		PyDict_SetItemString(d, "CS_INIT", SWIG_From_int((int) (CS_INIT)));
+	}
+	{
+		PyDict_SetItemString(d, "CS_RING", SWIG_From_int((int) (CS_RING)));
+	}
+	{
+		PyDict_SetItemString(d, "CS_TRANSMIT", SWIG_From_int((int) (CS_TRANSMIT)));
+	}
+	{
+		PyDict_SetItemString(d, "CS_EXECUTE", SWIG_From_int((int) (CS_EXECUTE)));
+	}
+	{
+		PyDict_SetItemString(d, "CS_LOOPBACK", SWIG_From_int((int) (CS_LOOPBACK)));
+	}
+	{
+		PyDict_SetItemString(d, "CS_HOLD", SWIG_From_int((int) (CS_HOLD)));
+	}
+	{
+		PyDict_SetItemString(d, "CS_HIBERNATE", SWIG_From_int((int) (CS_HIBERNATE)));
+	}
+	{
+		PyDict_SetItemString(d, "CS_HANGUP", SWIG_From_int((int) (CS_HANGUP)));
+	}
+	{
+		PyDict_SetItemString(d, "CS_DONE", SWIG_From_int((int) (CS_DONE)));
+	}
+}

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,18 +1,14 @@
-include sm.mak
+WANT_CURL=yes
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+LOCAL_CFLAGS=
+LOCAL_LDFLAGS=
+LOCAL_LIBADD=
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install js/nsprpub --prefix=$(PREFIX) --with-pic
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install js --prefix=$(PREFIX) --with-pic --with-nspr=yes
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install curl --prefix=$(PREFIX) --without-libidn
+include sm.mak
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(OBJS) $(LDFLAGS)
+depend_install: $(DESTDIR)$(PREFIX)/lib/libjs.la
 
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+$(DESTDIR)$(PREFIX)/lib/libjs.la: $(JSLA)
+	cd $(JS_DIR)/nsprpub/ && $(MAKE) install
+	cd $(JS_DIR) && $(MAKE) install
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/mod_spidermonkey.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/mod_spidermonkey.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/mod_spidermonkey.c	Tue Apr 24 10:14:28 2007
@@ -41,8 +41,9 @@
 static const char modname[] = "mod_spidermonkey";
 
 
-static void session_destroy(JSContext *cx, JSObject *obj);
-static JSBool session_construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
+static void session_destroy(JSContext * cx, JSObject * obj);
+static JSBool session_construct(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval);
+static JSBool session_originate(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval);
 static switch_api_interface_t js_run_interface;
 
 static struct {
@@ -58,16 +59,16 @@
 
 
 static JSClass global_class = {
-	"Global", JSCLASS_HAS_PRIVATE, 
-	JS_PropertyStub,  JS_PropertyStub,	JS_PropertyStub,  JS_PropertyStub, 
-	JS_EnumerateStub, JS_ResolveStub,	JS_ConvertStub,	  JS_FinalizeStub
+	"Global", JSCLASS_HAS_PRIVATE,
+	JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
+	JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub
 };
 
 
 static struct {
 	switch_hash_t *mod_hash;
 	switch_hash_t *load_hash;
-    switch_memory_pool_t *pool;
+	switch_memory_pool_t *pool;
 } module_manager;
 
 struct sm_loadable_module {
@@ -79,7 +80,9 @@
 typedef struct sm_loadable_module sm_loadable_module_t;
 
 typedef enum {
-	S_HUP = (1 << 0)
+	S_HUP = (1 << 0),
+	S_FREE = (1 << 1),
+	S_RDLOCK = (1 << 2)
 } session_flag_t;
 
 struct input_callback_state {
@@ -94,7 +97,7 @@
 	jsval ret;
 	JSContext *cx;
 	JSObject *obj;
-    jsrefcount saveDepth;
+	jsrefcount saveDepth;
 	void *extra;
 };
 
@@ -115,7 +118,7 @@
 
 /* Event Object */
 /*********************************************************************************/
-static JSBool event_construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool event_construct(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	if (argc > 0) {
 		switch_event_t *event;
@@ -126,26 +129,27 @@
 		if ((eo = malloc(sizeof(*eo)))) {
 
 			if (switch_name_event(ename, &etype) != SWITCH_STATUS_SUCCESS) {
-				*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Unknown event %s\n", ename);
+				*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 				return JS_TRUE;
 			}
 
 			if (etype == SWITCH_EVENT_CUSTOM) {
 				char *subclass_name;
 				if (argc < 1) {
-					*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+					*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 					return JS_TRUE;
 				}
-				
+
 				subclass_name = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
 				if (switch_event_create_subclass(&event, etype, subclass_name) != SWITCH_STATUS_SUCCESS) {
-					*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+					*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 					return JS_TRUE;
 				}
 
 			} else {
-				if (!switch_event_create(&event, etype) != SWITCH_STATUS_SUCCESS) {
-					*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+				if (switch_event_create(&event, etype) != SWITCH_STATUS_SUCCESS) {
+					*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 					return JS_TRUE;
 				}
 			}
@@ -161,7 +165,7 @@
 	return JS_FALSE;
 }
 
-static void event_destroy(JSContext *cx, JSObject *obj)
+static void event_destroy(JSContext * cx, JSObject * obj)
 {
 	struct event_obj *eo = JS_GetPrivate(cx, obj);
 
@@ -173,12 +177,12 @@
 	}
 }
 
-static JSBool event_add_header(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool event_add_header(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct event_obj *eo = JS_GetPrivate(cx, obj);
 
 	if (!eo || eo->freed) {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
 
@@ -186,90 +190,90 @@
 		char *hname = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		char *hval = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
 		switch_event_add_header(eo->event, SWITCH_STACK_BOTTOM, hname, "%s", hval);
-		*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+		*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 		return JS_TRUE;
 	}
 
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 	return JS_TRUE;
 }
 
-static JSBool event_get_header(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool event_get_header(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct event_obj *eo = JS_GetPrivate(cx, obj);
 
 	if (!eo) {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
 
 	if (argc > 0) {
 		char *hname = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		char *val = switch_event_get_header(eo->event, hname);
-		*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, val));
+		*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, val));
 		return JS_TRUE;
 	}
 
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 	return JS_TRUE;
 }
 
-static JSBool event_add_body(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool event_add_body(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct event_obj *eo = JS_GetPrivate(cx, obj);
 
 	if (!eo || eo->freed) {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
 
 	if (argc > 0) {
 		char *body = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		switch_event_add_body(eo->event, "%s", body);
-		*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+		*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 		return JS_TRUE;
 	}
 
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 	return JS_TRUE;
 }
 
-static JSBool event_get_body(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool event_get_body(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct event_obj *eo = JS_GetPrivate(cx, obj);
 
 	if (!eo) {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
 
-	*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, switch_event_get_body(eo->event)));
+	*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, switch_event_get_body(eo->event)));
 
 	return JS_TRUE;
 }
 
-static JSBool event_get_type(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool event_get_type(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct event_obj *eo = JS_GetPrivate(cx, obj);
 
 	if (!eo) {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
 
-	*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, switch_event_name(eo->event->event_id)));
-	
+	*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, switch_event_name(eo->event->event_id)));
+
 	return JS_TRUE;
 }
 
-static JSBool event_serialize(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool event_serialize(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct event_obj *eo = JS_GetPrivate(cx, obj);
 	char *buf;
 	uint8_t isxml = 0;
 
 	if (!eo) {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
 
@@ -283,17 +287,17 @@
 	if (isxml) {
 		switch_xml_t xml;
 		char *xmlstr;
-		if ((xml = switch_event_xmlize(eo->event, NULL))) {
-            xmlstr = switch_xml_toxml(xml);
-			*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, xmlstr));
+		if ((xml = switch_event_xmlize(eo->event, SWITCH_VA_NONE))) {
+			xmlstr = switch_xml_toxml(xml);
+			*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, xmlstr));
 			switch_xml_free(xml);
-            free(xmlstr);
+			free(xmlstr);
 		} else {
-			*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+			*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		}
 	} else {
 		if (switch_event_serialize(eo->event, &buf) == SWITCH_STATUS_SUCCESS) {
-			*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, buf));
+			*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, buf));
 			switch_safe_free(buf);
 		}
 	}
@@ -301,7 +305,7 @@
 	return JS_TRUE;
 }
 
-static JSBool event_fire(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool event_fire(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct event_obj *eo = JS_GetPrivate(cx, obj);
 
@@ -309,29 +313,29 @@
 		switch_event_fire(&eo->event);
 		JS_SetPrivate(cx, obj, NULL);
 		switch_safe_free(eo);
-		*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+		*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 		return JS_TRUE;
 	}
 
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 	return JS_TRUE;
 }
 
-static JSBool event_destroy_(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool event_destroy_(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct event_obj *eo = JS_GetPrivate(cx, obj);
-	
+
 	if (eo) {
 		if (!eo->freed) {
 			switch_event_destroy(&eo->event);
 		}
 		JS_SetPrivate(cx, obj, NULL);
 		switch_safe_free(eo);
-		*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+		*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 		return JS_TRUE;
 	}
 
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 	return JS_TRUE;
 }
 
@@ -355,35 +359,35 @@
 
 
 static JSPropertySpec event_props[] = {
-	{"ready", EVENT_READY, JSPROP_READONLY|JSPROP_PERMANENT}, 
+	{"ready", EVENT_READY, JSPROP_READONLY | JSPROP_PERMANENT},
 	{0}
 };
 
 
-static JSBool event_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
+static JSBool event_getProperty(JSContext * cx, JSObject * obj, jsval id, jsval * vp)
 {
 	JSBool res = JS_TRUE;
 	switch_event_t *event = JS_GetPrivate(cx, obj);
 	char *name;
 	int param = 0;
 
-    if (!event) {
-        *vp = BOOLEAN_TO_JSVAL( JS_FALSE );
+	if (!event) {
+		*vp = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
-    }
+	}
+
 
-	
 	name = JS_GetStringBytes(JS_ValueToString(cx, id));
-    /* numbers are our props anything else is a method */
-    if (name[0] >= 48 && name[0] <= 57) {
-        param = atoi(name);
-    } else {
-        return JS_TRUE;
-    }
-	
-	switch(param) {
+	/* numbers are our props anything else is a method */
+	if (name[0] >= 48 && name[0] <= 57) {
+		param = atoi(name);
+	} else {
+		return JS_TRUE;
+	}
+
+	switch (param) {
 	case EVENT_READY:
-		*vp = BOOLEAN_TO_JSVAL( JS_TRUE );
+		*vp = BOOLEAN_TO_JSVAL(JS_TRUE);
 		break;
 	}
 
@@ -391,46 +395,38 @@
 }
 
 JSClass event_class = {
-	"Event", JSCLASS_HAS_PRIVATE, 
-	JS_PropertyStub,  JS_PropertyStub,	event_getProperty,  JS_PropertyStub, 
-	JS_EnumerateStub, JS_ResolveStub,	JS_ConvertStub,	  event_destroy, NULL, NULL, NULL,
+	"Event", JSCLASS_HAS_PRIVATE,
+	JS_PropertyStub, JS_PropertyStub, event_getProperty, JS_PropertyStub,
+	JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, event_destroy, NULL, NULL, NULL,
 	event_construct
 };
 
 
 
 
-static void js_error(JSContext *cx, const char *message, JSErrorReport *report)
+static void js_error(JSContext * cx, const char *message, JSErrorReport * report)
 {
-    const char *filename = __FILE__;
-    int line = __LINE__;
-    const char *text = "";
-    char *ex = "";
-    
+	const char *filename = __FILE__;
+	int line = __LINE__;
+	const char *text = "";
+	char *ex = "";
+
 	if (message && report) {
-        if (report->filename) {
-            filename = report->filename;
-        }
-        line = report->lineno;
-        if (report->linebuf) {
-            text = report->linebuf;
-            ex = "near ";
-        }
-	}
-    
-    if (!message) {
-        message = "(N/A)";
-    }
-    
-    switch_log_printf(SWITCH_CHANNEL_ID_LOG, 
-                      filename,
-                      modname,
-                      line,
-                      SWITCH_LOG_ERROR,
-                      "%s %s%s\n",
-                      ex,
-                      message,
-                      text);
+		if (report->filename) {
+			filename = report->filename;
+		}
+		line = report->lineno;
+		if (report->linebuf) {
+			text = report->linebuf;
+			ex = "near ";
+		}
+	}
+
+	if (!message) {
+		message = "(N/A)";
+	}
+
+	switch_log_printf(SWITCH_CHANNEL_ID_LOG, filename, modname, line, SWITCH_LOG_ERROR, "%s %s%s\n", ex, message, text);
 
 }
 
@@ -438,9 +434,9 @@
 static switch_status_t sm_load_file(char *filename)
 {
 	sm_loadable_module_t *module = NULL;
-	apr_dso_handle_t *dso = NULL;
-	apr_status_t status = SWITCH_STATUS_SUCCESS;
-	apr_dso_handle_sym_t function_handle = NULL;
+	switch_dso_handle_t *dso = NULL;
+	switch_status_t status = SWITCH_STATUS_SUCCESS;
+	switch_dso_handle_sym_t function_handle = NULL;
 	spidermonkey_init_t spidermonkey_init = NULL;
 	const sm_module_interface_t *module_interface = NULL, *mp;
 
@@ -450,23 +446,23 @@
 
 	assert(filename != NULL);
 
-	status = apr_dso_load(&dso, filename, module_manager.pool);
+	status = switch_dso_load(&dso, filename, module_manager.pool);
 
 	while (loading) {
-		if (status != APR_SUCCESS) {
-			apr_dso_error(dso, derr, sizeof(derr));
+		if (status != SWITCH_STATUS_SUCCESS) {
+			switch_dso_error(dso, derr, sizeof(derr));
 			err = derr;
 			break;
 		}
 
-		status = apr_dso_sym(&function_handle, dso, "spidermonkey_init");
-		spidermonkey_init = (spidermonkey_init_t)(intptr_t) function_handle;
-			
+		status = switch_dso_sym(&function_handle, dso, "spidermonkey_init");
+		spidermonkey_init = (spidermonkey_init_t) (intptr_t) function_handle;
+
 		if (spidermonkey_init == NULL) {
 			err = "Cannot Load";
 			break;
 		}
-		
+
 		if (spidermonkey_init(&module_interface) != SWITCH_STATUS_SUCCESS) {
 			err = "Module load routine returned an error";
 			break;
@@ -488,17 +484,17 @@
 	module->filename = switch_core_permanent_strdup(filename);
 	module->spidermonkey_init = spidermonkey_init;
 	module->module_interface = module_interface;
-	
+
 	module->lib = dso;
 
 	switch_core_hash_insert(module_manager.mod_hash, (char *) module->filename, (void *) module);
-	
+
 	for (mp = module->module_interface; mp; mp = mp->next) {
-		switch_core_hash_insert(module_manager.load_hash, (char *)mp->name, (void *) mp);
+		switch_core_hash_insert(module_manager.load_hash, (char *) mp->name, (void *) mp);
 	}
-	
+
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Successfully Loaded [%s]\n", module->filename);
-	
+
 	return SWITCH_STATUS_SUCCESS;
 
 }
@@ -539,7 +535,7 @@
 			snprintf(path, len, "%s%s%s%s", dir, SWITCH_PATH_SEPARATOR, file, ext);
 		}
 	}
-	
+
 	return sm_load_file(path);
 }
 
@@ -581,7 +577,7 @@
 			}
 		}
 		switch_xml_free(xml);
-		
+
 	} else {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "open of %s failed\n", cf);
 	}
@@ -596,14 +592,14 @@
 	globals.gErrFile = NULL;
 	globals.gOutFile = NULL;
 	globals.gStackChunkSize = 8192;
-	globals.gStackBase = (jsuword)&globals.stackDummy;
+	globals.gStackBase = (jsuword) & globals.stackDummy;
 	globals.gErrFile = stderr;
 	globals.gOutFile = stdout;
 
 	if (!(globals.rt = JS_NewRuntime(64L * 1024L * 1024L))) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	if (load_modules() != SWITCH_STATUS_SUCCESS) {
 		return SWITCH_STATUS_FALSE;
 	}
@@ -611,7 +607,7 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-JSObject *new_js_event(switch_event_t *event, char *name, JSContext *cx, JSObject *obj)
+JSObject *new_js_event(switch_event_t *event, char *name, JSContext * cx, JSObject * obj)
 {
 	struct event_obj *eo;
 	JSObject *Event = NULL;
@@ -620,9 +616,7 @@
 		eo->event = event;
 		eo->freed = 1;
 		if ((Event = JS_DefineObject(cx, obj, name, &event_class, NULL, 0))) {
-			if ((JS_SetPrivate(cx, Event, eo) &&
-				 JS_DefineProperties(cx, Event, event_props) &&
-				 JS_DefineFunctions(cx, Event, event_methods))) {
+			if ((JS_SetPrivate(cx, Event, eo) && JS_DefineProperties(cx, Event, event_props) && JS_DefineFunctions(cx, Event, event_methods))) {
 			}
 		}
 	}
@@ -640,7 +634,8 @@
 	jsval argv[4];
 	JSObject *Event = NULL;
 
-	if (!jss) {
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
 		return SWITCH_STATUS_FALSE;
 	}
 
@@ -648,7 +643,7 @@
 	case SWITCH_INPUT_TYPE_EVENT:
 		if ((event = (switch_event_t *) input)) {
 			if ((Event = new_js_event(event, "_XX_EVENT_XX_", cb_state->cx, cb_state->obj))) {
-				argv[argc++] = STRING_TO_JSVAL (JS_NewStringCopyZ(cb_state->cx, "event"));
+				argv[argc++] = STRING_TO_JSVAL(JS_NewStringCopyZ(cb_state->cx, "event"));
 				argv[argc++] = OBJECT_TO_JSVAL(Event);
 			}
 		}
@@ -656,10 +651,10 @@
 			return SWITCH_STATUS_FALSE;
 		}
 		break;
-	case SWITCH_INPUT_TYPE_DTMF: 
+	case SWITCH_INPUT_TYPE_DTMF:
 		dtmf = (char *) input;
-		argv[argc++] = STRING_TO_JSVAL (JS_NewStringCopyZ(cb_state->cx, "dtmf"));
-		argv[argc++] = STRING_TO_JSVAL (JS_NewStringCopyZ(cb_state->cx, dtmf));
+		argv[argc++] = STRING_TO_JSVAL(JS_NewStringCopyZ(cb_state->cx, "dtmf"));
+		argv[argc++] = STRING_TO_JSVAL(JS_NewStringCopyZ(cb_state->cx, dtmf));
 		break;
 	}
 
@@ -667,9 +662,9 @@
 		argv[argc++] = cb_state->arg;
 	}
 
-    JS_ResumeRequest(cb_state->cx, cb_state->saveDepth);
+	JS_ResumeRequest(cb_state->cx, cb_state->saveDepth);
 	JS_CallFunction(cb_state->cx, cb_state->obj, cb_state->function, argc, argv, &cb_state->ret);
-    cb_state->saveDepth = JS_SuspendRequest(cb_state->cx);
+	cb_state->saveDepth = JS_SuspendRequest(cb_state->cx);
 
 	return SWITCH_STATUS_SUCCESS;
 }
@@ -690,7 +685,7 @@
 	if ((ret = JS_GetStringBytes(JS_ValueToString(cb_state->cx, cb_state->ret)))) {
 		if (!strncasecmp(ret, "speed", 4)) {
 			char *p;
-			
+
 			if ((p = strchr(ret, ':'))) {
 				p++;
 				if (*p == '+' || *p == '-') {
@@ -705,7 +700,7 @@
 				}
 				return SWITCH_STATUS_SUCCESS;
 			}
-			
+
 			return SWITCH_STATUS_FALSE;
 		} else if (!strcasecmp(ret, "pause")) {
 			if (switch_test_flag(fh, SWITCH_FILE_PAUSE)) {
@@ -735,7 +730,7 @@
 					}
 					if (step > 0) {
 						samps = step * (codec->implementation->samples_per_second / 1000);
-						switch_core_file_seek(fh, &pos, samps, SEEK_CUR);		
+						switch_core_file_seek(fh, &pos, samps, SEEK_CUR);
 					} else {
 						samps = step * (codec->implementation->samples_per_second / 1000);
 						switch_core_file_seek(fh, &pos, fh->pos - samps, SEEK_SET);
@@ -750,8 +745,8 @@
 		}
 
 		if (!strcmp(ret, "true") || !strcmp(ret, "undefined")) {
-            return SWITCH_STATUS_SUCCESS;
-        }
+			return SWITCH_STATUS_SUCCESS;
+		}
 
 		return SWITCH_STATUS_BREAK;
 
@@ -769,7 +764,7 @@
 	if ((status = js_common_callback(session, input, itype, buf, buflen)) != SWITCH_STATUS_SUCCESS) {
 		return status;
 	}
-	
+
 	if ((ret = JS_GetStringBytes(JS_ValueToString(cb_state->cx, cb_state->ret)))) {
 		if (!strcasecmp(ret, "pause")) {
 			if (switch_test_flag(fh, SWITCH_FILE_PAUSE)) {
@@ -786,8 +781,8 @@
 		}
 
 		if (!strcmp(ret, "true") || !strcmp(ret, "undefined")) {
-            return SWITCH_STATUS_SUCCESS;
-        }
+			return SWITCH_STATUS_SUCCESS;
+		}
 
 		return SWITCH_STATUS_BREAK;
 
@@ -815,55 +810,55 @@
 	return SWITCH_STATUS_BREAK;
 }
 
-static JSBool session_flush_digits(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_flush_digits(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	char buf[256];
 	switch_size_t has;
 	switch_channel_t *channel;
 
-	channel = switch_core_session_get_channel(jss->session);
-    assert(channel != NULL);
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	channel = switch_core_session_get_channel(jss->session);
+	assert(channel != NULL);
 
 	while ((has = switch_channel_has_dtmf(channel))) {
 		switch_channel_dequeue_dtmf(channel, buf, sizeof(buf));
 	}
 
-	*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
-    return JS_TRUE;
+	*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
+	return JS_TRUE;
 }
 
-static JSBool session_flush_events(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_flush_events(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_event_t *event;
-    switch_channel_t *channel;
+	switch_channel_t *channel;
+
+	if (!jss || !jss->session) {
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
-    channel = switch_core_session_get_channel(jss->session);
-    assert(channel != NULL);
+	channel = switch_core_session_get_channel(jss->session);
+	assert(channel != NULL);
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
 
 	while (switch_core_session_dequeue_event(jss->session, &event) == SWITCH_STATUS_SUCCESS) {
 		switch_event_destroy(&event);
 	}
-	
-	*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
-    return JS_TRUE;
-	
+
+	*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
+	return JS_TRUE;
+
 }
 
-static JSBool session_recordfile(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_recordfile(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
@@ -871,22 +866,28 @@
 	void *bp = NULL;
 	int len = 0;
 	switch_input_callback_function_t dtmf_func = NULL;
-	struct input_callback_state cb_state = {0};
-	switch_file_handle_t fh = {0};
+	struct input_callback_state cb_state = { 0 };
+	switch_file_handle_t fh = { 0 };
 	JSFunction *function;
-    int32 limit = 0;
-    switch_input_args_t args = {0};
+	int32 limit = 0;
+	switch_input_args_t args = { 0 };
+
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!switch_channel_ready(channel)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 
-	
 	if (argc > 0) {
 		file_name = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		if (switch_strlen_zero(file_name)) {
@@ -899,49 +900,49 @@
 			cb_state.session_state = jss;
 			cb_state.function = function;
 			cb_state.cx = cx;
-            cb_state.obj = obj;
+			cb_state.obj = obj;
 			if (argc > 2) {
-                cb_state.arg = argv[2];
-            }
+				cb_state.arg = argv[2];
+			}
 
 			dtmf_func = js_record_input_callback;
 			bp = &cb_state;
 			len = sizeof(cb_state);
 		}
 
-        if (argc > 3) {
-            JS_ValueToInt32(cx, argv[3], &limit);
-        }
-
-        if (argc > 4) {
-            int32 thresh;
-            JS_ValueToInt32(cx, argv[4], &thresh);
-            fh.thresh = thresh;
-        }
-
-        if (argc > 5) {
-            int32 silence_hits;
-            JS_ValueToInt32(cx, argv[5], &silence_hits);
-            fh.silence_hits = silence_hits;
-        }
+		if (argc > 3) {
+			JS_ValueToInt32(cx, argv[3], &limit);
+		}
+
+		if (argc > 4) {
+			int32 thresh;
+			JS_ValueToInt32(cx, argv[4], &thresh);
+			fh.thresh = thresh;
+		}
+
+		if (argc > 5) {
+			int32 silence_hits;
+			JS_ValueToInt32(cx, argv[5], &silence_hits);
+			fh.silence_hits = silence_hits;
+		}
 	}
 
-    
+
 	cb_state.extra = &fh;
-	cb_state.ret = BOOLEAN_TO_JSVAL( JS_FALSE );
-    cb_state.saveDepth = JS_SuspendRequest(cx);
-    args.input_callback = dtmf_func;
-    args.buf = bp;
-    args.buflen = len;
+	cb_state.ret = BOOLEAN_TO_JSVAL(JS_FALSE);
+	cb_state.saveDepth = JS_SuspendRequest(cx);
+	args.input_callback = dtmf_func;
+	args.buf = bp;
+	args.buflen = len;
 	switch_ivr_record_file(jss->session, &fh, file_name, &args, limit);
-    JS_ResumeRequest(cx, cb_state.saveDepth);
+	JS_ResumeRequest(cx, cb_state.saveDepth);
 	*rval = cb_state.ret;
 
 	return JS_TRUE;
 }
 
 
-static JSBool session_collect_input(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_collect_input(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
@@ -949,32 +950,39 @@
 	int len = 0;
 	int32 to = 0;
 	switch_input_callback_function_t dtmf_func = NULL;
-	struct input_callback_state cb_state = {0};
+	struct input_callback_state cb_state = { 0 };
 	JSFunction *function;
-    switch_input_args_t args = {0};
+	switch_input_args_t args = { 0 };
+
+
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!switch_channel_ready(channel)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 
-	
 	if (argc > 0) {
 		if ((function = JS_ValueToFunction(cx, argv[0]))) {
 			memset(&cb_state, 0, sizeof(cb_state));
 			cb_state.function = function;
 
 			if (argc > 1) {
-                cb_state.arg = argv[1];
-            }
-			
+				cb_state.arg = argv[1];
+			}
+
 			cb_state.session_state = jss;
 			cb_state.cx = cx;
-            cb_state.obj = obj;
+			cb_state.obj = obj;
 			dtmf_func = js_collect_input_callback;
 			bp = &cb_state;
 			len = sizeof(cb_state);
@@ -985,12 +993,12 @@
 		JS_ValueToInt32(jss->cx, argv[2], &to);
 	}
 
-    cb_state.saveDepth = JS_SuspendRequest(cx);
-    args.input_callback = dtmf_func;
-    args.buf = bp;
-    args.buflen = len;
+	cb_state.saveDepth = JS_SuspendRequest(cx);
+	args.input_callback = dtmf_func;
+	args.buf = bp;
+	args.buflen = len;
 	switch_ivr_collect_digits_callback(jss->session, &args, to);
-    JS_ResumeRequest(cx, cb_state.saveDepth);
+	JS_ResumeRequest(cx, cb_state.saveDepth);
 
 	*rval = cb_state.ret;
 
@@ -999,31 +1007,37 @@
 
 /* session.sayphrase(phrase_name, phrase_data, language, dtmf_callback, dtmf_callback_args)*/
 
-static JSBool session_sayphrase(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_sayphrase(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
 	char *phrase_name = NULL;
-    char *phrase_data = NULL;
-    char *phrase_lang = NULL;
+	char *phrase_data = NULL;
+	char *phrase_lang = NULL;
 	//char *input_callback = NULL;
 	void *bp = NULL;
 	int len = 0;
 	switch_input_callback_function_t dtmf_func = NULL;
-	struct input_callback_state cb_state = {0};
+	struct input_callback_state cb_state = { 0 };
 	JSFunction *function;
-    switch_input_args_t args = {0};
+	switch_input_args_t args = { 0 };
+
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!switch_channel_ready(channel)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 
-	
 	if (argc > 0) {
 		phrase_name = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		if (switch_strlen_zero(phrase_name)) {
@@ -1034,13 +1048,13 @@
 	}
 
 
-    if (argc > 1) {
-        phrase_data = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
-    }
-
-    if (argc > 2) {
-        phrase_lang = JS_GetStringBytes(JS_ValueToString(cx, argv[2]));
-    }
+	if (argc > 1) {
+		phrase_data = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
+	}
+
+	if (argc > 2) {
+		phrase_lang = JS_GetStringBytes(JS_ValueToString(cx, argv[2]));
+	}
 
 	if (argc > 3) {
 		if ((function = JS_ValueToFunction(cx, argv[3]))) {
@@ -1060,21 +1074,83 @@
 		}
 	}
 
-	cb_state.ret = BOOLEAN_TO_JSVAL( JS_FALSE );
-    cb_state.saveDepth = JS_SuspendRequest(cx);
-    args.input_callback = dtmf_func;
-    args.buf = bp;
-    args.buflen = len;
+	cb_state.ret = BOOLEAN_TO_JSVAL(JS_FALSE);
+	cb_state.saveDepth = JS_SuspendRequest(cx);
+	args.input_callback = dtmf_func;
+	args.buf = bp;
+	args.buflen = len;
 
-    switch_ivr_phrase_macro(jss->session, phrase_name, phrase_data, phrase_lang, &args);
+	switch_ivr_phrase_macro(jss->session, phrase_name, phrase_data, phrase_lang, &args);
 
-    JS_ResumeRequest(cx, cb_state.saveDepth);
+	JS_ResumeRequest(cx, cb_state.saveDepth);
 	*rval = cb_state.ret;
-	
+
 	return JS_TRUE;
 }
 
-static JSBool session_streamfile(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static void check_hangup_hook(struct js_session *jss)
+{
+	jsval argv[3] = { 0 };
+	int argc = 0;
+	jsval ret;
+
+	if (jss->on_hangup && (jss->hook_state == CS_HANGUP || jss->hook_state == CS_RING)) {
+		argv[argc++] = OBJECT_TO_JSVAL(jss->obj);
+		if (jss->hook_state == CS_HANGUP) {
+			argv[argc++] = STRING_TO_JSVAL(JS_NewStringCopyZ(jss->cx, "hangup"));
+		} else {
+			argv[argc++] = STRING_TO_JSVAL(JS_NewStringCopyZ(jss->cx, "transfer"));
+		}
+		JS_CallFunction(jss->cx, jss->obj, jss->on_hangup, argc, argv, &ret);
+	}
+}
+
+static switch_status_t hanguphook(switch_core_session_t *session)
+{
+	switch_channel_t *channel;
+	struct js_session *jss = NULL;
+	switch_channel_state_t state;
+
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
+
+	state = switch_channel_get_state(channel);
+
+	if ((jss = switch_channel_get_private(channel, "jss"))) {
+		if (jss->hook_state != state) {
+			jss->hook_state = state;
+			check_hangup_hook(jss);
+		}
+	}
+
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+static JSBool session_hanguphook(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
+{
+	JSFunction *function;
+	struct js_session *jss;
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+
+	if ((jss = JS_GetPrivate(cx, obj)) && jss->session) {
+		if (argc > 0) {
+			if ((function = JS_ValueToFunction(cx, argv[0]))) {
+				switch_channel_t *channel = switch_core_session_get_channel(jss->session);
+				assert(channel != NULL);
+				jss->on_hangup = function;
+				jss->hook_state = switch_channel_get_state(channel);
+				switch_channel_set_private(channel, "jss", jss);
+				switch_core_event_hook_add_state_change(jss->session, hanguphook);
+				*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+			}
+		}
+	}
+
+	return JS_TRUE;
+}
+
+static JSBool session_streamfile(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
@@ -1083,21 +1159,27 @@
 	void *bp = NULL;
 	int len = 0;
 	switch_input_callback_function_t dtmf_func = NULL;
-	struct input_callback_state cb_state = {0};
-	switch_file_handle_t fh = {0};
+	struct input_callback_state cb_state = { 0 };
+	switch_file_handle_t fh = { 0 };
 	JSFunction *function;
-    switch_input_args_t args = {0};
+	switch_input_args_t args = { 0 };
+
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!switch_channel_ready(channel)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 
-	
 	if (argc > 0) {
 		file_name = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		if (switch_strlen_zero(file_name)) {
@@ -1123,39 +1205,38 @@
 		}
 	}
 
-    if (argc > 3) {
-        int32 samps;
-        JS_ValueToInt32(cx, argv[3], &samps);
-        fh.samples = samps;
-    }
+	if (argc > 3) {
+		int32 samps;
+		JS_ValueToInt32(cx, argv[3], &samps);
+		fh.samples = samps;
+	}
 
 	cb_state.extra = &fh;
-	cb_state.ret = BOOLEAN_TO_JSVAL( JS_FALSE );
-    cb_state.saveDepth = JS_SuspendRequest(cx);
-    args.input_callback = dtmf_func;
-    args.buf = bp;
-    args.buflen = len;
+	cb_state.ret = BOOLEAN_TO_JSVAL(JS_FALSE);
+	cb_state.saveDepth = JS_SuspendRequest(cx);
+	args.input_callback = dtmf_func;
+	args.buf = bp;
+	args.buflen = len;
 	switch_ivr_play_file(jss->session, &fh, file_name, &args);
-    JS_ResumeRequest(cx, cb_state.saveDepth);
+	JS_ResumeRequest(cx, cb_state.saveDepth);
 	*rval = cb_state.ret;
-	
+
 	return JS_TRUE;
 }
 
-static JSBool session_set_variable(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_set_variable(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
-    switch_channel_t *channel;
-
-	channel = switch_core_session_get_channel(jss->session);
-    assert(channel != NULL);
+	switch_channel_t *channel;
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
+	channel = switch_core_session_get_channel(jss->session);
+	assert(channel != NULL);
 
 	if (argc > 1) {
 		char *var, *val;
@@ -1163,49 +1244,47 @@
 		var = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		val = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
 		switch_channel_set_variable(channel, var, val);
-		*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+		*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 	} else {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 	}
- 	
+
 	return JS_TRUE;
 }
 
-static JSBool session_get_variable(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_get_variable(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
-    switch_channel_t *channel;
-
-	channel = switch_core_session_get_channel(jss->session);
-    assert(channel != NULL);
+	switch_channel_t *channel;
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!jss || !jss->session) {
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
+	channel = switch_core_session_get_channel(jss->session);
+	assert(channel != NULL);
 
 	if (argc > 0) {
 		char *var, *val;
-		
+
 		var = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		val = switch_channel_get_variable(channel, var);
 
 		if (val) {
-			*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, val));
+			*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, val));
 		} else {
-			*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+			*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		}
 	} else {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 	}
- 	
+
 	return JS_TRUE;
 }
 
 
-static JSBool session_speak(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_speak(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
@@ -1215,26 +1294,32 @@
 	switch_codec_t *codec;
 	void *bp = NULL;
 	int len = 0;
-	struct input_callback_state cb_state = {0};
+	struct input_callback_state cb_state = { 0 };
 	switch_input_callback_function_t dtmf_func = NULL;
 	JSFunction *function;
-    switch_input_args_t args = {0};
+	switch_input_args_t args = { 0 };
+
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!switch_channel_ready(channel)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 
-	
 	if (argc > 0) {
 		tts_name = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 	}
 	if (argc > 1) {
-		voice_name= JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
+		voice_name = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
 	}
 	if (argc > 2) {
 		text = JS_GetStringBytes(JS_ValueToString(cx, argv[2]));
@@ -1244,11 +1329,11 @@
 			memset(&cb_state, 0, sizeof(cb_state));
 			cb_state.function = function;
 			if (argc > 4) {
-                cb_state.arg = argv[4];
-            }
+				cb_state.arg = argv[4];
+			}
 
 			cb_state.cx = cx;
-            cb_state.obj = obj;
+			cb_state.obj = obj;
 			cb_state.session_state = jss;
 			dtmf_func = js_collect_input_callback;
 			bp = &cb_state;
@@ -1261,50 +1346,52 @@
 	}
 
 	codec = switch_core_session_get_read_codec(jss->session);
-	cb_state.ret = BOOLEAN_TO_JSVAL( JS_FALSE );
-    cb_state.saveDepth = JS_SuspendRequest(cx);
-    args.input_callback = dtmf_func;
-    args.buf = bp;
-    args.buflen = len;
-	switch_ivr_speak_text(jss->session,
-						  tts_name,
-						  voice_name && strlen(voice_name) ? voice_name : NULL, 
-						  codec->implementation->samples_per_second,
-						  text,
-                          &args);
-    JS_ResumeRequest(cx, cb_state.saveDepth);
+	cb_state.ret = BOOLEAN_TO_JSVAL(JS_FALSE);
+	cb_state.saveDepth = JS_SuspendRequest(cx);
+	args.input_callback = dtmf_func;
+	args.buf = bp;
+	args.buflen = len;
+	switch_ivr_speak_text(jss->session, tts_name, voice_name
+						  && strlen(voice_name) ? voice_name : NULL, codec->implementation->samples_per_second, text, &args);
+	JS_ResumeRequest(cx, cb_state.saveDepth);
 	*rval = cb_state.ret;
 
 	return JS_TRUE;
 }
 
-static JSBool session_get_digits(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_get_digits(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	char *terminators = NULL;
-	char buf[513] = {0};
+	char buf[513] = { 0 };
 	int32 digits = 0, timeout = 5000;
 	switch_channel_t *channel;
 
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 	channel = switch_core_session_get_channel(jss->session);
-    assert(channel != NULL);
+	assert(channel != NULL);
+
+	if (!switch_channel_ready(channel)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
 
-	
 	if (argc > 0) {
 		char term;
 		JS_ValueToInt32(cx, argv[0], &digits);
 
 		if (digits > sizeof(buf) - 1) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Exceeded max digits of %d\n",  sizeof(buf) - 1);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Exceeded max digits of %" SWITCH_SIZE_T_FMT "\n", sizeof(buf) - 1);
 			return JS_FALSE;
 		}
-		
+
 		if (argc > 1) {
 			terminators = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
 		}
@@ -1314,26 +1401,57 @@
 
 
 		switch_ivr_collect_digits_count(jss->session, buf, sizeof(buf), digits, terminators, &term, timeout);
-		*rval = STRING_TO_JSVAL ( JS_NewStringCopyZ(cx, buf) );
+		*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, buf));
 		return JS_TRUE;
 	}
 
 	return JS_FALSE;
 }
 
-static JSBool session_answer(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_autohangup(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
+{
+	struct js_session *jss = JS_GetPrivate(cx, obj);
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
+	if (argv[0]) {
+		JSBool tf;
+		JS_ValueToBoolean(cx, argv[0], &tf);
+		if (tf == JS_TRUE) {
+			switch_set_flag(jss, S_HUP);
+		} else {
+			switch_clear_flag(jss, S_HUP);
+		}
+		*rval = BOOLEAN_TO_JSVAL(tf);
+	}
+
+	return JS_TRUE;
+}
+
+static JSBool session_answer(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
 
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!switch_channel_ready(channel)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 
 	switch_channel_answer(channel);
@@ -1341,18 +1459,23 @@
 }
 
 
-static JSBool session_cdr(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_cdr(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_xml_t cdr;
 
-	/*Always a pessimist... sheesh!*/
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	/*Always a pessimist... sheesh! */
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		return JS_TRUE;
+	}
 
-    if (switch_ivr_generate_xml_cdr(jss->session, &cdr) == SWITCH_STATUS_SUCCESS) {
+	if (switch_ivr_generate_xml_cdr(jss->session, &cdr) == SWITCH_STATUS_SUCCESS) {
 		char *xml_text;
 		if ((xml_text = switch_xml_toxml(cdr))) {
-			*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, xml_text));
+			*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, xml_text));
 		}
 		switch_safe_free(xml_text);
 		switch_xml_free(cdr);
@@ -1361,22 +1484,28 @@
 	return JS_TRUE;
 }
 
-static JSBool session_ready(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_ready(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
 
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
-	*rval = BOOLEAN_TO_JSVAL( switch_channel_ready(channel) ? JS_TRUE : JS_FALSE );
+	*rval = BOOLEAN_TO_JSVAL(switch_channel_ready(channel) ? JS_TRUE : JS_FALSE);
 
 	return JS_TRUE;
 }
 
 
 
-static JSBool session_wait_for_media(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_wait_for_media(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
@@ -1384,6 +1513,12 @@
 	unsigned int elapsed;
 	int32 timeout = 60;
 
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
@@ -1393,25 +1528,27 @@
 		JS_ValueToInt32(cx, argv[0], &timeout);
 	}
 
-	for(;;) {
-		if (((elapsed = (unsigned int)((switch_time_now() - started) / 1000)) > (switch_time_t)timeout) || switch_channel_get_state(channel) >= CS_HANGUP) {
-			*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-            break;
+	for (;;) {
+		if (((elapsed = (unsigned int) ((switch_time_now() - started) / 1000)) > (switch_time_t) timeout)
+			|| switch_channel_get_state(channel) >= CS_HANGUP) {
+			*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+			break;
 		}
 
-		if (switch_channel_ready(channel) && (switch_channel_test_flag(channel, CF_ANSWERED) || switch_channel_test_flag(channel, CF_EARLY_MEDIA))) {
-			*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+		if (switch_channel_ready(channel)
+			&& (switch_channel_test_flag(channel, CF_ANSWERED) || switch_channel_test_flag(channel, CF_EARLY_MEDIA))) {
+			*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 			break;
 		}
-		
+
 		switch_yield(1000);
 	}
-	
+
 	return JS_TRUE;
 }
 
 
-static JSBool session_wait_for_answer(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_wait_for_answer(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
@@ -1419,6 +1556,12 @@
 	unsigned int elapsed;
 	int32 timeout = 60;
 
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
@@ -1428,37 +1571,44 @@
 		JS_ValueToInt32(cx, argv[0], &timeout);
 	}
 
-	for(;;) {
-		if (((elapsed = (unsigned int)((switch_time_now() - started) / 1000)) > (switch_time_t)timeout) || switch_channel_get_state(channel) >= CS_HANGUP) {
-			*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-            break;
+	for (;;) {
+		if (((elapsed = (unsigned int) ((switch_time_now() - started) / 1000)) > (switch_time_t) timeout)
+			|| switch_channel_get_state(channel) >= CS_HANGUP) {
+			*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+			break;
 		}
 
 		if (switch_channel_ready(channel) && switch_channel_test_flag(channel, CF_ANSWERED)) {
-			*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+			*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 			break;
 		}
-		
+
 		switch_yield(1000);
 	}
-	
+
 	return JS_TRUE;
 }
 
-static JSBool session_execute(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_execute(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	JSBool retval = JS_FALSE;
 	switch_channel_t *channel;
-    struct js_session *jss = JS_GetPrivate(cx, obj);
+	struct js_session *jss = JS_GetPrivate(cx, obj);
+
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 	channel = switch_core_session_get_channel(jss->session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!switch_channel_ready(channel)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 
 	if (argc > 1) {
@@ -1468,71 +1618,76 @@
 		struct js_session *jss = JS_GetPrivate(cx, obj);
 		jsrefcount saveDepth;
 
+		if (!jss || !jss->session) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+			*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+			return JS_TRUE;
+		}
+
 		if ((application_interface = switch_loadable_module_get_application_interface(app_name))) {
 			if (application_interface->application_function) {
 				saveDepth = JS_SuspendRequest(cx);
-				application_interface->application_function(jss->session, app_arg);
+				switch_core_session_exec(jss->session, application_interface, app_arg);
 				JS_ResumeRequest(cx, saveDepth);
 				retval = JS_TRUE;
 			}
-		} 
+		}
 	}
-	
-	*rval = BOOLEAN_TO_JSVAL( retval );
+
+	*rval = BOOLEAN_TO_JSVAL(retval);
 	return JS_TRUE;
 }
 
-static JSBool session_get_event(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_get_event(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_event_t *event;
-	switch_channel_t *channel;
-
-	channel = switch_core_session_get_channel(jss->session);
-    assert(channel != NULL);
-
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
 
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 	if (switch_core_session_dequeue_event(jss->session, &event) == SWITCH_STATUS_SUCCESS) {
 		JSObject *Event;
 		struct event_obj *eo;
-			
+
 		if ((eo = malloc(sizeof(*eo)))) {
 			eo->event = event;
 			eo->freed = 0;
 
 			if ((Event = JS_DefineObject(cx, obj, "__event__", &event_class, NULL, 0))) {
-				if ((JS_SetPrivate(cx, Event, eo) &&
-					 JS_DefineProperties(cx, Event, event_props) &&
-					 JS_DefineFunctions(cx, Event, event_methods))) {
-					*rval = OBJECT_TO_JSVAL ( Event );
+				if ((JS_SetPrivate(cx, Event, eo) && JS_DefineProperties(cx, Event, event_props) && JS_DefineFunctions(cx, Event, event_methods))) {
+					*rval = OBJECT_TO_JSVAL(Event);
 					return JS_TRUE;
 				}
 			}
 		}
 	}
-	
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-    return JS_TRUE;
-	
+
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+	return JS_TRUE;
+
 }
 
-static JSBool session_send_event(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_send_event(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	JSObject *Event;
 	struct event_obj *eo;
 
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 	if (argc > 0) {
 		if (JS_ValueToObject(cx, argv[0], &Event)) {
 			if ((eo = JS_GetPrivate(cx, Event))) {
 				if (switch_core_session_receive_event(jss->session, &eo->event) != SWITCH_STATUS_SUCCESS) {
-					*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+					*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 					return JS_TRUE;
 				}
 
@@ -1541,27 +1696,33 @@
 		}
 	}
 
-	*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
-    return JS_TRUE;
-	
+	*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
+	return JS_TRUE;
+
 }
 
 
-static JSBool session_hangup(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool session_hangup(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	switch_channel_t *channel;
 	char *cause_name = NULL;
 	switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
 
+	if (!jss || !jss->session) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "You must call the session.originate method before calling this method!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
+
 	channel = switch_core_session_get_channel(jss->session);
 	assert(channel != NULL);
 
-    if (!switch_channel_ready(channel)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
-        *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        return JS_TRUE;
-    }
+	if (!switch_channel_ready(channel)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Session is not active!\n");
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+		return JS_TRUE;
+	}
 
 	if (argc > 1) {
 		cause_name = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
@@ -1599,7 +1760,7 @@
 				*nextline = '\0';
 				nextline++;
 			}
-			
+
 			if ((val = strchr(line, '='))) {
 				*val = '\0';
 				val++;
@@ -1607,14 +1768,14 @@
 					*val = '\0';
 					val++;
 				}
-				
+
 				for (p = line; p && *p == ' '; p++);
 				line = p;
-				for (p=line+strlen(line)-1;*p == ' '; p--)
+				for (p = line + strlen(line) - 1; *p == ' '; p--)
 					*p = '\0';
 				for (p = val; p && *p == ' '; p++);
 				val = p;
-				for (p=val+strlen(val)-1;*p == ' '; p--)
+				for (p = val + strlen(val) - 1; *p == ' '; p--)
 					*p = '\0';
 
 				snprintf(code, sizeof(code), "~%s[\"%s\"] = \"%s\"", config_data->name, line, val);
@@ -1624,7 +1785,7 @@
 
 			line = nextline;
 		}
-	} 
+	}
 	return realsize;
 
 }
@@ -1633,7 +1794,7 @@
 
 static size_t file_callback(void *ptr, size_t size, size_t nmemb, void *data)
 {
-	register unsigned int realsize = (unsigned int)(size * nmemb);
+	register unsigned int realsize = (unsigned int) (size * nmemb);
 	struct config_data *config_data = data;
 
 	write(config_data->fd, ptr, realsize);
@@ -1641,13 +1802,13 @@
 }
 
 
-static JSBool js_fetchurl_hash(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_fetchurl_hash(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	char *url = NULL, *name = NULL;
 	CURL *curl_handle = NULL;
 	struct config_data config_data;
-	
-	if ( argc > 1 ) {
+
+	if (argc > 1) {
 		url = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		name = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
 
@@ -1664,7 +1825,7 @@
 		}
 		curl_easy_setopt(curl_handle, CURLOPT_URL, url);
 		curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, hash_callback);
-		curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&config_data);
+		curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *) &config_data);
 		curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "freeswitch-js/1.0");
 		curl_easy_perform(curl_handle);
 		curl_easy_cleanup(curl_handle);
@@ -1678,13 +1839,13 @@
 
 
 
-static JSBool js_fetchurl_file(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_fetchurl_file(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	char *url = NULL, *filename = NULL;
 	CURL *curl_handle = NULL;
 	struct config_data config_data;
-	
-	if ( argc > 1 ) {
+
+	if (argc > 1) {
 		url = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		filename = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
 
@@ -1701,7 +1862,7 @@
 		if ((config_data.fd = open(filename, O_CREAT | O_RDWR | O_TRUNC)) > -1) {
 			curl_easy_setopt(curl_handle, CURLOPT_URL, url);
 			curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, file_callback);
-			curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&config_data);
+			curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *) &config_data);
 			curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "freeswitch-js/1.0");
 			curl_easy_perform(curl_handle);
 			curl_easy_cleanup(curl_handle);
@@ -1722,74 +1883,90 @@
 /*********************************************************************************/
 enum session_tinyid {
 	SESSION_NAME, SESSION_STATE,
-	PROFILE_DIALPLAN, PROFILE_CID_NAME, PROFILE_CID_NUM, PROFILE_IP, PROFILE_ANI, PROFILE_ANI_II, PROFILE_DEST, SESSION_UUID
+	PROFILE_DIALPLAN, PROFILE_CID_NAME, PROFILE_CID_NUM, PROFILE_IP, PROFILE_ANI, PROFILE_ANI_II, PROFILE_DEST,
+	SESSION_UUID, SESSION_CAUSE
 };
 
 static JSFunctionSpec session_methods[] = {
-    {"sayPhrase", session_sayphrase, 1}, 
-    {"streamFile", session_streamfile, 1}, 
-	{"collectInput", session_collect_input, 1}, 
-	{"recordFile", session_recordfile, 1}, 
-	{"flushEvents", session_flush_events, 1}, 
-	{"flushDigits", session_flush_digits, 1}, 
-	{"speak", session_speak, 1}, 
-	{"setVariable", session_set_variable, 1}, 
-	{"getVariable", session_get_variable, 1}, 
+	{"originate", session_originate, 2},
+	{"setHangupHook", session_hanguphook, 1},
+	{"setAutoHangup", session_autohangup, 1},
+	{"sayPhrase", session_sayphrase, 1},
+	{"streamFile", session_streamfile, 1},
+	{"collectInput", session_collect_input, 1},
+	{"recordFile", session_recordfile, 1},
+	{"flushEvents", session_flush_events, 1},
+	{"flushDigits", session_flush_digits, 1},
+	{"speak", session_speak, 1},
+	{"setVariable", session_set_variable, 1},
+	{"getVariable", session_get_variable, 1},
 	{"getDigits", session_get_digits, 1},
-	{"answer", session_answer, 0}, 
-	{"generateXmlCdr", session_cdr, 0}, 
-	{"ready", session_ready, 0}, 
-	{"waitForAnswer", session_wait_for_answer, 0}, 
-	{"waitForMedia", session_wait_for_media, 0}, 
+	{"answer", session_answer, 0},
+	{"generateXmlCdr", session_cdr, 0},
+	{"ready", session_ready, 0},
+	{"waitForAnswer", session_wait_for_answer, 0},
+	{"waitForMedia", session_wait_for_media, 0},
 	{"getEvent", session_get_event, 0},
 	{"sendEvent", session_send_event, 0},
-	{"hangup", session_hangup, 0}, 
-	{"execute", session_execute, 0}, 
+	{"hangup", session_hangup, 0},
+	{"execute", session_execute, 0},
 	{0}
 };
 
 
 static JSPropertySpec session_props[] = {
-	{"name", SESSION_NAME, JSPROP_READONLY|JSPROP_PERMANENT}, 
-	{"state", SESSION_STATE, JSPROP_READONLY|JSPROP_PERMANENT}, 
-	{"dialplan", PROFILE_DIALPLAN, JSPROP_READONLY|JSPROP_PERMANENT},
-	{"caller_id_name", PROFILE_CID_NAME, JSPROP_READONLY|JSPROP_PERMANENT}, 
-	{"caller_id_num", PROFILE_CID_NUM, JSPROP_READONLY|JSPROP_PERMANENT}, 
-	{"network_addr", PROFILE_IP, JSPROP_READONLY|JSPROP_PERMANENT}, 
-	{"ani", PROFILE_ANI, JSPROP_READONLY|JSPROP_PERMANENT}, 
-	{"aniii", PROFILE_ANI_II, JSPROP_READONLY|JSPROP_PERMANENT}, 
-	{"destination", PROFILE_DEST, JSPROP_READONLY|JSPROP_PERMANENT}, 
-	{"uuid", SESSION_UUID, JSPROP_READONLY|JSPROP_PERMANENT}, 
+	{"name", SESSION_NAME, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"state", SESSION_STATE, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"dialplan", PROFILE_DIALPLAN, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"caller_id_name", PROFILE_CID_NAME, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"caller_id_num", PROFILE_CID_NUM, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"network_addr", PROFILE_IP, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"ani", PROFILE_ANI, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"aniii", PROFILE_ANI_II, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"destination", PROFILE_DEST, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"uuid", SESSION_UUID, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"cause", SESSION_CAUSE, JSPROP_READONLY | JSPROP_PERMANENT},
 	{0}
 };
 
-static JSBool session_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
+static JSBool session_getProperty(JSContext * cx, JSObject * obj, jsval id, jsval * vp)
 {
 	struct js_session *jss = JS_GetPrivate(cx, obj);
 	int param = 0;
-	JSBool res = JS_TRUE;
-	switch_channel_t *channel;
-	switch_caller_profile_t *caller_profile;
-	char *name;
-	
-	if (!jss || !jss->session) {
-		return JS_FALSE;
+	switch_channel_t *channel = NULL;
+	switch_caller_profile_t *caller_profile = NULL;
+	char *name = NULL;
+
+	if (jss && jss->session) {
+		channel = switch_core_session_get_channel(jss->session);
+		assert(channel != NULL);
+		caller_profile = switch_channel_get_caller_profile(channel);
 	}
 
-	channel = switch_core_session_get_channel(jss->session);
-	assert(channel != NULL);
-
-	caller_profile = switch_channel_get_caller_profile(channel);
-
 	name = JS_GetStringBytes(JS_ValueToString(cx, id));
+
 	/* numbers are our props anything else is a method */
 	if (name[0] >= 48 && name[0] <= 57) {
 		param = atoi(name);
 	} else {
 		return JS_TRUE;
 	}
-	
-	switch(param) {
+
+	if (!channel) {
+		switch (param) {
+		case SESSION_CAUSE:
+			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, switch_channel_cause2str(jss->cause)));
+			break;
+		default:
+			*vp = BOOLEAN_TO_JSVAL(JS_FALSE);
+		}
+		return JS_TRUE;
+	}
+
+	switch (param) {
+	case SESSION_CAUSE:
+		*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, switch_channel_cause2str(switch_channel_get_cause(channel))));
+		break;
 	case SESSION_NAME:
 		*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, switch_channel_get_name(channel)));
 		break;
@@ -1835,23 +2012,23 @@
 		}
 		break;
 	default:
-		res = JS_FALSE;
+		*vp = BOOLEAN_TO_JSVAL(JS_FALSE);
 		break;
 
 	}
 
-	return res;
+	return JS_TRUE;
 }
 
 JSClass session_class = {
-	"Session", JSCLASS_HAS_PRIVATE, 
-	JS_PropertyStub,  JS_PropertyStub,	session_getProperty,  JS_PropertyStub, 
-	JS_EnumerateStub, JS_ResolveStub,	JS_ConvertStub,	  session_destroy, NULL, NULL, NULL,
+	"Session", JSCLASS_HAS_PRIVATE,
+	JS_PropertyStub, JS_PropertyStub, session_getProperty, JS_PropertyStub,
+	JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, session_destroy, NULL, NULL, NULL,
 	session_construct
 };
 
 
-static JSObject *new_js_session(JSContext *cx, JSObject *obj, switch_core_session_t *session, struct js_session *jss, char *name, int flags) 
+static JSObject *new_js_session(JSContext * cx, JSObject * obj, switch_core_session_t *session, struct js_session *jss, char *name, int flags)
 {
 	JSObject *session_obj;
 	if ((session_obj = JS_DefineObject(cx, obj, name, &session_class, NULL, 0))) {
@@ -1859,29 +2036,46 @@
 		jss->session = session;
 		jss->flags = flags;
 		jss->cx = cx;
-		jss->obj = obj;
+		jss->obj = session_obj;
 		if ((JS_SetPrivate(cx, session_obj, jss) &&
-			 JS_DefineProperties(cx, session_obj, session_props) &&
-			 JS_DefineFunctions(cx, session_obj, session_methods))) {
+			 JS_DefineProperties(cx, session_obj, session_props) && JS_DefineFunctions(cx, session_obj, session_methods))) {
 			return session_obj;
 		}
 	}
-	
+
 	return NULL;
 }
 
-
 /* Session Object */
 /*********************************************************************************/
-static JSBool session_construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+
+static JSBool session_construct(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
+{
+	struct js_session *jss = NULL;
+
+	assert((jss = malloc(sizeof(*jss))));
+	memset(jss, 0, sizeof(*jss));
+	jss->cx = cx;
+	jss->obj = obj;
+	switch_set_flag(jss, S_FREE);
+
+	JS_SetPrivate(cx, obj, jss);
+
+	return JS_TRUE;
+}
+
+static JSBool session_originate(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
+	struct js_session *jss = NULL;
 	switch_memory_pool_t *pool = NULL;
+
+	jss = JS_GetPrivate(cx, obj);
+	jss->cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
+
 	if (argc > 1) {
-		switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
-		struct js_session *jss = NULL;
 		JSObject *session_obj;
 		switch_core_session_t *session = NULL, *peer_session = NULL;
-		switch_caller_profile_t *caller_profile = NULL;
+		switch_caller_profile_t *caller_profile = NULL, *orig_caller_profile = NULL;
 		char *dest = NULL;
 		char *dialplan = NULL;
 		char *cid_name = "";
@@ -1893,12 +2087,22 @@
 		char *context = "";
 		char *username = NULL;
 		char *to = NULL;
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 
 		if (JS_ValueToObject(cx, argv[0], &session_obj)) {
 			struct js_session *old_jss = NULL;
 			if ((old_jss = JS_GetPrivate(cx, session_obj))) {
 				session = old_jss->session;
+				orig_caller_profile = switch_channel_get_caller_profile(switch_core_session_get_channel(session));
+				dialplan = orig_caller_profile->dialplan;
+				cid_name = orig_caller_profile->caller_id_name;
+				cid_num = orig_caller_profile->caller_id_number;
+				ani = orig_caller_profile->ani;
+				aniii = orig_caller_profile->aniii;
+				rdnis = orig_caller_profile->rdnis;
+				context = orig_caller_profile->context;
+				username = orig_caller_profile->username;
 			}
 		}
 
@@ -1906,7 +2110,7 @@
 
 		if (!strchr(dest, '/')) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid Channel String\n");
-			return JS_TRUE;
+			goto done;
 		}
 
 		if (argc > 2) {
@@ -1939,71 +2143,69 @@
 		if (argc > 11) {
 			to = JS_GetStringBytes(JS_ValueToString(cx, argv[11]));
 		}
-		
-		
+
 		if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "OH OH no pool\n");
 			return JS_FALSE;
 		}
 
 		caller_profile = switch_caller_profile_new(pool,
-												   username,
-												   dialplan,
-												   cid_name,
-												   cid_num,
-												   network_addr,
-												   ani,
-												   aniii,
-												   rdnis,
-												   (char *)modname,
-												   context,
+												   username, dialplan, cid_name, cid_num, network_addr, ani, aniii, rdnis, (char *) modname, context,
 												   dest);
-		
-		if (switch_ivr_originate(session, &peer_session, &cause, dest, to ? atoi(to) : 60, NULL, NULL, NULL, caller_profile) != SWITCH_STATUS_SUCCESS) {
+
+		if (switch_ivr_originate(session, &peer_session, &jss->cause, dest, to ? atoi(to) : 60, NULL, NULL, NULL, caller_profile) != SWITCH_STATUS_SUCCESS) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Cannot Create Outgoing Channel! [%s]\n", dest);
-			return JS_TRUE;
+			goto done;
 		}
 
-		*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, switch_channel_cause2str(cause)));
-
-		jss = switch_core_session_alloc(peer_session, sizeof(*jss));
 		jss->session = peer_session;
-		jss->flags = 0;
-		jss->cx = cx;
-		jss->obj = obj;
-		JS_SetPrivate(cx, obj, jss);
-		switch_set_flag(jss, S_HUP);
+		jss->flags = S_RDLOCK;
+
+		*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 
 	} else {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Missing Args\n");
 	}
 
+  done:
 	return JS_TRUE;
 }
 
-static void session_destroy(JSContext *cx, JSObject *obj)
+
+
+
+static void session_destroy(JSContext * cx, JSObject * obj)
 {
 	struct js_session *jss;
-	
+	switch_channel_t *channel = NULL;
+
 	if (cx && obj) {
 		if ((jss = JS_GetPrivate(cx, obj))) {
-			if (switch_test_flag(jss, S_HUP)) {
-				switch_channel_t *channel;
+			if (jss->session) {
+				channel = switch_core_session_get_channel(jss->session);
+				switch_channel_set_private(channel, "jss", NULL);
+			}
 
-				if (jss->session) {
-					channel = switch_core_session_get_channel(jss->session);
-					switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
-				}
+			if (channel && switch_test_flag(jss, S_HUP)) {
+				switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
+			}
+
+			if (jss->session && switch_test_flag(jss, S_RDLOCK)) {
+				switch_core_session_rwunlock(jss->session);
+			}
+			
+			if (switch_test_flag(jss, S_FREE)) {
+				free(jss);
 			}
 		}
 	}
-		
+
 	return;
 }
 
 /* FileIO Object */
 /*********************************************************************************/
-static JSBool fileio_construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool fileio_construct(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	switch_memory_pool_t *pool;
 	switch_file_t *fd;
@@ -2014,7 +2216,7 @@
 	if (argc > 1) {
 		path = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		flags_str = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
-		
+
 		if (strchr(flags_str, 'r')) {
 			flags |= SWITCH_FOPEN_READ;
 		}
@@ -2034,10 +2236,10 @@
 			flags |= SWITCH_FOPEN_BINARY;
 		}
 		switch_core_new_memory_pool(&pool);
-		if (switch_file_open(&fd, path, flags, SWITCH_FPROT_UREAD|SWITCH_FPROT_UWRITE, pool) != SWITCH_STATUS_SUCCESS) {
+		if (switch_file_open(&fd, path, flags, SWITCH_FPROT_UREAD | SWITCH_FPROT_UWRITE, pool) != SWITCH_STATUS_SUCCESS) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Open File: %s\n", path);
 			switch_core_destroy_memory_pool(&pool);
-			*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+			*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 			return JS_TRUE;
 		}
 		fio = switch_core_alloc(pool, sizeof(*fio));
@@ -2051,13 +2253,13 @@
 
 	return JS_TRUE;
 }
-static void fileio_destroy(JSContext *cx, JSObject *obj)
+static void fileio_destroy(JSContext * cx, JSObject * obj)
 {
 	struct fileio_obj *fio = JS_GetPrivate(cx, obj);
 
 	if (fio) {
 		switch_memory_pool_t *pool;
-			if (fio->fd) {
+		if (fio->fd) {
 			switch_file_close(fio->fd);
 		}
 		pool = fio->pool;
@@ -2066,22 +2268,23 @@
 	}
 }
 
-static JSBool fileio_read(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool fileio_read(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct fileio_obj *fio = JS_GetPrivate(cx, obj);
 	int32 bytes = 0;
 	switch_size_t read = 0;
 
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 
-	if (fio) {
+	if (!fio) {
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
 
 	if (!(fio->flags & SWITCH_FOPEN_READ)) {
 		return JS_TRUE;
 	}
-	
+
 	if (argc > 0) {
 		JS_ValueToInt32(cx, argv[0], &bytes);
 	}
@@ -2094,51 +2297,51 @@
 		read = bytes;
 		switch_file_read(fio->fd, fio->buf, &read);
 		fio->buflen = read;
-		*rval = BOOLEAN_TO_JSVAL( (read > 0) ? JS_TRUE : JS_FALSE );
-	} 
+		*rval = BOOLEAN_TO_JSVAL((read > 0) ? JS_TRUE : JS_FALSE);
+	}
 
 	return JS_TRUE;
 }
 
-static JSBool fileio_data(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool fileio_data(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct fileio_obj *fio = JS_GetPrivate(cx, obj);
 
 	if (!fio) {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
 
-	*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, fio->buf));
+	*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, fio->buf));
 	return JS_TRUE;
 }
 
-static JSBool fileio_write(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool fileio_write(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct fileio_obj *fio = JS_GetPrivate(cx, obj);
 	switch_size_t wrote = 0;
 	char *data = NULL;
 
 	if (!fio) {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
 
 	if (!(fio->flags & SWITCH_FOPEN_WRITE)) {
-		*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+		*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 		return JS_TRUE;
 	}
-	
+
 	if (argc > 0) {
 		data = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 	}
 
 	if (data) {
 		wrote = strlen(data);
-		*rval = BOOLEAN_TO_JSVAL( (switch_file_write(fio->fd, data, &wrote) == SWITCH_STATUS_SUCCESS) ? JS_TRUE : JS_FALSE);
+		*rval = BOOLEAN_TO_JSVAL((switch_file_write(fio->fd, data, &wrote) == SWITCH_STATUS_SUCCESS) ? JS_TRUE : JS_FALSE);
 	}
 
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 	return JS_TRUE;
 }
 
@@ -2155,37 +2358,37 @@
 
 
 static JSPropertySpec fileio_props[] = {
-	{"path", FILEIO_PATH, JSPROP_READONLY|JSPROP_PERMANENT}, 
-	{"open", FILEIO_OPEN, JSPROP_READONLY|JSPROP_PERMANENT}, 
+	{"path", FILEIO_PATH, JSPROP_READONLY | JSPROP_PERMANENT},
+	{"open", FILEIO_OPEN, JSPROP_READONLY | JSPROP_PERMANENT},
 	{0}
 };
 
 
-static JSBool fileio_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
+static JSBool fileio_getProperty(JSContext * cx, JSObject * obj, jsval id, jsval * vp)
 {
 	JSBool res = JS_TRUE;
 	struct fileio_obj *fio = JS_GetPrivate(cx, obj);
 	char *name;
 	int param = 0;
-	
+
 	name = JS_GetStringBytes(JS_ValueToString(cx, id));
-    /* numbers are our props anything else is a method */
-    if (name[0] >= 48 && name[0] <= 57) {
-        param = atoi(name);
-    } else {
-        return JS_TRUE;
-    }
-	
-	switch(param) {
+	/* numbers are our props anything else is a method */
+	if (name[0] >= 48 && name[0] <= 57) {
+		param = atoi(name);
+	} else {
+		return JS_TRUE;
+	}
+
+	switch (param) {
 	case FILEIO_PATH:
 		if (fio) {
 			*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, fio->path));
 		} else {
-			*vp = BOOLEAN_TO_JSVAL( JS_FALSE );
+			*vp = BOOLEAN_TO_JSVAL(JS_FALSE);
 		}
 		break;
 	case FILEIO_OPEN:
-		*vp = BOOLEAN_TO_JSVAL( fio ? JS_TRUE : JS_FALSE );
+		*vp = BOOLEAN_TO_JSVAL(fio ? JS_TRUE : JS_FALSE);
 		break;
 	}
 
@@ -2193,21 +2396,21 @@
 }
 
 JSClass fileio_class = {
-	"FileIO", JSCLASS_HAS_PRIVATE, 
-	JS_PropertyStub,  JS_PropertyStub,	fileio_getProperty,  JS_PropertyStub, 
-	JS_EnumerateStub, JS_ResolveStub,	JS_ConvertStub,	  fileio_destroy, NULL, NULL, NULL,
+	"FileIO", JSCLASS_HAS_PRIVATE,
+	JS_PropertyStub, JS_PropertyStub, fileio_getProperty, JS_PropertyStub,
+	JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, fileio_destroy, NULL, NULL, NULL,
 	fileio_construct
 };
 
 
 /* Built-In*/
 /*********************************************************************************/
-static JSBool js_exit(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_exit(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	return JS_FALSE;
 }
 
-static JSBool js_log(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_log(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	char *level_str, *msg;
 	switch_log_level_t level = SWITCH_LOG_DEBUG;
@@ -2215,14 +2418,14 @@
 	const char *file = __FILE__;
 	int line = __LINE__;
 	JSStackFrame *caller;
-	
+
 	caller = JS_GetScriptedCaller(cx, NULL);
 	script = JS_GetFrameScript(cx, caller);
 
 	if (script) {
 		file = JS_GetScriptFilename(cx, script);
 		line = JS_GetScriptBaseLineNumber(cx, script);
-	}	
+	}
 
 
 	if (argc > 1) {
@@ -2233,7 +2436,7 @@
 		if ((msg = JS_GetStringBytes(JS_ValueToString(cx, argv[1])))) {
 			switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, "console_log", line, level, "%s", msg);
 			return JS_TRUE;
-		} 
+		}
 	} else if (argc > 0) {
 		if ((msg = JS_GetStringBytes(JS_ValueToString(cx, argv[0])))) {
 			switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, "console_log", line, level, "%s", msg);
@@ -2244,18 +2447,20 @@
 	return JS_FALSE;
 }
 
-static JSBool js_include(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_include(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	char *code;
-	if ( argc > 0 && (code = JS_GetStringBytes(JS_ValueToString(cx, argv[0])))) {
-		eval_some_js(code, cx, obj, rval);
+	if (argc > 0 && (code = JS_GetStringBytes(JS_ValueToString(cx, argv[0])))) {
+		if (eval_some_js(code, cx, obj, rval) < 0) {
+			return JS_FALSE;
+		}
 		return JS_TRUE;
 	}
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Arguements\n");
 	return JS_FALSE;
 }
 
-static JSBool js_api_use(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_api_use(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	char *mod_name = NULL;
 
@@ -2273,17 +2478,17 @@
 	}
 
 	return JS_TRUE;
-	
+
 }
 
-static JSBool js_api_execute(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_api_execute(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 
 	if (argc > 1) {
 		char *cmd = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		char *arg = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
 		switch_core_session_t *session = NULL;
-		switch_stream_handle_t stream = {0};
+		switch_stream_handle_t stream = { 0 };
 		char retbuf[2048] = "";
 
 		if (argc > 2) {
@@ -2295,30 +2500,30 @@
 				}
 			}
 		}
-		
-		
+
+
 		stream.data = retbuf;
 		stream.end = stream.data;
 		stream.data_size = sizeof(retbuf);
 		stream.write_function = switch_console_stream_write;
 		switch_api_execute(cmd, arg, session, &stream);
 
-		*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, retbuf));
+		*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, retbuf));
 	} else {
-		*rval = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, ""));
+		*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, ""));
 	}
 
 	return JS_TRUE;
 }
 
-static JSBool js_bridge(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_bridge(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct js_session *jss_a = NULL, *jss_b = NULL;
 	JSObject *session_obj_a = NULL, *session_obj_b = NULL;
 	void *bp = NULL;
 	int len = 0;
 	switch_input_callback_function_t dtmf_func = NULL;
-	struct input_callback_state cb_state = {0};
+	struct input_callback_state cb_state = { 0 };
 	JSFunction *function;
 
 	if (argc > 1) {
@@ -2327,15 +2532,15 @@
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Find Session [1]\n");
 				return JS_FALSE;
 			}
-		} 
+		}
 		if (JS_ValueToObject(cx, argv[1], &session_obj_b)) {
 			if (!(jss_b = JS_GetPrivate(cx, session_obj_b))) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Find Session [1]\n");
 				return JS_FALSE;
 			}
-		} 
+		}
 	}
-	
+
 	if (!(jss_a && jss_b)) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failure! %s %s\n", jss_a ? "y" : "n", jss_b ? "y" : "n");
 		return JS_FALSE;
@@ -2348,12 +2553,12 @@
 			cb_state.function = function;
 
 			if (argc > 3) {
-                cb_state.arg = argv[3];
-            }
+				cb_state.arg = argv[3];
+			}
 
 			cb_state.cx = cx;
-            cb_state.obj = obj;
-			
+			cb_state.obj = obj;
+
 			cb_state.session_state = jss_a;
 			dtmf_func = js_collect_input_callback;
 			bp = &cb_state;
@@ -2361,37 +2566,37 @@
 		}
 	}
 
-    cb_state.saveDepth = JS_SuspendRequest(cx);
+	cb_state.saveDepth = JS_SuspendRequest(cx);
 	switch_ivr_multi_threaded_bridge(jss_a->session, jss_b->session, dtmf_func, bp, bp);
-    JS_ResumeRequest(cx, cb_state.saveDepth);
+	JS_ResumeRequest(cx, cb_state.saveDepth);
 
 
 	return JS_TRUE;
 }
 
 /* Replace this with more robust version later */
-static JSBool js_system(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_system(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
-    char *cmd;
-    *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	char *cmd;
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 
-    if (argc > 0 && (cmd = JS_GetStringBytes(JS_ValueToString(cx, argv[0])))) {
-        *rval = INT_TO_JSVAL( system(cmd) );
-        return JS_TRUE;
-    }
+	if (argc > 0 && (cmd = JS_GetStringBytes(JS_ValueToString(cx, argv[0])))) {
+		*rval = INT_TO_JSVAL(system(cmd));
+		return JS_TRUE;
+	}
 
-    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Arguements\n");
-    return JS_FALSE;
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Arguements\n");
+	return JS_FALSE;
 }
 
 
-static JSBool js_file_unlink(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_file_unlink(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	const char *path;
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-	if ( argc > 0 && (path = (const char *)JS_GetStringBytes(JS_ValueToString(cx, argv[0])))) {
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
+	if (argc > 0 && (path = (const char *) JS_GetStringBytes(JS_ValueToString(cx, argv[0])))) {
 		if ((switch_file_remove(path, NULL)) == SWITCH_STATUS_SUCCESS) {
-			*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+			*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 		}
 		return JS_TRUE;
 	}
@@ -2400,64 +2605,34 @@
 }
 
 static JSFunctionSpec fs_functions[] = {
-	{"console_log", js_log, 2}, 
-	{"exit", js_exit, 0}, 
-	{"include", js_include, 1}, 
+	{"console_log", js_log, 2},
+	{"exit", js_exit, 0},
+	{"include", js_include, 1},
 	{"bridge", js_bridge, 2},
 	{"apiExecute", js_api_execute, 2},
 	{"use", js_api_use, 1},
 	{"fileDelete", js_file_unlink, 1},
 	{"system", js_system, 1},
 #ifdef HAVE_CURL
-	{"fetchURLHash", js_fetchurl_hash, 1}, 
-	{"fetchURLFile", js_fetchurl_file, 1}, 
-#endif 
+	{"fetchURLHash", js_fetchurl_hash, 1},
+	{"fetchURLFile", js_fetchurl_file, 1},
+#endif
 	{0}
 };
 
 
-static int env_init(JSContext *cx, JSObject *javascript_object)
+static int env_init(JSContext * cx, JSObject * javascript_object)
 {
 
 	JS_DefineFunctions(cx, javascript_object, fs_functions);
 
 	JS_InitStandardClasses(cx, javascript_object);
 
-	JS_InitClass(cx,
-				 javascript_object,
-				 NULL,
-				 &session_class,
-				 session_construct,
-				 3,
-				 session_props,
-				 session_methods,
-				 session_props,
-				 session_methods
-				 );
-
-	JS_InitClass(cx,
-				 javascript_object,
-				 NULL,
-				 &fileio_class,
-				 fileio_construct,
-				 3,
-				 fileio_props,
-				 fileio_methods,
-				 fileio_props,
-				 fileio_methods
-				 );
-
-	JS_InitClass(cx,
-				 javascript_object,
-				 NULL,
-				 &event_class,
-				 event_construct,
-				 3,
-				 event_props,
-				 event_methods,
-				 event_props,
-				 event_methods
-				 );
+	JS_InitClass(cx, javascript_object, NULL, &session_class, session_construct, 3, session_props, session_methods, session_props, session_methods);
+
+	JS_InitClass(cx, javascript_object, NULL, &fileio_class, fileio_construct, 3, fileio_props, fileio_methods, fileio_props, fileio_methods);
+
+	JS_InitClass(cx, javascript_object, NULL, &event_class, event_construct, 3, event_props, event_methods, event_props, event_methods);
 
 	return 1;
 }
@@ -2472,7 +2647,7 @@
 	JSContext *cx = NULL;
 	jsval rval;
 
-	
+
 	if ((cx = JS_NewContext(globals.rt, globals.gStackChunkSize))) {
 		JS_BeginRequest(cx);
 		JS_SetErrorReporter(cx, js_error);
@@ -2493,10 +2668,10 @@
 
 	if ((arg = strchr(script, ' '))) {
 		*arg++ = '\0';
-		argc = switch_separate_string(arg, ':', argv, (sizeof(argv) / sizeof(argv[0])));
+		argc = switch_separate_string(arg, ' ', argv, (sizeof(argv) / sizeof(argv[0])));
 	}
-	
-	if (argc) { /* create a js doppleganger of this argc/argv*/
+
+	if (argc) {					/* create a js doppleganger of this argc/argv */
 		snprintf(buf, sizeof(buf), "~var argv = new Array(%d);", argc);
 		eval_some_js(buf, cx, javascript_global_object, &rval);
 		snprintf(buf, sizeof(buf), "~var argc = %d", argc);
@@ -2505,7 +2680,6 @@
 		for (y = 0; y < argc; y++) {
 			snprintf(buf, sizeof(buf), "~argv[%d] = \"%s\";", x++, argv[y]);
 			eval_some_js(buf, cx, javascript_global_object, &rval);
-
 		}
 	}
 
@@ -2518,7 +2692,7 @@
 
 
 
-static void *SWITCH_THREAD_FUNC js_thread_run(switch_thread_t *thread, void *obj)
+static void *SWITCH_THREAD_FUNC js_thread_run(switch_thread_t * thread, void *obj)
 {
 	char *input_code = obj;
 
@@ -2545,7 +2719,7 @@
 			return;
 		}
 	}
-	
+
 	switch_threadattr_create(&thd_attr, module_pool);
 	switch_threadattr_detach_set(thd_attr, 1);
 	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
@@ -2573,8 +2747,9 @@
 	/* long_desc */ "Run a javascript ivr on a channel",
 	/* short_desc */ "Launch JS ivr.",
 	/* syntax */ "<script> [additional_vars [...]]",
-	/* flags */ SAF_NONE, /* should we support no media mode here?  If so, we need to detect the mode, and either disable the media functions or indicate media if/when we need */
-	/*.next*/ NULL
+	/* flags */ SAF_NONE,
+	/* should we support no media mode here?  If so, we need to detect the mode, and either disable the media functions or indicate media if/when we need */
+	/*.next */ NULL
 };
 
 static switch_api_interface_t js_run_interface = {
@@ -2598,6 +2773,28 @@
 	/*.directory_interface */ NULL
 };
 
+static void  message_query_handler(switch_event_t *event)
+{
+	char *account = switch_event_get_header(event, "message-account");
+
+	if (account) {
+		char *path, *cmd;
+
+		path  = switch_mprintf("%s%smwi.js", SWITCH_GLOBAL_dirs.script_dir, SWITCH_PATH_SEPARATOR);
+		assert(path != NULL);
+
+		if (switch_file_exists(path, NULL) == SWITCH_STATUS_SUCCESS) {
+			cmd = switch_mprintf("%s %s", path, account);
+			assert(cmd != NULL);
+			js_thread_launch(cmd);
+			switch_safe_free(cmd);
+		}
+
+		switch_safe_free(path);
+	}
+
+}
+
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)
 {
 	switch_status_t status;
@@ -2605,7 +2802,13 @@
 	if ((status = init_js()) != SWITCH_STATUS_SUCCESS) {
 		return status;
 	}
-	
+
+	if (switch_event_bind((char *) modname, SWITCH_EVENT_MESSAGE_QUERY, SWITCH_EVENT_SUBCLASS_ANY, message_query_handler, NULL)
+		!= SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind!\n");
+		return SWITCH_STATUS_GENERR;
+	}
+
 	/* connect my internal structure to the blank pointer passed to me */
 	*module_interface = &spidermonkey_module_interface;
 

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/mod_spidermonkey.h
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/mod_spidermonkey.h	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/mod_spidermonkey.h	Tue Apr 24 10:14:28 2007
@@ -52,18 +52,14 @@
 #include "jsscript.h"
 
 SWITCH_BEGIN_EXTERN_C
-
 #define JS_BUFFER_SIZE 1024 * 32
 #define JS_BLOCK_SIZE JS_BUFFER_SIZE
-
 #ifdef __ICC
 #pragma warning (disable:310 193 1418)
 #endif
-
 #ifdef _MSC_VER
 #pragma warning(disable: 4311)
 #endif
-
 #ifdef WIN32
 #if defined(SWITCH_SM_DECLARE_STATIC)
 #define SWITCH_SM_DECLARE(type)		type __cdecl
@@ -75,13 +71,13 @@
 #else //not win32
 #define SWITCH_SM_DECLARE(type) type
 #endif
-
-int eval_some_js(char *code, JSContext *cx, JSObject *obj, jsval *rval)
+int eval_some_js(char *code, JSContext * cx, JSObject * obj, jsval * rval)
 {
 	JSScript *script = NULL;
 	char *cptr;
 	char *path = NULL;
-	int res = 0;
+	char *script_name = NULL;
+	int result = 0;
 
 	JS_ClearPendingException(cx);
 
@@ -90,23 +86,32 @@
 		script = JS_CompileScript(cx, obj, cptr, strlen(cptr), "inline", 1);
 	} else {
 		if (*code == '/') {
-			script = JS_CompileFile(cx, obj, code);
+			script_name = code;
 		} else if ((path = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.script_dir, SWITCH_PATH_SEPARATOR, code))) {
-			script = JS_CompileFile(cx, obj, path);
-			switch_safe_free(path);
+			script_name = path;
+		}
+		if (script_name) {
+			if (switch_file_exists(script_name, NULL) == SWITCH_STATUS_SUCCESS) {
+				script = JS_CompileFile(cx, obj, script_name);
+			} else {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Open File: %s\n", script_name);
+			}
 		}
 	}
 
 	if (script) {
-		res = JS_ExecuteScript(cx, obj, script, rval) == JS_TRUE ? 1 : 0;
+		result = JS_ExecuteScript(cx, obj, script, rval) == JS_TRUE ? 1 : 0;
 		JS_DestroyScript(cx, script);
+	} else {
+		result = -1;
 	}
 
-	return res;
+	switch_safe_free(path);
+	return result;
 }
 
 
-typedef switch_status_t(*spidermonkey_load_t)(JSContext *cx, JSObject *obj);
+typedef switch_status_t (*spidermonkey_load_t) (JSContext * cx, JSObject * obj);
 
 struct sm_module_interface {
 	const char *name;
@@ -115,18 +120,19 @@
 };
 
 typedef struct sm_module_interface sm_module_interface_t;
-typedef switch_status_t(*spidermonkey_init_t)(const sm_module_interface_t **module_interface);
+typedef switch_status_t (*spidermonkey_init_t) (const sm_module_interface_t ** module_interface);
 
 struct js_session {
 	switch_core_session_t *session;
 	JSContext *cx;
 	JSObject *obj;
 	unsigned int flags;
+	switch_call_cause_t cause;
+	JSFunction *on_hangup;
+	switch_channel_state_t hook_state;
 };
 
 
 
 SWITCH_END_EXTERN_C
-
 #endif
-

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/sm.mak
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/sm.mak	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey/sm.mak	Tue Apr 24 10:14:28 2007
@@ -1,2 +1,14 @@
-CFLAGS += -I$(PREFIX)/include/js -I$(PREFIX)/include/nspr -DXP_UNIX -I../mod_spidermonkey -DJS_THREADSAFE -DJS_HAS_FILE_OBJECT=1
-LDFLAGS += -lnspr4 -ljs -lcurl
+switch_srcdir=../../../..
+JS_DIR=$(switch_srcdir)/libs/js
+JSLA=$(JS_DIR)/libjs.la
+
+LOCAL_CFLAGS+=-I$(JS_DIR)/src -I$(JS_DIR)/nsprpub/dist/include/nspr  -DXP_UNIX -I../mod_spidermonkey  -DJS_THREADSAFE -DJS_HAS_FILE_OBJECT=1
+LOCAL_LDFLAGS+=-L$(JS_DIR)/nsprpub/pr/src -L$(JS_DIR)/nsprpub/dist/lib -lnspr4
+LOCAL_LIBADD+=$(JSLA)
+
+include $(switch_srcdir)/build/modmake.rules
+
+$(JSLA): $(JS_DIR) $(JS_DIR)/.update
+	cd $(JS_DIR)/nsprpub && $(MAKE)
+	cd $(JS_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_core_db/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_core_db/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_core_db/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,15 +1,6 @@
+switch_srcdir=../../../..
+LOCAL_CFLAGS=
+LOCAL_LDFLAGS=
+LOCAL_LIBADD=
 include ../mod_spidermonkey/sm.mak
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(OBJS) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_core_db/mod_spidermonkey_core_db.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_core_db/mod_spidermonkey_core_db.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_core_db/mod_spidermonkey_core_db.c	Tue Apr 24 10:14:28 2007
@@ -34,19 +34,19 @@
 static const char modname[] = "CoreDB";
 
 struct db_obj {
-    switch_memory_pool_t *pool;
-    switch_core_db_t *db;
-    switch_core_db_stmt_t *stmt;
-    char *dbname;
-    char code_buffer[2048];
-    JSContext *cx;
-    JSObject *obj;
+	switch_memory_pool_t *pool;
+	switch_core_db_t *db;
+	switch_core_db_stmt_t *stmt;
+	char *dbname;
+	char code_buffer[2048];
+	JSContext *cx;
+	JSObject *obj;
 };
 
 
 /* DB Object */
 /*********************************************************************************/
-static JSBool db_construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool db_construct(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	switch_memory_pool_t *pool;
 	switch_core_db_t *db;
@@ -55,7 +55,7 @@
 	if (argc > 0) {
 		char *dbname = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 		switch_core_new_memory_pool(&pool);
-		if (! (db = switch_core_db_open_file(dbname))) {
+		if (!(db = switch_core_db_open_file(dbname))) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Open DB!\n");
 			switch_core_destroy_memory_pool(&pool);
 			return JS_FALSE;
@@ -73,10 +73,10 @@
 	return JS_FALSE;
 }
 
-static void db_destroy(JSContext *cx, JSObject *obj)
+static void db_destroy(JSContext * cx, JSObject * obj)
 {
 	struct db_obj *dbo = JS_GetPrivate(cx, obj);
-	
+
 	if (dbo) {
 		switch_memory_pool_t *pool = dbo->pool;
 		if (dbo->stmt) {
@@ -85,7 +85,7 @@
 		}
 		switch_core_db_close(dbo->db);
 		switch_core_destroy_memory_pool(&pool);
-        pool = NULL;
+		pool = NULL;
 	}
 }
 
@@ -100,7 +100,7 @@
 	snprintf(code, sizeof(code), "~var _Db_RoW_ = {}");
 	eval_some_js(code, dbo->cx, dbo->obj, &rval);
 
-	for(x=0; x < argc; x++) {
+	for (x = 0; x < argc; x++) {
 		snprintf(code, sizeof(code), "~_Db_RoW_[\"%s\"] = \"%s\"", columnNames[x], argv[x]);
 		eval_some_js(code, dbo->cx, dbo->obj, &rval);
 	}
@@ -110,53 +110,57 @@
 
 	snprintf(code, sizeof(code), "~delete _Db_RoW_");
 	eval_some_js(code, dbo->cx, dbo->obj, &rval);
-	
+
 	return 0;
 }
 
-static JSBool db_exec(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool db_exec(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
-    struct db_obj *dbo = JS_GetPrivate(cx, obj);
-    *rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+	struct db_obj *dbo = JS_GetPrivate(cx, obj);
+	*rval = INT_TO_JSVAL(0);
+
+	if (argc > 0) {
+		char *sql = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
+		char *err = NULL;
+		void *arg = NULL;
+		switch_core_db_callback_func_t cb_func = NULL;
+
+
+		if (argc > 1) {
+			char *js_func = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
+			switch_copy_string(dbo->code_buffer, js_func, sizeof(dbo->code_buffer));
+			cb_func = db_callback;
+			arg = dbo;
+		}
 
-    if (argc > 0) {
-        char *sql = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
-        char *err = NULL;
-        void *arg = NULL;
-        switch_core_db_callback_func_t cb_func = NULL;
-
-
-        if (argc > 1) {
-            char *js_func = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
-            switch_copy_string(dbo->code_buffer, js_func, sizeof(dbo->code_buffer));
-            cb_func = db_callback;
-            arg = dbo;
-        }
-
-        switch_core_db_exec(dbo->db, sql, cb_func, arg, &err);
-        if (err) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error %s\n", err);
-            switch_core_db_free(err);
-            *rval = BOOLEAN_TO_JSVAL( JS_FALSE );
-        }
-    }
-    return JS_TRUE;
+		switch_core_db_exec(dbo->db, sql, cb_func, arg, &err);
+		if (err) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error %s\n", err);
+			switch_core_db_free(err);
+			*rval = INT_TO_JSVAL(-1);
+		} else {
+			int count = switch_core_db_changes(dbo->db);
+
+			*rval = INT_TO_JSVAL(count);
+		}
+	}
+	return JS_TRUE;
 }
 
 
-static JSBool db_next(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool db_next(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct db_obj *dbo = JS_GetPrivate(cx, obj);
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 
-    if (dbo->stmt) {
+	if (dbo->stmt) {
 		int running = 1;
 		while (running < 5000) {
 			int result = switch_core_db_step(dbo->stmt);
-			if (result == SQLITE_ROW) {
-				*rval = BOOLEAN_TO_JSVAL( JS_TRUE );	
+			if (result == SWITCH_CORE_DB_ROW) {
+				*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 				break;
-			} else if (result == SQLITE_BUSY) {
+			} else if (result == SWITCH_CORE_DB_BUSY) {
 				running++;
 				continue;
 			}
@@ -169,7 +173,7 @@
 	return JS_TRUE;
 }
 
-static JSBool db_fetch(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool db_fetch(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct db_obj *dbo = JS_GetPrivate(cx, obj);
 	int colcount = switch_core_db_column_count(dbo->stmt);
@@ -179,16 +183,15 @@
 	snprintf(code, sizeof(code), "~var _dB_RoW_DaTa_ = {}");
 	eval_some_js(code, dbo->cx, dbo->obj, rval);
 	if (*rval == JS_FALSE) {
-		return JS_TRUE; 
+		return JS_TRUE;
 	}
 	for (x = 0; x < colcount; x++) {
-		snprintf(code, sizeof(code), "~_dB_RoW_DaTa_[\"%s\"] = \"%s\"", 
-				 (char *) switch_core_db_column_name(dbo->stmt, x),
-				 (char *) switch_core_db_column_text(dbo->stmt, x));
+		snprintf(code, sizeof(code), "~_dB_RoW_DaTa_[\"%s\"] = \"%s\"",
+				 (char *) switch_core_db_column_name(dbo->stmt, x), (char *) switch_core_db_column_text(dbo->stmt, x));
 
 		eval_some_js(code, dbo->cx, dbo->obj, rval);
 		if (*rval == JS_FALSE) {
-			return JS_TRUE; 
+			return JS_TRUE;
 		}
 	}
 
@@ -198,11 +201,11 @@
 }
 
 
-static JSBool db_prepare(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool db_prepare(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct db_obj *dbo = JS_GetPrivate(cx, obj);
 
-	*rval = BOOLEAN_TO_JSVAL( JS_FALSE );	
+	*rval = BOOLEAN_TO_JSVAL(JS_FALSE);
 
 	if (dbo->stmt) {
 		switch_core_db_finalize(dbo->stmt);
@@ -211,10 +214,10 @@
 
 	if (argc > 0) {
 		char *sql = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
-		if(switch_core_db_prepare(dbo->db, sql, -1, &dbo->stmt, 0)) {
+		if (switch_core_db_prepare(dbo->db, sql, -1, &dbo->stmt, 0)) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error %s\n", switch_core_db_errmsg(dbo->db));
 		} else {
-			*rval = BOOLEAN_TO_JSVAL( JS_TRUE );
+			*rval = BOOLEAN_TO_JSVAL(JS_TRUE);
 		}
 	}
 	return JS_TRUE;
@@ -234,27 +237,27 @@
 
 
 static JSPropertySpec db_props[] = {
-	{"path", DB_NAME, JSPROP_READONLY|JSPROP_PERMANENT}, 
+	{"path", DB_NAME, JSPROP_READONLY | JSPROP_PERMANENT},
 	{0}
 };
 
 
-static JSBool db_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
+static JSBool db_getProperty(JSContext * cx, JSObject * obj, jsval id, jsval * vp)
 {
 	JSBool res = JS_TRUE;
 	struct db_obj *dbo = JS_GetPrivate(cx, obj);
 	char *name;
 	int param = 0;
-	
+
 	name = JS_GetStringBytes(JS_ValueToString(cx, id));
-    /* numbers are our props anything else is a method */
-    if (name[0] >= 48 && name[0] <= 57) {
-        param = atoi(name);
-    } else {
-        return JS_TRUE;
-    }
-	
-	switch(param) {
+	/* numbers are our props anything else is a method */
+	if (name[0] >= 48 && name[0] <= 57) {
+		param = atoi(name);
+	} else {
+		return JS_TRUE;
+	}
+
+	switch (param) {
 	case DB_NAME:
 		*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, dbo->dbname));
 		break;
@@ -264,38 +267,28 @@
 }
 
 JSClass db_class = {
-	modname, JSCLASS_HAS_PRIVATE, 
-	JS_PropertyStub,  JS_PropertyStub,	db_getProperty,  JS_PropertyStub, 
-	JS_EnumerateStub, JS_ResolveStub,	JS_ConvertStub,	  db_destroy, NULL, NULL, NULL,
+	modname, JSCLASS_HAS_PRIVATE,
+	JS_PropertyStub, JS_PropertyStub, db_getProperty, JS_PropertyStub,
+	JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, db_destroy, NULL, NULL, NULL,
 	db_construct
 };
 
 
-switch_status_t db_load(JSContext *cx, JSObject *obj)
+switch_status_t db_load(JSContext * cx, JSObject * obj)
 {
 
-	JS_InitClass(cx,
-				 obj,
-				 NULL,
-				 &db_class,
-				 db_construct,
-				 3,
-				 db_props,
-				 db_methods,
-				 db_props,
-				 db_methods
-				 );
+	JS_InitClass(cx, obj, NULL, &db_class, db_construct, 3, db_props, db_methods, db_props, db_methods);
 	return SWITCH_STATUS_SUCCESS;
 }
 
 
 const sm_module_interface_t DB_module_interface = {
 	/*.name = */ modname,
-	/*.spidermonkey_load*/ db_load,
-	/*.next*/ NULL
+	/*.spidermonkey_load */ db_load,
+	/*.next */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t **module_interface)
+SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t ** module_interface)
 {
 	*module_interface = &DB_module_interface;
 	return SWITCH_STATUS_SUCCESS;

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_etpan/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_etpan/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_etpan/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,20 +1,12 @@
-include ../mod_spidermonkey/sm.mak
-
-OBJS=#$(BASE)/libs/mozilla/js/src/$(OS_CONFIG)_$(VER).OBJ/libjs.a $(BASE)/libs/mozilla/nsprpub/dist/lib/libnspr4.a  -letpan
-LINKER=$(CC)
-
+switch_srcdir=../../../..
+ETPAN_DIR=$(switch_srcdir)/libs/libetpan
+ETPANLA=$(ETPAN_DIR)/src/libetpan.la
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
+LOCAL_CFLAGS=-I$(ETPAN_DIR)/include
+LOCAL_LIBADD=$(ETPANLA)
 
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install libetpan --prefix=$(PREFIX)
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(LINKER) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(OBJS) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+include ../mod_spidermonkey/sm.mak
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+$(ETPANLA): $(ETPAN_DIR) $(ETPAN_DIR)/.update
+	cd $(ETPAN_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_etpan/mod_spidermonkey_etpan.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_etpan/mod_spidermonkey_etpan.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_etpan/mod_spidermonkey_etpan.c	Tue Apr 24 10:14:28 2007
@@ -40,9 +40,10 @@
 #define B64BUFFLEN 1024
 static const char c64[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 
-static int write_buf(int fd, char *buf) {
+static int write_buf(int fd, char *buf)
+{
 
-	int len = (int)strlen(buf);
+	int len = (int) strlen(buf);
 	if (fd && write(fd, buf, len) != len) {
 		close(fd);
 		return 0;
@@ -53,45 +54,45 @@
 
 /* etpan Object */
 /*********************************************************************************/
-static JSBool etpan_construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool etpan_construct(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	return JS_TRUE;
 }
 
-static void etpan_destroy(JSContext *cx, JSObject *obj)
+static void etpan_destroy(JSContext * cx, JSObject * obj)
 {
 }
 
-static JSBool etpan_my_method(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+#if 0
+static JSBool etpan_my_method(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	return JS_FALSE;
 }
+#endif
 
 enum etpan_tinyid {
 	etpan_NAME
 };
 
-static JSBool js_email(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool js_email(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	char *to = NULL, *from = NULL, *headers, *body = NULL, *file = NULL;
 	char *bound = "XXXX_boundary_XXXX";
 	char filename[80], buf[B64BUFFLEN];
 	int fd = 0, ifd = 0;
-	int x=0, y=0, bytes=0, ilen=0;
-	unsigned int b=0, l=0;
+	int x = 0, y = 0, bytes = 0, ilen = 0;
+	unsigned int b = 0, l = 0;
 	unsigned char in[B64BUFFLEN];
-	unsigned char out[B64BUFFLEN+512];
+	unsigned char out[B64BUFFLEN + 512];
 	char *path = NULL;
 
-	
-	if ( 
-		argc > 3 && 
+
+	if (argc > 3 &&
 		(from = JS_GetStringBytes(JS_ValueToString(cx, argv[0]))) &&
 		(to = JS_GetStringBytes(JS_ValueToString(cx, argv[1]))) &&
-		(headers = JS_GetStringBytes(JS_ValueToString(cx, argv[2]))) &&
-		(body = JS_GetStringBytes(JS_ValueToString(cx, argv[3]))) 
+		(headers = JS_GetStringBytes(JS_ValueToString(cx, argv[2]))) && (body = JS_GetStringBytes(JS_ValueToString(cx, argv[3])))
 		) {
-		if ( argc > 4) {
+		if (argc > 4) {
 			file = JS_GetStringBytes(JS_ValueToString(cx, argv[4]));
 		}
 		snprintf(filename, 80, "%smail.%ld%04x", SWITCH_GLOBAL_dirs.temp_dir, time(NULL), rand() & 0xffff);
@@ -108,63 +109,63 @@
 					return JS_FALSE;
 				}
 			}
-			
+
 			if (!write_buf(fd, headers))
 				return JS_FALSE;
 
 			if (!write_buf(fd, "\n\n"))
 				return JS_FALSE;
-			
+
 			if (file) {
 				snprintf(buf, B64BUFFLEN, "--%s\nContent-Type: text/plain\n\n", bound);
 				if (!write_buf(fd, buf))
 					return JS_FALSE;
 			}
-			
+
 			if (!write_buf(fd, body))
 				return JS_FALSE;
-			
+
 			if (file) {
 				snprintf(buf, B64BUFFLEN, "\n\n--%s\nContent-Type: application/octet-stream\n"
 						 "Content-Transfer-Encoding: base64\n"
-						 "Content-Description: Sound attachment.\n"
-						 "Content-Disposition: attachment; filename=\"%s\"\n\n", bound, file);
+						 "Content-Description: Sound attachment.\n" "Content-Disposition: attachment; filename=\"%s\"\n\n", bound, file);
 				if (!write_buf(fd, buf))
 					return JS_FALSE;
-				
-				while((ilen=read(ifd, in, B64BUFFLEN))) {
-					for (x=0;x<ilen;x++) {
-						b = (b<<8) + in[x];
+
+				while ((ilen = read(ifd, in, B64BUFFLEN))) {
+					for (x = 0; x < ilen; x++) {
+						b = (b << 8) + in[x];
 						l += 8;
 						while (l >= 6) {
-							out[bytes++] = c64[(b>>(l-=6))%64];
-							if (++y!=72)
+							out[bytes++] = c64[(b >> (l -= 6)) % 64];
+							if (++y != 72)
 								continue;
 							out[bytes++] = '\n';
-							y=0;
+							y = 0;
 						}
 					}
-					if (write(fd, &out, bytes) != bytes) { 
+					if (write(fd, &out, bytes) != bytes) {
 						return -1;
-					} else 
-						bytes=0;
-					
+					} else
+						bytes = 0;
+
 				}
-				
+
 				if (l > 0) {
-					out[bytes++] = c64[((b%16)<<(6-l))%64];
+					out[bytes++] = c64[((b % 16) << (6 - l)) % 64];
 				}
-				if (l != 0) while (l < 6) {
-					out[bytes++] = '=', l += 2;
-				}
-				if (write(fd, &out, bytes) != bytes) { 
+				if (l != 0)
+					while (l < 6) {
+						out[bytes++] = '=', l += 2;
+					}
+				if (write(fd, &out, bytes) != bytes) {
 					return -1;
 				}
 
 			}
-			
 
-			
+
+
 			if (file) {
 				snprintf(buf, B64BUFFLEN, "\n\n--%s--\n.\n", bound);
 				if (!write_buf(fd, buf))
@@ -190,23 +191,23 @@
 		}
 		return JS_TRUE;
 	}
-	
+
 
 	return JS_FALSE;
 }
 
 static JSFunctionSpec etpan_methods[] = {
-//	{"myMethod", odbc_my_method, 1},
+//  {"myMethod", odbc_my_method, 1},
 	{0}
 };
 
 static JSPropertySpec etpan_props[] = {
-//	{"name", etpan_NAME, JSPROP_READONLY|JSPROP_PERMANENT}, 
+//  {"name", etpan_NAME, JSPROP_READONLY|JSPROP_PERMANENT}, 
 	{0}
 };
 
 
-static JSBool etpan_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
+static JSBool etpan_getProperty(JSContext * cx, JSObject * obj, jsval id, jsval * vp)
 {
 	JSBool res = JS_TRUE;
 
@@ -214,44 +215,34 @@
 }
 
 JSClass etpan_class = {
-	modname, JSCLASS_HAS_PRIVATE, 
-	JS_PropertyStub,  JS_PropertyStub,	etpan_getProperty,  JS_PropertyStub, 
-	JS_EnumerateStub, JS_ResolveStub,	JS_ConvertStub,	  etpan_destroy, NULL, NULL, NULL,
+	modname, JSCLASS_HAS_PRIVATE,
+	JS_PropertyStub, JS_PropertyStub, etpan_getProperty, JS_PropertyStub,
+	JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, etpan_destroy, NULL, NULL, NULL,
 	etpan_construct
 };
 
 
 static JSFunctionSpec etpan_functions[] = {
-	{"email", js_email, 2}, 
+	{"email", js_email, 2},
 	{0}
 };
 
-switch_status_t etpan_load(JSContext *cx, JSObject *obj)
+switch_status_t etpan_load(JSContext * cx, JSObject * obj)
 {
 	JS_DefineFunctions(cx, obj, etpan_functions);
 
-	JS_InitClass(cx,
-				 obj,
-				 NULL,
-				 &etpan_class,
-				 etpan_construct,
-				 3,
-				 etpan_props,
-				 etpan_methods,
-				 etpan_props,
-				 etpan_methods
-				 );
+	JS_InitClass(cx, obj, NULL, &etpan_class, etpan_construct, 3, etpan_props, etpan_methods, etpan_props, etpan_methods);
 	return SWITCH_STATUS_SUCCESS;
 }
 
 
 const sm_module_interface_t etpan_module_interface = {
 	/*.name = */ modname,
-	/*.spidermonkey_load*/ etpan_load,
-	/*.next*/ NULL
+	/*.spidermonkey_load */ etpan_load,
+	/*.next */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t **module_interface)
+SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t ** module_interface)
 {
 	*module_interface = &etpan_module_interface;
 	return SWITCH_STATUS_SUCCESS;
@@ -269,259 +260,252 @@
 int smtp_esmtp = 1;
 
 struct mem_message {
-  char *data;
-  size_t len;
-  MMAPString *mstring;
+	char *data;
+	size_t len;
+	MMAPString *mstring;
 };
 
 #define BLOCKSIZE 4096
 
-int collect(struct mem_message *message) {
-  struct stat sb;
-  int len;
+int collect(struct mem_message *message)
+{
+	struct stat sb;
+	int len;
 
-  memset(message, 0, sizeof(struct mem_message));
+	memset(message, 0, sizeof(struct mem_message));
 
 #ifndef MMAP_UNAVAILABLE
-  /* if stdin is a file whose size is known, try to mmap it */
-  if (!fstat(0, &sb) && S_ISREG(sb.st_mode) && sb.st_size >= 0) {
-    message->len = sb.st_size;
-    if ((message->data = mmap(NULL, message->len, PROT_READ, MAP_SHARED,
-			      STDIN_FILENO, 0)) != MAP_FAILED)
-      return 0;
-  }
+	/* if stdin is a file whose size is known, try to mmap it */
+	if (!fstat(0, &sb) && S_ISREG(sb.st_mode) && sb.st_size >= 0) {
+		message->len = sb.st_size;
+		if ((message->data = mmap(NULL, message->len, PROT_READ, MAP_SHARED, STDIN_FILENO, 0)) != MAP_FAILED)
+			return 0;
+	}
 #endif
 
-  /* read the buffer from stdin by blocks, until EOF or error.
-     save the message in a mmap_string */
-  if ((message->mstring = mmap_string_sized_new(BLOCKSIZE)) == NULL) {
-    perror("mmap_string_new");
-    goto error;
-  }
-  message->len = 0;
-
-  while ((len = read(STDIN_FILENO,
-		     message->mstring->str + message->len, BLOCKSIZE)) > 0) {
-    message->len += len;
-    /* reserve room for next block */
-    if ((mmap_string_set_size(message->mstring,
-			      message->len + BLOCKSIZE)) == NULL) {
-      perror("mmap_string_set_size");
-      goto error;
-    }
-  }
-
-  if (len == 0) {
-    message->data = message->mstring->str;
-    return 0; /* OK */
-  }
-
-  perror("read");
-
- error:
-  if (message->mstring != NULL)
-    mmap_string_free(message->mstring);
-  return -1;
+	/* read the buffer from stdin by blocks, until EOF or error.
+	   save the message in a mmap_string */
+	if ((message->mstring = mmap_string_sized_new(BLOCKSIZE)) == NULL) {
+		perror("mmap_string_new");
+		goto error;
+	}
+	message->len = 0;
+
+	while ((len = read(STDIN_FILENO, message->mstring->str + message->len, BLOCKSIZE)) > 0) {
+		message->len += len;
+		/* reserve room for next block */
+		if ((mmap_string_set_size(message->mstring, message->len + BLOCKSIZE)) == NULL) {
+			perror("mmap_string_set_size");
+			goto error;
+		}
+	}
+
+	if (len == 0) {
+		message->data = message->mstring->str;
+		return 0;				/* OK */
+	}
+
+	perror("read");
+
+  error:
+	if (message->mstring != NULL)
+		mmap_string_free(message->mstring);
+	return -1;
 }
 
-char *guessfrom() {
+char *guessfrom()
+{
 #ifndef _MSC_VER
-  uid_t uid;
-  struct passwd *pw;
-  char hostname[256];
-  int len;
-  char *gfrom;
-
-  if (gethostname(hostname, sizeof(hostname))) {
-    perror("gethostname");
-    return NULL;
-  }
-  hostname[sizeof(hostname) - 1] = '\0';
-
-  uid = getuid();
-  pw = getpwuid(uid);
-  
-  len = ((pw != NULL) ? strlen(pw->pw_name) : 12)
-    + strlen(hostname) + 2;
-
-  if ((gfrom = malloc(len)) == NULL) {
-    perror("malloc");
-    return NULL;
-  }
-  if (pw != NULL && pw->pw_name != NULL) 
-    snprintf(gfrom, len, "%s@%s", pw->pw_name, hostname);
-  else
-    snprintf(gfrom, len, "#%u@%s", uid, hostname);
-  return gfrom;
+	uid_t uid;
+	struct passwd *pw;
+	char hostname[256];
+	int len;
+	char *gfrom;
+
+	if (gethostname(hostname, sizeof(hostname))) {
+		perror("gethostname");
+		return NULL;
+	}
+	hostname[sizeof(hostname) - 1] = '\0';
+
+	uid = getuid();
+	pw = getpwuid(uid);
+
+	len = ((pw != NULL) ? strlen(pw->pw_name) : 12)
+		+ strlen(hostname) + 2;
+
+	if ((gfrom = malloc(len)) == NULL) {
+		perror("malloc");
+		return NULL;
+	}
+	if (pw != NULL && pw->pw_name != NULL)
+		snprintf(gfrom, len, "%s@%s", pw->pw_name, hostname);
+	else
+		snprintf(gfrom, len, "#%u@%s", uid, hostname);
+	return gfrom;
 #else
 	return NULL;
 #endif
 }
 
-void release(struct mem_message *message) {
-  if (message->mstring != NULL)
-    mmap_string_free(message->mstring);
+void release(struct mem_message *message)
+{
+	if (message->mstring != NULL)
+		mmap_string_free(message->mstring);
 #ifndef MMAP_UNAVAILABLE
-  else if (message->data != NULL)
-    munmap(message->data, message->len);
+	else if (message->data != NULL)
+		munmap(message->data, message->len);
 #endif
 }
 
-int send_message(char *data, size_t len, char**rcpts) {
-  int s = -1;
-  int ret;
-  char **r;
-  int esmtp = 0;
-  mailsmtp *smtp = NULL;
-
-  if ((smtp = mailsmtp_new(0, NULL)) == NULL) {
-    perror("mailsmtp_new");
-    goto error;
-  }
-
-  /* first open the stream */
-  if ((ret = mailsmtp_socket_connect(smtp, 
-				     (smtp_server != NULL ? smtp_server : "localhost"),
-				     smtp_port)) != MAILSMTP_NO_ERROR) {
-    fprintf(stderr, "mailsmtp_socket_connect: %s\n", mailsmtp_strerror(ret));
-    goto error;
-  }
-  
-  /* then introduce ourselves */
-  if (smtp_esmtp && (ret = mailesmtp_ehlo(smtp)) == MAILSMTP_NO_ERROR)
-    esmtp = 1;
-  else if (!smtp_esmtp || ret == MAILSMTP_ERROR_NOT_IMPLEMENTED)
-    ret = mailsmtp_helo(smtp);
-  if (ret != MAILSMTP_NO_ERROR) {
-    fprintf(stderr, "mailsmtp_helo: %s\n", mailsmtp_strerror(ret));
-    goto error;
-  }
-
-  if (esmtp && smtp_tls &&
-      (ret = mailsmtp_socket_starttls(smtp)) != MAILSMTP_NO_ERROR) {
-    fprintf(stderr, "mailsmtp_starttls: %s\n", mailsmtp_strerror(ret));
-    goto error;
-  }
-  
-  if (esmtp && smtp_user != NULL &&
-      (ret = mailsmtp_auth(smtp, smtp_user,
-			   (smtp_password != NULL) ? smtp_password : ""))
-      != MAILSMTP_NO_ERROR) {
-    fprintf(stderr, "mailsmtp_auth: %s: %s\n", smtp_user, mailsmtp_strerror(ret));
-    goto error;
-  }
-
-  /* source */
-  if ((ret = (esmtp ?
-	      mailesmtp_mail(smtp, smtp_from, 1, "etPanSMTPTest") :
-	      mailsmtp_mail(smtp, smtp_from))) != MAILSMTP_NO_ERROR) {
-    fprintf(stderr, "mailsmtp_mail: %s, %s\n", smtp_from, mailsmtp_strerror(ret));
-    goto error;
-  }
-  
-  /* recipients */
-  for (r = rcpts; *r != NULL; r++) {
-    if ((ret = (esmtp ?
-		mailesmtp_rcpt(smtp, *r,
-			       MAILSMTP_DSN_NOTIFY_FAILURE|MAILSMTP_DSN_NOTIFY_DELAY,
-			       NULL) :
-		mailsmtp_rcpt(smtp, *r))) != MAILSMTP_NO_ERROR) {
-      fprintf(stderr, "mailsmtp_rcpt: %s: %s\n", *r, mailsmtp_strerror(ret));
-      goto error;
-    }
-  }
-  
-  /* message */
-  if ((ret = mailsmtp_data(smtp)) != MAILSMTP_NO_ERROR) {
-    fprintf(stderr, "mailsmtp_data: %s\n", mailsmtp_strerror(ret));
-    goto error;
-  }
-  if ((ret = mailsmtp_data_message(smtp, data, len)) != MAILSMTP_NO_ERROR) {
-    fprintf(stderr, "mailsmtp_data_message: %s\n", mailsmtp_strerror(ret));
-    goto error;
-  }
-  mailsmtp_free(smtp);
-  return 0;
-
- error:
-  if (smtp != NULL)
-    mailsmtp_free(smtp);
-  if (s >= 0)
-    close(s);
-  return -1;
-}
-
-int main(int argc, char **argv) {
-  struct mem_message message;
-  int index, r;
-
-  static struct option long_options[] = {
-    {"server",   1, 0, 's'},
-    {"port",     1, 0, 'p'},
-    {"user",     1, 0, 'u'},
-    {"password", 1, 0, 'v'},
-    {"from",     1, 0, 'f'},
-    {"tls",      0, 0, 'S'},
-    {"no-esmtp", 0, 0, 'E'},
-  };
-
-  while(1) {
-    if ((r = getopt_long(argc, argv, "s:p:u:v:f:SE", long_options, &index)) < 0)
-      break;
-    switch (r) {
-    case 's':
-      if (smtp_server != NULL)
-	free(smtp_server);
-      smtp_server = strdup(optarg);
-      break;
-    case 'p':
-      smtp_port = (uint16_t) strtoul(optarg, NULL, 10);
-      break;
-    case 'u':
-      if (smtp_user != NULL)
-	free(smtp_user);
-      smtp_user = strdup(optarg);
-      break;
-    case 'v':
-      if (smtp_password != NULL)
-	free(smtp_password);
-      smtp_password = strdup(optarg);
-      break;
-    case 'f':
-      if (smtp_from != NULL)
-	free(smtp_from);
-      smtp_from = strdup(optarg);
-      break;
-    case 'S':
-      smtp_tls = 1;
-      break;
-    case 'E':
-      smtp_esmtp = 0;
-      break;
-    }
-  }
-
-  argc -= optind;
-  argv += optind;
-
-  if (argc < 1) {
-    fprintf(stderr, "usage: smtpsend [-f from] [-u user] [-v password] [-s server] [-p port] [-S] <rcpts>...\n");
-    return EXIT_FAILURE;
-  }
-
-  if (smtp_from == NULL && (smtp_from = guessfrom()) == NULL) {
-    fprintf(stderr, "can't guess a valid from, please use -f option.\n");
-    return EXIT_FAILURE;
-  }
-  
-  /* reads message from stdin */
-  if (collect(&message))
-    return EXIT_FAILURE;
-  
-  send_message(message.data, message.len, argv);
+int send_message(char *data, size_t len, char **rcpts)
+{
+	int s = -1;
+	int ret;
+	char **r;
+	int esmtp = 0;
+	mailsmtp *smtp = NULL;
+
+	if ((smtp = mailsmtp_new(0, NULL)) == NULL) {
+		perror("mailsmtp_new");
+		goto error;
+	}
+
+	/* first open the stream */
+	if ((ret = mailsmtp_socket_connect(smtp, (smtp_server != NULL ? smtp_server : "localhost"), smtp_port)) != MAILSMTP_NO_ERROR) {
+		fprintf(stderr, "mailsmtp_socket_connect: %s\n", mailsmtp_strerror(ret));
+		goto error;
+	}
+
+	/* then introduce ourselves */
+	if (smtp_esmtp && (ret = mailesmtp_ehlo(smtp)) == MAILSMTP_NO_ERROR)
+		esmtp = 1;
+	else if (!smtp_esmtp || ret == MAILSMTP_ERROR_NOT_IMPLEMENTED)
+		ret = mailsmtp_helo(smtp);
+	if (ret != MAILSMTP_NO_ERROR) {
+		fprintf(stderr, "mailsmtp_helo: %s\n", mailsmtp_strerror(ret));
+		goto error;
+	}
+
+	if (esmtp && smtp_tls && (ret = mailsmtp_socket_starttls(smtp)) != MAILSMTP_NO_ERROR) {
+		fprintf(stderr, "mailsmtp_starttls: %s\n", mailsmtp_strerror(ret));
+		goto error;
+	}
+
+	if (esmtp && smtp_user != NULL && (ret = mailsmtp_auth(smtp, smtp_user, (smtp_password != NULL) ? smtp_password : ""))
+		!= MAILSMTP_NO_ERROR) {
+		fprintf(stderr, "mailsmtp_auth: %s: %s\n", smtp_user, mailsmtp_strerror(ret));
+		goto error;
+	}
+
+	/* source */
+	if ((ret = (esmtp ? mailesmtp_mail(smtp, smtp_from, 1, "etPanSMTPTest") : mailsmtp_mail(smtp, smtp_from))) != MAILSMTP_NO_ERROR) {
+		fprintf(stderr, "mailsmtp_mail: %s, %s\n", smtp_from, mailsmtp_strerror(ret));
+		goto error;
+	}
+
+	/* recipients */
+	for (r = rcpts; *r != NULL; r++) {
+		if ((ret = (esmtp ?
+					mailesmtp_rcpt(smtp, *r, MAILSMTP_DSN_NOTIFY_FAILURE | MAILSMTP_DSN_NOTIFY_DELAY, NULL) : mailsmtp_rcpt(smtp,
+																															*r))) != MAILSMTP_NO_ERROR) {
+			fprintf(stderr, "mailsmtp_rcpt: %s: %s\n", *r, mailsmtp_strerror(ret));
+			goto error;
+		}
+	}
+
+	/* message */
+	if ((ret = mailsmtp_data(smtp)) != MAILSMTP_NO_ERROR) {
+		fprintf(stderr, "mailsmtp_data: %s\n", mailsmtp_strerror(ret));
+		goto error;
+	}
+	if ((ret = mailsmtp_data_message(smtp, data, len)) != MAILSMTP_NO_ERROR) {
+		fprintf(stderr, "mailsmtp_data_message: %s\n", mailsmtp_strerror(ret));
+		goto error;
+	}
+	mailsmtp_free(smtp);
+	return 0;
+
+  error:
+	if (smtp != NULL)
+		mailsmtp_free(smtp);
+	if (s >= 0)
+		close(s);
+	return -1;
+}
+
+int main(int argc, char **argv)
+{
+	struct mem_message message;
+	int index, r;
+
+	static struct option long_options[] = {
+		{"server", 1, 0, 's'},
+		{"port", 1, 0, 'p'},
+		{"user", 1, 0, 'u'},
+		{"password", 1, 0, 'v'},
+		{"from", 1, 0, 'f'},
+		{"tls", 0, 0, 'S'},
+		{"no-esmtp", 0, 0, 'E'},
+	};
+
+	while (1) {
+		if ((r = getopt_long(argc, argv, "s:p:u:v:f:SE", long_options, &index)) < 0)
+			break;
+		switch (r) {
+		case 's':
+			if (smtp_server != NULL)
+				free(smtp_server);
+			smtp_server = strdup(optarg);
+			break;
+		case 'p':
+			smtp_port = (uint16_t) strtoul(optarg, NULL, 10);
+			break;
+		case 'u':
+			if (smtp_user != NULL)
+				free(smtp_user);
+			smtp_user = strdup(optarg);
+			break;
+		case 'v':
+			if (smtp_password != NULL)
+				free(smtp_password);
+			smtp_password = strdup(optarg);
+			break;
+		case 'f':
+			if (smtp_from != NULL)
+				free(smtp_from);
+			smtp_from = strdup(optarg);
+			break;
+		case 'S':
+			smtp_tls = 1;
+			break;
+		case 'E':
+			smtp_esmtp = 0;
+			break;
+		}
+	}
+
+	argc -= optind;
+	argv += optind;
+
+	if (argc < 1) {
+		fprintf(stderr, "usage: smtpsend [-f from] [-u user] [-v password] [-s server] [-p port] [-S] <rcpts>...\n");
+		return EXIT_FAILURE;
+	}
+
+	if (smtp_from == NULL && (smtp_from = guessfrom()) == NULL) {
+		fprintf(stderr, "can't guess a valid from, please use -f option.\n");
+		return EXIT_FAILURE;
+	}
+
+	/* reads message from stdin */
+	if (collect(&message))
+		return EXIT_FAILURE;
+
+	send_message(message.data, message.len, argv);
 
-  release(&message);
-  return EXIT_SUCCESS;
+	release(&message);
+	return EXIT_SUCCESS;
 }
 
 #endif

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_odbc/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_odbc/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_odbc/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,17 +1,4 @@
-include ../mod_spidermonkey/sm.mak
-LDFLAGS+=-lodbc
-
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install unixODBC-2.2.12.tar.gz --prefix=$(PREFIX) --disable-gui --without-x --with-pic
+switch_srcdir=../../../..
 
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(OBJS) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+include ../mod_spidermonkey/sm.mak
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_odbc/mod_spidermonkey_odbc.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_odbc/mod_spidermonkey_odbc.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_odbc/mod_spidermonkey_odbc.c	Tue Apr 24 10:14:28 2007
@@ -30,450 +30,339 @@
  *
  */
 #include "mod_spidermonkey.h"
-
-
-#include <sql.h>
-#ifdef _MSC_VER
-#pragma warning(push)
-#pragma warning(disable:4201)
-#include <sqlext.h>
-#pragma warning(pop)
-#else
-#include <sqlext.h>
-#endif
-#include <sqltypes.h>
+#include <switch_odbc.h>
 
 static const char modname[] = "ODBC";
 
 struct odbc_obj {
-    char *dsn;
-    char *username;
-    char *password;
-    SQLHENV  env;
-    SQLHDBC  con;
-    SQLHSTMT stmt;
-    uint32_t state;
-    SQLCHAR *colbuf;
-    int32 cblen;
-    SQLCHAR *code;
-    int32 codelen;
+	switch_odbc_handle_t *handle;
+	SQLHSTMT stmt;
+	SQLCHAR *colbuf;
+	int32 cblen;
+	SQLCHAR *code;
+	int32 codelen;
 };
-
-typedef enum {
-    ODBC_STATE_INIT,
-    ODBC_STATE_DOWN,
-    ODBC_STATE_CONNECTED,
-    ODBC_STATE_ERROR
-} odbc_state_t;
-typedef struct odbc_obj odbc_obj_t;
-
-typedef enum {
-    ODBC_SUCCESS = 0,
-    ODBC_FAIL = -1
-} odbc_status_t;
-
+typedef struct odbc_obj  odbc_obj_t;
 
 static odbc_obj_t *new_odbc_obj(char *dsn, char *username, char *password)
 {
 	odbc_obj_t *new_obj;
 
-    if (!(new_obj = malloc(sizeof(*new_obj)))) {
-        goto err;
-    }
-    
-    if (!(new_obj->dsn = strdup(dsn))) {
-        goto err;
-    }
-
-    if (!(new_obj->username = strdup(username))) {
-        goto err;
-    }
-
-    if (!(new_obj->password = strdup(password))) {
-        goto err;
-    }
+	if (!(new_obj = malloc(sizeof(*new_obj)))) {
+		goto err;
+	}
 
-	new_obj->env = SQL_NULL_HANDLE;
-	new_obj->state = ODBC_STATE_INIT;
-    
+	if (!(new_obj->handle = switch_odbc_handle_new(dsn, username, password))) {
+		goto err;
+	}
+	
 	return new_obj;
 
-err:
+  err:
 	if (new_obj) {
-		switch_safe_free(new_obj->dsn);
-		switch_safe_free(new_obj->username);
-		switch_safe_free(new_obj->password);
-		switch_safe_free(new_obj);	
+		if (new_obj->handle) {
+			switch_odbc_handle_destroy(&new_obj->handle);
+		}
+		switch_safe_free(new_obj);
 	}
 
 	return NULL;
 }
 
-odbc_status_t odbc_obj_disconnect(odbc_obj_t *obj)
+switch_odbc_status_t odbc_obj_connect(odbc_obj_t *obj)
 {
-	int result;
-
-    if (obj->state == ODBC_STATE_CONNECTED) {
-        result = SQLDisconnect(obj->con);
-        if (result == ODBC_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Disconnected %d from [%s]\n", result, obj->dsn);
-        } else {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Disconnectiong [%s]\n", obj->dsn);
-        }
-    } else {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "[%s] already disconnected\n", obj->dsn);
-    }
-    
-	obj->state = ODBC_STATE_DOWN;
-
-	return ODBC_SUCCESS;
+	
+	return switch_odbc_handle_connect(obj->handle);
 }
 
-odbc_status_t odbc_obj_connect(odbc_obj_t *obj)
+static void destroy_odbc_obj(odbc_obj_t ** objp)
 {
-	int result;
-	SQLINTEGER err;
-	int16_t mlen;
-	unsigned char msg[200], stat[10];
+	odbc_obj_t *obj = *objp;
 
-	if (obj->env == SQL_NULL_HANDLE) {
-		result = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &obj->env);
-
-		if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error AllocHandle\n");
-			return ODBC_FAIL;
-		}
-
-		result = SQLSetEnvAttr(obj->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
-
-		if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error SetEnv\n");
-			SQLFreeHandle(SQL_HANDLE_ENV, obj->env);
-			return ODBC_FAIL;
-		}
-
-		result = SQLAllocHandle(SQL_HANDLE_DBC, obj->env, &obj->con);
-
-		if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error AllocHDB %d\n", result);
-			SQLFreeHandle(SQL_HANDLE_ENV, obj->env);
-			return ODBC_FAIL;
-		}
-		SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
+	if (obj->handle) {
+		switch_odbc_handle_destroy(&obj->handle);
 	}
-	if (obj->state == ODBC_STATE_CONNECTED) {
-		odbc_obj_disconnect(obj);
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Re-connecting %s\n", obj->dsn);
+	if (obj->stmt) {
+		SQLFreeHandle(SQL_HANDLE_STMT, obj->stmt);
 	}
+	switch_safe_free(obj->colbuf);
+	switch_safe_free(obj->code);
+	switch_safe_free(obj);
+}
 
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Connecting %s\n", obj->dsn);
 
-	result = SQLConnect(obj->con,
-                        (SQLCHAR *) obj->dsn, SQL_NTS,
-                        (SQLCHAR *) obj->username, SQL_NTS,
-                        (SQLCHAR *) obj->password, SQL_NTS);
-    
-	if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
-		SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, stat, &err, msg, 100, &mlen);
-		SQLFreeHandle(SQL_HANDLE_ENV, obj->env);
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error SQLConnect=%d errno=%d %s\n", result, (int)err, msg);
-		return ODBC_FAIL;
-	} else {
+/* ODBC Object */
+/*********************************************************************************/
+static JSBool odbc_construct(JSContext * cx, JSObject * obj, uintN argc, jsval *argv, jsval *rval)
+{
+	odbc_obj_t *odbc_obj = NULL;
+	char *dsn, *username, *password;
+	int32 blen = 1024;
 
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Connected to [%s]\n", obj->dsn);
-		obj->state = ODBC_STATE_CONNECTED;
+	if (argc < 3) {
+		return JS_FALSE;
 	}
 
-	return ODBC_SUCCESS;
-}
+	dsn = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
+	username = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
+	password = JS_GetStringBytes(JS_ValueToString(cx, argv[2]));
+
+	if (argc > 3) {
+		int32 len;
+		JS_ValueToInt32(cx, argv[3], &len);
 
-static void destroy_odbc_obj(odbc_obj_t **objp)
-{
-    odbc_obj_t *obj = *objp;
-
-	odbc_obj_disconnect(obj);
+		if (len > 0) {
+			blen = len;
+		}
+	}
 
-	SQLFreeHandle(SQL_HANDLE_STMT, obj->stmt);
-	SQLFreeHandle(SQL_HANDLE_DBC, obj->con);
-	SQLFreeHandle(SQL_HANDLE_ENV, obj->env);
+	if (switch_strlen_zero(username)) {
+		username = NULL;
+	}
 
-	switch_safe_free(obj->dsn);
-    switch_safe_free(obj->username);
-    switch_safe_free(obj->password);
-	switch_safe_free(obj->colbuf);
-	switch_safe_free(obj->code);
-    switch_safe_free(obj);
-}
+	if (switch_strlen_zero(password)) {
+		password = NULL;
+	}
 
+	if (dsn) {
+		odbc_obj = new_odbc_obj(dsn, username, password);
+	}
 
-/* ODBC Object */
-/*********************************************************************************/
-static JSBool odbc_construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
-{
-    odbc_obj_t *odbc_obj = NULL;
-    char *dsn, *username, *password;
-    int32 blen = 1024;
-
-    if (argc < 3) {
-        return JS_FALSE;
-    } 
-
-    dsn = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
-    username = JS_GetStringBytes(JS_ValueToString(cx, argv[1]));
-    password = JS_GetStringBytes(JS_ValueToString(cx, argv[2]));
-
-    if (argc > 3) {
-        int32 len;
-        JS_ValueToInt32(cx, argv[3], &len);
-
-        if (len > 0) {
-            blen = len;
-        }
-    }
-    
-    if (dsn && username && password) {
-        odbc_obj = new_odbc_obj(dsn, username, password);
-    }
+	if (!odbc_obj) {
+		return JS_FALSE;
+	}
 
-    if (!odbc_obj) {
-        return JS_FALSE;
-    }
+	if (!(odbc_obj->colbuf = (SQLCHAR *) malloc(blen))) {
+		destroy_odbc_obj(&odbc_obj);
+		return JS_FALSE;
+	}
 
-    if (!(odbc_obj->colbuf = (SQLCHAR *) malloc(blen))) {
-        destroy_odbc_obj(&odbc_obj);
-        return JS_FALSE;
-    }
+	odbc_obj->cblen = blen;
 
-    odbc_obj->cblen = blen;
+	blen += 1536;
 
-    blen += 1536;
+	if (!(odbc_obj->code = (SQLCHAR *) malloc(blen))) {
+		destroy_odbc_obj(&odbc_obj);
+		return JS_FALSE;
+	}
 
-    if (!(odbc_obj->code = (SQLCHAR *) malloc(blen))) {
-        destroy_odbc_obj(&odbc_obj);
-        return JS_FALSE;
-    }
-    
-    odbc_obj->codelen = blen;
+	odbc_obj->codelen = blen;
 
 	JS_SetPrivate(cx, obj, odbc_obj);
 
 	return JS_TRUE;
 }
 
-static void odbc_destroy(JSContext *cx, JSObject *obj)
+static void odbc_destroy(JSContext * cx, JSObject * obj)
 {
-    odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
+	odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
 
-    if (odbc_obj) {
-        destroy_odbc_obj(&odbc_obj);
-    }
+	if (odbc_obj) {
+		destroy_odbc_obj(&odbc_obj);
+	}
 }
 
-static JSBool odbc_connect(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool odbc_connect(JSContext * cx, JSObject * obj, uintN argc, jsval *argv, jsval *rval)
 {
-    odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
-    JSBool tf = JS_TRUE;
+	odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
+	JSBool tf = JS_TRUE;
 
-    if (odbc_obj) {
-        if (odbc_obj_connect(odbc_obj) == ODBC_SUCCESS) {
-            tf = JS_TRUE;
-        } else {
-            tf = JS_FALSE;
-        }
-    }
-    
-    *rval = BOOLEAN_TO_JSVAL( tf );
+	if (odbc_obj) {
+		if (odbc_obj_connect(odbc_obj) == SWITCH_ODBC_SUCCESS) {
+			tf = JS_TRUE;
+		} else {
+			tf = JS_FALSE;
+		}
+	}
+
+	*rval = BOOLEAN_TO_JSVAL(tf);
 
 	return JS_TRUE;
 }
 
-static JSBool odbc_exec(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool odbc_exec(JSContext * cx, JSObject * obj, uintN argc, jsval *argv, jsval *rval)
 {
-    odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
-    char *sql;
-    JSBool tf = JS_FALSE;
-    int result;
+	odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
+	char *sql;
+	JSBool tf = JS_FALSE;
 
-    if (argc < 1) {
-        goto done;
-    }
+	if (argc < 1) {
+		goto done;
+	}
 
-    if (odbc_obj->state != ODBC_STATE_CONNECTED) {
-        goto done;
-    }
+	if (switch_odbc_handle_get_state(odbc_obj->handle) != SWITCH_ODBC_STATE_CONNECTED) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Database is not connected!\n");
+		goto done;
+	}
 
-    if (odbc_obj->stmt) {
-        SQLFreeHandle (SQL_HANDLE_STMT, odbc_obj->stmt);
-        odbc_obj->stmt = NULL;
-    }
-    
-    sql = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
+	if (odbc_obj->stmt) {
+		SQLFreeHandle(SQL_HANDLE_STMT, odbc_obj->stmt);
+		odbc_obj->stmt = NULL;
+	}
 
-    if (SQLAllocHandle(SQL_HANDLE_STMT, odbc_obj->con, &odbc_obj->stmt) != SQL_SUCCESS) {
-        goto done;
-    }
+	sql = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 
-    if (SQLPrepare(odbc_obj->stmt, (unsigned char *)sql, SQL_NTS) != SQL_SUCCESS) {
-        goto done;
-    }
 
-    result = SQLExecute(odbc_obj->stmt);
+	if (switch_odbc_handle_exec(odbc_obj->handle, sql, &odbc_obj->stmt) != SWITCH_ODBC_SUCCESS) {
+		goto done;
+	}
 
-    if (result != SQL_SUCCESS && result != SQL_SUCCESS_WITH_INFO) {
-        goto done;
-    }
-    
-    tf = JS_TRUE;
-    
- done:
+	tf = JS_TRUE;
+
+  done:
 
-    *rval = BOOLEAN_TO_JSVAL( tf );
+	*rval = BOOLEAN_TO_JSVAL(tf);
 
-    return JS_TRUE;
+	return JS_TRUE;
 }
 
-static JSBool odbc_num_rows(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool odbc_num_rows(JSContext * cx, JSObject * obj, uintN argc, jsval *argv, jsval *rval)
 {
-    odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
+	odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
 
-    SQLSMALLINT rows = 0;    
+	SQLSMALLINT rows = 0;
 
-    if (odbc_obj->state != ODBC_STATE_CONNECTED) {
-        goto done;
-    }
+	if (switch_odbc_handle_get_state(odbc_obj->handle) != SWITCH_ODBC_STATE_CONNECTED) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Database is not connected!\n");
+		goto done;
+	}
 
-    if (odbc_obj->stmt) {
-        SQLNumResultCols(odbc_obj->stmt, &rows);
-    }
+	if (odbc_obj->stmt) {
+		SQLNumResultCols(odbc_obj->stmt, &rows);
+	}
 
- done:
+  done:
 
-    *rval = INT_TO_JSVAL( rows );
+	*rval = INT_TO_JSVAL(rows);
 
-    return JS_TRUE;
+	return JS_TRUE;
 
 }
 
 
-static JSBool odbc_next_row(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool odbc_next_row(JSContext * cx, JSObject * obj, uintN argc, jsval *argv, jsval *rval)
 {
-    odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
-    int result = 0;
-    JSBool tf = JS_FALSE;
+	odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
+	int result = 0;
+	JSBool tf = JS_FALSE;
 
-    if (odbc_obj->state != ODBC_STATE_CONNECTED) {
+	if (switch_odbc_handle_get_state(odbc_obj->handle) != SWITCH_ODBC_STATE_CONNECTED) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Database is not connected!\n");
         goto done;
     }
 
-    if (odbc_obj->stmt) {
-        if ((result = SQLFetch(odbc_obj->stmt) == SQL_SUCCESS)) {
-            tf = JS_TRUE;
-        }
-    }
 
- done:
+	if (odbc_obj->stmt) {
+		if ((result = SQLFetch(odbc_obj->stmt) == SQL_SUCCESS)) {
+			tf = JS_TRUE;
+		}
+	}
 
-    *rval = BOOLEAN_TO_JSVAL( tf );
+  done:
 
-    return JS_TRUE;
+	*rval = BOOLEAN_TO_JSVAL(tf);
+
+	return JS_TRUE;
 }
 
 static char *escape_data(char *in)
 {
-    switch_size_t nlen = strlen(in);
-    uint32_t qc = 0;
-    char *p, *q, *r;
-
-    for(p = in; p && *p; p++) {
-        if (*p == '"') {
-            qc += 2;
-        }
-    }
-    
-    nlen += qc + 1;
+	switch_size_t nlen = strlen(in);
+	uint32_t qc = 0;
+	char *p, *q, *r;
+
+	for (p = in; p && *p; p++) {
+		if (*p == '"') {
+			qc += 2;
+		}
+	}
 
-    if (!(q = (char *) malloc(nlen))) {
-        return NULL;
-    }
+	nlen += qc + 1;
 
-    r = q;
-    qc = 0;
-    for(p = in; p && *p; p++) {
-        if (*p == '"') {
-            *r++ = '\\';
-        }
-        *r++ = *p;
-        if (++qc > nlen) {
-            break;
-        }
-    }
-    
-    *r++ = '\0';
+	if (!(q = (char *) malloc(nlen))) {
+		return NULL;
+	}
+
+	r = q;
+	qc = 0;
+	for (p = in; p && *p; p++) {
+		if (*p == '"') {
+			*r++ = '\\';
+		}
+		*r++ = *p;
+		if (++qc > nlen) {
+			break;
+		}
+	}
+
+	*r++ = '\0';
+
+	return q;
 
-    return q;
-    
 }
 
 
-static JSBool odbc_get_data(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool odbc_get_data(JSContext * cx, JSObject * obj, uintN argc, jsval *argv, jsval *rval)
 {
 
-    odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
-    JSBool tf = JS_FALSE;
+	odbc_obj_t *odbc_obj = (odbc_obj_t *) JS_GetPrivate(cx, obj);
+	JSBool tf = JS_FALSE;
 
-    if (odbc_obj->state != ODBC_STATE_CONNECTED) {
+	if (switch_odbc_handle_get_state(odbc_obj->handle) != SWITCH_ODBC_STATE_CONNECTED) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Database is not connected!\n");
         goto done;
     }
 
-    if (odbc_obj->stmt) {
-        SQLSMALLINT c = 0, x = 0;
-        int result;
-        char code[66560];
-
-        snprintf(code, sizeof(code), "~var _oDbC_dB_RoW_DaTa_ = {}");
-        eval_some_js(code, cx, obj, rval);
-        if (*rval == JS_FALSE) {
-            return JS_TRUE; 
-        }
-
-        result = SQLNumResultCols(odbc_obj->stmt, &c);
-        if (result == SQL_SUCCESS || result == SQL_SUCCESS_WITH_INFO) {
-            for (x = 1; x <= c; x++) {
-                SQLSMALLINT NameLength, DataType, DecimalDigits, Nullable;
-                SQLUINTEGER ColumnSize;
-                SQLCHAR name[1024] = "";
-                SQLCHAR *data = odbc_obj->colbuf;
-                SQLCHAR *esc = NULL;
-
-                SQLDescribeCol(odbc_obj->stmt, x, name, sizeof(name), &NameLength, &DataType, &ColumnSize, &DecimalDigits, &Nullable);
-                SQLGetData(odbc_obj->stmt, x, SQL_C_CHAR, odbc_obj->colbuf, odbc_obj->cblen, NULL);
-                
-                if (strchr((char *)odbc_obj->colbuf, '"')) { /* please don't */
-                    esc = (SQLCHAR *) escape_data((char *)odbc_obj->colbuf);
-                    data = esc;
-                }
-
-                snprintf((char *)odbc_obj->code, odbc_obj->codelen, "~_oDbC_dB_RoW_DaTa_[\"%s\"] = \"%s\"", name, data);
-                switch_safe_free(esc);
-
-                eval_some_js((char *)odbc_obj->code, cx, obj, rval);
-
-                if (*rval == JS_FALSE) {
-                    return JS_TRUE; 
-                }
-            }
-
-            JS_GetProperty(cx, obj, "_oDbC_dB_RoW_DaTa_", rval);
-            return JS_TRUE; 
-        }
+	if (odbc_obj->stmt) {
+		SQLSMALLINT c = 0, x = 0;
+		SQLINTEGER m = 0;
+		char code[66560];
+
+		snprintf(code, sizeof(code), "~var _oDbC_dB_RoW_DaTa_ = {}");
+		eval_some_js(code, cx, obj, rval);
+		if (*rval == JS_FALSE) {
+			return JS_TRUE;
+		}
 
-    }
+		SQLNumResultCols(odbc_obj->stmt, &c);
+		SQLRowCount(odbc_obj->stmt, &m);
+		if (m > 0) {
+			for (x = 1; x <= c; x++) {
+				SQLSMALLINT NameLength, DataType, DecimalDigits, Nullable;
+				SQLUINTEGER ColumnSize;
+				SQLCHAR name[1024] = "";
+				SQLCHAR *data = odbc_obj->colbuf;
+				SQLCHAR *esc = NULL;
+				
+				SQLDescribeCol(odbc_obj->stmt, x, name, sizeof(name), &NameLength, &DataType, &ColumnSize, &DecimalDigits, &Nullable);
+				SQLGetData(odbc_obj->stmt, x, SQL_C_CHAR, odbc_obj->colbuf, odbc_obj->cblen, NULL);
+
+				if (strchr((char *) odbc_obj->colbuf, '"')) {	/* please don't */
+					esc = (SQLCHAR *) escape_data((char *) odbc_obj->colbuf);
+					data = esc;
+				}
+
+				snprintf((char *) odbc_obj->code, odbc_obj->codelen, "~_oDbC_dB_RoW_DaTa_[\"%s\"] = \"%s\"", name, data);
+				switch_safe_free(esc);
+
+				eval_some_js((char *) odbc_obj->code, cx, obj, rval);
+
+				if (*rval == JS_FALSE) {
+					return JS_TRUE;
+				}
+			}
 
- done:
+			JS_GetProperty(cx, obj, "_oDbC_dB_RoW_DaTa_", rval);
+			return JS_TRUE;
+		}
+
+	}
 
-    *rval = BOOLEAN_TO_JSVAL( tf );
+  done:
 
-    return JS_TRUE;
+	*rval = BOOLEAN_TO_JSVAL(tf);
+
+	return JS_TRUE;
 
 }
 
@@ -492,50 +381,40 @@
 
 
 static JSPropertySpec odbc_props[] = {
-//	{"name", odbc_NAME, JSPROP_READONLY|JSPROP_PERMANENT}, 
+//  {"name", odbc_NAME, JSPROP_READONLY|JSPROP_PERMANENT}, 
 	{0}
 };
 
 
-static JSBool odbc_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
+static JSBool odbc_getProperty(JSContext * cx, JSObject * obj, jsval id, jsval * vp)
 {
 	JSBool res = JS_TRUE;
-    
+
 	return res;
 }
 
 JSClass odbc_class = {
-	modname, JSCLASS_HAS_PRIVATE, 
-	JS_PropertyStub,  JS_PropertyStub,	odbc_getProperty,  JS_PropertyStub, 
-	JS_EnumerateStub, JS_ResolveStub,	JS_ConvertStub,	  odbc_destroy, NULL, NULL, NULL,
+	modname, JSCLASS_HAS_PRIVATE,
+	JS_PropertyStub, JS_PropertyStub, odbc_getProperty, JS_PropertyStub,
+	JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, odbc_destroy, NULL, NULL, NULL,
 	odbc_construct
 };
 
 
-switch_status_t odbc_load(JSContext *cx, JSObject *obj)
+switch_status_t odbc_load(JSContext * cx, JSObject * obj)
 {
-	JS_InitClass(cx,
-				 obj,
-				 NULL,
-				 &odbc_class,
-				 odbc_construct,
-				 3,
-				 odbc_props,
-				 odbc_methods,
-				 odbc_props,
-				 odbc_methods
-				 );
+	JS_InitClass(cx, obj, NULL, &odbc_class, odbc_construct, 3, odbc_props, odbc_methods, odbc_props, odbc_methods);
 	return SWITCH_STATUS_SUCCESS;
 }
 
 
 const sm_module_interface_t odbc_module_interface = {
 	/*.name = */ modname,
-	/*.spidermonkey_load*/ odbc_load,
-	/*.next*/ NULL
+	/*.spidermonkey_load */ odbc_load,
+	/*.next */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t **module_interface)
+SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t ** module_interface)
 {
 	*module_interface = &odbc_module_interface;
 	return SWITCH_STATUS_SUCCESS;

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_skel/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_skel/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_skel/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,19 +1,7 @@
-include ../mod_spidermonkey/sm.mak
-
-OBJS=#$(BASE)/libs/mozilla/js/src/$(OS_CONFIG)_$(VER).OBJ/libjs.a $(BASE)/libs/mozilla/nsprpub/dist/lib/libnspr4.a
-LINKER=$(CC)
-
-
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
 
-depends:
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(LINKER) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(OBJS) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
+switch_srcdir=../../../..
+LOCAL_CFLAGS=
+LOCAL_LDFLAGS=
+LOCAL_LIBADD=
+include ../mod_spidermonkey/sm.mak
 
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_skel/mod_spidermonkey_skel.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_skel/mod_spidermonkey_skel.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_skel/mod_spidermonkey_skel.c	Tue Apr 24 10:14:28 2007
@@ -35,16 +35,16 @@
 
 /* Skel Object */
 /*********************************************************************************/
-static JSBool skel_construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool skel_construct(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	return JS_TRUE;
 }
 
-static void skel_destroy(JSContext *cx, JSObject *obj)
+static void skel_destroy(JSContext * cx, JSObject * obj)
 {
 }
 
-static JSBool skel_my_method(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool skel_my_method(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	return JS_FALSE;
 }
@@ -60,12 +60,12 @@
 
 
 static JSPropertySpec skel_props[] = {
-	{"name", SKEL_NAME, JSPROP_READONLY|JSPROP_PERMANENT}, 
+	{"name", SKEL_NAME, JSPROP_READONLY | JSPROP_PERMANENT},
 	{0}
 };
 
 
-static JSBool skel_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
+static JSBool skel_getProperty(JSContext * cx, JSObject * obj, jsval id, jsval * vp)
 {
 	JSBool res = JS_TRUE;
 
@@ -73,37 +73,27 @@
 }
 
 JSClass skel_class = {
-	modname, JSCLASS_HAS_PRIVATE, 
-	JS_PropertyStub,  JS_PropertyStub,	skel_getProperty,  JS_PropertyStub, 
-	JS_EnumerateStub, JS_ResolveStub,	JS_ConvertStub,	  skel_destroy, NULL, NULL, NULL,
+	modname, JSCLASS_HAS_PRIVATE,
+	JS_PropertyStub, JS_PropertyStub, skel_getProperty, JS_PropertyStub,
+	JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, skel_destroy, NULL, NULL, NULL,
 	skel_construct
 };
 
 
-switch_status_t spidermonkey_load(JSContext *cx, JSObject *obj)
+switch_status_t spidermonkey_load(JSContext * cx, JSObject * obj)
 {
-	JS_InitClass(cx,
-				 obj,
-				 NULL,
-				 &skel_class,
-				 skel_construct,
-				 3,
-				 skel_props,
-				 skel_methods,
-				 skel_props,
-				 skel_methods
-				 );
+	JS_InitClass(cx, obj, NULL, &skel_class, skel_construct, 3, skel_props, skel_methods, skel_props, skel_methods);
 	return SWITCH_STATUS_SUCCESS;
 }
 
 
 const sm_module_interface_t skel_module_interface = {
 	/*.name = */ modname,
-	/*.spidermonkey_load*/ spidermonkey_load,
-	/*.next*/ NULL
+	/*.spidermonkey_load */ spidermonkey_load,
+	/*.next */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t **module_interface)
+SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t ** module_interface)
 {
 	*module_interface = &skel_module_interface;
 	return SWITCH_STATUS_SUCCESS;

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_teletone/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_teletone/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_teletone/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,16 +1,4 @@
+switch_srcdir=../../../..
+LOCAL_CFLAGS=-I$(switch_srcdir)/libs/libteletone/src
 include ../mod_spidermonkey/sm.mak
-LDFLAGS+=-lteletone
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(OBJS) $(LDFLAGS)
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod

Modified: freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_teletone/mod_spidermonkey_teletone.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_teletone/mod_spidermonkey_teletone.c	(original)
+++ freeswitch/branches/cparker/src/mod/languages/mod_spidermonkey_teletone/mod_spidermonkey_teletone.c	Tue Apr 24 10:14:28 2007
@@ -46,7 +46,6 @@
 	switch_core_session_t *session;
 	switch_codec_t codec;
 	switch_buffer_t *audio_buffer;
-	switch_buffer_t *loop_buffer;
 	switch_memory_pool_t *pool;
 	switch_timer_t *timer;
 	switch_timer_t timer_base;
@@ -57,7 +56,7 @@
 };
 
 
-static int teletone_handler(teletone_generation_session_t *ts, teletone_tone_map_t *map)
+static int teletone_handler(teletone_generation_session_t * ts, teletone_tone_map_t * map)
 {
 	struct teletone_obj *tto = ts->user_data;
 	int wrote;
@@ -74,7 +73,7 @@
 
 /* TeleTone Object */
 /*********************************************************************************/
-static JSBool teletone_construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool teletone_construct(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	JSObject *session_obj;
 	struct teletone_obj *tto = NULL;
@@ -116,8 +115,7 @@
 							   read_codec->implementation->samples_per_second,
 							   read_codec->implementation->microseconds_per_frame / 1000,
 							   read_codec->implementation->number_of_channels,
-							   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-							   NULL, pool) == SWITCH_STATUS_SUCCESS) {
+							   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL, pool) == SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activated\n");
 	} else {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Failed\n");
@@ -129,8 +127,8 @@
 		if (switch_core_timer_init(&tto->timer_base,
 								   timer_name,
 								   ms,
-								   (read_codec->implementation->samples_per_second / 50) * read_codec->implementation->number_of_channels,
-								   pool) == SWITCH_STATUS_SUCCESS) {
+								   (read_codec->implementation->samples_per_second / 50) *
+								   read_codec->implementation->number_of_channels, pool) == SWITCH_STATUS_SUCCESS) {
 			tto->timer = &tto->timer_base;
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Timer INIT Success %u\n", ms);
 		} else {
@@ -149,7 +147,7 @@
 	return JS_TRUE;
 }
 
-static void teletone_destroy(JSContext *cx, JSObject *obj)
+static void teletone_destroy(JSContext * cx, JSObject * obj)
 {
 	struct teletone_obj *tto = JS_GetPrivate(cx, obj);
 	switch_memory_pool_t *pool;
@@ -159,7 +157,6 @@
 		}
 		teletone_destroy_session(&tto->ts);
 		switch_buffer_destroy(&tto->audio_buffer);
-		switch_buffer_destroy(&tto->loop_buffer);
 		switch_core_codec_destroy(&tto->codec);
 		pool = tto->pool;
 		tto->pool = NULL;
@@ -169,26 +166,26 @@
 	}
 }
 
-static JSBool teletone_add_tone(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool teletone_add_tone(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct teletone_obj *tto = JS_GetPrivate(cx, obj);
-	if (argc > 2) { 
+	if (argc > 2) {
 		int x;
 		char *fval;
 		char *map_str;
 		map_str = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
 
-		for(x = 1; x < TELETONE_MAX_TONES; x++) {
+		for (x = 1; x < TELETONE_MAX_TONES; x++) {
 			fval = JS_GetStringBytes(JS_ValueToString(cx, argv[x]));
-			tto->ts.TONES[(int)*map_str].freqs[x-1] = strtod(fval, NULL);
+			tto->ts.TONES[(int) *map_str].freqs[x - 1] = strtod(fval, NULL);
 		}
 		return JS_TRUE;
 	}
-	
+
 	return JS_FALSE;
 }
 
-static JSBool teletone_on_dtmf(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool teletone_on_dtmf(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct teletone_obj *tto = JS_GetPrivate(cx, obj);
 	if (argc > 0) {
@@ -201,7 +198,7 @@
 	return JS_TRUE;
 }
 
-static JSBool teletone_generate(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
+static JSBool teletone_generate(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
 {
 	struct teletone_obj *tto = JS_GetPrivate(cx, obj);
 	int32 loops = 0;
@@ -209,7 +206,7 @@
 	if (argc > 0) {
 		char *script;
 		switch_core_session_t *session;
-		switch_frame_t write_frame = {0};
+		switch_frame_t write_frame = { 0 };
 		unsigned char *fdata[1024];
 		switch_frame_t *read_frame;
 		int stream_id;
@@ -222,17 +219,12 @@
 				return JS_FALSE;
 			}
 			loops--;
-			if (!tto->loop_buffer) {
-				switch_buffer_create_dynamic(&tto->loop_buffer, JS_BLOCK_SIZE, JS_BUFFER_SIZE, 0);
-			}
-		} 
+		}
 
 		if (tto->audio_buffer) {
 			switch_buffer_zero(tto->audio_buffer);
 		}
-		if (tto->loop_buffer) {
-			switch_buffer_zero(tto->loop_buffer);
-		}
+
 		tto->ts.debug = 1;
 		tto->ts.debug_stream = switch_core_get_console();
 
@@ -244,25 +236,29 @@
 		write_frame.data = fdata;
 
 		channel = switch_core_session_get_channel(session);
-		
+
 		if (tto->timer) {
 			for (stream_id = 0; stream_id < switch_core_session_get_stream_count(session); stream_id++) {
 				switch_core_service_session(session, &thread_session, stream_id);
 			}
 		}
 
-		for(;;) {
+		if (loops) {
+			switch_buffer_set_loops(tto->audio_buffer, loops);
+		}
+
+		for (;;) {
 
 			if (switch_test_flag(tto, TTF_DTMF)) {
 				char dtmf[128];
 				char *ret;
-
+				
 				if (switch_channel_has_dtmf(channel)) {
 					uintN aargc = 0;
 					jsval aargv[4];
 
 					switch_channel_dequeue_dtmf(channel, dtmf, sizeof(dtmf));
-					aargv[aargc++] = STRING_TO_JSVAL (JS_NewStringCopyZ(cx, dtmf));
+					aargv[aargc++] = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, dtmf));
 					JS_CallFunction(cx, obj, tto->function, aargc, aargv, &tto->ret);
 					ret = JS_GetStringBytes(JS_ValueToString(cx, tto->ret));
 					if (strcmp(ret, "true") && strcmp(ret, "undefined")) {
@@ -271,37 +267,23 @@
 					}
 				}
 			}
-			
+
 			if (tto->timer) {
-				if (switch_core_timer_next(tto->timer)< 0) {
+				if (switch_core_timer_next(tto->timer) != SWITCH_STATUS_SUCCESS) {
 					break;
 				}
 
 			} else {
 				switch_status_t status;
 				status = switch_core_session_read_frame(session, &read_frame, -1, 0);
-				
+
 				if (!SWITCH_READ_ACCEPTABLE(status)) {
 					break;
 				}
 			}
-			if ((write_frame.datalen = (uint32_t)switch_buffer_read(tto->audio_buffer, fdata, write_frame.codec->implementation->bytes_per_frame)) <= 0) {
-				if (loops) { 
-					switch_buffer_t *tmp;
-
-					/* Switcharoo*/
-					tmp = tto->audio_buffer;
-					tto->audio_buffer = tto->loop_buffer;
-					tto->loop_buffer = tmp;
-					loops--;
-					/* try again */
-					if ((write_frame.datalen = 
-						 (uint32_t)switch_buffer_read(tto->audio_buffer, fdata, write_frame.codec->implementation->bytes_per_frame)) <= 0) {
-						break;
-					}
-				} else {
-					break;
-				}
+			if ((write_frame.datalen = (uint32_t) switch_buffer_read_loop(tto->audio_buffer,
+																		  fdata, write_frame.codec->implementation->bytes_per_frame)) <= 0) {
+				break;
 			}
 
 			write_frame.samples = write_frame.datalen / 2;
@@ -311,9 +293,6 @@
 					break;
 				}
 			}
-			if (tto->loop_buffer && loops) {
-				switch_buffer_write(tto->loop_buffer, write_frame.data, write_frame.datalen);
-			}
 		}
 
 		if (tto->timer) {
@@ -321,7 +300,7 @@
 		}
 		return JS_TRUE;
 	}
-	
+
 	return JS_FALSE;
 }
 
@@ -332,18 +311,18 @@
 static JSFunctionSpec teletone_methods[] = {
 	{"generate", teletone_generate, 1},
 	{"onDTMF", teletone_on_dtmf, 1},
-	{"addTone", teletone_add_tone, 10},	 
+	{"addTone", teletone_add_tone, 10},
 	{0}
 };
 
 
 static JSPropertySpec teletone_props[] = {
-	{"name", TELETONE_NAME, JSPROP_READONLY|JSPROP_PERMANENT}, 
+	{"name", TELETONE_NAME, JSPROP_READONLY | JSPROP_PERMANENT},
 	{0}
 };
 
 
-static JSBool teletone_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
+static JSBool teletone_getProperty(JSContext * cx, JSObject * obj, jsval id, jsval * vp)
 {
 	JSBool res = JS_TRUE;
 
@@ -351,37 +330,27 @@
 }
 
 JSClass teletone_class = {
-	modname, JSCLASS_HAS_PRIVATE, 
-	JS_PropertyStub,  JS_PropertyStub,	teletone_getProperty,  JS_PropertyStub, 
-	JS_EnumerateStub, JS_ResolveStub,	JS_ConvertStub,	  teletone_destroy, NULL, NULL, NULL,
+	modname, JSCLASS_HAS_PRIVATE,
+	JS_PropertyStub, JS_PropertyStub, teletone_getProperty, JS_PropertyStub,
+	JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, teletone_destroy, NULL, NULL, NULL,
 	teletone_construct
 };
 
 
-switch_status_t teletone_load(JSContext *cx, JSObject *obj)
+switch_status_t teletone_load(JSContext * cx, JSObject * obj)
 {
-	JS_InitClass(cx,
-				 obj,
-				 NULL,
-				 &teletone_class,
-				 teletone_construct,
-				 3,
-				 teletone_props,
-				 teletone_methods,
-				 teletone_props,
-				 teletone_methods
-				 );
+	JS_InitClass(cx, obj, NULL, &teletone_class, teletone_construct, 3, teletone_props, teletone_methods, teletone_props, teletone_methods);
 	return SWITCH_STATUS_SUCCESS;
 }
 
 
 const sm_module_interface_t teletone_module_interface = {
 	/*.name = */ modname,
-	/*.spidermonkey_load*/ teletone_load,
-	/*.next*/ NULL
+	/*.spidermonkey_load */ teletone_load,
+	/*.next */ NULL
 };
 
-SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t **module_interface)
+SWITCH_MOD_DECLARE(switch_status_t) spidermonkey_init(const sm_module_interface_t ** module_interface)
 {
 	*module_interface = &teletone_module_interface;
 	return SWITCH_STATUS_SUCCESS;

Modified: freeswitch/branches/cparker/src/mod/loggers/mod_console/mod_console.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/loggers/mod_console/mod_console.c	(original)
+++ freeswitch/branches/cparker/src/mod/loggers/mod_console/mod_console.c	Tue Apr 24 10:14:28 2007
@@ -32,10 +32,27 @@
 #include <switch.h>
 
 static const char modname[] = "mod_console";
-static const uint8_t STATIC_LEVELS[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
+static const uint8_t STATIC_LEVELS[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
 static int COLORIZE = 0;
-static const char *COLORS[] = 
-	{ SWITCH_SEQ_FRED, SWITCH_SEQ_FRED, SWITCH_SEQ_FRED, SWITCH_SEQ_FRED, SWITCH_SEQ_FMAGEN, SWITCH_SEQ_FCYAN, SWITCH_SEQ_FGREEN, SWITCH_SEQ_FYELLOW, "" };
+#ifdef WIN32
+static HANDLE hStdout;
+static WORD wOldColorAttrs;
+static CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
+static WORD COLORS[] = { FOREGROUND_RED | FOREGROUND_INTENSITY,
+	FOREGROUND_RED | FOREGROUND_INTENSITY,
+	FOREGROUND_RED | FOREGROUND_INTENSITY,
+	FOREGROUND_RED | FOREGROUND_INTENSITY,
+	FOREGROUND_BLUE | FOREGROUND_INTENSITY,
+	FOREGROUND_BLUE | FOREGROUND_INTENSITY,
+	FOREGROUND_GREEN | FOREGROUND_INTENSITY,
+	FOREGROUND_GREEN | FOREGROUND_INTENSITY,
+	FOREGROUND_GREEN | FOREGROUND_INTENSITY
+};
+#else
+static const char *COLORS[] = { SWITCH_SEQ_FRED, SWITCH_SEQ_FRED, SWITCH_SEQ_FRED, SWITCH_SEQ_FRED, SWITCH_SEQ_FMAGEN, SWITCH_SEQ_FCYAN,
+	SWITCH_SEQ_FGREEN, SWITCH_SEQ_FYELLOW, ""
+};
+#endif
 
 static switch_loadable_module_interface_t console_module_interface = {
 	/*.module_name */ modname,
@@ -55,7 +72,8 @@
 static switch_hash_t *name_hash = NULL;
 static int8_t all_level = -1;
 
-static void del_mapping(char *var) {
+static void del_mapping(char *var)
+{
 	if (!strcasecmp(var, "all")) {
 		all_level = -1;
 		return;
@@ -78,7 +96,7 @@
 	}
 
 	del_mapping(name);
-	switch_core_hash_insert(log_hash, name, (void *) &STATIC_LEVELS[(uint8_t)switch_log_str2level(val)]);
+	switch_core_hash_insert(log_hash, name, (void *) &STATIC_LEVELS[(uint8_t) switch_log_str2level(val)]);
 }
 
 static switch_status_t config_logger(void)
@@ -93,7 +111,7 @@
 
 	switch_core_hash_init(&log_hash, module_pool);
 	switch_core_hash_init(&name_hash, module_pool);
-	
+
 	if ((settings = switch_xml_child(cfg, "mappings"))) {
 		for (param = switch_xml_child(settings, "param"); param; param = param->next) {
 			char *var = (char *) switch_xml_attr_soft(param, "name");
@@ -109,7 +127,15 @@
 			char *val = (char *) switch_xml_attr_soft(param, "value");
 
 			if (!strcasecmp(var, "colorize") && switch_true(val)) {
+#ifdef WIN32
+				hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
+				if (switch_core_get_console() == stdout && hStdout != INVALID_HANDLE_VALUE && GetConsoleScreenBufferInfo(hStdout, &csbiInfo)) {
+					wOldColorAttrs = csbiInfo.wAttributes;
+					COLORIZE = 1;
+				}
+#else
 				COLORIZE = 1;
+#endif
 			}
 		}
 	}
@@ -125,11 +151,11 @@
 
 	if ((handle = switch_core_data_channel(SWITCH_CHANNEL_ID_LOG))) {
 		uint8_t *lookup = NULL;
-		switch_log_level_t level = SWITCH_LOG_DEBUG;		
+		switch_log_level_t level = SWITCH_LOG_DEBUG;
 
 		if (log_hash) {
 			lookup = switch_core_hash_find(log_hash, node->file);
-			
+
 			if (!lookup) {
 				lookup = switch_core_hash_find(log_hash, node->func);
 			}
@@ -139,11 +165,17 @@
 			level = (switch_log_level_t) *lookup;
 		} else if (all_level > -1) {
 			level = (switch_log_level_t) all_level;
-		} 
+		}
 
-		if (!log_hash || (((all_level > - 1) || lookup) && level >= node->level)) {
+		if (!log_hash || (((all_level > -1) || lookup) && level >= node->level)) {
 			if (COLORIZE) {
+#ifdef WIN32
+				SetConsoleTextAttribute(hStdout, COLORS[node->level]);
+				WriteFile(hStdout, node->data, (DWORD) strlen(node->data), NULL, NULL);
+				SetConsoleTextAttribute(hStdout, wOldColorAttrs);
+#else
 				fprintf(handle, "%s%s%s", COLORS[node->level], node->data, SWITCH_SEQ_DEFAULT_COLOR);
+#endif
 			} else {
 				fprintf(handle, "%s", node->data);
 			}
@@ -152,7 +184,7 @@
 		fprintf(stderr, "HELP I HAVE NO CONSOLE TO LOG TO!\n");
 		fflush(stderr);
 	}
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -169,7 +201,7 @@
 
 	/* setup my logger function */
 	switch_log_bind_logger(switch_console_logger, SWITCH_LOG_DEBUG);
-	
+
 	config_logger();
 
 	/* indicate that the module should continue to be loaded */

Modified: freeswitch/branches/cparker/src/mod/loggers/mod_syslog/mod_syslog.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/loggers/mod_syslog/mod_syslog.c	(original)
+++ freeswitch/branches/cparker/src/mod/loggers/mod_syslog/mod_syslog.c	Tue Apr 24 10:14:28 2007
@@ -50,56 +50,56 @@
 } globals;
 
 SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_ident, globals.ident)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_level, globals.level)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_format, globals.format)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_facility, globals.facility)
-
-static switch_loadable_module_interface_t console_module_interface = {
-	/*.module_name */ modname,
-	/*.endpoint_interface */ NULL,
-	/*.timer_interface */ NULL,
-	/*.dialplan_interface */ NULL,
-	/*.codec_interface */ NULL,
-	/*.application_interface */ NULL,
-	/*.api_interface */ NULL,
-	/*.file_interface */ NULL,
-	/*.speech_interface */ NULL,
-	/*.directory_interface */ NULL
-};
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_level, globals.level)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_format, globals.format)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_facility, globals.facility)
+
+	 static switch_loadable_module_interface_t console_module_interface = {
+		 /*.module_name */ modname,
+		 /*.endpoint_interface */ NULL,
+		 /*.timer_interface */ NULL,
+		 /*.dialplan_interface */ NULL,
+		 /*.codec_interface */ NULL,
+		 /*.application_interface */ NULL,
+		 /*.api_interface */ NULL,
+		 /*.file_interface */ NULL,
+		 /*.speech_interface */ NULL,
+		 /*.directory_interface */ NULL
+	 };
 
 static switch_status_t mod_syslog_logger(const switch_log_node_t *node, switch_log_level_t level)
 {
 	char *message = NULL;
-	char line_no[sizeof(int)*8+1];
+	char line_no[sizeof(int) * 8 + 1];
 	char date[80] = "";
 	switch_time_exp_t time;
 	switch_size_t retsize;
 
-	message = (char *)malloc(strlen(globals.format)+2);
+	message = (char *) malloc(strlen(globals.format) + 2);
 
-	switch_copy_string(message, globals.format, strlen(globals.format)+1);
+	switch_copy_string(message, globals.format, strlen(globals.format) + 1);
 
 	message = switch_string_replace(message, "${message}", node->content);
-	
+
 	if (switch_time_exp_lt(&time, node->timestamp) != SWITCH_STATUS_SUCCESS) {
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	switch_strftime(date, &retsize, sizeof(date), "%Y-%m-%d %T", &time);
 	message = switch_string_replace(message, "${time}", date);
-	
+
 	message = switch_string_replace(message, "${file}", node->file);
 	message = switch_string_replace(message, "${func}", node->func);
-	
+
 	snprintf(line_no, sizeof(line_no), "%d", node->line);
 	message = switch_string_replace(message, "${line}", line_no);
-	
+
 	if (!switch_strlen_zero(message)) {
 		syslog(LOG_ERR, "%s", message);
 	}
 
 	free(message);
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -125,7 +125,7 @@
 				} else if (!strcmp(var, "level")) {
 					set_global_level(val);;
 				}
-	
+
 			}
 		}
 		switch_xml_free(xml);
@@ -153,21 +153,21 @@
 	switch_status_t status;
 	*interface = &console_module_interface;
 
-	if ((status=load_config()) != SWITCH_STATUS_SUCCESS) {
+	if ((status = load_config()) != SWITCH_STATUS_SUCCESS) {
 		return status;
 	}
 
 	openlog(globals.ident, LOG_PID, LOG_USER);
 
 	switch_log_bind_logger(mod_syslog_logger, SWITCH_LOG_DEBUG);
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_unload(const switch_loadable_module_interface_t **interface)
 {
 	closelog();
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 

Modified: freeswitch/branches/cparker/src/mod/say/mod_say_en/mod_say_en.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/say/mod_say_en/mod_say_en.c	(original)
+++ freeswitch/branches/cparker/src/mod/say/mod_say_en/mod_say_en.c	Tue Apr 24 10:14:28 2007
@@ -56,38 +56,27 @@
 		}}\
 
 
-static switch_status_t en_spell(switch_core_session_t *session,
-								char *tosay,
-								switch_say_type_t type,
-								switch_say_method_t method,
-								switch_input_args_t *args)
+static switch_status_t en_spell(switch_core_session_t *session, char *tosay, switch_say_type_t type, switch_say_method_t method, switch_input_args_t *args)
 {
 	char *p;
 
-	for(p = tosay; p && *p; p++) {
+	for (p = tosay; p && *p; p++) {
 		int a = tolower((int) *p);
-        if (a >= 48 && a <= 57) {
-            say_file("digits/%d.wav", a-48);
-        }
-        else {
-    		if (type == SST_NAME_SPELLED) {
-    			say_file("ascii/%d.wav", a);
-    		} else if (type == SST_NAME_PHONETIC) {
-    			say_file("phonetic-ascii/%d.wav", a);
-    		}
-        }
+		if (a >= 48 && a <= 57) {
+			say_file("digits/%d.wav", a - 48);
+		} else {
+			if (type == SST_NAME_SPELLED) {
+				say_file("ascii/%d.wav", a);
+			} else if (type == SST_NAME_PHONETIC) {
+				say_file("phonetic-ascii/%d.wav", a);
+			}
+		}
 	}
 
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static switch_status_t play_group(switch_say_method_t method,
-								  int a,
-								  int b,
-								  int c,
-								  char *what,
-								  switch_core_session_t *session,
-								  switch_input_args_t *args)
+static switch_status_t play_group(switch_say_method_t method, int a, int b, int c, char *what, switch_core_session_t *session, switch_input_args_t *args)
 {
 
 	if (a) {
@@ -118,14 +107,14 @@
 
 	return SWITCH_STATUS_SUCCESS;
 }
-					   
+
 static char *strip_commas(char *in, char *out, switch_size_t len)
 {
 	char *p = in, *q = out;
 	char *ret = out;
 	switch_size_t x = 0;
-	
-	for(;p && *p; p++) {
+
+	for (; p && *p; p++) {
 		if ((*p > 47 && *p < 58)) {
 			*q++ = *p;
 		} else if (*p != ',') {
@@ -148,10 +137,10 @@
 	char *ret = out;
 	switch_size_t x = 0;
 	// valid are 0 - 9, period (.), minus (-), and plus (+) - remove all others
-	for(;p && *p; p++) {
+	for (; p && *p; p++) {
 		if ((*p > 47 && *p < 58) || *p == '.' || *p == '-' || *p == '+') {
 			*q++ = *p;
-		} 
+		}
 
 		if (++x > len) {
 			ret = NULL;
@@ -163,17 +152,14 @@
 }
 
 static switch_status_t en_say_general_count(switch_core_session_t *session,
-											char *tosay,
-											switch_say_type_t type,
-											switch_say_method_t method,
-											switch_input_args_t *args)
+											char *tosay, switch_say_type_t type, switch_say_method_t method, switch_input_args_t *args)
 {
 	switch_channel_t *channel;
 	int in;
-	int x = 0, places[9] = {0};
+	int x = 0, places[9] = { 0 };
 	char sbuf[13] = "";
 	switch_status_t status;
-	
+
 	assert(session != NULL);
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
@@ -186,13 +172,13 @@
 	in = atoi(tosay);
 
 	if (in != 0) {
-		for(x = 8; x >= 0; x--) {
-			int num = (int)pow(10, x);
+		for (x = 8; x >= 0; x--) {
+			int num = (int) pow(10, x);
 			if ((places[x] = in / num)) {
 				in -= places[x] * num;
 			}
 		}
-	
+
 		switch (method) {
 		case SSM_COUNTED:
 		case SSM_PRONOUNCED:
@@ -219,8 +205,7 @@
 		default:
 			break;
 		}
-	}
-	else {
+	} else {
 		say_file("digits/0.wav");
 	}
 
@@ -228,11 +213,7 @@
 }
 
 
-static switch_status_t en_ip(switch_core_session_t *session,
-								char *tosay,
-								switch_say_type_t type,
-								switch_say_method_t method,
-								switch_input_args_t *args)
+static switch_status_t en_ip(switch_core_session_t *session, char *tosay, switch_say_type_t type, switch_say_method_t method, switch_input_args_t *args)
 {
 	char *a, *b, *c, *d;
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
@@ -269,23 +250,20 @@
 	say_file("digits/dot.wav");
 	say_num(atoi(d), method);
 
- done:
+  done:
 	switch_safe_free(a);
 	return status;
 }
 
 
-static switch_status_t en_say_time(switch_core_session_t *session,
-								   char *tosay,
-								   switch_say_type_t type,
-								   switch_say_method_t method,
+static switch_status_t en_say_time(switch_core_session_t *session, char *tosay, switch_say_type_t type, switch_say_method_t method,
 								   switch_input_args_t *args)
 {
 	int32_t t;
 	switch_time_t target = 0;
 	switch_time_exp_t tm;
 	uint8_t say_date = 0, say_time = 0;
-	
+
 	if (type == SST_TIME_MEASUREMENT) {
 		int64_t hours = 0;
 		int64_t minutes = 0;
@@ -295,7 +273,7 @@
 		if (strchr(tosay, ':')) {
 			char *tme = switch_core_session_strdup(session, tosay);
 			char *p;
-			
+
 			if ((p = strrchr(tme, ':'))) {
 				*p++ = '\0';
 				seconds = atoi(p);
@@ -305,10 +283,9 @@
 					if (tme) {
 						hours = atoi(tme);
 					}
+				} else {
+					minutes = atoi(tme);
 				}
-                else {
-                     minutes = atoi(tme);
-                }
 			}
 		} else {
 			if ((seconds = atoi(tosay)) <= 0) {
@@ -320,7 +297,7 @@
 				r = seconds % 60;
 				seconds = r;
 			}
-			
+
 			if (minutes >= 60) {
 				hours = minutes / 60;
 				r = minutes % 60;
@@ -330,45 +307,39 @@
 
 		if (hours) {
 			say_num(hours, SSM_PRONOUNCED);
-            if (hours == 1) {
-                say_file("time/hour.wav");  //TODO -- NEED TO GET "hour.wav" recorded
-            }
-            else {
-                say_file("time/hours.wav");
-            }
-		}
-        else {
-            say_file("digits/0.wav");
-            say_file("time/hours.wav");
-        }
+			if (hours == 1) {
+				say_file("time/hour.wav");	//TODO -- NEED TO GET "hour.wav" recorded
+			} else {
+				say_file("time/hours.wav");
+			}
+		} else {
+			say_file("digits/0.wav");
+			say_file("time/hours.wav");
+		}
 
 		if (minutes) {
 			say_num(minutes, SSM_PRONOUNCED);
-            if (minutes == 1) {
-                say_file("time/minute.wav");
-            }
-            else {
-                say_file("time/minutes.wav");
-            }
-		}
-        else {
-            say_file("digits/0.wav");
-            say_file("time/minutes.wav");
-        }
+			if (minutes == 1) {
+				say_file("time/minute.wav");
+			} else {
+				say_file("time/minutes.wav");
+			}
+		} else {
+			say_file("digits/0.wav");
+			say_file("time/minutes.wav");
+		}
 
 		if (seconds) {
 			say_num(seconds, SSM_PRONOUNCED);
-            if (seconds == 1) {
-                say_file("time/second.wav");
-            }
-            else {
-                say_file("time/seconds.wav");
-            }
-		}
-        else {
-            say_file("digits/0.wav");
-            say_file("time/seconds.wav");
-        }
+			if (seconds == 1) {
+				say_file("time/second.wav");
+			} else {
+				say_file("time/seconds.wav");
+			}
+		} else {
+			say_file("digits/0.wav");
+			say_file("time/seconds.wav");
+		}
 
 		return SWITCH_STATUS_SUCCESS;
 	}
@@ -379,8 +350,8 @@
 		target = switch_time_now();
 	}
 	switch_time_exp_lt(&tm, target);
-	
-	switch(type) {
+
+	switch (type) {
 	case SST_CURRENT_DATE_TIME:
 		say_date = say_time = 1;
 		break;
@@ -403,10 +374,10 @@
 
 	if (say_time) {
 		int32_t hour = tm.tm_hour, pm = 0;
-		
+
 		if (hour > 12) {
 			hour -= 12;
-            pm = 1;
+			pm = 1;
 		} else if (hour == 12) {
 			pm = 1;
 		} else if (hour == 0) {
@@ -432,22 +403,19 @@
 }
 
 
-static switch_status_t en_say_money(switch_core_session_t *session,
-											char *tosay,
-											switch_say_type_t type,
-											switch_say_method_t method,
-											switch_input_args_t *args)
+static switch_status_t en_say_money(switch_core_session_t *session, char *tosay, switch_say_type_t type, switch_say_method_t method,
+									switch_input_args_t *args)
 {
 	switch_channel_t *channel;
-		
-	char sbuf[16] = ""; /* enuough for 999,999,999,999.99 (w/o the commas or leading $) */
+
+	char sbuf[16] = "";			/* enuough for 999,999,999,999.99 (w/o the commas or leading $) */
 	char *dollars = NULL;
 	char *cents = NULL;
-		
+
 	assert(session != NULL);
 	channel = switch_core_session_get_channel(session);
 	assert(channel != NULL);
-			
+
 	if (strlen(tosay) > 15 || !(tosay = strip_nonnumerics(tosay, sbuf, sizeof(sbuf)))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Parse Error!\n");
 		return SWITCH_STATUS_GENERR;
@@ -457,64 +425,57 @@
 
 	if ((cents = strchr(sbuf, '.'))) {
 		*cents++ = '\0';
-        if (strlen(cents) > 2) {
-            cents[2] = '\0';
-        }
+		if (strlen(cents) > 2) {
+			cents[2] = '\0';
+		}
 	}
 
-    /* If positive sign - skip over" */
-    if (sbuf[0] == '+') {
-        dollars++;
-    }
+	/* If positive sign - skip over" */
+	if (sbuf[0] == '+') {
+		dollars++;
+	}
 
 	/* If negative say "negative" */
 	if (sbuf[0] == '-') {
 		say_file("currency/negative.wav");
 		dollars++;
 	}
-			
+
 	/* Say dollar amount */
 	en_say_general_count(session, dollars, type, method, args);
 	if (atoi(dollars) == 1) {
 		say_file("currency/dollar.wav");
-	}
-	else {
+	} else {
 		say_file("currency/dollars.wav");
 	}
-		
+
 	/* Say "and" */
 	say_file("currency/and.wav");
-	
-    /* Say cents */
-    if (cents) {
-        en_say_general_count(session, cents, type, method, args);
-        if (atoi(cents) == 1) {
-            say_file("currency/cent.wav");
-        }
-        else {
-            say_file("currency/cents.wav");
-        }
-    }
-    else {
-        say_file("digits/0.wav");
-        say_file("currency/cents.wav");
-    }
-	
+
+	/* Say cents */
+	if (cents) {
+		en_say_general_count(session, cents, type, method, args);
+		if (atoi(cents) == 1) {
+			say_file("currency/cent.wav");
+		} else {
+			say_file("currency/cents.wav");
+		}
+	} else {
+		say_file("digits/0.wav");
+		say_file("currency/cents.wav");
+	}
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
 
 
-static switch_status_t en_say(switch_core_session_t *session,
-							  char *tosay,
-							  switch_say_type_t type,
-							  switch_say_method_t method,
-							  switch_input_args_t *args)
+static switch_status_t en_say(switch_core_session_t *session, char *tosay, switch_say_type_t type, switch_say_method_t method, switch_input_args_t *args)
 {
-	
+
 	switch_say_callback_t say_cb = NULL;
 
-	switch(type) {
+	switch (type) {
 	case SST_NUMBER:
 	case SST_ITEMS:
 	case SST_PERSONS:
@@ -541,17 +502,23 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unknown Say type=[%d]\n", type);
 		break;
 	}
-	
+
 	if (say_cb) {
 		return say_cb(session, tosay, type, method, args);
-	} 
+	}
 
 	return SWITCH_STATUS_FALSE;
 }
 
-static const switch_say_interface_t en_say_interface= {
+static const switch_say_interface_t es_say_interface = {
+	/*.name */ "es",
+	/*.say_function */ en_say,
+};
+
+static const switch_say_interface_t en_say_interface = {
 	/*.name */ "en",
 	/*.say_function */ en_say,
+	/*.next */ &es_say_interface
 };
 
 static switch_loadable_module_interface_t say_en_module_interface = {
@@ -566,8 +533,8 @@
 	/*.speech_interface */ NULL,
 	/*.directory_interface */ NULL,
 	/*.chat_interface */ NULL,
-	/*.say_inteface*/ &en_say_interface,
-	/*.asr_interface*/ NULL
+	/*.say_inteface */ &en_say_interface,
+	/*.asr_interface */ NULL
 };
 
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_load(const switch_loadable_module_interface_t **module_interface, char *filename)

Modified: freeswitch/branches/cparker/src/mod/timers/mod_softtimer/mod_softtimer.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/timers/mod_softtimer/mod_softtimer.c	(original)
+++ freeswitch/branches/cparker/src/mod/timers/mod_softtimer/mod_softtimer.c	Tue Apr 24 10:14:28 2007
@@ -32,6 +32,13 @@
 #include <switch.h>
 #include <stdio.h>
 
+#ifndef UINT32_MAX
+#define UINT32_MAX 0xffffffff
+#endif
+
+#define MAX_TICK UINT32_MAX - 1024
+
+
 static switch_memory_pool_t *module_pool = NULL;
 
 static struct {
@@ -43,17 +50,21 @@
 #define MAX_ELEMENTS 1000
 
 struct timer_private {
-    uint64_t reference;
+	switch_size_t reference;
+	switch_size_t start;
+	uint32_t roll;
+	uint32_t ready;
 };
 typedef struct timer_private timer_private_t;
 
 struct timer_matrix {
-	uint64_t tick;
+	switch_size_t tick;
 	uint32_t count;
+	uint32_t roll;
 };
 typedef struct timer_matrix timer_matrix_t;
 
-static timer_matrix_t TIMER_MATRIX[MAX_ELEMENTS+1];
+static timer_matrix_t TIMER_MATRIX[MAX_ELEMENTS + 1];
 
 #define IDLE_SPEED 100
 
@@ -71,38 +82,59 @@
 		TIMER_MATRIX[timer->interval].count++;
 		switch_mutex_unlock(globals.mutex);
 		timer->private_info = private_info;
-		private_info->reference = TIMER_MATRIX[timer->interval].tick;
+		private_info->start = private_info->reference = TIMER_MATRIX[timer->interval].tick;
+		private_info->roll = TIMER_MATRIX[timer->interval].roll;
+		private_info->ready = 1;
 		return SWITCH_STATUS_SUCCESS;
 	}
 
 	return SWITCH_STATUS_MEMERR;
 }
 
+
+#define check_roll() if (private_info->roll < TIMER_MATRIX[timer->interval].roll) {\
+		private_info->roll++;\
+		private_info->reference = private_info->start = TIMER_MATRIX[timer->interval].tick;\
+	}\
+
+
+
 static inline switch_status_t timer_step(switch_timer_t *timer)
 {
 	timer_private_t *private_info = timer->private_info;
+	uint64_t samples;
 
-	if (globals.RUNNING != 1) {
+	if (globals.RUNNING != 1 || private_info->ready == 0) {
 		return SWITCH_STATUS_FALSE;
 	}
 
-    private_info->reference += timer->interval;
-    return SWITCH_STATUS_SUCCESS;
+	check_roll();
+	samples = timer->samples * (private_info->reference - private_info->start);
+
+	if (samples > UINT32_MAX) {
+		private_info->start = private_info->reference;
+		samples = timer->samples;
+	}
+
+	timer->samplecount = (uint32_t) samples;
+	private_info->reference++;
+
+	return SWITCH_STATUS_SUCCESS;
 }
 
 
 static inline switch_status_t timer_next(switch_timer_t *timer)
 {
 	timer_private_t *private_info = timer->private_info;
-    
+
 	timer_step(timer);
 
-	while (globals.RUNNING == 1 && TIMER_MATRIX[timer->interval].tick < private_info->reference) {
-        switch_yield(1000);
+	while (globals.RUNNING == 1 && private_info->ready && TIMER_MATRIX[timer->interval].tick < private_info->reference) {
+		check_roll();
+		switch_yield(1000);
 	}
 
 	if (globals.RUNNING == 1) {
-		timer->samplecount += timer->samples;
 		return SWITCH_STATUS_SUCCESS;
 	}
 
@@ -110,27 +142,28 @@
 }
 
 static inline switch_status_t timer_check(switch_timer_t *timer)
-
 {
 	timer_private_t *private_info = timer->private_info;
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
-    uint64_t diff;
+	switch_size_t diff;
 
-	if (globals.RUNNING != 1) {
+	if (globals.RUNNING != 1 || !private_info->ready) {
 		return SWITCH_STATUS_SUCCESS;
 	}
 
+	check_roll();
+
 	if (TIMER_MATRIX[timer->interval].tick < private_info->reference) {
-        diff = private_info->reference - TIMER_MATRIX[timer->interval].tick;
+		diff = private_info->reference - TIMER_MATRIX[timer->interval].tick;
 	} else {
-        diff = 0;
+		diff = 0;
 	}
 
-    if (diff) {
-        status = SWITCH_STATUS_FALSE;
-    } else {
-        timer_step(timer);
-    }
+	if (diff) {
+		status = SWITCH_STATUS_FALSE;
+	} else {
+		timer_step(timer);
+	}
 
 	return status;
 }
@@ -138,10 +171,14 @@
 
 static inline switch_status_t timer_destroy(switch_timer_t *timer)
 {
+	timer_private_t *private_info = timer->private_info;
 	switch_mutex_lock(globals.mutex);
 	TIMER_MATRIX[timer->interval].count--;
+	if (TIMER_MATRIX[timer->interval].count == 0) {
+		TIMER_MATRIX[timer->interval].tick = 0;
+	}
 	switch_mutex_unlock(globals.mutex);
-	timer->private_info = NULL;
+	private_info->ready = 0;
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -186,13 +223,13 @@
 	switch_time_t reference = switch_time_now();
 	uint32_t current_ms = 0;
 	uint32_t x;
-	
+
 	memset(&globals, 0, sizeof(globals));
 	switch_mutex_init(&globals.mutex, SWITCH_MUTEX_NESTED, module_pool);
 
 	globals.RUNNING = 1;
 
-	while(globals.RUNNING == 1) {
+	while (globals.RUNNING == 1) {
 		reference += STEP_MIC;
 
 		while (switch_time_now() < reference) {
@@ -206,11 +243,15 @@
 			if (i == 0) {
 				i = 1;
 			}
-			
-			index = (current_ms % i == 0) ? i : 0; 
+
+			index = (current_ms % i == 0) ? i : 0;
 
 			if (TIMER_MATRIX[index].count) {
-				TIMER_MATRIX[index].tick += index;
+				TIMER_MATRIX[index].tick++;
+				if (TIMER_MATRIX[index].tick == MAX_TICK) {
+					TIMER_MATRIX[index].tick = 0;
+					TIMER_MATRIX[index].roll++;
+				}
 			}
 		}
 
@@ -229,12 +270,12 @@
 
 SWITCH_MOD_DECLARE(switch_status_t) switch_module_shutdown(void)
 {
-	
+
 	if (globals.RUNNING) {
 		switch_mutex_lock(globals.mutex);
 		globals.RUNNING = -1;
 		switch_mutex_unlock(globals.mutex);
-		
+
 		while (globals.RUNNING) {
 			switch_yield(10000);
 		}

Modified: freeswitch/branches/cparker/src/mod/xml_int/mod_xml_cdr/mod_xml_cdr.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/xml_int/mod_xml_cdr/mod_xml_cdr.c	(original)
+++ freeswitch/branches/cparker/src/mod/xml_int/mod_xml_cdr/mod_xml_cdr.c	Tue Apr 24 10:14:28 2007
@@ -37,7 +37,7 @@
 static switch_status_t my_on_hangup(switch_core_session_t *session)
 {
 	switch_xml_t cdr;
-	
+
 	if (switch_ivr_generate_xml_cdr(session, &cdr) == SWITCH_STATUS_SUCCESS) {
 		switch_channel_t *channel = switch_core_session_get_channel(session);
 		char *xml_text;
@@ -51,16 +51,16 @@
 		if ((alt = switch_channel_get_variable(channel, "xml_cdr_base"))) {
 			logdir = alt;
 		}
-		
+
 		if ((path = switch_mprintf("%s/xml_cdr/%s.cdr.xml", logdir, uuid_str))) {
 			if ((xml_text = switch_xml_toxml(cdr))) {
-				if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC,  S_IRUSR | S_IWUSR)) > -1) {
-					write(fd, header, (unsigned)strlen(header));
-					write(fd, xml_text, (unsigned)strlen(xml_text));
+				if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) > -1) {
+					write(fd, header, (unsigned) strlen(header));
+					write(fd, xml_text, (unsigned) strlen(xml_text));
 					close(fd);
 					fd = -1;
 				} else {
-					char ebuf[512] = {0};
+					char ebuf[512] = { 0 };
 #ifdef WIN32
 					strerror_s(ebuf, sizeof(ebuf), errno);
 #else
@@ -77,7 +77,7 @@
 	} else {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Generating Data!\n");
 	}
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 

Modified: freeswitch/branches/cparker/src/mod/xml_int/mod_xml_cdr/mod_xml_cdr.vcproj
==============================================================================
--- freeswitch/branches/cparker/src/mod/xml_int/mod_xml_cdr/mod_xml_cdr.vcproj	(original)
+++ freeswitch/branches/cparker/src/mod/xml_int/mod_xml_cdr/mod_xml_cdr.vcproj	Tue Apr 24 10:14:28 2007
@@ -3,7 +3,7 @@
 	ProjectType="Visual C++"
 	Version="8.00"
 	Name="mod_xml_cdr"
-	ProjectGUID="{FE3540C5-3303-46E0-A69E-D92F775687F1}"
+	ProjectGUID="{08DAD348-9E0A-4A2E-97F1-F1E7E24A7836}"
 	RootNamespace="mod_xml_cdr"
 	Keyword="Win32Proj"
 	>

Modified: freeswitch/branches/cparker/src/mod/xml_int/mod_xml_curl/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/xml_int/mod_xml_curl/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/xml_int/mod_xml_curl/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,18 +1,2 @@
-LDFLAGS += -lcurl
-
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install curl --prefix=$(PREFIX)
-
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
-
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+WANT_CURL=yes
+include ../../../../build/modmake.rules

Modified: freeswitch/branches/cparker/src/mod/xml_int/mod_xml_curl/mod_xml_curl.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/xml_int/mod_xml_curl/mod_xml_curl.c	(original)
+++ freeswitch/branches/cparker/src/mod/xml_int/mod_xml_curl/mod_xml_curl.c	Tue Apr 24 10:14:28 2007
@@ -36,7 +36,7 @@
 struct xml_binding {
 	char *url;
 	char *bindings;
-    char *cred;
+	char *cred;
 };
 
 typedef struct xml_binding xml_binding_t;
@@ -48,7 +48,7 @@
 
 static size_t file_callback(void *ptr, size_t size, size_t nmemb, void *data)
 {
-	register unsigned int realsize = (unsigned int)(size * nmemb);
+	register unsigned int realsize = (unsigned int) (size * nmemb);
 	struct config_data *config_data = data;
 
 	write(config_data->fd, ptr, realsize);
@@ -56,47 +56,42 @@
 }
 
 
-static switch_xml_t xml_url_fetch(char *section,
-								  char *tag_name,
-								  char *key_name,
-								  char *key_value,
-								  char *params,
-                                  void *user_data)
+static switch_xml_t xml_url_fetch(const char *section, const char *tag_name, const char *key_name, const char *key_value, const char *params,
+								  void *user_data)
 {
 	char filename[512] = "";
 	CURL *curl_handle = NULL;
 	struct config_data config_data;
 	switch_xml_t xml = NULL;
-    char *data = NULL;
+	char *data = NULL;
 	switch_uuid_t uuid;
 	char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1];
-    xml_binding_t *binding = (xml_binding_t *) user_data;
-    char *file_url;
+	xml_binding_t *binding = (xml_binding_t *) user_data;
+	char *file_url;
 
-    if (!binding) {
-        return NULL;
-    }
-
-    if (file_url = strstr(binding->url, "file:")) {
-        file_url += 5;
-     
-        if (!(xml = switch_xml_parse_file(file_url))) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Parsing Result!\n");
-        }
-   
-        return xml;
-    }
-
-    if (!(data = switch_mprintf("section=%s&tag_name=%s&key_name=%s&key_value=%s%s%s", 
-                                section,
-                                tag_name ? tag_name : "",
-                                key_name ? key_name : "",
-                                key_value ? key_value : "",
-                                params ? strchr(params,'=') ? "&" : "&params=" : "", params ? params : ""))) {
-
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-        return NULL;
-    }
+	if (!binding) {
+		return NULL;
+	}
+
+	if ((file_url = strstr(binding->url, "file:"))) {
+		file_url += 5;
+
+		if (!(xml = switch_xml_parse_file(file_url))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Parsing Result!\n");
+		}
+
+		return xml;
+	}
+
+	if (!(data = switch_mprintf("section=%s&tag_name=%s&key_name=%s&key_value=%s%s%s",
+								section,
+								tag_name ? tag_name : "",
+								key_name ? key_name : "",
+								key_value ? key_value : "", params ? strchr(params, '=') ? "&" : "&params=" : "", params ? params : ""))) {
+
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
+		return NULL;
+	}
 
 	switch_uuid_get(&uuid);
 	switch_uuid_format(uuid_str, &uuid);
@@ -107,18 +102,18 @@
 		curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
 		curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
 	}
-		
+
 	config_data.name = filename;
-	if ((config_data.fd = open(filename, O_CREAT | O_RDWR | O_TRUNC)) > -1) {
-        if (!switch_strlen_zero(binding->cred)) {
-            curl_easy_setopt(curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
-            curl_easy_setopt(curl_handle, CURLOPT_USERPWD, binding->cred);
-        }
-        curl_easy_setopt(curl_handle, CURLOPT_POST, 1);
-        curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, data);
+	if ((config_data.fd = open(filename, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)) > -1) {
+		if (!switch_strlen_zero(binding->cred)) {
+			curl_easy_setopt(curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
+			curl_easy_setopt(curl_handle, CURLOPT_USERPWD, binding->cred);
+		}
+		curl_easy_setopt(curl_handle, CURLOPT_POST, 1);
+		curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, data);
 		curl_easy_setopt(curl_handle, CURLOPT_URL, binding->url);
 		curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, file_callback);
-		curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&config_data);
+		curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *) &config_data);
 		curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "freeswitch-xml/1.0");
 		curl_easy_perform(curl_handle);
 		curl_easy_cleanup(curl_handle);
@@ -127,14 +122,14 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error!\n");
 	}
 
-    switch_safe_free(data);
+	switch_safe_free(data);
 
 	if (!(xml = switch_xml_parse_file(filename))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Parsing Result!\n");
 	}
 
 	unlink(filename);
-	
+
 	return xml;
 }
 
@@ -152,12 +147,12 @@
 	/*.directory_interface */ NULL
 };
 
-static switch_status_t do_config(void) 
+static switch_status_t do_config(void)
 {
 	char *cf = "xml_curl.conf";
 	switch_xml_t cfg, xml, bindings_tag, binding_tag, param;
-    xml_binding_t *binding = NULL;
-    int x = 0;
+	xml_binding_t *binding = NULL;
+	int x = 0;
 
 	if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", cf);
@@ -165,56 +160,54 @@
 	}
 
 	if (!(bindings_tag = switch_xml_child(cfg, "bindings"))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing <bindings> tag!\n");
-        return SWITCH_STATUS_FALSE;
-    }
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing <bindings> tag!\n");
+		return SWITCH_STATUS_FALSE;
+	}
 
 	for (binding_tag = switch_xml_child(bindings_tag, "binding"); binding_tag; binding_tag = binding_tag->next) {
-        char *bname = (char *) switch_xml_attr_soft(binding_tag, "name");
-        char *url = NULL;
-        char *bind_cred = NULL;
-        char *bind_mask = NULL;
+		char *bname = (char *) switch_xml_attr_soft(binding_tag, "name");
+		char *url = NULL;
+		char *bind_cred = NULL;
+		char *bind_mask = NULL;
 
 		for (param = switch_xml_child(binding_tag, "param"); param; param = param->next) {
 			char *var = (char *) switch_xml_attr_soft(param, "name");
 			char *val = (char *) switch_xml_attr_soft(param, "value");
-            if (!strcasecmp(var, "gateway-url")) {
+			if (!strcasecmp(var, "gateway-url")) {
 				bind_mask = (char *) switch_xml_attr_soft(param, "bindings");
-                if (val) {
-                    url = val;
-                }
+				if (val) {
+					url = val;
+				}
 			} else if (!strcasecmp(var, "gateway-credentials")) {
-                bind_cred = val;
-            }
+				bind_cred = val;
+			}
 		}
-        
-        if (!url) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Binding has no url!\n");
-            continue;
-        }
-
-        if (!(binding = malloc(sizeof(*binding)))) {
-            return SWITCH_STATUS_FALSE;
-        }
-        memset(binding, 0, sizeof(*binding));
-
-        binding->url = strdup(url);
-
-        if (bind_mask) {
-            binding->bindings = strdup(bind_mask);
-        }
-
-        if (bind_cred) {
-            binding->cred = strdup(bind_cred);
-        }
-        
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Binding [%s] XML Fetch Function [%s] [%s]\n", 
-                          switch_strlen_zero(bname) ? "N/A" : bname,
-                          binding->url,
-                          binding->bindings ? binding->bindings : "all");
+
+		if (!url) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Binding has no url!\n");
+			continue;
+		}
+
+		if (!(binding = malloc(sizeof(*binding)))) {
+			return SWITCH_STATUS_FALSE;
+		}
+		memset(binding, 0, sizeof(*binding));
+
+		binding->url = strdup(url);
+
+		if (bind_mask) {
+			binding->bindings = strdup(bind_mask);
+		}
+
+		if (bind_cred) {
+			binding->cred = strdup(bind_cred);
+		}
+
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Binding [%s] XML Fetch Function [%s] [%s]\n",
+						  switch_strlen_zero(bname) ? "N/A" : bname, binding->url, binding->bindings ? binding->bindings : "all");
 		switch_xml_bind_search_function(xml_url_fetch, switch_xml_parse_section_string(binding->bindings), binding);
-        x++;
-        binding = NULL;
+		x++;
+		binding = NULL;
 	}
 
 	switch_xml_free(xml);
@@ -229,10 +222,10 @@
 	*module_interface = &xml_curl_module_interface;
 
 	if (do_config() == SWITCH_STATUS_SUCCESS) {
-        curl_global_init(CURL_GLOBAL_ALL);
-    } else {
-        return SWITCH_STATUS_FALSE;
-    }
+		curl_global_init(CURL_GLOBAL_ALL);
+	} else {
+		return SWITCH_STATUS_FALSE;
+	}
 
 	/* indicate that the module should continue to be loaded */
 	return SWITCH_STATUS_SUCCESS;

Modified: freeswitch/branches/cparker/src/mod/xml_int/mod_xml_rpc/Makefile
==============================================================================
--- freeswitch/branches/cparker/src/mod/xml_int/mod_xml_rpc/Makefile	(original)
+++ freeswitch/branches/cparker/src/mod/xml_int/mod_xml_rpc/Makefile	Tue Apr 24 10:14:28 2007
@@ -1,18 +1,18 @@
-LDFLAGS += -lxmlrpc -lxmlrpc_abyss -lxmlrpc_server -lxmlrpc_server_abyss -lxmlrpc_xmlparse
+BASE=../../../..
+XMLRPC_DIR=$(BASE)/libs/xmlrpc-c
 
-all:	depends $(MODNAME).$(DYNAMIC_LIB_EXTEN)
-
-depends:
-	MAKE=$(MAKE) $(BASE)/build/buildlib.sh $(BASE) install xmlrpc-c --prefix=$(PREFIX) --disable-cplusplus --disable-wininet-client --disable-libwww-client
-
-
-$(MODNAME).$(DYNAMIC_LIB_EXTEN): $(MODNAME).c
-	$(CC) $(CFLAGS) -fPIC -c $(MODNAME).c -o $(MODNAME).o 
-	$(CC) $(SOLINK) -o $(MODNAME).$(DYNAMIC_LIB_EXTEN)  $(MODNAME).o $(LDFLAGS)
-
-
-clean:
-	rm -fr *.$(DYNAMIC_LIB_EXTEN) *.o *~
-
-install:
-	cp -f $(MODNAME).$(DYNAMIC_LIB_EXTEN) $(PREFIX)/mod
+#XMLRPCLAS  = $(XMLRPC_DIR)/src/libxmlrpc.la 
+#dont ask...
+XMLRPCLAS  = $(XMLRPC_DIR)/src/*.o
+XMLRPCLAS += $(XMLRPC_DIR)/src/libxmlrpc_server.la 
+XMLRPCLAS += $(XMLRPC_DIR)/src/libxmlrpc_server_abyss.la $(XMLRPC_DIR)/lib/abyss/src/libxmlrpc_abyss.la
+XMLRPCLAS += $(XMLRPC_DIR)/lib/expat/xmlparse/libxmlrpc_xmlparse.la $(XMLRPC_DIR)/lib/expat/xmltok/libxmlrpc_xmltok.la
+
+LOCAL_LIBADD =$(XMLRPCLAS)
+LOCAL_CFLAGS=-I$(XMLRPC_DIR)/include
+
+include $(BASE)/build/modmake.rules
+
+$(XMLRPCLAS): $(XMLRPC_DIR) $(XMLRPC_DIR)/.update
+	cd $(XMLRPC_DIR) && $(MAKE)
+	$(TOUCH_TARGET)

Modified: freeswitch/branches/cparker/src/mod/xml_int/mod_xml_rpc/mod_xml_rpc.c
==============================================================================
--- freeswitch/branches/cparker/src/mod/xml_int/mod_xml_rpc/mod_xml_rpc.c	(original)
+++ freeswitch/branches/cparker/src/mod/xml_int/mod_xml_rpc/mod_xml_rpc.c	Tue Apr 24 10:14:28 2007
@@ -66,10 +66,10 @@
 } globals;
 
 SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_realm, globals.realm)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_user, globals.user)
-SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_pass, globals.pass)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_user, globals.user)
+	SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_pass, globals.pass)
 
-static switch_status_t do_config(void) 
+	 static switch_status_t do_config(void)
 {
 	char *cf = "xml_rpc.conf";
 	switch_xml_t cfg, xml, settings, param;
@@ -93,11 +93,11 @@
 			} else if (!strcasecmp(var, "auth-pass")) {
 				pass = val;
 			} else if (!strcasecmp(var, "http-port")) {
-				globals.port = (uint16_t)atoi(val);
+				globals.port = (uint16_t) atoi(val);
 			}
 		}
 	}
-	
+
 	if (!globals.port) {
 		globals.port = 8080;
 	}
@@ -119,7 +119,7 @@
 
 	memset(&globals, 0, sizeof(globals));
 
-    do_config();
+	do_config();
 
 	/* indicate that the module should continue to be loaded */
 	return SWITCH_STATUS_SUCCESS;
@@ -134,128 +134,183 @@
 	char *data;
 
 	va_start(ap, fmt);
-#ifdef HAVE_VASPRINTF
-	ret = vasprintf(&data, fmt, ap);
-#else
-	if ((data = (char *) malloc(2048))) {
-		vsnprintf(data, 2048, fmt, ap);
-	}
-#endif
+	ret = switch_vasprintf(&data, fmt, ap);
 	va_end(ap);
-	
+
 	if (data) {
 		ret = 0;
-		HTTPWrite(r, data, (uint32_t)strlen(data));
+		HTTPWrite(r, data, (uint32_t) strlen(data));
 		free(data);
 	}
-	
+
 	return ret ? SWITCH_STATUS_FALSE : SWITCH_STATUS_SUCCESS;
 }
 
 
-abyss_bool HandleHook(TSession *r)
+abyss_bool HandleHook(TSession * r)
 {
-    char *m = "text/html";
-	switch_stream_handle_t stream = {0};
+	char *m = "text/html";
+	switch_stream_handle_t stream = { 0 };
 	char *command;
 
 	stream.data = r;
 	stream.write_function = http_stream_write;
 
 	if (globals.realm) {
-		if (!RequestAuth(r,globals.realm, globals.user, globals.pass)) {
+		if (!RequestAuth(r, globals.realm, globals.user, globals.pass)) {
 			return TRUE;
 		}
 	}
 
 
 
-	if(strncmp(r->uri, "/api/", 5)) {
+	if (strncmp(r->uri, "/api/", 5)) {
 		return FALSE;
 	}
 
 	if (switch_event_create(&stream.event, SWITCH_EVENT_API) == SWITCH_STATUS_SUCCESS) {
-		if (r->uri) switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-URI", "%s", r->uri);
-		if (r->query) switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-QUERY", "%s", r->query);
-		if (r->host) switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-HOST", "%s", r->host);
-		if (r->from) switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-FROM", "%s", r->from);
-		if (r->useragent) switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-USER-AGENT", "%s", r->useragent);
-		if (r->referer) switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-REFERER", "%s", r->referer);
-		if (r->requestline) switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-REQUESTLINE", "%s", r->requestline);
-		if (r->user) switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-USER", "%s", r->user);
-		if (r->port) switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-PORT", "%u", r->port);
+		if (r->uri)
+			switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-URI", "%s", r->uri);
+		if (r->query)
+			switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-QUERY", "%s", r->query);
+		if (r->host)
+			switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-HOST", "%s", r->host);
+		if (r->from)
+			switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-FROM", "%s", r->from);
+		if (r->useragent)
+			switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-USER-AGENT", "%s", r->useragent);
+		if (r->referer)
+			switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-REFERER", "%s", r->referer);
+		if (r->requestline)
+			switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-REQUESTLINE", "%s", r->requestline);
+		if (r->user)
+			switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-USER", "%s", r->user);
+		if (r->port)
+			switch_event_add_header(stream.event, SWITCH_STACK_BOTTOM, "HTTP-PORT", "%u", r->port);
 	}
 
 	command = r->uri + 5;
-	
+
 	ResponseChunked(r);
-	ResponseStatus(r,200);
+	ResponseStatus(r, 200);
 	ResponseContentType(r, m);
-    ResponseWrite(r);
+	ResponseWrite(r);
 	switch_api_execute(command, r->query, NULL, &stream);
 	HTTPWriteEnd(r);
-    return TRUE;
+	return TRUE;
 }
 
-#define CMDLEN 1024 * 256
-static xmlrpc_value *freeswitch_api(xmlrpc_env *const envP, xmlrpc_value *const paramArrayP, void *const userData) 
+
+static xmlrpc_value *freeswitch_api(xmlrpc_env * const envP, xmlrpc_value * const paramArrayP, void *const userData)
 {
 	char *command, *arg;
-	char *retbuf = malloc(CMDLEN);
-	switch_stream_handle_t stream = {0};
+	switch_stream_handle_t stream = { 0 };
+	xmlrpc_value *val = NULL;
+
+
+	/* Parse our argument array. */
+	xmlrpc_decompose_value(envP, paramArrayP, "(ss)", &command, &arg);
+	if (envP->fault_occurred) {
+		return NULL;
+	}
+
+	SWITCH_STANDARD_STREAM(stream);
+	if (switch_api_execute(command, arg, NULL, &stream) == SWITCH_STATUS_SUCCESS) {
+		/* Return our result. */
+		val = xmlrpc_build_value(envP, "s", stream.data);
+		free(stream.data);
+	} else {
+		val = xmlrpc_build_value(envP, "s", "ERROR!");
+	}
+
+	return val;
+}
+
+static xmlrpc_value *freeswitch_man(xmlrpc_env * const envP, xmlrpc_value * const paramArrayP, void *const userData)
+{
+	char *oid, *relative_oid, *s_action, *data;
+	char buf[SWITCH_MAX_MANAGEMENT_BUFFER_LEN] = "";
+	switch_management_action_t action = SMA_NONE;
 	xmlrpc_value *val;
 
-    /* Parse our argument array. */
-    xmlrpc_decompose_value(envP, paramArrayP, "(ss)", &command, &arg);
-    if (envP->fault_occurred) {
-        return NULL;
-	}
-
-	memset(retbuf, 0, CMDLEN);
-	stream.data = retbuf;
-	stream.end = stream.data;
-	stream.data_size = CMDLEN;
-	stream.write_function = switch_console_stream_write;
-	switch_api_execute(command, arg, NULL, &stream);
-
-    /* Return our result. */
-    val = xmlrpc_build_value(envP, "s", retbuf);
-	free(retbuf);
+	/* Parse our argument array. */
+	xmlrpc_decompose_value(envP, paramArrayP, "(sss)", &oid, &s_action, &data);
+	if (envP->fault_occurred) {
+		return NULL;
+	}
+
+	if (!strncasecmp(oid, FREESWITCH_OID_PREFIX, strlen(FREESWITCH_OID_PREFIX))) {
+		relative_oid = oid + strlen(FREESWITCH_OID_PREFIX);
+	} else {
+		relative_oid = oid;
+	}
+
+	if (!switch_strlen_zero(data)) {
+		switch_copy_string(buf, data, sizeof(buf));
+	}
+
+	if (!strcasecmp(s_action, "get")) {
+		action = SMA_GET;
+	} else if (!strcasecmp(s_action, "set")) {
+		action = SMA_SET;
+	}
+
+	if (action) {
+		if (switch_core_management_exec(relative_oid, action, buf, sizeof(buf)) == SWITCH_STATUS_SUCCESS) {
+			if (action == SMA_SET) {
+				if (switch_strlen_zero(buf)) {
+					snprintf(buf, sizeof(buf), "OK\n");
+				}
+			}
+		} else {
+			if (switch_strlen_zero(buf)) {
+				snprintf(buf, sizeof(buf), "ERROR\n");
+			}
+		}
+	} else {
+		snprintf(buf, sizeof(buf), "Invalid Action %s\n", s_action);
+	}
+
+	/* Return our result. */
+	val = xmlrpc_build_value(envP, "s", buf);
+
 
 	return val;
 }
 
-SWITCH_MOD_DECLARE(switch_status_t) switch_module_runtime(void) 
+SWITCH_MOD_DECLARE(switch_status_t) switch_module_runtime(void)
 {
-    TServer abyssServer;
-    xmlrpc_registry * registryP;
-    xmlrpc_env env;
+	TServer abyssServer;
+	xmlrpc_registry *registryP;
+	xmlrpc_env env;
 	char logfile[512];
 
 	globals.running = 1;
-    
-    xmlrpc_env_init(&env);
 
-    registryP = xmlrpc_registry_new(&env);
-	
-    xmlrpc_registry_add_method(&env, registryP, NULL, "freeswitch.api", &freeswitch_api, NULL);
-	xmlrpc_registry_add_method(&env, registryP, NULL,"freeswitch_api", &freeswitch_api, NULL);
+	xmlrpc_env_init(&env);
+
+	registryP = xmlrpc_registry_new(&env);
 
-    MIMETypeInit();
+	xmlrpc_registry_add_method(&env, registryP, NULL, "freeswitch.api", &freeswitch_api, NULL);
+	xmlrpc_registry_add_method(&env, registryP, NULL, "freeswitch_api", &freeswitch_api, NULL);
+	xmlrpc_registry_add_method(&env, registryP, NULL, "freeswitch.management", &freeswitch_man, NULL);
+	xmlrpc_registry_add_method(&env, registryP, NULL, "freeswitch_management", &freeswitch_man, NULL);
+
+	MIMETypeInit();
 	MIMETypeAdd("text/html", "html");
 
 	snprintf(logfile, sizeof(logfile), "%s%s%s", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, "freeswitch_http.log");
-    ServerCreate(&abyssServer, "XmlRpcServer", globals.port, SWITCH_GLOBAL_dirs.htdocs_dir, logfile);
-    
-    xmlrpc_server_abyss_set_handler(&env, &abyssServer, "/RPC2", registryP);
+	ServerCreate(&abyssServer, "XmlRpcServer", globals.port, SWITCH_GLOBAL_dirs.htdocs_dir, logfile);
+
+	xmlrpc_server_abyss_set_handler(&env, &abyssServer, "/RPC2", registryP);
 
-    ServerInit(&abyssServer);
+	ServerInit(&abyssServer);
 	ServerAddHandler(&abyssServer, HandleHook);
-	
+
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Starting HTTP Port %d, DocRoot [%s]\n", globals.port, SWITCH_GLOBAL_dirs.htdocs_dir);
-    while (globals.running) {
-        ServerRunOnce2(&abyssServer, ABYSS_FOREGROUND);
-    }
+	while (globals.running) {
+		ServerRunOnce2(&abyssServer, ABYSS_FOREGROUND);
+	}
 
 
 	return SWITCH_STATUS_SUCCESS;

Modified: freeswitch/branches/cparker/src/switch.c
==============================================================================
--- freeswitch/branches/cparker/src/switch.c	(original)
+++ freeswitch/branches/cparker/src/switch.c	Tue Apr 24 10:14:28 2007
@@ -33,20 +33,24 @@
  *
  */
 
+#ifndef _XOPEN_SOURCE
+#define _XOPEN_SOURCE 600
+#endif
+
 #include <switch.h>
 
-//pid filename: Stores the process id of the freeswitch process
+/* pid filename: Stores the process id of the freeswitch process */
 #define PIDFILE "freeswitch.pid"
 static char *pfile = PIDFILE;
 
-//log filename: Filename of the freeswitch log file to be used if we are in background mode
+/* log filename: Filename of the freeswitch log file to be used if we are in background mode */
 #define LOGFILE "freeswitch.log"
 static char *lfile = LOGFILE;
 
-//If we are a windows service, what should we be called
+/* If we are a windows service, what should we be called */
 #define SERVICENAME "Freeswitch"
 
-//Picky compiler
+/* Picky compiler */
 #ifdef __ICC
 #pragma warning (disable:167)
 #endif
@@ -55,73 +59,74 @@
 #include <winsock2.h>
 #include <windows.h>
 
-//event to signal shutdown (for you unix people, this is like a pthread_cond)
+/* event to signal shutdown (for you unix people, this is like a pthread_cond) */
 static HANDLE shutdown_event;
 #endif
 
-//signal handler for when freeswitch is running in background mode.
-//signal triggers the shutdown of freeswitch
+/* signal handler for when freeswitch is running in background mode.
+ * signal triggers the shutdown of freeswitch
+ */
 static void handle_SIGHUP(int sig)
 {
 	uint32_t arg = 0;
-	if(sig);
-	//send shutdown signal to the freeswitch core
+	if (sig);
+	/* send shutdown signal to the freeswitch core */
 	switch_core_session_ctl(SCSC_SHUTDOWN, &arg);
 	return;
 }
 
-//kill a freeswitch process running in background mode
+/* kill a freeswitch process running in background mode */
 static int freeswitch_kill_background()
 {
-	FILE *f;				//FILE handle to open the pid file
-	char path[256] = "";	//full path of the PID file
-	pid_t pid = 0;			//pid from the pid file	
+	FILE *f;					/* FILE handle to open the pid file */
+	char path[256] = "";		/* full path of the PID file */
+	pid_t pid = 0;				/* pid from the pid file */
 
-	//set the globals so we can use the global paths.
+	/* set the globals so we can use the global paths. */
 	switch_core_set_globals();
 
-	//get the full path of the pid file.
+	/* get the full path of the pid file. */
 	snprintf(path, sizeof(path), "%s%s%s", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, pfile);
 
-	//open the pid file
+	/* open the pid file */
 	if ((f = fopen(path, "r")) == 0) {
-		//pid file does not exist
+		/* pid file does not exist */
 		fprintf(stderr, "Cannot open pid file %s.\n", path);
 		return 255;
 	}
 
-	//pull the pid from the file
+	/* pull the pid from the file */
 	fscanf(f, "%d", &pid);
 
-	//if we have a valid pid
+	/* if we have a valid pid */
 	if (pid > 0) {
 
-		//kill the freeswitch running at the pid we found
+		/* kill the freeswitch running at the pid we found */
 		fprintf(stderr, "Killing: %d\n", (int) pid);
 #ifdef WIN32
-		//for windows we need the event to signal for shutting down a background freewitc
+		/* for windows we need the event to signal for shutting down a background freewitch */
 		snprintf(path, sizeof(path), "Global\\Freeswitch.%d", pid);
 
-		//open the event so we can signal it
+		/* open the event so we can signal it */
 		shutdown_event = OpenEvent(EVENT_MODIFY_STATE, FALSE, path);
 
-		//did we sucessfully open the event
+		/* did we sucessfully open the event */
 		if (!shutdown_event) {
 			/* we can't get the event, so we can't signal the process to shutdown */
 			fprintf(stderr, "ERROR: Can't Shutdown: %d\n", (int) pid);
 		} else {
-			//signal the event to shutdown
+			/* signal the event to shutdown */
 			SetEvent(shutdown_event);
 		}
-		//cleanup
+		/* cleanup */
 		CloseHandle(shutdown_event);
 #else
-		//for unix, send the signal to kill.
+		/* for unix, send the signal to kill. */
 		kill(pid, SIGTERM);
 #endif
 	}
 
-	//be nice and close the file handle to the pid file
+	/* be nice and close the file handle to the pid file */
 	fclose(f);
 
 	return 0;
@@ -129,123 +134,118 @@
 
 #ifdef WIN32
 
-//we need these vars to handle the service
+/* we need these vars to handle the service */
 SERVICE_STATUS_HANDLE hStatus;
 SERVICE_STATUS status;
 
-//Handler function for service start/stop from the service 
-void WINAPI ServiceCtrlHandler( DWORD control )
+/* Handler function for service start/stop from the service */
+void WINAPI ServiceCtrlHandler(DWORD control)
 {
-	switch( control )
-	{
+	switch (control) {
 	case SERVICE_CONTROL_SHUTDOWN:
 	case SERVICE_CONTROL_STOP:
-		//Shutdown freeswitch
-		switch_core_destroy(0);
-		//set service status valuse
+		/* Shutdown freeswitch */
+		switch_core_destroy();
+		/* set service status valuse */
 		status.dwCurrentState = SERVICE_STOPPED;
 		status.dwWin32ExitCode = 0;
 		status.dwCheckPoint = 0;
 		status.dwWaitHint = 0;
 		break;
 	case SERVICE_CONTROL_INTERROGATE:
-		// we already set the service status every time it changes.
-		// if there are other times we change it and don't update, we should do so here
+		/* we already set the service status every time it changes. */
+		/* if there are other times we change it and don't update, we should do so here */
 		break;
 	}
 
-	SetServiceStatus( hStatus, &status );
+	SetServiceStatus(hStatus, &status);
 }
 
-//the main service entry point
-void WINAPI service_main( DWORD numArgs, char **args )
+/* the main service entry point */
+void WINAPI service_main(DWORD numArgs, char **args)
 {
-	const char *err = NULL;		//error value for return from freeswitch initialization
-	// we have to initialize the service-specific stuff
-	memset( &status, 0, sizeof(SERVICE_STATUS) );
+	const char *err = NULL;		/* error value for return from freeswitch initialization */
+	/*  we have to initialize the service-specific stuff */
+	memset(&status, 0, sizeof(SERVICE_STATUS));
 	status.dwServiceType = SERVICE_WIN32;
 	status.dwCurrentState = SERVICE_START_PENDING;
 	status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
 
-	//register our handler for service control messages
-	hStatus = RegisterServiceCtrlHandler( SERVICENAME, &ServiceCtrlHandler );
+	/* register our handler for service control messages */
+	hStatus = RegisterServiceCtrlHandler(SERVICENAME, &ServiceCtrlHandler);
 
-	//update the service status
-	SetServiceStatus( hStatus, &status );
+	/* update the service status */
+	SetServiceStatus(hStatus, &status);
 
-	//run freeswitch with elevated priority
+	/* run freeswitch with elevated priority */
 	set_high_priority();
 
-	//attempt to initialize freeswitch and load modules
+	/* attempt to initialize freeswitch and load modules */
 	if (switch_core_init_and_modload(lfile, &err) != SWITCH_STATUS_SUCCESS) {
-		//freeswitch did not start sucessfully
+		/* freeswitch did not start sucessfully */
 		status.dwCurrentState = SERVICE_STOPPED;
 	} else {
-		//freeswitch started
+		/* freeswitch started */
 		status.dwCurrentState = SERVICE_RUNNING;
 	}
 
-	//update the service status
-	SetServiceStatus( hStatus, &status );
+	/* update the service status */
+	SetServiceStatus(hStatus, &status);
 }
 
 #endif
 
-//the main application entry point
+/* the main application entry point */
 int main(int argc, char *argv[])
 {
-	char pid_path[256] = "";	// full path to the pid file
-	const char *err = NULL;		// error value for return from freeswitch initialization
+	char pid_path[256] = "";	/* full path to the pid file */
+	const char *err = NULL;		/* error value for return from freeswitch initialization */
 #ifndef WIN32
-	int nf = 0;					// TRUE if we are running in nofork mode
+	int nf = 0;					/* TRUE if we are running in nofork mode */
 #endif
-	int nc = 0;					// TRUE if we are running in noconsole mode
-	FILE *f;					// file handle to the pid file
-	pid_t pid = 0;				// 
-	int x;						//
-	int die = 0;				//
-    char *usageDesc;
+	int nc = 0;					/* TRUE if we are running in noconsole mode */
+	FILE *f;					/* file handle to the pid file */
+	pid_t pid = 0;
+	int x;
+	int die = 0;
+	char *usageDesc;
 	int alt_dirs = 0;
+	int known_opt;
 
 #ifdef WIN32
-	SERVICE_TABLE_ENTRY dispatchTable[] =
-	{
-		{ SERVICENAME, &service_main },
-		{ NULL, NULL }
+	SERVICE_TABLE_ENTRY dispatchTable[] = {
+		{SERVICENAME, &service_main},
+		{NULL, NULL}
 	};
-    usageDesc = "these are the optional arguments you can pass to freeswitch\n"
-        "\t-service         -- start freeswitch as a service, cannot be used if loaded as a console app\n"
-        "\t-install         -- install freeswitch as a service\n"
-        "\t-uninstall       -- remove freeswitch as a service\n"
-        "\t-hp              -- enable high priority settings\n"
-        "\t-stop            -- stop freeswitch\n"
-        "\t-nc              -- do not output to a console and background\n"
-        "\t-conf [confdir]  -- specify an alternate config dir\n"
-        "\t-log [logdir]    -- specify an alternate log dir\n"
-        "\t-db [dbdir]      -- specify an alternate db dir\n";
+	usageDesc = "these are the optional arguments you can pass to freeswitch\n"
+		"\t-service         -- start freeswitch as a service, cannot be used if loaded as a console app\n"
+		"\t-install         -- install freeswitch as a service\n"
+		"\t-uninstall       -- remove freeswitch as a service\n"
+		"\t-hp              -- enable high priority settings\n"
+		"\t-stop            -- stop freeswitch\n"
+		"\t-nc              -- do not output to a console and background\n"
+		"\t-conf [confdir]  -- specify an alternate config dir\n"
+		"\t-log [logdir]    -- specify an alternate log dir\n" "\t-db [dbdir]      -- specify an alternate db dir\n";
 #else
-    usageDesc = "these are the optional arguments you can pass to freeswitch\n"
-        "\t-help            -- this message\n"
-        "\t-nf              -- no forking\n"
-        "\t-hp              -- enable high priority settings\n"
-        "\t-stop            -- stop freeswitch\n"
-        "\t-nc              -- do not output to a console and background\n"
-        "\t-conf [confdir]  -- specify an alternate config dir\n"
-        "\t-log [logdir]    -- specify an alternate log dir\n"
-        "\t-db [dbdir]      -- specify an alternate db dir\n";
+	usageDesc = "these are the optional arguments you can pass to freeswitch\n"
+		"\t-help            -- this message\n"
+		"\t-nf              -- no forking\n"
+		"\t-hp              -- enable high priority settings\n"
+		"\t-stop            -- stop freeswitch\n"
+		"\t-nc              -- do not output to a console and background\n"
+		"\t-conf [confdir]  -- specify an alternate config dir\n"
+		"\t-log [logdir]    -- specify an alternate log dir\n" "\t-db [dbdir]      -- specify an alternate db dir\n";
 
 #endif
 
 	for (x = 1; x < argc; x++) {
-		if (argv[x] && !strcmp(argv[x], "-help")) {
-			printf("%s\n",usageDesc);
-            exit(0);
-		}
+		known_opt = 0;
 #ifdef WIN32
 		if (x == 1) {
 			if (argv[x] && !strcmp(argv[x], "-service")) {
-				if(StartServiceCtrlDispatcher( dispatchTable ) == 0 ) {
-					//Not loaded as a service
+				known_opt++;
+				if (StartServiceCtrlDispatcher(dispatchTable) == 0) {
+					/* Not loaded as a service */
 					fprintf(stderr, "Error Freeswitch loaded as a console app with -service option\n");
 					fprintf(stderr, "To install the service load freeswitch with -install\n");
 				}
@@ -255,32 +255,24 @@
 				char exePath[1024];
 				char servicePath[1024];
 
-				SC_HANDLE handle = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
-				GetModuleFileName( NULL, exePath, 1024 );
+				SC_HANDLE handle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
+				known_opt++;
+				GetModuleFileName(NULL, exePath, 1024);
 				snprintf(servicePath, sizeof(servicePath), "%s -service", exePath);
-				CreateService(
-					handle,
-					SERVICENAME,
-					SERVICENAME,
-					GENERIC_READ | GENERIC_EXECUTE,
-					SERVICE_WIN32_OWN_PROCESS,
-					SERVICE_AUTO_START,
-					SERVICE_ERROR_IGNORE,
-					servicePath,
-					NULL,
-					NULL,
-					NULL,
-					NULL,
-					NULL
-					);
+				CreateService(handle,
+							  SERVICENAME,
+							  SERVICENAME,
+							  GENERIC_READ | GENERIC_EXECUTE,
+							  SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, servicePath, NULL, NULL, NULL, NULL, NULL);
 				exit(0);
 			}
 			if (argv[x] && !strcmp(argv[x], "-uninstall")) {
-				SC_HANDLE handle = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
-				SC_HANDLE service = OpenService( handle, SERVICENAME, DELETE );
-				if( service != NULL ) {
-					// remove the service!
-					DeleteService( service );
+				SC_HANDLE handle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
+				SC_HANDLE service = OpenService(handle, SERVICENAME, DELETE);
+				known_opt++;
+				if (service != NULL) {
+					/* remove the service! */
+					DeleteService(service);
 				}
 				exit(0);
 			}
@@ -289,64 +281,76 @@
 
 		if (argv[x] && !strcmp(argv[x], "-nf")) {
 			nf++;
+			known_opt++;
 		}
 #endif
 		if (argv[x] && !strcmp(argv[x], "-hp")) {
 			set_high_priority();
+			known_opt++;
 		}
 
 		if (argv[x] && !strcmp(argv[x], "-stop")) {
 			die++;
+			known_opt++;
 		}
 
 		if (argv[x] && !strcmp(argv[x], "-nc")) {
 			nc++;
+			known_opt++;
 		}
 
 
-        if (argv[x] && !strcmp(argv[x], "-conf")) {
-            x++;
-            if (argv[x] && strlen(argv[x])) {
-                SWITCH_GLOBAL_dirs.conf_dir = (char *) malloc(strlen(argv[x])+1);
-                strcpy(SWITCH_GLOBAL_dirs.conf_dir,argv[x]);
+		if (argv[x] && !strcmp(argv[x], "-conf")) {
+			x++;
+			if (argv[x] && strlen(argv[x])) {
+				SWITCH_GLOBAL_dirs.conf_dir = (char *) malloc(strlen(argv[x]) + 1);
+				strcpy(SWITCH_GLOBAL_dirs.conf_dir, argv[x]);
 				alt_dirs++;
-            } else {
-                fprintf(stderr, "When using -conf you must specify a config directory\n");
-                return 255;
-            }
-        }
-
-        if (argv[x] && !strcmp(argv[x], "-log")) {
-            x++;
-            if (argv[x] && strlen(argv[x])) {
-                SWITCH_GLOBAL_dirs.log_dir = (char *) malloc(strlen(argv[x])+1);
-                strcpy(SWITCH_GLOBAL_dirs.log_dir,argv[x]);
+			} else {
+				fprintf(stderr, "When using -conf you must specify a config directory\n");
+				return 255;
+			}
+			known_opt++;
+		}
+
+		if (argv[x] && !strcmp(argv[x], "-log")) {
+			x++;
+			if (argv[x] && strlen(argv[x])) {
+				SWITCH_GLOBAL_dirs.log_dir = (char *) malloc(strlen(argv[x]) + 1);
+				strcpy(SWITCH_GLOBAL_dirs.log_dir, argv[x]);
 				alt_dirs++;
-            } else {
-                fprintf(stderr, "When using -log you must specify a log directory\n");
-                return 255;
-            }
-        }
-
-        if (argv[x] && !strcmp(argv[x], "-db")) {
-            x++;
-            if (argv[x] && strlen(argv[x])) {
-                SWITCH_GLOBAL_dirs.db_dir = (char *) malloc(strlen(argv[x])+1);
-                strcpy(SWITCH_GLOBAL_dirs.db_dir,argv[x]);
+			} else {
+				fprintf(stderr, "When using -log you must specify a log directory\n");
+				return 255;
+			}
+			known_opt++;
+		}
+
+		if (argv[x] && !strcmp(argv[x], "-db")) {
+			x++;
+			if (argv[x] && strlen(argv[x])) {
+				SWITCH_GLOBAL_dirs.db_dir = (char *) malloc(strlen(argv[x]) + 1);
+				strcpy(SWITCH_GLOBAL_dirs.db_dir, argv[x]);
 				alt_dirs++;
-            } else {
-                fprintf(stderr, "When using -db you must specify a db directory\n");
-                return 255;
-            }
-        }
-            
+			} else {
+				fprintf(stderr, "When using -db you must specify a db directory\n");
+				return 255;
+			}
+			known_opt++;
+		}
+
+		if ((!known_opt || argv[x]) && !strcmp(argv[x], "-help")) {
+			printf("%s\n", usageDesc);
+			exit(0);
+		}
+
 	}
 
 	if (die) {
 		return freeswitch_kill_background();
 	}
 
-	if (alt_dirs && alt_dirs !=3) {
+	if (alt_dirs && alt_dirs != 3) {
 		fprintf(stderr, "You must use -conf, -log, and -db together\n");
 		return 255;
 	}
@@ -360,7 +364,7 @@
 		FreeConsole();
 #else
 		if (!nf && (pid = fork())) {
-			fprintf(stderr, "%d Backgrounding.\n", (int)pid);
+			fprintf(stderr, "%d Backgrounding.\n", (int) pid);
 			exit(0);
 		}
 #endif

Modified: freeswitch/branches/cparker/src/switch_buffer.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_buffer.c	(original)
+++ freeswitch/branches/cparker/src/switch_buffer.c	Tue Apr 24 10:14:28 2007
@@ -35,7 +35,7 @@
 static uint32_t buffer_id = 0;
 
 typedef enum {
-	SWITCH_BUFFER_FLAG_DYNAMIC = (1 <<  0)
+	SWITCH_BUFFER_FLAG_DYNAMIC = (1 << 0)
 } switch_buffer_flag_t;
 
 struct switch_buffer {
@@ -48,14 +48,14 @@
 	switch_size_t blocksize;
 	uint32_t flags;
 	uint32_t id;
+	int32_t loops;
 };
 
 SWITCH_DECLARE(switch_status_t) switch_buffer_create(switch_memory_pool_t *pool, switch_buffer_t **buffer, switch_size_t max_len)
 {
 	switch_buffer_t *new_buffer;
 
-	if ((new_buffer = switch_core_alloc(pool, sizeof(switch_buffer_t))) != 0
-		&& (new_buffer->data = switch_core_alloc(pool, max_len)) != 0) {
+	if ((new_buffer = switch_core_alloc(pool, sizeof(switch_buffer_t))) != 0 && (new_buffer->data = switch_core_alloc(pool, max_len)) != 0) {
 		new_buffer->datalen = max_len;
 		new_buffer->id = buffer_id++;
 		new_buffer->head = new_buffer->data;
@@ -65,9 +65,7 @@
 	return SWITCH_STATUS_MEMERR;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_buffer_create_dynamic(switch_buffer_t **buffer,
-															 switch_size_t blocksize,
-															 switch_size_t start_len,
+SWITCH_DECLARE(switch_status_t) switch_buffer_create_dynamic(switch_buffer_t **buffer, switch_size_t blocksize, switch_size_t start_len,
 															 switch_size_t max_len)
 {
 	switch_buffer_t *new_buffer;
@@ -89,7 +87,7 @@
 		new_buffer->blocksize = blocksize;
 		new_buffer->head = new_buffer->data;
 		switch_set_flag(new_buffer, SWITCH_BUFFER_FLAG_DYNAMIC);
-		
+
 		*buffer = new_buffer;
 		return SWITCH_STATUS_SUCCESS;
 	}
@@ -144,12 +142,32 @@
 		reading = buffer->used;
 	}
 
-    buffer->used -= reading;
-    buffer->head += reading;
+	buffer->used -= reading;
+	buffer->head += reading;
 
 	return buffer->used;
 }
 
+SWITCH_DECLARE(void) switch_buffer_set_loops(switch_buffer_t *buffer, int32_t loops)
+{
+	buffer->loops = loops;
+}
+
+SWITCH_DECLARE(switch_size_t) switch_buffer_read_loop(switch_buffer_t *buffer, void *data, switch_size_t datalen)
+{
+	switch_size_t len;
+	if ((len = switch_buffer_read(buffer, data, datalen)) == 0) {
+		if (buffer->loops == 0) {
+			return 0;
+		}
+		buffer->head = buffer->data;
+		buffer->used = buffer->actually_used;
+		len = switch_buffer_read(buffer, data, datalen);
+		buffer->loops--;
+	}
+	return len;
+}
+
 SWITCH_DECLARE(switch_size_t) switch_buffer_read(switch_buffer_t *buffer, void *data, switch_size_t datalen)
 {
 	switch_size_t reading = 0;
@@ -171,7 +189,7 @@
 	buffer->used -= reading;
 	buffer->head += reading;
 
-	//if (buffer->id == 4) printf("%u o %d = %d\n", buffer->id, (uint32_t)reading, (uint32_t)buffer->used);
+	/* if (buffer->id == 4) printf("%u o %d = %d\n", buffer->id, (uint32_t)reading, (uint32_t)buffer->used); */
 	return reading;
 }
 
@@ -182,7 +200,7 @@
 	assert(buffer != NULL);
 	assert(data != NULL);
 	assert(buffer->data != NULL);
-	
+
 	if (!datalen) {
 		return buffer->used;
 	}
@@ -198,11 +216,11 @@
 	freespace = buffer->datalen - buffer->used;
 
 	/*
-	if (buffer->data != buffer->head) {
-		memmove(buffer->data, buffer->head, buffer->used);
-		buffer->head = buffer->data;
-	}
-	*/
+	   if (buffer->data != buffer->head) {
+	   memmove(buffer->data, buffer->head, buffer->used);
+	   buffer->head = buffer->data;
+	   }
+	 */
 	if (switch_test_flag(buffer, SWITCH_BUFFER_FLAG_DYNAMIC)) {
 		if (freespace < datalen) {
 			switch_size_t new_size, new_block_size;
@@ -221,7 +239,7 @@
 			buffer->datalen = new_size;
 		}
 	}
-	
+
 	freespace = buffer->datalen - buffer->used;
 
 	if (freespace < datalen) {
@@ -231,7 +249,7 @@
 		buffer->used += datalen;
 		buffer->actually_used += datalen;
 	}
-	//if (buffer->id == 4) printf("%u i %d = %d\n", buffer->id, (uint32_t)datalen, (uint32_t)buffer->used);
+	/* if (buffer->id == 4) printf("%u i %d = %d\n", buffer->id, (uint32_t)datalen, (uint32_t)buffer->used); */
 
 	return buffer->used;
 }
@@ -239,7 +257,7 @@
 SWITCH_DECLARE(void) switch_buffer_zero(switch_buffer_t *buffer)
 {
 	assert(buffer != NULL);
-    assert(buffer->data != NULL);
+	assert(buffer->data != NULL);
 
 	buffer->used = 0;
 	buffer->head = buffer->data;

Modified: freeswitch/branches/cparker/src/switch_caller.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_caller.c	(original)
+++ freeswitch/branches/cparker/src/switch_caller.c	Tue Apr 24 10:14:28 2007
@@ -39,10 +39,8 @@
 																	const char *caller_id_number,
 																	const char *network_addr,
 																	const char *ani,
-																	const char *aniii, 
-																	const char *rdnis,
-																	const char *source,
-																	const char *context,
+																	const char *aniii,
+																	const char *rdnis, const char *source, const char *context,
 																	const char *destination_number)
 {
 
@@ -72,7 +70,6 @@
 
 
 SWITCH_DECLARE(switch_caller_profile_t *) switch_caller_profile_clone(switch_core_session_t *session, switch_caller_profile_t *tocopy)
-																	
 {
 	switch_caller_profile_t *profile = NULL;
 	if ((profile = switch_core_session_alloc(session, sizeof(switch_caller_profile_t))) != 0) {
@@ -139,8 +136,7 @@
 	return NULL;
 }
 
-SWITCH_DECLARE(void) switch_caller_profile_event_set_data(switch_caller_profile_t *caller_profile, char *prefix,
-														  switch_event_t *event)
+SWITCH_DECLARE(void) switch_caller_profile_event_set_data(switch_caller_profile_t *caller_profile, char *prefix, switch_event_t *event)
 {
 	char header_name[1024];
 
@@ -211,8 +207,7 @@
 
 }
 
-SWITCH_DECLARE(switch_caller_extension_t *) switch_caller_extension_new(switch_core_session_t *session,
-																	  char *extension_name, char *extension_number)
+SWITCH_DECLARE(switch_caller_extension_t *) switch_caller_extension_new(switch_core_session_t *session, char *extension_name, char *extension_number)
 {
 	switch_caller_extension_t *caller_extension = NULL;
 
@@ -227,8 +222,7 @@
 
 
 SWITCH_DECLARE(void) switch_caller_extension_add_application(switch_core_session_t *session,
-															 switch_caller_extension_t *caller_extension,
-															 char *application_name, char *application_data)
+															 switch_caller_extension_t *caller_extension, char *application_name, char *application_data)
 {
 	switch_caller_application_t *caller_application = NULL;
 

Modified: freeswitch/branches/cparker/src/switch_channel.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_channel.c	(original)
+++ freeswitch/branches/cparker/src/switch_channel.c	Tue Apr 24 10:14:28 2007
@@ -39,63 +39,64 @@
 };
 
 static struct switch_cause_table CAUSE_CHART[] = {
-	{ "UNALLOCATED", SWITCH_CAUSE_UNALLOCATED },
-	{ "SUCCESS", SWITCH_CAUSE_SUCCESS },
-	{ "NO_ROUTE_TRANSIT_NET", SWITCH_CAUSE_NO_ROUTE_TRANSIT_NET },
-	{ "NO_ROUTE_DESTINATION", SWITCH_CAUSE_NO_ROUTE_DESTINATION },
-	{ "CHANNEL_UNACCEPTABLE", SWITCH_CAUSE_CHANNEL_UNACCEPTABLE },
-	{ "CALL_AWARDED_DELIVERED", SWITCH_CAUSE_CALL_AWARDED_DELIVERED },
-	{ "NORMAL_CLEARING", SWITCH_CAUSE_NORMAL_CLEARING },
-	{ "USER_BUSY", SWITCH_CAUSE_USER_BUSY },
-	{ "NO_USER_RESPONSE", SWITCH_CAUSE_NO_USER_RESPONSE },
-	{ "NO_ANSWER", SWITCH_CAUSE_NO_ANSWER },
-	{ "SUBSCRIBER_ABSENT", SWITCH_CAUSE_SUBSCRIBER_ABSENT },
-	{ "CALL_REJECTED", SWITCH_CAUSE_CALL_REJECTED },
-	{ "NUMBER_CHANGED", SWITCH_CAUSE_NUMBER_CHANGED },
-	{ "REDIRECTION_TO_NEW_DESTINATION", SWITCH_CAUSE_REDIRECTION_TO_NEW_DESTINATION },
-	{ "EXCHANGE_ROUTING_ERROR", SWITCH_CAUSE_EXCHANGE_ROUTING_ERROR },
-	{ "DESTINATION_OUT_OF_ORDER", SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER },
-	{ "INVALID_NUMBER_FORMAT", SWITCH_CAUSE_INVALID_NUMBER_FORMAT },
-	{ "FACILITY_REJECTED", SWITCH_CAUSE_FACILITY_REJECTED },
-	{ "RESPONSE_TO_STATUS_ENQUIRY", SWITCH_CAUSE_RESPONSE_TO_STATUS_ENQUIRY },
-	{ "NORMAL_UNSPECIFIED", SWITCH_CAUSE_NORMAL_UNSPECIFIED },
-	{ "NORMAL_CIRCUIT_CONGESTION", SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION },
-	{ "NETWORK_OUT_OF_ORDER", SWITCH_CAUSE_NETWORK_OUT_OF_ORDER },
-	{ "NORMAL_TEMPORARY_FAILURE", SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE },
-	{ "SWITCH_CONGESTION", SWITCH_CAUSE_SWITCH_CONGESTION },
-	{ "ACCESS_INFO_DISCARDED", SWITCH_CAUSE_ACCESS_INFO_DISCARDED },
-	{ "REQUESTED_CHAN_UNAVAIL", SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL },
-	{ "PRE_EMPTED", SWITCH_CAUSE_PRE_EMPTED },
-	{ "FACILITY_NOT_SUBSCRIBED", SWITCH_CAUSE_FACILITY_NOT_SUBSCRIBED },
-	{ "OUTGOING_CALL_BARRED", SWITCH_CAUSE_OUTGOING_CALL_BARRED },
-	{ "INCOMING_CALL_BARRED", SWITCH_CAUSE_INCOMING_CALL_BARRED },
-	{ "BEARERCAPABILITY_NOTAUTH", SWITCH_CAUSE_BEARERCAPABILITY_NOTAUTH },
-	{ "BEARERCAPABILITY_NOTAVAIL", SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL },
-	{ "SERVICE_UNAVAILABLE", SWITCH_CAUSE_SERVICE_UNAVAILABLE },
-	{ "CHAN_NOT_IMPLEMENTED", SWITCH_CAUSE_CHAN_NOT_IMPLEMENTED },
-	{ "FACILITY_NOT_IMPLEMENTED", SWITCH_CAUSE_FACILITY_NOT_IMPLEMENTED },
-	{ "SERVICE_NOT_IMPLEMENTED", SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED },
-	{ "INVALID_CALL_REFERENCE", SWITCH_CAUSE_INVALID_CALL_REFERENCE },
-	{ "INCOMPATIBLE_DESTINATION", SWITCH_CAUSE_INCOMPATIBLE_DESTINATION },
-	{ "INVALID_MSG_UNSPECIFIED", SWITCH_CAUSE_INVALID_MSG_UNSPECIFIED },
-	{ "MANDATORY_IE_MISSING", SWITCH_CAUSE_MANDATORY_IE_MISSING },
-	{ "MESSAGE_TYPE_NONEXIST", SWITCH_CAUSE_MESSAGE_TYPE_NONEXIST },
-	{ "WRONG_MESSAGE", SWITCH_CAUSE_WRONG_MESSAGE },
-	{ "IE_NONEXIST", SWITCH_CAUSE_IE_NONEXIST },
-	{ "INVALID_IE_CONTENTS", SWITCH_CAUSE_INVALID_IE_CONTENTS },
-	{ "WRONG_CALL_STATE", SWITCH_CAUSE_WRONG_CALL_STATE },
-	{ "RECOVERY_ON_TIMER_EXPIRE", SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE },
-	{ "MANDATORY_IE_LENGTH_ERROR", SWITCH_CAUSE_MANDATORY_IE_LENGTH_ERROR },
-	{ "PROTOCOL_ERROR", SWITCH_CAUSE_PROTOCOL_ERROR },
-	{ "INTERWORKING", SWITCH_CAUSE_INTERWORKING },
-	{ "ORIGINATOR_CANCEL", SWITCH_CAUSE_ORIGINATOR_CANCEL },
-	{ "CRASH", SWITCH_CAUSE_CRASH },
-	{ "SYSTEM_SHUTDOWN", SWITCH_CAUSE_SYSTEM_SHUTDOWN },
-	{ "LOSE_RACE", SWITCH_CAUSE_LOSE_RACE },
-	{ "MANAGER_REQUEST", SWITCH_CAUSE_MANAGER_REQUEST },
-	{ "BLIND_TRANSFER", SWITCH_CAUSE_BLIND_TRANSFER },
-	{ "ATTENDED_TRANSFER", SWITCH_CAUSE_ATTENDED_TRANSFER },
-	{ NULL, 0 }
+	{"UNALLOCATED", SWITCH_CAUSE_UNALLOCATED},
+	{"SUCCESS", SWITCH_CAUSE_SUCCESS},
+	{"NO_ROUTE_TRANSIT_NET", SWITCH_CAUSE_NO_ROUTE_TRANSIT_NET},
+	{"NO_ROUTE_DESTINATION", SWITCH_CAUSE_NO_ROUTE_DESTINATION},
+	{"CHANNEL_UNACCEPTABLE", SWITCH_CAUSE_CHANNEL_UNACCEPTABLE},
+	{"CALL_AWARDED_DELIVERED", SWITCH_CAUSE_CALL_AWARDED_DELIVERED},
+	{"NORMAL_CLEARING", SWITCH_CAUSE_NORMAL_CLEARING},
+	{"USER_BUSY", SWITCH_CAUSE_USER_BUSY},
+	{"NO_USER_RESPONSE", SWITCH_CAUSE_NO_USER_RESPONSE},
+	{"NO_ANSWER", SWITCH_CAUSE_NO_ANSWER},
+	{"SUBSCRIBER_ABSENT", SWITCH_CAUSE_SUBSCRIBER_ABSENT},
+	{"CALL_REJECTED", SWITCH_CAUSE_CALL_REJECTED},
+	{"NUMBER_CHANGED", SWITCH_CAUSE_NUMBER_CHANGED},
+	{"REDIRECTION_TO_NEW_DESTINATION", SWITCH_CAUSE_REDIRECTION_TO_NEW_DESTINATION},
+	{"EXCHANGE_ROUTING_ERROR", SWITCH_CAUSE_EXCHANGE_ROUTING_ERROR},
+	{"DESTINATION_OUT_OF_ORDER", SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER},
+	{"INVALID_NUMBER_FORMAT", SWITCH_CAUSE_INVALID_NUMBER_FORMAT},
+	{"FACILITY_REJECTED", SWITCH_CAUSE_FACILITY_REJECTED},
+	{"RESPONSE_TO_STATUS_ENQUIRY", SWITCH_CAUSE_RESPONSE_TO_STATUS_ENQUIRY},
+	{"NORMAL_UNSPECIFIED", SWITCH_CAUSE_NORMAL_UNSPECIFIED},
+	{"NORMAL_CIRCUIT_CONGESTION", SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION},
+	{"NETWORK_OUT_OF_ORDER", SWITCH_CAUSE_NETWORK_OUT_OF_ORDER},
+	{"NORMAL_TEMPORARY_FAILURE", SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE},
+	{"SWITCH_CONGESTION", SWITCH_CAUSE_SWITCH_CONGESTION},
+	{"ACCESS_INFO_DISCARDED", SWITCH_CAUSE_ACCESS_INFO_DISCARDED},
+	{"REQUESTED_CHAN_UNAVAIL", SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL},
+	{"PRE_EMPTED", SWITCH_CAUSE_PRE_EMPTED},
+	{"FACILITY_NOT_SUBSCRIBED", SWITCH_CAUSE_FACILITY_NOT_SUBSCRIBED},
+	{"OUTGOING_CALL_BARRED", SWITCH_CAUSE_OUTGOING_CALL_BARRED},
+	{"INCOMING_CALL_BARRED", SWITCH_CAUSE_INCOMING_CALL_BARRED},
+	{"BEARERCAPABILITY_NOTAUTH", SWITCH_CAUSE_BEARERCAPABILITY_NOTAUTH},
+	{"BEARERCAPABILITY_NOTAVAIL", SWITCH_CAUSE_BEARERCAPABILITY_NOTAVAIL},
+	{"SERVICE_UNAVAILABLE", SWITCH_CAUSE_SERVICE_UNAVAILABLE},
+	{"CHAN_NOT_IMPLEMENTED", SWITCH_CAUSE_CHAN_NOT_IMPLEMENTED},
+	{"FACILITY_NOT_IMPLEMENTED", SWITCH_CAUSE_FACILITY_NOT_IMPLEMENTED},
+	{"SERVICE_NOT_IMPLEMENTED", SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED},
+	{"INVALID_CALL_REFERENCE", SWITCH_CAUSE_INVALID_CALL_REFERENCE},
+	{"INCOMPATIBLE_DESTINATION", SWITCH_CAUSE_INCOMPATIBLE_DESTINATION},
+	{"INVALID_MSG_UNSPECIFIED", SWITCH_CAUSE_INVALID_MSG_UNSPECIFIED},
+	{"MANDATORY_IE_MISSING", SWITCH_CAUSE_MANDATORY_IE_MISSING},
+	{"MESSAGE_TYPE_NONEXIST", SWITCH_CAUSE_MESSAGE_TYPE_NONEXIST},
+	{"WRONG_MESSAGE", SWITCH_CAUSE_WRONG_MESSAGE},
+	{"IE_NONEXIST", SWITCH_CAUSE_IE_NONEXIST},
+	{"INVALID_IE_CONTENTS", SWITCH_CAUSE_INVALID_IE_CONTENTS},
+	{"WRONG_CALL_STATE", SWITCH_CAUSE_WRONG_CALL_STATE},
+	{"RECOVERY_ON_TIMER_EXPIRE", SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE},
+	{"MANDATORY_IE_LENGTH_ERROR", SWITCH_CAUSE_MANDATORY_IE_LENGTH_ERROR},
+	{"PROTOCOL_ERROR", SWITCH_CAUSE_PROTOCOL_ERROR},
+	{"INTERWORKING", SWITCH_CAUSE_INTERWORKING},
+	{"ORIGINATOR_CANCEL", SWITCH_CAUSE_ORIGINATOR_CANCEL},
+	{"CRASH", SWITCH_CAUSE_CRASH},
+	{"SYSTEM_SHUTDOWN", SWITCH_CAUSE_SYSTEM_SHUTDOWN},
+	{"LOSE_RACE", SWITCH_CAUSE_LOSE_RACE},
+	{"MANAGER_REQUEST", SWITCH_CAUSE_MANAGER_REQUEST},
+	{"BLIND_TRANSFER", SWITCH_CAUSE_BLIND_TRANSFER},
+	{"ATTENDED_TRANSFER", SWITCH_CAUSE_ATTENDED_TRANSFER},
+	{"ALLOTTED_TIMEOUT", SWITCH_CAUSE_ALLOTTED_TIMEOUT},
+	{NULL, 0}
 };
 
 struct switch_channel {
@@ -122,7 +123,7 @@
 	uint8_t x;
 	char *str = "UNKNOWN";
 
-	for(x = 0; CAUSE_CHART[x].name; x++) {
+	for (x = 0; CAUSE_CHART[x].name; x++) {
 		if (CAUSE_CHART[x].cause == cause) {
 			str = (char *) CAUSE_CHART[x].name;
 		}
@@ -136,7 +137,7 @@
 	uint8_t x;
 	switch_call_cause_t cause = SWITCH_CAUSE_UNALLOCATED;
 
-	for(x = 0; CAUSE_CHART[x].name; x++) {
+	for (x = 0; CAUSE_CHART[x].name; x++) {
 		if (!strcasecmp(CAUSE_CHART[x].name, str)) {
 			cause = CAUSE_CHART[x].cause;
 		}
@@ -152,14 +153,14 @@
 
 SWITCH_DECLARE(switch_channel_timetable_t *) switch_channel_get_timetable(switch_channel_t *channel)
 {
-    switch_channel_timetable_t *times = NULL;
+	switch_channel_timetable_t *times = NULL;
 
 	assert(channel != NULL);
-    if (channel->caller_profile) {
-        switch_mutex_lock(channel->profile_mutex);
-        times = channel->caller_profile->times;
-        switch_mutex_unlock(channel->profile_mutex);
-    }
+	if (channel->caller_profile) {
+		switch_mutex_lock(channel->profile_mutex);
+		times = channel->caller_profile->times;
+		switch_mutex_unlock(channel->profile_mutex);
+	}
 
 	return times;
 }
@@ -209,13 +210,13 @@
 
 	inuse = switch_buffer_inuse(channel->dtmf_buffer);
 	len = strlen(dtmf);
-	
+
 	if (len + inuse > switch_buffer_len(channel->dtmf_buffer)) {
 		switch_buffer_toss(channel->dtmf_buffer, strlen(dtmf));
 	}
 
 	p = dtmf;
-	while(wr < len && p) {
+	while (wr < len && p) {
 		if (is_dtmf(*p)) {
 			wr++;
 		} else {
@@ -258,9 +259,8 @@
 	switch_buffer_destroy(&channel->dtmf_buffer);
 }
 
-SWITCH_DECLARE(switch_status_t) switch_channel_init(switch_channel_t *channel,
-												  switch_core_session_t *session,
-												  switch_channel_state_t state, uint32_t flags)
+SWITCH_DECLARE(switch_status_t) switch_channel_init(switch_channel_t *channel, switch_core_session_t *session, switch_channel_state_t state,
+													uint32_t flags)
 {
 	assert(channel != NULL);
 	channel->state = state;
@@ -306,7 +306,7 @@
 	char *v = NULL;
 	assert(channel != NULL);
 
-	if (!(v=switch_core_hash_find(channel->variables, varname))) {
+	if (!(v = switch_core_hash_find(channel->variables, varname))) {
 		if (!channel->caller_profile || !(v = switch_caller_get_field_by_name(channel->caller_profile, varname))) {
 			if (!strcmp(varname, "base_dir")) {
 				return SWITCH_GLOBAL_dirs.base_dir;
@@ -314,7 +314,7 @@
 			v = switch_core_get_variable(varname);
 		}
 	}
-	
+
 	return v;
 }
 
@@ -396,6 +396,42 @@
 	return switch_test_flag(channel, flags) ? 1 : 0;
 }
 
+SWITCH_DECLARE(switch_bool_t) switch_channel_set_flag_partner(switch_channel_t *channel, switch_channel_flag_t flags)
+{
+	char *uuid;
+
+	assert(channel != NULL);
+
+	if ((uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE))) {
+		switch_core_session_t *session;
+		if ((session = switch_core_session_locate(uuid))) {
+			switch_channel_set_flag(switch_core_session_get_channel(session), flags);
+			switch_core_session_rwunlock(session);
+			return SWITCH_TRUE;
+		}
+	}
+
+	return SWITCH_FALSE;
+}
+
+SWITCH_DECLARE(switch_bool_t) switch_channel_clear_flag_partner(switch_channel_t *channel, switch_channel_flag_t flags)
+{
+	char *uuid;
+
+	assert(channel != NULL);
+
+	if ((uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE))) {
+		switch_core_session_t *session;
+		if ((session = switch_core_session_locate(uuid))) {
+			switch_channel_clear_flag(switch_core_session_get_channel(session), flags);
+			switch_core_session_rwunlock(session);
+			return SWITCH_TRUE;
+		}
+	}
+
+	return SWITCH_FALSE;
+}
+
 SWITCH_DECLARE(void) switch_channel_set_flag(switch_channel_t *channel, switch_channel_flag_t flags)
 {
 	assert(channel != NULL);
@@ -431,8 +467,20 @@
 
 SWITCH_DECLARE(uint8_t) switch_channel_ready(switch_channel_t *channel)
 {
+	uint8_t ret = 0;
+
 	assert(channel != NULL);
-	return (channel->state > CS_RING && channel->state < CS_HANGUP && !switch_test_flag(channel, CF_TRANSFER)) ? 1 : 0;
+	
+	if (!channel->hangup_cause && channel->state > CS_RING && channel->state < CS_HANGUP && !switch_test_flag(channel, CF_TRANSFER)) {
+		ret++;
+	}
+
+	if (switch_test_flag(channel, CF_BREAK)) {
+		switch_clear_flag_locked(channel, CF_BREAK);
+		ret = (uint8_t) 0;
+	}
+
+	return ret;
 }
 
 static const char *state_names[] = {
@@ -458,7 +506,7 @@
 SWITCH_DECLARE(switch_channel_state_t) switch_channel_name_state(char *name)
 {
 	uint32_t x = 0;
-	for(x = 0; state_names[x]; x++) {
+	for (x = 0; state_names[x]; x++) {
 		if (!strcasecmp(state_names[x], name)) {
 			return (switch_channel_state_t) x;
 		}
@@ -468,10 +516,7 @@
 }
 
 SWITCH_DECLARE(switch_channel_state_t) switch_channel_perform_set_state(switch_channel_t *channel,
-                                                                        const char *file,
-                                                                        const char *func,
-                                                                        int line,
-                                                                        switch_channel_state_t state)
+																		const char *file, const char *func, int line, switch_channel_state_t state)
 {
 	switch_channel_state_t last_state;
 	int ok = 0;
@@ -489,7 +534,7 @@
 	if (last_state >= CS_HANGUP && state < last_state) {
 		goto done;
 	}
-	
+
 	/* STUB for more dev
 	   case CS_INIT:
 	   switch(state) {
@@ -627,12 +672,10 @@
 
 	if (ok) {
 		if (state > CS_RING) {
-			switch_channel_presence(channel, "unknown", (char*)state_names[state]);
+			switch_channel_presence(channel, "unknown", (char *) state_names[state]);
 		}
-		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_DEBUG, "%s State Change %s -> %s\n", 
-						  channel->name,
-						  state_names[last_state], 
-						  state_names[state]);
+		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_DEBUG, "%s State Change %s -> %s\n",
+						  channel->name, state_names[last_state], state_names[state]);
 		switch_mutex_lock(channel->flag_mutex);
 		channel->state = state;
 		switch_mutex_unlock(channel->flag_mutex);
@@ -656,25 +699,23 @@
 				switch_event_fire(&event);
 			}
 		}
-				
+
 		if (state < CS_DONE) {
 			switch_core_session_signal_state_change(channel->session);
 		}
-		
+
 	} else {
-		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_WARNING, "%s Invalid State Change %s -> %s\n", 
-						  channel->name,
-						  state_names[last_state],
-						  state_names[state]);
+		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_WARNING,
+						  "%s Invalid State Change %s -> %s\n", channel->name, state_names[last_state], state_names[state]);
 
-		//we won't tolerate an invalid state change so we can make sure we are as robust as a nice cup of dark coffee!
+		/* we won't tolerate an invalid state change so we can make sure we are as robust as a nice cup of dark coffee! */
 		if (channel->state < CS_HANGUP) {
-			// not cool lets crash this bad boy and figure out wtf is going on
+			/* not cool lets crash this bad boy and figure out wtf is going on */
 			assert(0);
 		}
 	}
- done:
-	
+  done:
+
 	if (channel->state_flags) {
 		channel->flags |= channel->state_flags;
 		channel->state_flags = 0;
@@ -694,22 +735,22 @@
 	char state_num[25];
 
 	if ((caller_profile = switch_channel_get_caller_profile(channel))) {
-        originator_caller_profile = caller_profile->originator_caller_profile;
-        originatee_caller_profile = caller_profile->originatee_caller_profile;
-    }
+		originator_caller_profile = caller_profile->originator_caller_profile;
+		originatee_caller_profile = caller_profile->originatee_caller_profile;
+	}
 
 	switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Channel-State", "%s", switch_channel_state_name(channel->state));
 	snprintf(state_num, sizeof(state_num), "%d", channel->state);
 	switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Channel-State-Number", "%s", state_num);
 	switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Channel-Name", "%s", switch_channel_get_name(channel));
 	switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Unique-ID", "%s", switch_core_session_get_uuid(channel->session));
-	
-	if ((codec = switch_core_session_get_read_codec(channel->session))) {
+
+	if ((codec = switch_core_session_get_read_codec(channel->session)) && codec->implementation) {
 		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Channel-Read-Codec-Name", "%s", switch_str_nil(codec->implementation->iananame));
 		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Channel-Read-Codec-Rate", "%u", codec->implementation->samples_per_second);
 	}
-	
-	if ((codec = switch_core_session_get_write_codec(channel->session))) {
+
+	if ((codec = switch_core_session_get_write_codec(channel->session)) && codec->implementation) {
 		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Channel-Write-Codec-Name", "%s", switch_str_nil(codec->implementation->iananame));
 		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Channel-Write-Codec-Rate", "%u", codec->implementation->samples_per_second);
 	}
@@ -730,13 +771,12 @@
 	}
 
 	/* Index Variables */
-	for (hi = switch_hash_first(switch_core_session_get_pool(channel->session), channel->variables); hi;
-		 hi = switch_hash_next(hi)) {
+	for (hi = switch_hash_first(switch_core_session_get_pool(channel->session), channel->variables); hi; hi = switch_hash_next(hi)) {
 		char buf[1024];
 		switch_hash_this(hi, &var, NULL, &val);
 		if (var && val) {
-			snprintf(buf, sizeof(buf), "variable_%s", (char *)var);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, buf, "%s", (char *)val);
+			snprintf(buf, sizeof(buf), "variable_%s", (char *) var);
+			switch_event_add_header(event, SWITCH_STACK_BOTTOM, buf, "%s", (char *) val);
 		}
 	}
 
@@ -770,15 +810,15 @@
 			switch_channel_event_set_data(channel, event);
 			switch_event_fire(&event);
 		}
-	} 
-    
-    caller_profile->times = (switch_channel_timetable_t *) switch_core_session_alloc(channel->session, sizeof(*caller_profile->times));
+	}
+
+	caller_profile->times = (switch_channel_timetable_t *) switch_core_session_alloc(channel->session, sizeof(*caller_profile->times));
 	caller_profile->times->created = switch_time_now();
 
-    if (channel->caller_profile && channel->caller_profile->times) {
-        channel->caller_profile->times->transferred = switch_time_now();
-        caller_profile->times->answered = channel->caller_profile->times->answered;
-    }
+	if (channel->caller_profile && channel->caller_profile->times) {
+		channel->caller_profile->times->transferred = switch_time_now();
+		caller_profile->times->answered = channel->caller_profile->times->answered;
+	}
 
 	caller_profile->next = channel->caller_profile;
 	channel->caller_profile = caller_profile;
@@ -798,28 +838,26 @@
 	return profile;
 }
 
-SWITCH_DECLARE(void) switch_channel_set_originator_caller_profile(switch_channel_t *channel,
-																  switch_caller_profile_t *caller_profile)
+SWITCH_DECLARE(void) switch_channel_set_originator_caller_profile(switch_channel_t *channel, switch_caller_profile_t *caller_profile)
 {
 	assert(channel != NULL);
-    if (channel->caller_profile) {
-        switch_mutex_lock(channel->profile_mutex);
-        caller_profile->next = channel->caller_profile->originator_caller_profile;
-        channel->caller_profile->originator_caller_profile = caller_profile;
-        switch_mutex_unlock(channel->profile_mutex);
-    }
+	if (channel->caller_profile) {
+		switch_mutex_lock(channel->profile_mutex);
+		caller_profile->next = channel->caller_profile->originator_caller_profile;
+		channel->caller_profile->originator_caller_profile = caller_profile;
+		switch_mutex_unlock(channel->profile_mutex);
+	}
 }
 
-SWITCH_DECLARE(void) switch_channel_set_originatee_caller_profile(switch_channel_t *channel,
-																  switch_caller_profile_t *caller_profile)
+SWITCH_DECLARE(void) switch_channel_set_originatee_caller_profile(switch_channel_t *channel, switch_caller_profile_t *caller_profile)
 {
 	assert(channel != NULL);
-    if (channel->caller_profile) {
-        switch_mutex_lock(channel->profile_mutex);
-        caller_profile->next = channel->caller_profile->originatee_caller_profile;
-        channel->caller_profile->originatee_caller_profile = caller_profile;
-        switch_mutex_unlock(channel->profile_mutex);
-    }
+	if (channel->caller_profile) {
+		switch_mutex_lock(channel->profile_mutex);
+		caller_profile->next = channel->caller_profile->originatee_caller_profile;
+		channel->caller_profile->originatee_caller_profile = caller_profile;
+		switch_mutex_unlock(channel->profile_mutex);
+	}
 }
 
 SWITCH_DECLARE(switch_caller_profile_t *) switch_channel_get_originator_caller_profile(switch_channel_t *channel)
@@ -827,11 +865,11 @@
 	switch_caller_profile_t *profile = NULL;
 	assert(channel != NULL);
 
-    if (channel->caller_profile) {
-        switch_mutex_lock(channel->profile_mutex);
-        profile = channel->caller_profile->originator_caller_profile;
-        switch_mutex_unlock(channel->profile_mutex);
-    }
+	if (channel->caller_profile) {
+		switch_mutex_lock(channel->profile_mutex);
+		profile = channel->caller_profile->originator_caller_profile;
+		switch_mutex_unlock(channel->profile_mutex);
+	}
 
 	return profile;
 }
@@ -841,11 +879,11 @@
 	switch_caller_profile_t *profile = NULL;
 	assert(channel != NULL);
 
-    if (channel->caller_profile) {
-        switch_mutex_lock(channel->profile_mutex);
-        profile = channel->caller_profile->originatee_caller_profile;
-        switch_mutex_unlock(channel->profile_mutex);
-    }
+	if (channel->caller_profile) {
+		switch_mutex_lock(channel->profile_mutex);
+		profile = channel->caller_profile->originatee_caller_profile;
+		switch_mutex_unlock(channel->profile_mutex);
+	}
 
 	return profile;
 }
@@ -857,8 +895,7 @@
 	return switch_core_session_get_uuid(channel->session);
 }
 
-SWITCH_DECLARE(int) switch_channel_add_state_handler(switch_channel_t *channel,
-													 const switch_state_handler_table_t *state_handler)
+SWITCH_DECLARE(int) switch_channel_add_state_handler(switch_channel_t *channel, const switch_state_handler_table_t *state_handler)
 {
 	int x, index;
 
@@ -876,10 +913,10 @@
 		index = -1;
 		goto end;
 	}
-	
+
 	channel->state_handlers[index] = state_handler;
 
- end:
+  end:
 	switch_mutex_unlock(channel->flag_mutex);
 	return index;
 }
@@ -904,7 +941,7 @@
 SWITCH_DECLARE(void) switch_channel_clear_state_handler(switch_channel_t *channel, const switch_state_handler_table_t *state_handler)
 {
 	int index, i = channel->state_handler_index;
-	const switch_state_handler_table_t *new_handlers[SWITCH_MAX_STATE_HANDLERS] = {0};
+	const switch_state_handler_table_t *new_handlers[SWITCH_MAX_STATE_HANDLERS] = { 0 };
 
 
 	switch_mutex_lock(channel->flag_mutex);
@@ -933,8 +970,7 @@
 
 }
 
-SWITCH_DECLARE(void) switch_channel_set_caller_extension(switch_channel_t *channel,
-														 switch_caller_extension_t *caller_extension)
+SWITCH_DECLARE(void) switch_channel_set_caller_extension(switch_channel_t *channel, switch_caller_extension_t *caller_extension)
 {
 	assert(channel != NULL);
 
@@ -947,29 +983,28 @@
 
 SWITCH_DECLARE(switch_caller_extension_t *) switch_channel_get_caller_extension(switch_channel_t *channel)
 {
-    switch_caller_extension_t *extension;
+	switch_caller_extension_t *extension = NULL;
 
 	assert(channel != NULL);
 	switch_mutex_lock(channel->profile_mutex);
-	extension = channel->caller_profile->caller_extension;
-    switch_mutex_unlock(channel->profile_mutex);
-    return extension;
+	if (channel->caller_profile) {
+		extension = channel->caller_profile->caller_extension;
+	}
+	switch_mutex_unlock(channel->profile_mutex);
+	return extension;
 }
 
 
-SWITCH_DECLARE(switch_channel_state_t) switch_channel_perform_hangup(switch_channel_t *channel, 
-                                                                     const char *file,
-                                                                     const char *func,
-                                                                     int line,
-                                                                     switch_call_cause_t hangup_cause)
+SWITCH_DECLARE(switch_channel_state_t) switch_channel_perform_hangup(switch_channel_t *channel,
+																	 const char *file, const char *func, int line, switch_call_cause_t hangup_cause)
 {
 	assert(channel != NULL);
 	switch_mutex_lock(channel->flag_mutex);
 
 	if (channel->caller_profile && channel->caller_profile->times && !channel->caller_profile->times->hungup) {
-        switch_mutex_lock(channel->profile_mutex);
+		switch_mutex_lock(channel->profile_mutex);
 		channel->caller_profile->times->hungup = switch_time_now();
-        switch_mutex_unlock(channel->profile_mutex);
+		switch_mutex_unlock(channel->profile_mutex);
 	}
 
 	if (channel->state < CS_HANGUP) {
@@ -977,15 +1012,14 @@
 		switch_channel_state_t last_state = channel->state;
 		channel->state = CS_HANGUP;
 		channel->hangup_cause = hangup_cause;
-		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_NOTICE, "Hangup %s [%s] [%s]\n", 
-						  channel->name,
-						  state_names[last_state], switch_channel_cause2str(channel->hangup_cause));
+		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_NOTICE, "Hangup %s [%s] [%s]\n",
+						  channel->name, state_names[last_state], switch_channel_cause2str(channel->hangup_cause));
 		if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_HANGUP) == SWITCH_STATUS_SUCCESS) {
 			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Hangup-Cause", "%s", switch_channel_cause2str(channel->hangup_cause));
 			switch_channel_event_set_data(channel, event);
 			switch_event_fire(&event);
 		}
-		
+
 		switch_channel_set_variable(channel, "hangup_cause", switch_channel_cause2str(channel->hangup_cause));
 		switch_channel_presence(channel, "unavailable", switch_channel_cause2str(channel->hangup_cause));
 
@@ -998,13 +1032,10 @@
 }
 
 
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_ring_ready(switch_channel_t *channel,
-																	   const char *file,
-																	   const char *func,
-																	   int line)
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_ring_ready(switch_channel_t *channel, const char *file, const char *func, int line)
 {
 	if (!switch_channel_test_flag(channel, CF_RING_READY)) {
-        switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_NOTICE, "Ring-Ready %s!\n", channel->name);
+		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_NOTICE, "Ring-Ready %s!\n", channel->name);
 		switch_channel_set_flag(channel, CF_RING_READY);
 		return SWITCH_STATUS_SUCCESS;
 	}
@@ -1014,52 +1045,46 @@
 
 
 
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_pre_answered(switch_channel_t *channel,
-																		 const char *file,
-																		 const char *func,
-																		 int line)
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_pre_answered(switch_channel_t *channel, const char *file, const char *func, int line)
 {
-    switch_event_t *event;
+	switch_event_t *event;
 
 	switch_channel_mark_ring_ready(channel);
 
-    if (!switch_channel_test_flag(channel, CF_EARLY_MEDIA)) {
-        char *uuid;
-        switch_core_session_t *other_session;
-
-        switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_NOTICE, "Pre-Answer %s!\n", channel->name);
-        switch_channel_set_flag(channel, CF_EARLY_MEDIA);
-        switch_channel_set_variable(channel, "endpoint_disposition", "EARLY MEDIA");
-        if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_PROGRESS) == SWITCH_STATUS_SUCCESS) {
-            switch_channel_event_set_data(channel, event);
-            switch_event_fire(&event);
-        }
-
-        /* if we're in a bridge and the other channel is in a blocking read they will never realize we have answered so send 
-           a SWITCH_SIG_BREAK to interrupt any blocking reads on that channel
-        */
-        if ((uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) && (other_session = switch_core_session_locate(uuid))) {
-            switch_core_session_kill_channel(other_session, SWITCH_SIG_BREAK);
-            switch_core_session_rwunlock(other_session);
-        }
-        return SWITCH_STATUS_SUCCESS;
-    }
-    
-    return SWITCH_STATUS_FALSE;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_pre_answer(switch_channel_t *channel,
-                                                                  const char *file,
-                                                                  const char *func,
-                                                                  int line)
+	if (!switch_channel_test_flag(channel, CF_EARLY_MEDIA)) {
+		char *uuid;
+		switch_core_session_t *other_session;
+
+		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_NOTICE, "Pre-Answer %s!\n", channel->name);
+		switch_channel_set_flag(channel, CF_EARLY_MEDIA);
+		switch_channel_set_variable(channel, "endpoint_disposition", "EARLY MEDIA");
+		if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_PROGRESS) == SWITCH_STATUS_SUCCESS) {
+			switch_channel_event_set_data(channel, event);
+			switch_event_fire(&event);
+		}
+
+		/* if we're the child of another channel and the other channel is in a blocking read they will never realize we have answered so send 
+		   a SWITCH_SIG_BREAK to interrupt any blocking reads on that channel
+		 */
+		if ((uuid = switch_channel_get_variable(channel, SWITCH_ORIGINATOR_VARIABLE))
+			&& (other_session = switch_core_session_locate(uuid))) {
+			switch_core_session_kill_channel(other_session, SWITCH_SIG_BREAK);
+			switch_core_session_rwunlock(other_session);
+		}
+		return SWITCH_STATUS_SUCCESS;
+	}
+
+	return SWITCH_STATUS_FALSE;
+}
+
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_pre_answer(switch_channel_t *channel, const char *file, const char *func, int line)
 {
 	switch_core_session_message_t msg;
-	char *uuid = switch_core_session_get_uuid(channel->session);
 	switch_status_t status;
-	
+
 	assert(channel != NULL);
 
-	if (channel->state >= CS_HANGUP) {
+	if (channel->hangup_cause || channel->state >= CS_HANGUP) {
 		return SWITCH_STATUS_FALSE;
 	}
 
@@ -1073,27 +1098,23 @@
 
 	msg.message_id = SWITCH_MESSAGE_INDICATE_PROGRESS;
 	msg.from = channel->name;
-	status = switch_core_session_message_send(uuid, &msg);
+	status = switch_core_session_receive_message(channel->session, &msg);
 
 	if (status == SWITCH_STATUS_SUCCESS) {
-        status = switch_channel_perform_mark_pre_answered(channel, file, func, line);
+		status = switch_channel_perform_mark_pre_answered(channel, file, func, line);
 	}
 
 	return status;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_ring_ready(switch_channel_t *channel,
-																  const char *file,
-																  const char *func,
-																  int line)
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_ring_ready(switch_channel_t *channel, const char *file, const char *func, int line)
 {
 	switch_core_session_message_t msg;
-	char *uuid = switch_core_session_get_uuid(channel->session);
 	switch_status_t status;
-	
+
 	assert(channel != NULL);
 
-	if (channel->state >= CS_HANGUP) {
+	if (channel->hangup_cause || channel->state >= CS_HANGUP) {
 		return SWITCH_STATUS_FALSE;
 	}
 
@@ -1107,7 +1128,7 @@
 
 	msg.message_id = SWITCH_MESSAGE_INDICATE_RINGING;
 	msg.from = channel->name;
-	status = switch_core_session_message_send(uuid, &msg);
+	status = switch_core_session_receive_message(channel->session, &msg);
 
 	if (status == SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_NOTICE, "Ring Ready %s!\n", channel->name);
@@ -1116,18 +1137,15 @@
 	return status;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_answered(switch_channel_t *channel,
-                                                                     const char *file,
-                                                                     const char *func,
-                                                                     int line)
-{
-    switch_event_t *event;
-    char *uuid;
-    switch_core_session_t *other_session;
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_mark_answered(switch_channel_t *channel, const char *file, const char *func, int line)
+{
+	switch_event_t *event;
+	char *uuid;
+	switch_core_session_t *other_session;
 
-    assert(channel != NULL);
+	assert(channel != NULL);
 
-	if (channel->state >= CS_HANGUP) {
+	if (channel->hangup_cause || channel->state >= CS_HANGUP) {
 		return SWITCH_STATUS_FALSE;
 	}
 
@@ -1135,41 +1153,42 @@
 		return SWITCH_STATUS_SUCCESS;
 	}
 
-    if (channel->caller_profile && channel->caller_profile->times) {
-        switch_mutex_lock(channel->profile_mutex);
-        channel->caller_profile->times->answered = switch_time_now();
-        switch_mutex_unlock(channel->profile_mutex);
-    }
-    
-    switch_channel_set_flag(channel, CF_ANSWERED);
-    
-    if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_ANSWER) == SWITCH_STATUS_SUCCESS) {
-        switch_channel_event_set_data(channel, event);
-        switch_event_fire(&event);
-    }
-
-    /* if we're in a bridge and the other channel is in a blocking read they will never realize we have answered so send 
-       a SWITCH_SIG_BREAK to interrupt any blocking reads on that channel
-     */
-    if ((uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) && (other_session = switch_core_session_locate(uuid))) {
-        switch_core_session_kill_channel(other_session, SWITCH_SIG_BREAK);
-        switch_core_session_rwunlock(other_session);
-    }
-
-    switch_channel_set_variable(channel, "endpoint_disposition", "ANSWER");
-    switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_NOTICE, "Channel [%s] has been answered\n", channel->name);
-    
-    return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_channel_perform_answer(switch_channel_t *channel,
-                                                              const char *file,
-                                                              const char *func,
-                                                              int line)
+	if (channel->caller_profile && channel->caller_profile->times) {
+		switch_mutex_lock(channel->profile_mutex);
+		channel->caller_profile->times->answered = switch_time_now();
+		switch_mutex_unlock(channel->profile_mutex);
+	}
+
+	switch_channel_set_flag(channel, CF_ANSWERED);
+
+	if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_ANSWER) == SWITCH_STATUS_SUCCESS) {
+		switch_channel_event_set_data(channel, event);
+		switch_event_fire(&event);
+	}
+
+	/* if we're the child of another channel and the other channel is in a blocking read they will never realize we have answered so send 
+	   a SWITCH_SIG_BREAK to interrupt any blocking reads on that channel
+	 */
+	if ((uuid = switch_channel_get_variable(channel, SWITCH_ORIGINATOR_VARIABLE))
+		&& (other_session = switch_core_session_locate(uuid))) {
+		switch_core_session_kill_channel(other_session, SWITCH_SIG_BREAK);
+		switch_core_session_rwunlock(other_session);
+	}
+
+	switch_channel_set_variable(channel, "endpoint_disposition", "ANSWER");
+	switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_NOTICE, "Channel [%s] has been answered\n", channel->name);
+
+	return SWITCH_STATUS_SUCCESS;
+}
+
+SWITCH_DECLARE(switch_status_t) switch_channel_perform_answer(switch_channel_t *channel, const char *file, const char *func, int line)
 {
+	switch_core_session_message_t msg;
+	switch_status_t status;
+
 	assert(channel != NULL);
 
-	if (channel->state >= CS_HANGUP) {
+	if (channel->hangup_cause || channel->state >= CS_HANGUP) {
 		return SWITCH_STATUS_FALSE;
 	}
 
@@ -1177,8 +1196,13 @@
 		return SWITCH_STATUS_SUCCESS;
 	}
 
-	if (switch_core_session_answer_channel(channel->session) == SWITCH_STATUS_SUCCESS) {
-        return switch_channel_perform_mark_answered(channel, file, func, line);
+
+	msg.message_id = SWITCH_MESSAGE_INDICATE_ANSWER;
+	msg.from = channel->name;
+	status = switch_core_session_receive_message(channel->session, &msg);
+
+	if (status == SWITCH_STATUS_SUCCESS) {
+		return switch_channel_perform_mark_answered(channel, file, func, line);
 	}
 
 	return SWITCH_STATUS_FALSE;
@@ -1201,6 +1225,7 @@
 	char *data, *indup;
 	size_t sp = 0, len = 0, olen = 0, vtype = 0, br = 0, cpos, block = 128;
 	char *sub_val = NULL, *func_val = NULL;
+	int nv = 0;
 
 	if (!in || !strchr(in, '$')) {
 		return in;
@@ -1212,14 +1237,32 @@
 	if ((data = malloc(olen))) {
 		memset(data, 0, olen);
 		c = data;
-		for(p = indup; *p; p++) {
+		for (p = indup; *p; p++) {
 			vtype = 0;
 
-			if (*p == '$') {
+			if (*p == '\\') {
+				if (*(p + 1) == '$') {
+					nv = 1;
+				} else if (*(p + 1) == '\\') {
+					*c++ = *p++;
+					len++;
+					continue;
+				}
+				p++;
+			}
+
+			if (*p == '$' && !nv) {
 				vtype = 1;
-                if (*(p+1) != '{') {
-                    vtype = 2;
-                }
+				if (*(p + 1) != '{') {
+					vtype = 2;
+				}
+			}
+
+			if (nv) {
+				*c++ = *p;
+				len++;
+				nv = 0;
+				continue;
 			}
 
 			if (vtype) {
@@ -1261,14 +1304,14 @@
 					e++;
 				}
 				p = e;
-				
+
 				if (vtype == 1) {
 					sub_val = switch_channel_get_variable(channel, vname);
 				} else {
-					switch_stream_handle_t stream = {0};
+					switch_stream_handle_t stream = { 0 };
 
 					SWITCH_STANDARD_STREAM(stream);
-					
+
 					if (stream.data) {
 						if (switch_api_execute(vname, vval, channel->session, &stream) == SWITCH_STATUS_SUCCESS) {
 							func_val = stream.data;
@@ -1285,22 +1328,22 @@
 				}
 				if ((nlen = sub_val ? strlen(sub_val) : 0)) {
 					if (len + nlen >= olen) {
-                        resize(nlen);
+						resize(nlen);
 					}
 
 					len += nlen;
 					strcat(c, sub_val);
 					c += nlen;
 				}
-				
+
 				switch_safe_free(func_val);
-                sub_val = NULL;
-                vname = NULL;
-                vtype = 0;
+				sub_val = NULL;
+				vname = NULL;
+				vtype = 0;
+			}
+			if (len + 1 >= olen) {
+				resize(1);
 			}
-            if (len + 1 >= olen) {
-                resize(1);
-            }
 
 			if (sp) {
 				*c++ = ' ';
@@ -1313,7 +1356,7 @@
 			} else {
 				*c++ = *p;
 				len++;
-			} 
+			}
 		}
 	}
 	free(indup);

Modified: freeswitch/branches/cparker/src/switch_config.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_config.c	(original)
+++ freeswitch/branches/cparker/src/switch_config.c	Tue Apr 24 10:14:28 2007
@@ -32,7 +32,7 @@
 #include <switch.h>
 #include <switch_config.h>
 
-SWITCH_DECLARE(int) switch_config_open_file(switch_config_t *cfg, char *file_path)
+SWITCH_DECLARE(int) switch_config_open_file(switch_config_t * cfg, char *file_path)
 {
 	FILE *f;
 	char *path = NULL;
@@ -88,7 +88,7 @@
 }
 
 
-SWITCH_DECLARE(void) switch_config_close_file(switch_config_t *cfg)
+SWITCH_DECLARE(void) switch_config_close_file(switch_config_t * cfg)
 {
 
 	if (cfg->file) {
@@ -100,7 +100,7 @@
 
 
 
-SWITCH_DECLARE(int) switch_config_next_pair(switch_config_t *cfg, char **var, char **val)
+SWITCH_DECLARE(int) switch_config_next_pair(switch_config_t * cfg, char **var, char **val)
 {
 	int ret = 0;
 	char *p, *end;
@@ -171,10 +171,10 @@
 		}
 		*var = p;
 
-		
+
 		if ((*val = strchr(*var, '=')) == 0) {
 			ret = -1;
-			//log_printf(0, server.log, "Invalid syntax on %s: line %d\n", cfg->path, cfg->lineno);
+			/* log_printf(0, server.log, "Invalid syntax on %s: line %d\n", cfg->path, cfg->lineno); */
 			continue;
 		} else {
 			p = *val - 1;

Modified: freeswitch/branches/cparker/src/switch_console.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_console.c	(original)
+++ freeswitch/branches/cparker/src/switch_console.c	Tue Apr 24 10:14:28 2007
@@ -41,27 +41,21 @@
 	char *buf = handle->data;
 	char *end = handle->end;
 	int ret = 0;
-	char *data;
+	char *data = NULL;
 
 	if (handle->data_len >= handle->data_size) {
 		return SWITCH_STATUS_FALSE;
 	}
 
 	va_start(ap, fmt);
-#ifdef HAVE_VASPRINTF
-	ret = vasprintf(&data, fmt, ap);
-#else
-	if ((data = (char *) malloc(2048))) {
-		ret = vsnprintf(data, 2048, fmt, ap);
-	}
-#endif
+	ret = switch_vasprintf(&data, fmt, ap);
 	va_end(ap);
-	
+
 	if (data) {
 		switch_size_t remaining = handle->data_size - handle->data_len;
 		switch_size_t need = strlen(data) + 1;
-		
-		
+
+
 		if ((remaining < need) && handle->alloc_len) {
 			switch_size_t new_len;
 			void *new_data;
@@ -69,10 +63,10 @@
 			new_len = handle->data_size + need + handle->alloc_chunk;
 			if ((new_data = realloc(handle->data, new_len))) {
 				handle->data_size = handle->alloc_len = new_len;
-                handle->data = new_data;
+				handle->data = new_data;
 				buf = handle->data;
 				remaining = handle->data_size - handle->data_len;
-				handle->end = (uint8_t *)(handle->data) + handle->data_len;
+				handle->end = (uint8_t *) (handle->data) + handle->data_len;
 				end = handle->end;
 			} else {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
@@ -87,11 +81,11 @@
 			ret = 0;
 			snprintf(end, remaining, "%s", data);
 			handle->data_len = strlen(buf);
-			handle->end = (uint8_t *)(handle->data) + handle->data_len;
+			handle->end = (uint8_t *) (handle->data) + handle->data_len;
 		}
 		free(data);
 	}
-	
+
 	return ret ? SWITCH_STATUS_FALSE : SWITCH_STATUS_SUCCESS;
 }
 
@@ -99,7 +93,7 @@
 static int switch_console_process(char *cmd)
 {
 	char *arg = NULL;
-	switch_stream_handle_t stream = {0};
+	switch_stream_handle_t stream = { 0 };
 
 	if (!strcmp(cmd, "shutdown") || !strcmp(cmd, "...")) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Bye!\n");
@@ -109,18 +103,18 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_CONSOLE, "FreeSwitch Version %s\n", SWITCH_VERSION_FULL);
 		return 1;
 	}
-	if ((arg = strchr(cmd, '\r')) != 0  || (arg = strchr(cmd, '\n')) != 0 )  {
+	if ((arg = strchr(cmd, '\r')) != 0 || (arg = strchr(cmd, '\n')) != 0) {
 		*arg = '\0';
 		arg = NULL;
 	}
 	if ((arg = strchr(cmd, ' ')) != 0) {
 		*arg++ = '\0';
 	}
-	
+
 	SWITCH_STANDARD_STREAM(stream);
 	if (stream.data) {
 		if (switch_api_execute(cmd, arg, NULL, &stream) == SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_CONSOLE, "API CALL [%s(%s)] output:\n%s\n", cmd, arg ? arg : "", (char *)stream.data);
+			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_CONSOLE, "API CALL [%s(%s)] output:\n%s\n", cmd, arg ? arg : "", (char *) stream.data);
 		} else {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Unknown Command: %s\n", cmd);
 		}
@@ -132,8 +126,7 @@
 	return 1;
 }
 
-SWITCH_DECLARE(void) switch_console_printf(switch_text_channel_t channel, const char *file, const char *func, int line,
-										   const char *fmt, ...)
+SWITCH_DECLARE(void) switch_console_printf(switch_text_channel_t channel, const char *file, const char *func, int line, const char *fmt, ...)
 {
 	char *data = NULL;
 	int ret = 0;
@@ -145,12 +138,7 @@
 
 	handle = switch_core_data_channel(channel);
 
-#ifdef HAVE_VASPRINTF
-	ret = vasprintf(&data, fmt, ap);
-#else
-	data = (char *) malloc(2048);
-	ret = vsnprintf(data, 2048, fmt, ap);
-#endif
+	ret = switch_vasprintf(&data, fmt, ap);
 	va_end(ap);
 	if (ret == -1) {
 		fprintf(stderr, "Memory Error\n");
@@ -171,8 +159,7 @@
 			}
 
 			else if (channel == SWITCH_CHANNEL_ID_EVENT &&
-					 switch_event_running() == SWITCH_STATUS_SUCCESS &&
-					 switch_event_create(&event, SWITCH_EVENT_LOG) == SWITCH_STATUS_SUCCESS) {
+					 switch_event_running() == SWITCH_STATUS_SUCCESS && switch_event_create(&event, SWITCH_EVENT_LOG) == SWITCH_STATUS_SUCCESS) {
 
 				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-Data", "%s", data);
 				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-File", "%s", filep);
@@ -182,7 +169,7 @@
 			}
 		}
 	}
-	if(data) {
+	if (data) {
 		free(data);
 	}
 	fflush(handle);
@@ -197,11 +184,11 @@
 
 	gethostname(hostname, sizeof(hostname));
 
-	while(running) {
+	while (running) {
 		uint32_t arg;
 #ifndef _MSC_VER
 		fd_set rfds, efds;
-		struct timeval tv = {0, 20000};
+		struct timeval tv = { 0, 20000 };
 #endif
 
 		switch_core_session_ctl(SCSC_CHECK_RUNNING, &arg);
@@ -213,7 +200,7 @@
 			switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_CONSOLE, "\nfreeswitch@%s> ", hostname);
 		}
 #ifdef _MSC_VER
-		activity = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE),20);
+		activity = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 20);
 
 		if (activity == 102) {
 			fflush(stdout);
@@ -224,9 +211,9 @@
 		FD_ZERO(&efds);
 		FD_SET(fileno(stdin), &rfds);
 		FD_SET(fileno(stdin), &efds);
-		if ((activity = select(fileno(stdin)+1, &rfds, NULL, &efds, &tv)) < 0) {
-            break;
-        }
+		if ((activity = select(fileno(stdin) + 1, &rfds, NULL, &efds, &tv)) < 0) {
+			break;
+		}
 
 		if (activity == 0) {
 			fflush(stdout);
@@ -236,13 +223,13 @@
 
 
 		memset(&cmd, 0, sizeof(cmd));
-		for (x = 0; x < (sizeof(cmd)-1); x++) {
-            int c = getchar();
-            if (c < 0) {
-                int y = read(fileno(stdin), cmd, sizeof(cmd));
-                cmd[y-1] = '\0';
-                break;
-            }
+		for (x = 0; x < (sizeof(cmd) - 1); x++) {
+			int c = getchar();
+			if (c < 0) {
+				int y = read(fileno(stdin), cmd, sizeof(cmd));
+				cmd[y - 1] = '\0';
+				break;
+			}
 
 			cmd[x] = (char) c;
 
@@ -251,12 +238,12 @@
 				break;
 			}
 		}
-	
+
 		if (cmd[0]) {
 			running = switch_console_process(cmd);
 		}
 	}
-	
+
 
 }
 

Modified: freeswitch/branches/cparker/src/switch_core.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_core.c	(original)
+++ freeswitch/branches/cparker/src/switch_core.c	Tue Apr 24 10:14:28 2007
@@ -26,6 +26,7 @@
  * Anthony Minessale II <anthmct at yahoo.com>
  * Michael Jerris <mike at jerris.com>
  * Paul D. Tinsley <pdt at jackhammer.org>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  *
  * switch_core.c -- Main Core Library
@@ -33,4203 +34,331 @@
  */
 
 #include <switch.h>
-#include <stdio.h>
 #include <switch_version.h>
+#include "private/switch_core.h"
 
-#ifdef HAVE_MLOCKALL
-#include <sys/mman.h>
-#endif
-
-//#define DEBUG_ALLOC
-#define DO_EVENTS
-
-#ifdef CRASH_PROT
-#define __CP "ENABLED"
-#else
-#define __CP "DISABLED"
-#endif
-
-#define SWITCH_EVENT_QUEUE_LEN 256
-#define SWITCH_MESSAGE_QUEUE_LEN 256
-#define SWITCH_SQL_QUEUE_LEN 2000
-
-#define SWITCH_BUFFER_BLOCK_FRAMES 25
-#define SWITCH_BUFFER_START_FRAMES 50
-
-struct switch_media_bug {
-	switch_buffer_t *raw_write_buffer;
-	switch_buffer_t *raw_read_buffer;
-    switch_frame_t *replace_frame_in;
-    switch_frame_t *replace_frame_out;
-	switch_media_bug_callback_t callback;
-	switch_mutex_t *read_mutex;
-	switch_mutex_t *write_mutex;
-	switch_core_session_t *session;
-	void *user_data;
-	uint32_t flags;
-    uint8_t ready;
-	struct switch_media_bug *next;
-};
-
-typedef enum {
-    SSF_NONE = 0,
-    SSF_DESTROYED = (1 << 0)
-} switch_session_flag_t;
-
-struct switch_core_session {
-	uint32_t id;
-	char name[80];
-    switch_session_flag_t flags;
-	int thread_running;
-	switch_memory_pool_t *pool;
-	switch_channel_t *channel;
-	switch_thread_t *thread;
-	const switch_endpoint_interface_t *endpoint_interface;
-	switch_io_event_hooks_t event_hooks;
-	switch_codec_t *read_codec;
-	switch_codec_t *write_codec;
-
-	switch_buffer_t *raw_write_buffer;
-	switch_frame_t raw_write_frame;
-	switch_frame_t enc_write_frame;
-	uint8_t raw_write_buf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-	uint8_t enc_write_buf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-
-	switch_buffer_t *raw_read_buffer;
-	switch_frame_t raw_read_frame;
-	switch_frame_t enc_read_frame;
-	uint8_t raw_read_buf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-	uint8_t enc_read_buf[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-
-
-	switch_audio_resampler_t *read_resampler;
-	switch_audio_resampler_t *write_resampler;
-
-	switch_mutex_t *mutex;
-	switch_thread_cond_t *cond;
-
-	switch_thread_rwlock_t *rwlock;
-
-	void *streams[SWITCH_MAX_STREAMS];
-	int stream_count;
+SWITCH_DECLARE_DATA switch_directories SWITCH_GLOBAL_dirs = { 0 };
 
-	char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1];
-	void *private_info;
-	switch_queue_t *event_queue;
-	switch_queue_t *message_queue;
-	switch_queue_t *private_event_queue;
-	switch_thread_rwlock_t *bug_rwlock;
-	switch_media_bug_t *bugs;
-};
-
-SWITCH_DECLARE_DATA switch_directories SWITCH_GLOBAL_dirs;
-
-struct switch_core_runtime {
+/* The main runtime obj we keep this hidden for ourselves */
+static struct {
 	switch_time_t initiated;
-	uint32_t session_id;
-	apr_pool_t *memory_pool;
-	switch_hash_t *session_table;
 	switch_hash_t *global_vars;
-	switch_mutex_t *session_table_mutex;
-#ifdef CRASH_PROT
-	switch_hash_t *stack_table;
-#endif
-	switch_core_db_t *db;
-	switch_core_db_t *event_db;
+	switch_memory_pool_t *memory_pool;
 	const switch_state_handler_table_t *state_handlers[SWITCH_MAX_STATE_HANDLERS];
-    int state_handler_index;
+	int state_handler_index;
 	FILE *console;
-	uint32_t session_count;
-	uint32_t session_limit;
-	switch_queue_t *sql_queue;
-	uint32_t no_new_sessions;
-	uint32_t shutting_down;
 	uint8_t running;
 	char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1];
-};
-
-/* Prototypes */
-static void *SWITCH_THREAD_FUNC switch_core_session_thread(switch_thread_t *thread, void *obj);
-static void switch_core_standard_on_init(switch_core_session_t *session);
-static void switch_core_standard_on_hangup(switch_core_session_t *session);
-static void switch_core_standard_on_ring(switch_core_session_t *session);
-static void switch_core_standard_on_execute(switch_core_session_t *session);
-static void switch_core_standard_on_loopback(switch_core_session_t *session);
-static void switch_core_standard_on_transmit(switch_core_session_t *session);
-static void switch_core_standard_on_hold(switch_core_session_t *session);
-
-
-/* The main runtime obj we keep this hidden for ourselves */
-static struct switch_core_runtime runtime;
-
-
-static void db_pick_path(char *dbname, char *buf, switch_size_t size)
-{
-
-	memset(buf, 0, size);
-	if (strchr(dbname, '/')) {
-		strncpy(buf, dbname, size);
-	} else {
-		snprintf(buf, size, "%s%s%s.db", SWITCH_GLOBAL_dirs.db_dir, SWITCH_PATH_SEPARATOR, dbname);
-	}
-}
-
-static void switch_core_media_bug_destroy(switch_media_bug_t *bug)
-{
-	switch_buffer_destroy(&bug->raw_read_buffer);
-	switch_buffer_destroy(&bug->raw_write_buffer);
-}
-
-
-SWITCH_DECLARE(switch_frame_t *) switch_core_media_bug_get_replace_frame(switch_media_bug_t *bug)
-{
-    return bug->replace_frame_in;
-}
-
-SWITCH_DECLARE(void) switch_core_media_bug_set_replace_frame(switch_media_bug_t *bug, switch_frame_t *frame)
-{
-    bug->replace_frame_out = frame;
-}
-
-SWITCH_DECLARE(void *) switch_core_media_bug_get_user_data(switch_media_bug_t *bug)
-{
-	return bug->user_data;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_media_bug_read(switch_media_bug_t *bug, switch_frame_t *frame)
-{
-	uint32_t bytes = 0;
-	uint8_t data[SWITCH_RECCOMMENDED_BUFFER_SIZE] = {0};
-	uint32_t datalen = 0;
-	int16_t *dp, *fp;
-	uint32_t x;
-	size_t rlen = 0;
-	size_t wlen = 0;
-	uint32_t blen;
-	size_t rdlen = 0;
-	uint32_t maxlen;
-
-
-	if (bug->raw_read_buffer) {
-		rlen = switch_buffer_inuse(bug->raw_read_buffer);
-	}
-
-	if (bug->raw_write_buffer) {
-		wlen = switch_buffer_inuse(bug->raw_write_buffer);
-	}
-
-	if ((bug->raw_read_buffer && bug->raw_write_buffer) && (!rlen && !wlen)) {
-		return SWITCH_STATUS_FALSE;
-	}
-
-
-	maxlen = sizeof(data) > frame->buflen ? frame->buflen :  sizeof(data);
-	if ((rdlen = rlen > wlen ? wlen : rlen) > maxlen) {
-		rdlen = maxlen;
-	}
-
-	if (!rdlen) {
-		rdlen = maxlen;
-	}
-
-	frame->datalen = 0;
-
-	if (rlen) {
-		switch_mutex_lock(bug->read_mutex);
-		
-		frame->datalen = (uint32_t) switch_buffer_read(bug->raw_read_buffer,
-													   frame->data,
-													   rdlen);
-		switch_mutex_unlock(bug->read_mutex);
-	}
-
-	if (wlen) {
-		switch_mutex_lock(bug->write_mutex);
-		datalen = (uint32_t) switch_buffer_read(bug->raw_write_buffer,
-												data,
-												rdlen);
-		switch_mutex_unlock(bug->write_mutex);
-	}
-
-
-	bytes = (datalen > frame->datalen) ? datalen : frame->datalen;
-
-	if (bytes) {
-		dp = (int16_t *) data;
-		fp = (int16_t *) frame->data;
-		
-		rlen = frame->datalen / 2;
-		wlen = datalen / 2;
-		blen = bytes / 2;
-		
-		for(x = 0; x < blen; x++) {
-			int32_t z = 0;
-
-			if (x < rlen) {
-				z += (int32_t) *(fp+x);
-			}
-			if (x < wlen) {
-				z += (int32_t)*(dp+x);
-			}
-			switch_normalize_to_16bit(z);
-			*(fp+x) = (int16_t) z;
-		}
-
-		frame->datalen = bytes;
-
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_FALSE;
-}
-
-#define MAX_BUG_BUFFER 1024 * 512
-SWITCH_DECLARE(switch_status_t) switch_core_media_bug_add(switch_core_session_t *session,
-														  switch_media_bug_callback_t callback,
-														  void *user_data,
-														  switch_media_bug_flag_t flags,
-														  switch_media_bug_t **new_bug)
-
-{
-	switch_media_bug_t *bug, *bp;
-	switch_size_t bytes;
-
-    if (flags & SMBF_WRITE_REPLACE) {
-        switch_thread_rwlock_wrlock(session->bug_rwlock);
-        for (bp = session->bugs; bp; bp = bp->next) {
-            if (switch_test_flag(bp, SMBF_WRITE_REPLACE)) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Only one bug of this type allowed!\n");
-                switch_thread_rwlock_unlock(session->bug_rwlock);
-                return SWITCH_STATUS_GENERR;
-            }
-        }
-        switch_thread_rwlock_unlock(session->bug_rwlock);
-    }
-
-	if (!(bug = switch_core_session_alloc(session, sizeof(*bug)))) {
-		return SWITCH_STATUS_MEMERR;
-	}
-
-	bug->callback = callback;
-	bug->user_data = user_data;
-	bug->session = session;
-	bug->flags = flags;
-    bug->ready = 1;
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Attaching BUG to %s\n", switch_channel_get_name(session->channel));
-	bytes = session->read_codec->implementation->bytes_per_frame;
-
-	if (!bug->flags) {
-		bug->flags = (SMBF_READ_STREAM | SMBF_WRITE_STREAM);
-	}
-
-	if (switch_test_flag(bug, SMBF_READ_STREAM)) {
-		switch_buffer_create_dynamic(&bug->raw_read_buffer, bytes * SWITCH_BUFFER_BLOCK_FRAMES, bytes * SWITCH_BUFFER_START_FRAMES, MAX_BUG_BUFFER);
-		switch_mutex_init(&bug->read_mutex, SWITCH_MUTEX_NESTED, session->pool);
-	}
-
-	bytes = session->write_codec->implementation->bytes_per_frame;
-
-	if (switch_test_flag(bug, SMBF_WRITE_STREAM)) {
-		switch_buffer_create_dynamic(&bug->raw_write_buffer, bytes * SWITCH_BUFFER_BLOCK_FRAMES, bytes * SWITCH_BUFFER_START_FRAMES, MAX_BUG_BUFFER);
-		switch_mutex_init(&bug->write_mutex, SWITCH_MUTEX_NESTED, session->pool);
-	}
-
-	switch_thread_rwlock_wrlock(session->bug_rwlock);
-	bug->next = session->bugs;
-	session->bugs = bug;
-	switch_thread_rwlock_unlock(session->bug_rwlock);
-	*new_bug = bug;
-
-	if (bug->callback) {
-		bug->callback(bug, bug->user_data, SWITCH_ABC_TYPE_INIT);
-	}
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_media_bug_remove_all(switch_core_session_t *session)
-{
-	switch_media_bug_t *bp;
-
-	if (session->bugs) {
-		switch_thread_rwlock_wrlock(session->bug_rwlock);
-		for (bp = session->bugs; bp; bp = bp->next) {
-			if (bp->callback) {
-				bp->callback(bp, bp->user_data, SWITCH_ABC_TYPE_CLOSE);
-			}
-			switch_core_media_bug_destroy(bp);
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Removing BUG from %s\n", switch_channel_get_name(session->channel));
-		}
-		switch_thread_rwlock_unlock(session->bug_rwlock);
-		session->bugs = NULL;
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_FALSE;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_media_bug_remove(switch_core_session_t *session, switch_media_bug_t **bug)
-{
-	switch_media_bug_t *bp = NULL, *last = NULL;
-
-	if (session->bugs) {
-		switch_thread_rwlock_wrlock(session->bug_rwlock);
-		for (bp = session->bugs; bp; bp = bp->next) {
-            if (!bp->ready) {
-                continue;
-            }
-			if (bp == *bug) {
-				if (last) {
-					last->next = bp->next;
-				} else {
-					session->bugs = bp->next;
-				}
-				break;
-			}
-			last = bp;
-		}
-		switch_thread_rwlock_unlock(session->bug_rwlock);
-
-		if (bp) {
-			if (bp->callback) {
-				bp->callback(bp, bp->user_data, SWITCH_ABC_TYPE_CLOSE);
-                bp->ready = 0;
-			}
-			switch_core_media_bug_destroy(bp);
-			*bug = NULL;
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Removing BUG from %s\n", switch_channel_get_name(session->channel));
-			return SWITCH_STATUS_SUCCESS;
-		}
-	}
-
-	return SWITCH_STATUS_FALSE;
-}
-
-struct switch_core_port_allocator {
-	switch_port_t start;
-	switch_port_t end;
-	switch_port_t next;
-	uint8_t inc;
-	switch_mutex_t *mutex;
-	switch_memory_pool_t *pool;
-};
-
-SWITCH_DECLARE(switch_status_t) switch_core_port_allocator_new(switch_port_t start,
-															   switch_port_t end,
-															   uint8_t inc,
-															   switch_core_port_allocator_t **new_allocator)
-{
-	switch_status_t status;
-	switch_memory_pool_t *pool;
-	switch_core_port_allocator_t *alloc;
-
-	if ((status = switch_core_new_memory_pool(&pool)) != SWITCH_STATUS_SUCCESS) {
-		return status;
-	}
-
-	if (!(alloc = switch_core_alloc(pool, sizeof(*alloc)))) {
-		switch_core_destroy_memory_pool(&pool);
-		return SWITCH_STATUS_MEMERR;
-	}
-	
-	alloc->start = start;
-	alloc->next = start;
-	alloc->end = end;
-	if (!(alloc->inc = inc)) {
-		alloc->inc = 2;
-	}
-	switch_mutex_init(&alloc->mutex, SWITCH_MUTEX_NESTED, pool);
-	alloc->pool = pool;
-	*new_allocator = alloc;
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_port_t) switch_core_port_allocator_request_port(switch_core_port_allocator_t *alloc)
-{
-	switch_port_t port;
-
-	switch_mutex_lock(alloc->mutex);
-	port = alloc->next;
-	alloc->next = alloc->next + alloc->inc;
-	if (alloc->next > alloc->end) {
-		alloc->next = alloc->start;
-	}
-	switch_mutex_unlock(alloc->mutex);
-	return port;
-}
-
-SWITCH_DECLARE(void) switch_core_port_allocator_destroy(switch_core_port_allocator_t **alloc)
-{
-	switch_memory_pool_t *pool = (*alloc)->pool;
-	switch_core_destroy_memory_pool(&pool);
-	*alloc = NULL;
-}
-
-SWITCH_DECLARE(switch_core_db_t *) switch_core_db_open_file(char *filename)
-{
-	switch_core_db_t *db;
-	char path[1024];
-
-	db_pick_path(filename, path, sizeof(path));
-	if (switch_core_db_open(path, &db)) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "SQL ERR [%s]\n", switch_core_db_errmsg(db));
-		switch_core_db_close(db);
-		db = NULL;
-	}
-	return db;
-}
-
-
-SWITCH_DECLARE(void) switch_core_db_test_reactive(switch_core_db_t *db, char *test_sql, char *reactive_sql) 
-{
-    char *errmsg;
-
-    if(db) {
-        if(test_sql) {
-            switch_core_db_exec(
-                         db,
-                         test_sql,
-                         NULL,
-                         NULL,
-                         &errmsg
-                         );
-
-            if (errmsg) {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SQL ERR [%s]\n[%s]\nAuto Generating Table!\n", errmsg, test_sql);
-                switch_core_db_free(errmsg);
-                errmsg = NULL;
-                switch_core_db_exec(
-									db,
-                             reactive_sql,
-                             NULL,
-                             NULL,
-                             &errmsg
-                             );
-                if (errmsg) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "SQL ERR [%s]\n[%s]\n", errmsg, reactive_sql);
-                    switch_core_db_free(errmsg);
-                    errmsg = NULL;
-                }
-            }
-        }
-    }
-
-}
-
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_set_console(char *console)
-{
-	if ((runtime.console = fopen(console, "a")) == 0) {
-		fprintf(stderr, "Cannot open output file %s.\n", console);
-		return SWITCH_STATUS_FALSE;
-	}
-	
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(FILE *) switch_core_get_console(void)
-{
-	return runtime.console;
-}
-
-SWITCH_DECLARE(FILE *) switch_core_data_channel(switch_text_channel_t channel)
-{
-	FILE *handle = stdout;
-
-	switch (channel) {
-	case SWITCH_CHANNEL_ID_LOG:
-	case SWITCH_CHANNEL_ID_LOG_CLEAN:
-		handle = runtime.console;
-		break;
-	default:
-		handle = runtime.console;
-		break;
-	}
-
-	return handle;
-}
-
-SWITCH_DECLARE(int) switch_core_add_state_handler(const switch_state_handler_table_t *state_handler)
-{
-	int index = runtime.state_handler_index++;
-
-	if (runtime.state_handler_index >= SWITCH_MAX_STATE_HANDLERS) {
-		return -1;
-	}
-
-	runtime.state_handlers[index] = state_handler;
-	return index;
-}
-
-SWITCH_DECLARE(const switch_state_handler_table_t *) switch_core_get_state_handler(int index)
-{
-
-	if (index > SWITCH_MAX_STATE_HANDLERS || index > runtime.state_handler_index) {
-		return NULL;
-	}
-
-	return runtime.state_handlers[index];
-}
-
-#ifdef SWITCH_DEBUG_RWLOCKS
-SWITCH_DECLARE(switch_status_t) switch_core_session_perform_read_lock(switch_core_session_t *session,
-                                                                      const char *file,
-                                                                      const char *func,
-                                                                      int line)
-#else
-SWITCH_DECLARE(switch_status_t) switch_core_session_read_lock(switch_core_session_t *session)
-#endif
-{
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-    if (session->rwlock) {
-        if (switch_test_flag(session, SSF_DESTROYED)) {
-            status = SWITCH_STATUS_FALSE;
-#ifdef SWITCH_DEBUG_RWLOCKS
-            switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_ERROR, "%s Read lock FAIL\n", 
-                              switch_channel_get_name(session->channel));
-#endif
-        } else {
-            status = (switch_status_t) switch_thread_rwlock_tryrdlock(session->rwlock);
-#ifdef SWITCH_DEBUG_RWLOCKS
-            switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_ERROR, "%s Read lock AQUIRED\n", 
-                              switch_channel_get_name(session->channel));
-#endif
-        }	
-    }
-
-	return status;
-}
-
-#ifdef SWITCH_DEBUG_RWLOCKS
-SWITCH_DECLARE(void) switch_core_session_perform_write_lock(switch_core_session_t *session,
-                                                            const char *file,
-                                                            const char *func,
-                                                            int line)
-{
-
-    switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_ERROR, "%s Write lock AQUIRED\n", 
-                      switch_channel_get_name(session->channel));
-#else
-SWITCH_DECLARE(void) switch_core_session_write_lock(switch_core_session_t *session)
-{
-#endif
-	switch_thread_rwlock_wrlock(session->rwlock);
-}
-
-#ifdef SWITCH_DEBUG_RWLOCKS
-SWITCH_DECLARE(void) switch_core_session_perform_rwunlock(switch_core_session_t *session,
-                                                  const char *file,
-                                                  const char *func,
-                                                  int line)
-{
-    switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_ERROR, "%s Read/Write lock CLEARED\n", 
-                      switch_channel_get_name(session->channel));
-#else
-SWITCH_DECLARE(void) switch_core_session_rwunlock(switch_core_session_t *session)
-{
-#endif
-	switch_thread_rwlock_unlock(session->rwlock);
-    
-}
-
-SWITCH_DECLARE(char *) switch_core_get_variable(char *varname)
-{
-	return (char *) switch_core_hash_find(runtime.global_vars, varname);
-}
-
-SWITCH_DECLARE(void) switch_core_set_variable(char *varname, char *value)
-{
-    switch_core_hash_insert(runtime.global_vars, switch_core_strdup(runtime.memory_pool, varname), switch_core_strdup(runtime.memory_pool, value));
-}
-
-
-#ifdef SWITCH_DEBUG_RWLOCKS
-SWITCH_DECLARE(switch_core_session_t *) switch_core_session_perform_locate(char *uuid_str,
-                                                                           const char *file,
-                                                                           const char *func,
-                                                                           int line)
-#else
-SWITCH_DECLARE(switch_core_session_t *) switch_core_session_locate(char *uuid_str)
-#endif
-{
-	switch_core_session_t *session = NULL;
-
-	if (uuid_str) {
-		switch_mutex_lock(runtime.session_table_mutex);
-		if ((session = switch_core_hash_find(runtime.session_table, uuid_str))) {
-			/* Acquire a read lock on the session */
-#ifdef SWITCH_DEBUG_RWLOCKS
-			if (switch_core_session_perform_read_lock(session, file, func, line) != SWITCH_STATUS_SUCCESS) {
-#else
-            if (switch_core_session_read_lock(session) != SWITCH_STATUS_SUCCESS) {
-#endif
-				/* not available, forget it */
-				session = NULL;
-			}
-		}
-		switch_mutex_unlock(runtime.session_table_mutex);
-	}
+	uint32_t no_new_sessions;
+	uint32_t shutting_down;
+} runtime;
 
-    /* if its not NULL, now it's up to you to rwunlock this */
-    return session;
-}
 
-SWITCH_DECLARE(void) switch_core_session_hupall(switch_call_cause_t cause)
+static void send_heartbeat(void)
 {
-	switch_hash_index_t *hi;
-	void *val;
-	switch_core_session_t *session;
-	switch_channel_t *channel;
-    uint32_t loops = 0;
-
-	switch_mutex_lock(runtime.session_table_mutex);
-	for (hi = switch_hash_first(runtime.memory_pool, runtime.session_table); hi; hi = switch_hash_next(hi)) {
-        switch_hash_this(hi, NULL, NULL, &val);
-		if (val) {
-			session = (switch_core_session_t *) val;
-			channel = switch_core_session_get_channel(session);
-			switch_channel_hangup(channel, cause);
-			switch_core_session_kill_channel(session, SWITCH_SIG_KILL);
-		}
-	}
-	switch_mutex_unlock(runtime.session_table_mutex);
-
-	while(runtime.session_count > 0) {
-		switch_yield(100000);
-        if (++loops == 100) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Giving up with %d session%s remaining\n", 
-                              runtime.session_count, runtime.session_count == 1 ? "" : "s");
-            break;
-        }
-	}
-}
+	switch_event_t *event;
+	switch_core_time_duration_t duration;
 
-SWITCH_DECLARE(switch_status_t) switch_core_session_message_send(char *uuid_str, switch_core_session_message_t *message)
-{
-	switch_core_session_t *session = NULL;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	switch_mutex_lock(runtime.session_table_mutex);
-	if ((session = switch_core_hash_find(runtime.session_table, uuid_str)) != 0) {
-		/* Acquire a read lock on the session or forget it the channel is dead */
-		if (switch_core_session_read_lock(session) == SWITCH_STATUS_SUCCESS) {
-			if (switch_channel_get_state(session->channel) < CS_HANGUP) {
-				status = switch_core_session_receive_message(session, message);
-			}
-            switch_core_session_rwunlock(session);
-		}
-	}
-	switch_mutex_unlock(runtime.session_table_mutex);
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_event_send(char *uuid_str, switch_event_t **event)
-{
-	switch_core_session_t *session = NULL;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	switch_mutex_lock(runtime.session_table_mutex);
-	if ((session = switch_core_hash_find(runtime.session_table, uuid_str)) != 0) {
-		/* Acquire a read lock on the session or forget it the channel is dead */
-		if (switch_core_session_read_lock(session) == SWITCH_STATUS_SUCCESS) {
-			if (switch_channel_get_state(session->channel) < CS_HANGUP) {
-				status = switch_core_session_queue_event(session, event);
-			}
-            switch_core_session_rwunlock(session);
-		}
-	}
-	switch_mutex_unlock(runtime.session_table_mutex);
-
-	return status;
-}
-
-SWITCH_DECLARE(char *) switch_core_get_uuid(void)
-{
-	return runtime.uuid_str;
-}
-
-SWITCH_DECLARE(char *) switch_core_session_get_uuid(switch_core_session_t *session)
-{
-	return session->uuid_str;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_set_read_codec(switch_core_session_t *session, switch_codec_t *codec)
-{
-	switch_event_t *event;
-
-	assert(session != NULL);
-
-	if (switch_event_create(&event, SWITCH_EVENT_CODEC) == SWITCH_STATUS_SUCCESS) {
-		switch_channel_event_set_data(session->channel, event);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "channel-read-codec-name", "%s", codec->implementation->iananame);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "channel-read-codec-rate", "%d", codec->implementation->samples_per_second);
-		switch_event_fire(&event);
-	}
-				
-	session->read_codec = codec;
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_codec_t *) switch_core_session_get_read_codec(switch_core_session_t *session)
-{
-	return session->read_codec;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_set_write_codec(switch_core_session_t *session, switch_codec_t *codec)
-{
-	switch_event_t *event;
-	assert(session != NULL);
-
-	if (switch_event_create(&event, SWITCH_EVENT_CODEC) == SWITCH_STATUS_SUCCESS) {
-		switch_channel_event_set_data(session->channel, event);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "channel-write-codec-name", "%s", codec->implementation->iananame);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "channel-write-codec-rate", "%d", codec->implementation->samples_per_second);
-		switch_event_fire(&event);
-	}
-
-	session->write_codec = codec;
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_codec_t *) switch_core_session_get_write_codec(switch_core_session_t *session)
-{
-	return session->write_codec;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_codec_init(switch_codec_t *codec, char *codec_name, char *fmtp, uint32_t rate, int ms,
-													 int channels, uint32_t flags,
-													 const switch_codec_settings_t *codec_settings,
-													 switch_memory_pool_t *pool)
-{
-	const switch_codec_interface_t *codec_interface;
-	const switch_codec_implementation_t *iptr, *implementation = NULL;
-	char *mode = fmtp; 
-
-	assert(codec != NULL);
-	assert(codec_name != NULL);
-
-	memset(codec, 0, sizeof(*codec));
-
-	if ((codec_interface = switch_loadable_module_get_codec_interface(codec_name)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "invalid codec %s!\n", codec_name);
-		return SWITCH_STATUS_GENERR;
-	}
-
-	if (!strcasecmp(codec_name, "ilbc") && mode && strncasecmp(mode, "mode=", 5)) {
-		int mms;
-		mode += 5;
-		if (mode) {
-			mms = atoi(mode);
-			if (mms > 0 && mms < 120) {
-				ms = mms;
-			}
-		}
-	}
-	
-    /* If no specific codec interval is requested opt for 20ms above all else because lots of stuff assumes it */
-    if (!ms) {
-        for (iptr = codec_interface->implementations; iptr; iptr = iptr->next) {
-            if ((!rate || rate == iptr->samples_per_second) &&
-                (20 == (iptr->microseconds_per_frame / 1000)) &&
-                (!channels || channels == iptr->number_of_channels)) {
-                implementation = iptr;
-                goto found;
-            }
-        }
-    }
-
-    /* Either looking for a specific interval or there was no interval specified and there wasn't one @20ms available*/
-	for (iptr = codec_interface->implementations; iptr; iptr = iptr->next) {
-		if ((!rate || rate == iptr->samples_per_second) &&
-			(!ms || ms == (iptr->microseconds_per_frame / 1000)) &&
-			(!channels || channels == iptr->number_of_channels)) {
-			implementation = iptr;
-			break;
-		}
-	}
-
- found:
-
-	if (implementation) {
-		switch_status_t status;
-		codec->codec_interface = codec_interface;
-		codec->implementation = implementation;
-		codec->flags = flags;
-		
-		if (pool) {
-			codec->memory_pool = pool;
-		} else {
-			if ((status = switch_core_new_memory_pool(&codec->memory_pool)) != SWITCH_STATUS_SUCCESS) {
-				return status;
-			}
-			switch_set_flag(codec, SWITCH_CODEC_FLAG_FREE_POOL);
-		}
-
-		if (fmtp) {
-			codec->fmtp_in = switch_core_strdup(codec->memory_pool, fmtp);
-		}
-
-		implementation->init(codec, flags, codec_settings);
-
-		return SWITCH_STATUS_SUCCESS;
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Codec %s Exists but not at the desired implementation. %dhz %dms\n",
-						  codec_name,
-						  rate,
-						  ms);
-	}
-
-	return SWITCH_STATUS_NOTIMPL;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_codec_encode(switch_codec_t *codec,
-													   switch_codec_t *other_codec,
-													   void *decoded_data,
-													   uint32_t decoded_data_len,
-													   uint32_t decoded_rate,
-													   void *encoded_data,
-													   uint32_t *encoded_data_len, uint32_t *encoded_rate, unsigned int *flag)
-{
-	assert(codec != NULL);
-	assert(encoded_data != NULL);
-	assert(decoded_data != NULL);
-
-	if (!codec->implementation) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec is not initilized!\n");
-		return SWITCH_STATUS_GENERR;
-	}
-
-	if (!switch_test_flag(codec, SWITCH_CODEC_FLAG_ENCODE)) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec's encoder is not initilized!\n");
-		return SWITCH_STATUS_GENERR;
-	}
-
-
-	return codec->implementation->encode(codec,
-										 other_codec,
-										 decoded_data,
-										 decoded_data_len,
-										 decoded_rate, encoded_data, encoded_data_len, encoded_rate, flag);
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_codec_decode(switch_codec_t *codec,
-													   switch_codec_t *other_codec,
-													   void *encoded_data,
-													   uint32_t encoded_data_len,
-													   uint32_t encoded_rate,
-													   void *decoded_data,
-													   uint32_t *decoded_data_len, 
-													   uint32_t *decoded_rate, 
-													   unsigned int *flag)
-{
-
-	assert(codec != NULL);
-	assert(encoded_data != NULL);
-	assert(decoded_data != NULL);
-
-
-
-	if (!codec->implementation) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec is not initilized!\n");
-		return SWITCH_STATUS_GENERR;
-	}
-
-	if (!switch_test_flag(codec, SWITCH_CODEC_FLAG_DECODE)) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec's decoder is not initilized!\n");
-		return SWITCH_STATUS_GENERR;
-	}
-
-
-	return codec->implementation->decode(codec,
-										 other_codec,
-										 encoded_data,
-										 encoded_data_len,
-										 encoded_rate, decoded_data, decoded_data_len, decoded_rate, flag);
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_codec_destroy(switch_codec_t *codec)
-{
-	assert(codec != NULL);
-
-	if (!codec->implementation) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec is not initilized!\n");
-		return SWITCH_STATUS_GENERR;
-	}
-
-	codec->implementation->destroy(codec);
-
-	if (switch_test_flag(codec, SWITCH_CODEC_FLAG_FREE_POOL)) {
-		switch_core_destroy_memory_pool(&codec->memory_pool);
-	}
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_file_open(switch_file_handle_t *fh, char *file_path, unsigned int flags,
-													switch_memory_pool_t *pool)
-{
-	char *ext;
-	switch_status_t status;
-
-	if ((ext = strrchr(file_path, '.')) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Format\n");
-		return SWITCH_STATUS_FALSE;
-	}
-	ext++;
-
-	if ((fh->file_interface = switch_loadable_module_get_file_interface(ext)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "invalid file format [%s]!\n", ext);
-		return SWITCH_STATUS_GENERR;
-	}
-
-	fh->flags = flags;
-	if (pool) {
-		fh->memory_pool = pool;
-	} else {
-		if ((status = switch_core_new_memory_pool(&fh->memory_pool)) != SWITCH_STATUS_SUCCESS) {
-			return status;
-		}
-		switch_set_flag(fh, SWITCH_FILE_FLAG_FREE_POOL);
-	}
-
-	return fh->file_interface->file_open(fh, file_path);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_file_read(switch_file_handle_t *fh, void *data, switch_size_t *len)
-{
-	assert(fh != NULL);
-
-	return fh->file_interface->file_read(fh, data, len);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_file_write(switch_file_handle_t *fh, void *data, switch_size_t *len)
-{
-	assert(fh != NULL);
-
-	return fh->file_interface->file_write(fh, data, len);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_file_seek(switch_file_handle_t *fh, unsigned int *cur_pos, int64_t samples,
-													int whence)
-{
-	assert(fh != NULL);
-	return fh->file_interface->file_seek(fh, cur_pos, samples, whence);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_file_set_string(switch_file_handle_t *fh, switch_audio_col_t col, const char *string)
-{
-	assert(fh != NULL);
-
-	return fh->file_interface->file_set_string(fh, col, string);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_file_get_string(switch_file_handle_t *fh, switch_audio_col_t col, const char **string)
-{
-	assert(fh != NULL);
-	
-	return fh->file_interface->file_get_string(fh, col, string);
-
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_file_close(switch_file_handle_t *fh)
-{
-	return fh->file_interface->file_close(fh);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_directory_open(switch_directory_handle_t *dh, 
-														 char *module_name, 
-														 char *source,
-														 char *dsn,
-														 char *passwd,
-														 switch_memory_pool_t *pool)
-{
-	switch_status_t status;
-
-	if ((dh->directory_interface = switch_loadable_module_get_directory_interface(module_name)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "invalid directory module [%s]!\n", module_name);
-		return SWITCH_STATUS_GENERR;
-	}
-
-	if (pool) {
-		dh->memory_pool = pool;
-	} else {
-		if ((status = switch_core_new_memory_pool(&dh->memory_pool)) != SWITCH_STATUS_SUCCESS) {
-			return status;
-		}
-		switch_set_flag(dh, SWITCH_DIRECTORY_FLAG_FREE_POOL);
-	}
-
-	return dh->directory_interface->directory_open(dh, source, dsn, passwd);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_directory_query(switch_directory_handle_t *dh, char *base, char *query)
-{
-	return dh->directory_interface->directory_query(dh, base, query);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_directory_next(switch_directory_handle_t *dh)
-{
-	return dh->directory_interface->directory_next(dh);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_directory_next_pair(switch_directory_handle_t *dh, char **var, char **val)
-{
-	return dh->directory_interface->directory_next_pair(dh, var, val);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_directory_close(switch_directory_handle_t *dh)
-{
-	return dh->directory_interface->directory_close(dh);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_speech_open(switch_speech_handle_t *sh, 
-														char *module_name, 
-														char *voice_name,
-														unsigned int rate,
-														switch_speech_flag_t *flags,
-														switch_memory_pool_t *pool)
-{
-	switch_status_t status;
-
-	if ((sh->speech_interface = switch_loadable_module_get_speech_interface(module_name)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "invalid speech module [%s]!\n", module_name);
-		return SWITCH_STATUS_GENERR;
-	}
-
-	switch_copy_string(sh->engine, module_name, sizeof(sh->engine));
-	sh->flags = *flags;
-	if (pool) {
-		sh->memory_pool = pool;
-	} else {
-		if ((status = switch_core_new_memory_pool(&sh->memory_pool)) != SWITCH_STATUS_SUCCESS) {
-			return status;
-		}
-		switch_set_flag(sh, SWITCH_SPEECH_FLAG_FREE_POOL);
-	}
-	sh->rate = rate;
-	sh->name = switch_core_strdup(pool, module_name);
-	return sh->speech_interface->speech_open(sh, voice_name, rate, flags);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_asr_open(switch_asr_handle_t *ah,
-													 char *module_name,
-													 char *codec,
-													 int rate,
-													 char *dest,
-													 switch_asr_flag_t *flags,
-													 switch_memory_pool_t *pool)
-{
-	switch_status_t status;
-
-	assert(ah != NULL);
-
-	if ((ah->asr_interface = switch_loadable_module_get_asr_interface(module_name)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "invalid asr module [%s]!\n", module_name);
-		return SWITCH_STATUS_GENERR;
-	}
-	
-	ah->flags = *flags;
-
-	if (pool) {
-		ah->memory_pool = pool;
-	} else {
-		if ((status = switch_core_new_memory_pool(&ah->memory_pool)) != SWITCH_STATUS_SUCCESS) {
-			return status;
-		}
-		switch_set_flag(ah, SWITCH_ASR_FLAG_FREE_POOL);
-	}
-
-	ah->rate = rate;
-	ah->name = switch_core_strdup(ah->memory_pool, module_name);
-
-	return ah->asr_interface->asr_open(ah, codec, rate, dest, flags);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_asr_load_grammar(switch_asr_handle_t *ah, char *grammar, char *path)
-{
-	char *epath = NULL;
-	switch_status_t status;
-
-	assert(ah != NULL);
-
-	if (*path != '/') {
-		epath = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.grammar_dir, SWITCH_PATH_SEPARATOR, path);
-		path = epath;
-	}
-
-	status = ah->asr_interface->asr_load_grammar(ah, grammar, path);
-	switch_safe_free(epath);
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_asr_unload_grammar(switch_asr_handle_t *ah, char *grammar)
-{
-	switch_status_t status;
-
-	assert(ah != NULL);
-	status = ah->asr_interface->asr_unload_grammar(ah, grammar);
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_asr_pause(switch_asr_handle_t *ah)
-{
-	assert(ah != NULL);
-
-	return ah->asr_interface->asr_pause(ah);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_asr_resume(switch_asr_handle_t *ah)
-{
-	assert(ah != NULL);
-
-	return ah->asr_interface->asr_resume(ah);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_asr_close(switch_asr_handle_t *ah, switch_asr_flag_t *flags)
-{
-	assert(ah != NULL);
-
-	return ah->asr_interface->asr_close(ah, flags);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_asr_feed(switch_asr_handle_t *ah, void *data, unsigned int len, switch_asr_flag_t *flags)
-{
-	assert(ah != NULL);
-	
-	return ah->asr_interface->asr_feed(ah, data, len, flags);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_asr_check_results(switch_asr_handle_t *ah, switch_asr_flag_t *flags)
-{
-	assert(ah != NULL);
-	
-	return ah->asr_interface->asr_check_results(ah, flags);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_asr_get_results(switch_asr_handle_t *ah, char **xmlstr, switch_asr_flag_t *flags)
-{
-	assert(ah != NULL);
-	
-	return ah->asr_interface->asr_get_results(ah, xmlstr, flags);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_speech_feed_tts(switch_speech_handle_t *sh, char *text, switch_speech_flag_t *flags)
-{
-	assert(sh != NULL);
-
-	return sh->speech_interface->speech_feed_tts(sh, text, flags);
-}
-
-SWITCH_DECLARE(void) switch_core_speech_flush_tts(switch_speech_handle_t *sh)
-{
-	assert(sh != NULL);
-
-	if (sh->speech_interface->speech_flush_tts) {
-		sh->speech_interface->speech_flush_tts(sh);
-	}
-}
-
-SWITCH_DECLARE(void) switch_core_speech_text_param_tts(switch_speech_handle_t *sh, char *param, char *val)
-{
-	assert(sh != NULL);
-
-	if (sh->speech_interface->speech_text_param_tts) {
-		sh->speech_interface->speech_text_param_tts(sh, param, val);
-	}
-}
-
-SWITCH_DECLARE(void) switch_core_speech_numeric_param_tts(switch_speech_handle_t *sh, char *param, int val)
-{
-	assert(sh != NULL);
-
-	if (sh->speech_interface->speech_numeric_param_tts) {
-		sh->speech_interface->speech_numeric_param_tts(sh, param, val);
-	}
-}
-
-SWITCH_DECLARE(void) switch_core_speech_float_param_tts(switch_speech_handle_t *sh, char *param, double val)
-{
-	assert(sh != NULL);
-
-	if (sh->speech_interface->speech_float_param_tts) {
-		sh->speech_interface->speech_float_param_tts(sh, param, val);
-	}
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_speech_read_tts(switch_speech_handle_t *sh, 
-														  void *data,
-														  switch_size_t *datalen,
-														  uint32_t *rate,
-														  switch_speech_flag_t *flags)
-{
-	assert(sh != NULL);
-
-	return sh->speech_interface->speech_read_tts(sh, data, datalen, rate, flags);
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_speech_close(switch_speech_handle_t *sh, switch_speech_flag_t *flags)
-{
-	return sh->speech_interface->speech_close(sh, flags);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_timer_init(switch_timer_t *timer, char *timer_name, int interval, int samples,
-													 switch_memory_pool_t *pool)
-{
-	switch_timer_interface_t *timer_interface;
-	switch_status_t status;
-	memset(timer, 0, sizeof(*timer));
-	if ((timer_interface = switch_loadable_module_get_timer_interface(timer_name)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "invalid timer %s!\n", timer_name);
-		return SWITCH_STATUS_GENERR;
-	}
-
-	timer->interval = interval;
-	timer->samples = samples;
-	timer->samplecount = 0;
-	timer->timer_interface = timer_interface;
-
-	if (pool) {
-		timer->memory_pool = pool;
-	} else {
-		if ((status = switch_core_new_memory_pool(&timer->memory_pool)) != SWITCH_STATUS_SUCCESS) {
-			return status;
-		}
-		switch_set_flag(timer, SWITCH_TIMER_FLAG_FREE_POOL);
-	}
-
-	timer->timer_interface->timer_init(timer);
-	return SWITCH_STATUS_SUCCESS;
-
-}
-
-SWITCH_DECLARE(int) switch_core_timer_next(switch_timer_t *timer)
-{
-	if (!timer->timer_interface) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Timer is not initilized!\n");
-		return SWITCH_STATUS_GENERR;
-	}
-
-	if (timer->timer_interface->timer_next(timer) == SWITCH_STATUS_SUCCESS) {
-		return timer->samplecount;
-	} else {
-		return -1;
-	}
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_timer_step(switch_timer_t *timer)
-{
-	if (!timer->timer_interface) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Timer is not initilized!\n");
-		return SWITCH_STATUS_GENERR;
-	}
-
-	return timer->timer_interface->timer_step(timer);
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_timer_check(switch_timer_t *timer)
-{
-	if (!timer->timer_interface) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Timer is not initilized!\n");
-		return SWITCH_STATUS_GENERR;
-	}
-
-	return timer->timer_interface->timer_check(timer);
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_timer_destroy(switch_timer_t *timer)
-{
-	if (!timer->timer_interface) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Timer is not initilized!\n");
-		return SWITCH_STATUS_GENERR;
-	}
-
-	timer->timer_interface->timer_destroy(timer);
-
-	if (switch_test_flag(timer, SWITCH_TIMER_FLAG_FREE_POOL)) {
-		switch_core_destroy_memory_pool(&timer->memory_pool);
-	}
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static void *switch_core_service_thread(switch_thread_t *thread, void *obj)
-{
-	switch_core_thread_session_t *data = obj;
-	switch_core_session_t *session = data->objs[0];
-	int *stream_id_p = data->objs[1];
-	switch_channel_t *channel;
-	switch_frame_t *read_frame;
-	int stream_id = *stream_id_p;
-
-	assert(thread != NULL);
-	assert(session != NULL);
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	switch_channel_set_flag(channel, CF_SERVICE);
-	while (data->running > 0) {
-		switch (switch_core_session_read_frame(session, &read_frame, -1, stream_id)) {
-		case SWITCH_STATUS_SUCCESS:
-		case SWITCH_STATUS_TIMEOUT:
-		case SWITCH_STATUS_BREAK:
-			break;
-		default:
-			data->running = -1;
-			continue;
-		}
-	}
-
-	switch_channel_clear_flag(channel, CF_SERVICE);
-	data->running = 0;
-	return NULL;
-}
-
-/* Either add a timeout here or make damn sure the thread cannot get hung somehow (my preference) */
-SWITCH_DECLARE(void) switch_core_thread_session_end(switch_core_thread_session_t *thread_session)
-{
-	if (thread_session->running > 0) {
-		thread_session->running = -1;
-
-		while (thread_session->running) {
-			switch_yield(1000);
-		}
-	}
-}
-
-SWITCH_DECLARE(void) switch_core_service_session(switch_core_session_t *session,
-												 switch_core_thread_session_t *thread_session, int stream_id)
-{
-	thread_session->running = 1;
-	thread_session->objs[0] = session;
-	thread_session->objs[1] = &stream_id;
-	switch_core_session_launch_thread(session, switch_core_service_thread, thread_session);
-}
-
-SWITCH_DECLARE(switch_memory_pool_t *) switch_core_session_get_pool(switch_core_session_t *session)
-{
-	return session->pool;
-}
-
-/* **ONLY** alloc things with this function that **WILL NOT** outlive
-   the session itself or expect an earth shattering KABOOM!*/
-SWITCH_DECLARE(void *) switch_core_session_alloc(switch_core_session_t *session, switch_size_t memory)
-{
-	void *ptr = NULL;
-	assert(session != NULL);
-	assert(session->pool != NULL);
-
-#ifdef DEBUG_ALLOC
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Allocate %d\n", memory);
-#endif
-
-
-	if ((ptr = apr_palloc(session->pool, memory)) != 0) {
-		memset(ptr, 0, memory);
-	}
-	return ptr;
-}
-
-/* **ONLY** alloc things with these functions that **WILL NOT** need
-   to be freed *EVER* ie this is for *PERMANENT* memory allocation */
-
-SWITCH_DECLARE(void *) switch_core_permanent_alloc(switch_size_t memory)
-{
-	void *ptr = NULL;
-	assert(runtime.memory_pool != NULL);
-
-#ifdef DEBUG_ALLOC
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Perm Allocate %d\n", memory);
-#endif
-
-	if ((ptr = apr_palloc(runtime.memory_pool, memory)) != 0) {
-		memset(ptr, 0, memory);
-	}
-	return ptr;
-}
-
-SWITCH_DECLARE(char *) switch_core_permanent_strdup(const char *todup)
-{
-	char *duped = NULL;
-	switch_size_t len;
-
-	assert(runtime.memory_pool != NULL);
-
-	if (!todup)
-		return NULL;
-
-	len = strlen(todup) + 1;
-
-#ifdef DEBUG_ALLOC
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Perm Allocate %d\n", len);
-#endif
-
-	if (todup && (duped = apr_palloc(runtime.memory_pool, len)) != 0) {
-		strncpy(duped, todup, len);
-	}
-	return duped;
-}
-
-SWITCH_DECLARE(char *) switch_core_session_sprintf(switch_core_session_t *session, const char *fmt, ...)
-{
-	va_list ap;
-	char *result = NULL;
-
-	assert(session != NULL);
-	assert(session->pool != NULL);
-	va_start(ap, fmt);
-	
-	result = apr_pvsprintf(session->pool ,fmt, ap);
-
-	va_end(ap);
-
-	return result;
-}
-
-SWITCH_DECLARE(char *) switch_core_sprintf(switch_memory_pool_t *pool, const char *fmt, ...)
-{
-	va_list ap;
-	char *result = NULL;
-
-	assert(pool != NULL);
-	va_start(ap, fmt);
-	
-	result = apr_pvsprintf(pool ,fmt, ap);
-
-	va_end(ap);
-
-	return result;
-}
-
-
-SWITCH_DECLARE(char *) switch_core_session_strdup(switch_core_session_t *session, const char *todup)
-{
-	char *duped = NULL;
-	switch_size_t len;
-	assert(session != NULL);
-	assert(session->pool != NULL);
-
-	if (!todup) {
-		return NULL;
-	}
-	len = strlen(todup) + 1;
-
-#ifdef DEBUG_ALLOC
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Allocate %d\n", len);
-#endif
-
-	if (todup && (duped = apr_palloc(session->pool, len)) != 0) {
-		strncpy(duped, todup, len);
-	}
-	return duped;
-}
-
-
-SWITCH_DECLARE(char *) switch_core_strdup(switch_memory_pool_t *pool, const char *todup)
-{
-	char *duped = NULL;
-	switch_size_t len;
-	assert(pool != NULL);
-
-	if (!todup) {
-		return NULL;
-	}
-	
-	len = strlen(todup) + 1;
-
-#ifdef DEBUG_ALLOC
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Allocate %d\n", len);
-#endif
-
-	if (todup && (duped = apr_palloc(pool, len)) != 0) {
-		strncpy(duped, todup, len);
-	}
-	return duped;
-}
-
-SWITCH_DECLARE(void *) switch_core_session_get_private(switch_core_session_t *session)
-{
-	assert(session != NULL);
-	return session->private_info;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_set_private(switch_core_session_t *session, void *private_info)
-{
-	assert(session != NULL);
-	session->private_info = private_info;
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(int) switch_core_session_add_stream(switch_core_session_t *session, void *private_info)
-{
-	session->streams[session->stream_count++] = private_info;
-	return session->stream_count - 1;
-}
-
-SWITCH_DECLARE(void *) switch_core_session_get_stream(switch_core_session_t *session, int index)
-{
-	return session->streams[index];
-}
-
-
-SWITCH_DECLARE(int) switch_core_session_get_stream_count(switch_core_session_t *session)
-{
-	return session->stream_count;
-}
-
-SWITCH_DECLARE(switch_call_cause_t) switch_core_session_outgoing_channel(switch_core_session_t *session,
-																		 char *endpoint_name,
-																		 switch_caller_profile_t *caller_profile,
-																		 switch_core_session_t **new_session,
-																		 switch_memory_pool_t *pool)
-{
-	switch_io_event_hook_outgoing_channel_t *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-	const switch_endpoint_interface_t *endpoint_interface;
-	switch_channel_t *channel = NULL;
-	switch_caller_profile_t *outgoing_profile = caller_profile;
-	switch_call_cause_t cause = SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL;
-
-	if ((endpoint_interface = switch_loadable_module_get_endpoint_interface(endpoint_name)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not locate channel type %s\n", endpoint_name);
-		return SWITCH_CAUSE_CHAN_NOT_IMPLEMENTED;
-	}
-
-	if (endpoint_interface->io_routines->outgoing_channel) {
-		if (session) {
-			channel = switch_core_session_get_channel(session);
-			if (caller_profile) {			
-				char *ecaller_id_name = NULL, *ecaller_id_number = NULL;
-
-				ecaller_id_name = switch_channel_get_variable(channel, "effective_caller_id_name");
-				ecaller_id_number = switch_channel_get_variable(channel, "effective_caller_id_number");
-
-				if (ecaller_id_name || ecaller_id_number) {
-                    if (!ecaller_id_name) {
-                        ecaller_id_name = caller_profile->caller_id_name;
-                    }
-                    if (!ecaller_id_number) {
-                        ecaller_id_number = caller_profile->caller_id_number;
-                    }
-					outgoing_profile = switch_caller_profile_new(switch_core_session_get_pool(session),
-																 caller_profile->username,
-																 caller_profile->dialplan,
-																 ecaller_id_name,
-																 ecaller_id_number,
-																 caller_profile->network_addr,
-																 caller_profile->ani,
-																 caller_profile->aniii, 
-																 caller_profile->rdnis,
-																 caller_profile->source,
-																 caller_profile->context,
-																 caller_profile->destination_number);
-					outgoing_profile->flags = caller_profile->flags;
-				} 
-			}
-			if (!outgoing_profile) {
-				outgoing_profile = switch_channel_get_caller_profile(channel);
-			}
-		}
-		
-		if ((cause = endpoint_interface->io_routines->outgoing_channel(session,
-																	   outgoing_profile,
-																	   new_session,
-																	   pool)) == SWITCH_CAUSE_SUCCESS) {
-			if (session) {
-				for (ptr = session->event_hooks.outgoing_channel; ptr; ptr = ptr->next) {
-					if ((status = ptr->outgoing_channel(session, caller_profile, *new_session)) != SWITCH_STATUS_SUCCESS) {
-						break;
-					}
-				}
-			}
-		} else {
-			return cause;
-		}
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not locate outgoing channel interface for %s\n", endpoint_name);
-		return SWITCH_CAUSE_CHAN_NOT_IMPLEMENTED;
-	}
-
-	if (*new_session) {
-		switch_caller_profile_t *profile = NULL, *peer_profile = NULL, *cloned_profile = NULL;
-		switch_event_t *event;
-		switch_channel_t *peer_channel = switch_core_session_get_channel(*new_session);
-
-		
-		if (session && channel) {
-			profile = switch_channel_get_caller_profile(channel);
-		}
-		if (peer_channel) {
-			peer_profile = switch_channel_get_caller_profile(peer_channel);
-		}
-
-		if (channel && peer_channel) {
-			char *export_vars, *val;
-            switch_codec_t *read_codec = switch_core_session_get_read_codec(session);
-
-            if (read_codec) {
-                char tmp[80];
-                switch_codec2str(read_codec, tmp, sizeof(tmp));
-                switch_channel_set_variable(peer_channel, SWITCH_ORIGINATOR_CODEC_VARIABLE, tmp);
-            }
-
-			switch_channel_set_variable(peer_channel, SWITCH_ORIGINATOR_VARIABLE, switch_core_session_get_uuid(session));            
-
-            /* A comma (,) separated list of variable names that should ne propagated from originator to originatee */
-			if ((export_vars = switch_channel_get_variable(channel, SWITCH_EXPORT_VARS_VARIABLE))) {
-				char *cptmp = switch_core_session_strdup(session, export_vars);
-				int argc;
-				char *argv[256];
-
-				if ((argc = switch_separate_string(cptmp, ',', argv, (sizeof(argv) / sizeof(argv[0]))))) {
-					int x;
-
-					for (x = 0; x < argc; x++) {
-						char *val;
-						if ((val = switch_channel_get_variable(channel, argv[x]))) {
-							switch_channel_set_variable(peer_channel, argv[x], val);
-						}
-					}
-				}
-			}
-
-			if ((val = switch_channel_get_variable(channel, SWITCH_R_SDP_VARIABLE))) {
-				switch_channel_set_variable(peer_channel, SWITCH_B_SDP_VARIABLE, val);
-			}
-
-			if ((val = switch_channel_get_variable(channel, SWITCH_MAX_FORWARDS_VARIABLE))) {
-				switch_channel_set_variable(peer_channel, SWITCH_MAX_FORWARDS_VARIABLE, val);
-			}
-			
-			if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
-				switch_channel_set_flag(peer_channel, CF_NOMEDIA);
-			}
-
-			if (profile) {
-				if ((cloned_profile = switch_caller_profile_clone(*new_session, profile)) != 0) {
-					switch_channel_set_originator_caller_profile(peer_channel, cloned_profile);
-				}
-			}
-
-			if (peer_profile) {
-				if (session && (cloned_profile = switch_caller_profile_clone(session, peer_profile)) != 0) {
-					switch_channel_set_originatee_caller_profile(channel, cloned_profile);
-				}
-			}
-		}
-
-		if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_OUTGOING) == SWITCH_STATUS_SUCCESS) {
-			switch_channel_event_set_data(peer_channel, event);
-			switch_event_fire(&event);
-		}
-	}
-
-	return cause;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_answer_channel(switch_core_session_t *session)
-{
-	switch_io_event_hook_answer_channel_t *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	assert(session != NULL);
-	if (session->endpoint_interface->io_routines->answer_channel) {
-		if ((status = session->endpoint_interface->io_routines->answer_channel(session)) == SWITCH_STATUS_SUCCESS) {
-			for (ptr = session->event_hooks.answer_channel; ptr; ptr = ptr->next) {
-				if ((status = ptr->answer_channel(session)) != SWITCH_STATUS_SUCCESS) {
-					break;
-				}
-			}
-		}
-	} else {
-		status = SWITCH_STATUS_SUCCESS;
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_receive_message(switch_core_session_t *session, switch_core_session_message_t *message)
-{
-	switch_io_event_hook_receive_message_t *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	assert(session != NULL);
-	if (session->endpoint_interface->io_routines->receive_message) {
-		if ((status =
-			 session->endpoint_interface->io_routines->receive_message(session, message)) == SWITCH_STATUS_SUCCESS) {
-			for (ptr = session->event_hooks.receive_message; ptr; ptr = ptr->next) {
-				if ((status = ptr->receive_message(session, message)) != SWITCH_STATUS_SUCCESS) {
-					break;
-				}
-			}
-		}
-	}
-	switch_core_session_kill_channel(session, SWITCH_SIG_BREAK);
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_queue_indication(switch_core_session_t *session, switch_core_session_message_types_t indication)
-{
-	switch_core_session_message_t *msg;
-
-	if ((msg = malloc(sizeof(*msg)))) {
-		memset(msg, 0, sizeof(*msg));
-		msg->message_id = indication;
-		msg->from = __FILE__;
-		switch_core_session_queue_message(session, msg);
-		switch_set_flag(msg, SCSMF_DYNAMIC);
-		return SWITCH_STATUS_SUCCESS;
-	}
-	
-	return SWITCH_STATUS_FALSE;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_queue_message(switch_core_session_t *session, switch_core_session_message_t *message)
-{
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	assert(session != NULL);
-
-	if (!session->message_queue) {
-		switch_queue_create(&session->message_queue, SWITCH_MESSAGE_QUEUE_LEN, session->pool);
-	}
-
-	if (session->message_queue) {
-		if (switch_queue_trypush(session->message_queue, message) == SWITCH_STATUS_SUCCESS) {
-			status = SWITCH_STATUS_SUCCESS;
-		}
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_dequeue_message(switch_core_session_t *session, switch_core_session_message_t **message)
-{
-	switch_status_t status = SWITCH_STATUS_FALSE;
-	void *pop;
-
-	assert(session != NULL);
-	
-	if (session->message_queue) {
-		if ((status = (switch_status_t) switch_queue_trypop(session->message_queue, &pop)) == SWITCH_STATUS_SUCCESS) {
-			*message = (switch_core_session_message_t *) pop;
-		}
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_flush_message(switch_core_session_t *session)
-{
-    switch_core_session_message_t *message;
-
-    if (switch_core_session_dequeue_message(session, &message) == SWITCH_STATUS_SUCCESS) {
-        if (switch_test_flag(message, SCSMF_DYNAMIC)) {
-            switch_safe_free(message);
-        } else {
-            message = NULL;
-        }
-    }
-    
-    return SWITCH_STATUS_SUCCESS;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_receive_event(switch_core_session_t *session, switch_event_t **event)
-	 
-{
-	switch_io_event_hook_receive_event_t *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	assert(session != NULL);
-
-	/* Acquire a read lock on the session or forget it the channel is dead */
-	if (switch_core_session_read_lock(session) == SWITCH_STATUS_SUCCESS) {
-		if (switch_channel_get_state(session->channel) < CS_HANGUP) {
-			if (session->endpoint_interface->io_routines->receive_event) {
-				status = session->endpoint_interface->io_routines->receive_event(session, *event);
-			} 
-	
-			if (status == SWITCH_STATUS_SUCCESS) {
-				for (ptr = session->event_hooks.receive_event; ptr; ptr = ptr->next) {
-					if ((status = ptr->receive_event(session, *event)) != SWITCH_STATUS_SUCCESS) {
-						break;
-					}
-				}
-			}
-
-			if (status == SWITCH_STATUS_BREAK) {
-				status = SWITCH_STATUS_SUCCESS;
-			}
-
-			if (status == SWITCH_STATUS_SUCCESS) {
-				switch_event_destroy(event);
-			}
-		}
-        switch_core_session_rwunlock(session);
-	}
-
-	switch_core_session_kill_channel(session, SWITCH_SIG_BREAK);
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_queue_event(switch_core_session_t *session, switch_event_t **event)
-{
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	assert(session != NULL);
-
-	if (!session->event_queue) {
-		switch_queue_create(&session->event_queue, SWITCH_EVENT_QUEUE_LEN, session->pool);
-	}
-
-	if (session->event_queue) {
-		if (switch_queue_trypush(session->event_queue, *event) == SWITCH_STATUS_SUCCESS) {
-			*event = NULL;
-			status = SWITCH_STATUS_SUCCESS;
-		}
-	} 
-
-	return status;
-}
-
-SWITCH_DECLARE(int32_t) switch_core_session_event_count(switch_core_session_t *session)
-{
-	if (session->event_queue) {
-		return (int32_t) switch_queue_size(session->event_queue);
-	}
-
-	return -1;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_dequeue_event(switch_core_session_t *session, switch_event_t **event)
-	 
-{
-	switch_status_t status = SWITCH_STATUS_FALSE;
-	void *pop;
-
-	assert(session != NULL);
-	
-	if (session->event_queue) {
-		if ((status = (switch_status_t) switch_queue_trypop(session->event_queue, &pop)) == SWITCH_STATUS_SUCCESS) {
-			*event = (switch_event_t *) pop;
-		}
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_queue_private_event(switch_core_session_t *session, switch_event_t **event)
-{
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	assert(session != NULL);
-	
-	if (!session->private_event_queue) {
-		switch_queue_create(&session->private_event_queue, SWITCH_EVENT_QUEUE_LEN, session->pool);
-	}
-
-	if (session->private_event_queue) {
-		(*event)->event_id = SWITCH_EVENT_PRIVATE_COMMAND;
-		if (switch_queue_trypush(session->private_event_queue, *event) == SWITCH_STATUS_SUCCESS) {
-			*event = NULL;
-			switch_core_session_kill_channel(session, SWITCH_SIG_BREAK);
-			status = SWITCH_STATUS_SUCCESS;
-		}
-	} 
-
-	return status;
-}
-
-SWITCH_DECLARE(int32_t) switch_core_session_private_event_count(switch_core_session_t *session)
-{
-	if (session->private_event_queue) {
-		return (int32_t) switch_queue_size(session->private_event_queue);
-	}
-
-	return -1;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_dequeue_private_event(switch_core_session_t *session, switch_event_t **event)
-	 
-{
-	switch_status_t status = SWITCH_STATUS_FALSE;
-	void *pop;
-	switch_channel_t *channel;
-
-	assert(session != NULL);
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-	
-	if (switch_channel_test_flag(channel, CF_EVENT_PARSE)) {
-		return status;
-	}
-
-	
-	if (session->private_event_queue) {
-		if ((status = (switch_status_t) switch_queue_trypop(session->private_event_queue, &pop)) == SWITCH_STATUS_SUCCESS) {
-			*event = (switch_event_t *) pop;
-		}
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_read_frame(switch_core_session_t *session, switch_frame_t **frame,
-															 int timeout, int stream_id)
-{
-	switch_io_event_hook_read_frame_t *ptr;
-	switch_status_t status;
-	int need_codec, perfect, do_bugs = 0;
-	unsigned int flag = 0;
- top:
-	
-	status = SWITCH_STATUS_FALSE;
-	need_codec = perfect = 0;
-	
-	assert(session != NULL);
-	*frame = NULL;
-
-	if (switch_channel_test_flag(session->channel, CF_HOLD)) {
-		status = SWITCH_STATUS_BREAK;
-		goto done;
-	}
-
-	if (session->endpoint_interface->io_routines->read_frame) {
-		if ((status = session->endpoint_interface->io_routines->read_frame(session,
-																		   frame,
-																		   timeout,
-																		   SWITCH_IO_FLAG_NOOP,
-																		   stream_id)) == SWITCH_STATUS_SUCCESS) {
-			for (ptr = session->event_hooks.read_frame; ptr; ptr = ptr->next) {
-				if ((status =
-					 ptr->read_frame(session, frame, timeout, SWITCH_IO_FLAG_NOOP,
-									 stream_id)) != SWITCH_STATUS_SUCCESS) {
-					break;
-				}
-			}
-		}
-	}
-
-	if (status != SWITCH_STATUS_SUCCESS) {
-		goto done;
-	}
-
-	if (!(*frame)) {
-		goto done;
-	}
-
-	assert(session != NULL);
-	assert(*frame != NULL);
-	
-	if (switch_test_flag(*frame, SFF_CNG)) {
-		status = SWITCH_STATUS_SUCCESS;
-		goto done;
-	}
-
-	if ((session->read_codec && (*frame)->codec && session->read_codec->implementation != (*frame)->codec->implementation)) {
-		need_codec = TRUE;
-	}
-
-	if (session->read_codec && !(*frame)->codec) {
-		need_codec = TRUE;
-	}
-
-	if (!session->read_codec && (*frame)->codec) {
-		need_codec = TRUE;
-	}
-
-	if (session->bugs && !need_codec) {
-		do_bugs = 1;
-		need_codec = 1;
-	}
-
-	if (status == SWITCH_STATUS_SUCCESS && need_codec) {
-		switch_frame_t *enc_frame, *read_frame = *frame;
-
-		if (read_frame->codec) {
-			session->raw_read_frame.datalen = session->raw_read_frame.buflen;
-			status = switch_core_codec_decode(read_frame->codec,
-											  session->read_codec,
-											  read_frame->data,
-											  read_frame->datalen,
-											  session->read_codec->implementation->samples_per_second,
-											  session->raw_read_frame.data,
-											  &session->raw_read_frame.datalen,
-											  &session->raw_read_frame.rate,
-											  &flag);
-
-			switch (status) {
-			case SWITCH_STATUS_RESAMPLE:
-				if (!session->read_resampler) {
-					switch_resample_create(&session->read_resampler,
-										   read_frame->codec->implementation->samples_per_second,
-										   read_frame->codec->implementation->bytes_per_frame * 20,
-										   session->read_codec->implementation->samples_per_second,
-										   session->read_codec->implementation->bytes_per_frame * 20, session->pool);
-				}
-			case SWITCH_STATUS_SUCCESS:
-				read_frame = &session->raw_read_frame;
-				break;
-			case SWITCH_STATUS_NOOP:
-				status = SWITCH_STATUS_SUCCESS;
-				break;
-			default:
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec %s decoder error!\n",
-								  session->read_codec->codec_interface->interface_name);
-				goto done;
-			}
-		}
-		if (session->read_resampler) {
-			short *data = read_frame->data;
-
-			session->read_resampler->from_len =
-				switch_short_to_float(data, session->read_resampler->from, (int) read_frame->datalen / 2);
-			session->read_resampler->to_len =
-				switch_resample_process(session->read_resampler, session->read_resampler->from,
-										session->read_resampler->from_len, session->read_resampler->to,
-										session->read_resampler->to_size, 0);
-			switch_float_to_short(session->read_resampler->to, data, read_frame->datalen);
-			read_frame->samples = session->read_resampler->to_len;
-			read_frame->datalen = session->read_resampler->to_len * 2;
-			read_frame->rate = session->read_resampler->to_rate;
-		}
-
-		if (session->bugs) {
-			switch_media_bug_t *bp;
-			switch_thread_rwlock_rdlock(session->bug_rwlock);
-			for (bp = session->bugs; bp; bp = bp->next) {
-				if (bp->ready && switch_test_flag(bp, SMBF_READ_STREAM)) {
-					switch_mutex_lock(bp->read_mutex);
-					switch_buffer_write(bp->raw_read_buffer, read_frame->data, read_frame->datalen);
-					if (bp->callback) {
-						bp->callback(bp, bp->user_data, SWITCH_ABC_TYPE_READ);
-					}
-					switch_mutex_unlock(bp->read_mutex);
-				}
-			}
-			switch_thread_rwlock_unlock(session->bug_rwlock);
-		}
-
-		if (do_bugs) {
-			goto done;
-		}
-
-		if (session->read_codec) {
-			if ((*frame)->datalen == session->read_codec->implementation->bytes_per_frame) {
-				perfect = TRUE;
-			} else {
-				if (!session->raw_read_buffer) {
-					switch_size_t bytes = session->read_codec->implementation->bytes_per_frame;
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Engaging Read Buffer at %u bytes\n", (uint32_t)bytes);
-					switch_buffer_create_dynamic(&session->raw_read_buffer, bytes * SWITCH_BUFFER_BLOCK_FRAMES, bytes * SWITCH_BUFFER_START_FRAMES, 0);
-				}
-				if (!switch_buffer_write(session->raw_read_buffer, read_frame->data, read_frame->datalen)) {
-					status = SWITCH_STATUS_MEMERR;
-					goto done;
-				}
-			}
-
-			if (perfect || switch_buffer_inuse(session->raw_read_buffer) >= session->read_codec->implementation->bytes_per_frame) {
-				if (perfect) {
-					enc_frame = *frame;
-					session->raw_read_frame.rate = (*frame)->rate;
-				} else {
-					session->raw_read_frame.datalen = (uint32_t)switch_buffer_read(session->raw_read_buffer,
-																				   session->raw_read_frame.data,
-																				   session->read_codec->implementation->bytes_per_frame);
-					
-					session->raw_read_frame.rate = session->read_codec->implementation->samples_per_second;
-					enc_frame = &session->raw_read_frame;
-				}
-				session->enc_read_frame.datalen = session->enc_read_frame.buflen;
-				assert(session->read_codec != NULL);				
-				assert(enc_frame != NULL);
-				assert(enc_frame->data != NULL);
-				
-				status = switch_core_codec_encode(session->read_codec,
-												  enc_frame->codec,
-												  enc_frame->data,
-												  enc_frame->datalen,
-												  session->read_codec->implementation->samples_per_second,
-												  session->enc_read_frame.data,
-												  &session->enc_read_frame.datalen,
-												  &session->enc_read_frame.rate, 
-												  &flag);
-
-
-				switch (status) {
-				case SWITCH_STATUS_RESAMPLE:
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "fixme 1\n");
-				case SWITCH_STATUS_SUCCESS:
-					*frame = &session->enc_read_frame;
-					break;
-				case SWITCH_STATUS_NOOP:
-					*frame = &session->raw_read_frame;
-					status = SWITCH_STATUS_SUCCESS;
-					break;
-				default:
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec %s encoder error!\n",
-										  session->read_codec->codec_interface->interface_name);
-					*frame = NULL;
-					status = SWITCH_STATUS_GENERR;
-					break;
-				}
-			} else {
-				goto top;
-			}
-		}
-	}
-
- done:
-	if (!(*frame)) {
-		status = SWITCH_STATUS_FALSE;
-	} else {
-		if (flag & SFF_CNG) {
-			switch_set_flag((*frame), SFF_CNG);
-		}
-	}
-
-	return status;
-}
-
-static switch_status_t perform_write(switch_core_session_t *session, switch_frame_t *frame, int timeout, switch_io_flag_t flags, int stream_id)
-{
-	switch_io_event_hook_write_frame_t *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (session->endpoint_interface->io_routines->write_frame) {
-
-		if ((status =
-			 session->endpoint_interface->io_routines->write_frame(session, frame, timeout, flags,
-																   stream_id)) == SWITCH_STATUS_SUCCESS) {
-			for (ptr = session->event_hooks.write_frame; ptr; ptr = ptr->next) {
-				if ((status = ptr->write_frame(session, frame, timeout, flags, stream_id)) != SWITCH_STATUS_SUCCESS) {
-					break;
-				}
-			}
-		}
-	}
-	return status;
-}
-
-SWITCH_DECLARE(void) switch_core_session_reset(switch_core_session_t *session)
-{
-	switch_channel_t *channel;
-	char buf[256];
-	switch_size_t has;
-
-	/* sweep theese under the rug, they wont be leaked they will be reclaimed
-	   when the session ends.
-	*/
-	session->read_resampler = NULL;
-	session->write_resampler = NULL;
-
-    /* clear indications */
-    switch_core_session_flush_message(session);
-
-	/* wipe theese, they will be recreated if need be */
-	switch_buffer_destroy(&session->raw_read_buffer);
-	switch_buffer_destroy(&session->raw_write_buffer);
-
-	/* flush dtmf */
-	channel = switch_core_session_get_channel(session);
-
-	while ((has = switch_channel_has_dtmf(channel))) {
-        switch_channel_dequeue_dtmf(channel, buf, sizeof(buf));
-    }
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_write_frame(switch_core_session_t *session, switch_frame_t *frame,
-															  int timeout, int stream_id)
-{
-
-	switch_status_t status = SWITCH_STATUS_FALSE;
-	switch_frame_t *enc_frame = NULL, *write_frame = frame;
-	unsigned int flag = 0, need_codec = 0, perfect = 0, do_bugs = 0, do_write = 0;
-	switch_io_flag_t io_flag = SWITCH_IO_FLAG_NOOP;
-
-	assert(session != NULL);
-	assert(frame != NULL);
-
-
-	if (switch_channel_test_flag(session->channel, CF_HOLD)) {
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	if (switch_test_flag(frame, SFF_CNG)) {
-
-		if (switch_channel_test_flag(session->channel, CF_ACCEPT_CNG)) { 
-			return perform_write(session, frame, timeout, flag, stream_id);
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	assert(frame->codec != NULL);
-
-	if ((session->write_codec && frame->codec && session->write_codec->implementation != frame->codec->implementation)) {
-		need_codec = TRUE;
-	}
-
-	if (session->write_codec && !frame->codec) {
-		need_codec = TRUE;
-	}
-
-	if (!session->write_codec && frame->codec) {
-		need_codec = TRUE;
-	}
-
-	if (session->bugs && !need_codec) {
-		do_bugs = 1;
-		need_codec = 1;
-	}
-
-	if (need_codec) {
-		if (frame->codec) {
-			session->raw_write_frame.datalen = session->raw_write_frame.buflen;
-			status = switch_core_codec_decode(frame->codec,
-											  session->write_codec,
-											  frame->data,
-											  frame->datalen,
-											  session->write_codec->implementation->samples_per_second,
-											  session->raw_write_frame.data,
-											  &session->raw_write_frame.datalen, &session->raw_write_frame.rate, &flag);
-			
-			
-			switch (status) {
-			case SWITCH_STATUS_RESAMPLE:
-				write_frame = &session->raw_write_frame;
-				if (!session->write_resampler) {
-					status = switch_resample_create(&session->write_resampler,
-													frame->codec->implementation->samples_per_second,
-													frame->codec->implementation->bytes_per_frame * 20,
-													session->write_codec->implementation->samples_per_second,
-													session->write_codec->implementation->bytes_per_frame * 20,
-													session->pool);
-				}
-				break;
-			case SWITCH_STATUS_SUCCESS:
-				write_frame = &session->raw_write_frame;
-				break;
-			case SWITCH_STATUS_BREAK:
-				return SWITCH_STATUS_SUCCESS;
-			case SWITCH_STATUS_NOOP:
-				write_frame = frame;
-				status = SWITCH_STATUS_SUCCESS;
-				break;
-			default:
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec %s decoder error!\n",
-									  frame->codec->codec_interface->interface_name);
-				return status;
-			}
-		}
-		if (session->write_resampler) {
-			short *data = write_frame->data;
-
-			session->write_resampler->from_len = write_frame->datalen / 2;
-			switch_short_to_float(data, session->write_resampler->from, session->write_resampler->from_len);
-
-
-
-			session->write_resampler->to_len = (uint32_t)
-				switch_resample_process(session->write_resampler, session->write_resampler->from,
-										session->write_resampler->from_len, session->write_resampler->to,
-										session->write_resampler->to_size, 0);
-			
-
-			switch_float_to_short(session->write_resampler->to, data, session->write_resampler->to_len);
-
-			write_frame->samples = session->write_resampler->to_len;
-			write_frame->datalen = write_frame->samples * 2;
-			write_frame->rate = session->write_resampler->to_rate;
-		}
-
-		if (session->bugs) {
-			switch_media_bug_t *bp;
-			switch_thread_rwlock_rdlock(session->bug_rwlock);
-			for (bp = session->bugs; bp; bp = bp->next) {
-                if (!bp->ready) {
-                    continue;
-                }
-				if (switch_test_flag(bp, SMBF_WRITE_STREAM)) {
-					switch_mutex_lock(bp->write_mutex);
-					switch_buffer_write(bp->raw_write_buffer, write_frame->data, write_frame->datalen);
-					switch_mutex_unlock(bp->write_mutex);
-					if (bp->callback) {
-						bp->callback(bp, bp->user_data, SWITCH_ABC_TYPE_WRITE);
-					}
-				} else if (switch_test_flag(bp, SMBF_WRITE_REPLACE)) {
-                    do_bugs = 0;
-					if (bp->callback) {
-                        bp->replace_frame_in = frame;
-                        bp->replace_frame_out = NULL;
-						bp->callback(bp, bp->user_data, SWITCH_ABC_TYPE_WRITE_REPLACE);
-                        write_frame = bp->replace_frame_out;
-					}
-				}
-			}
-			switch_thread_rwlock_unlock(session->bug_rwlock);
-		}
-
-		if (do_bugs) {
-            do_write = 1;
-            write_frame = frame;
-            goto done;
-		}
-
-		if (session->write_codec) {
-			if (write_frame->datalen == session->write_codec->implementation->bytes_per_frame) {
-				perfect = TRUE;
-			} else {
-				if (!session->raw_write_buffer) {
-					switch_size_t bytes = session->write_codec->implementation->bytes_per_frame;
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
-									  "Engaging Write Buffer at %u bytes to accomodate %u->%u\n",
-									  (uint32_t)bytes,
-									  write_frame->datalen, session->write_codec->implementation->bytes_per_frame);
-					if ((status =switch_buffer_create_dynamic(&session->raw_write_buffer,
-															  bytes * SWITCH_BUFFER_BLOCK_FRAMES,
-															  bytes * SWITCH_BUFFER_START_FRAMES,
-															  0)) != SWITCH_STATUS_SUCCESS) {
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Write Buffer Failed!\n");
-						return status;
-					}
-				}
-
-				if (!(switch_buffer_write(session->raw_write_buffer, write_frame->data, write_frame->datalen))) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Write Buffer %u bytes Failed!\n", write_frame->datalen);
-					return SWITCH_STATUS_MEMERR;
-				}
-			}
-
-			
-			if (perfect) {
-				enc_frame = write_frame;
-				session->enc_write_frame.datalen = session->enc_write_frame.buflen;
-
-				status = switch_core_codec_encode(session->write_codec,
-												  frame->codec,
-												  enc_frame->data,
-												  enc_frame->datalen,
-												  session->write_codec->implementation->samples_per_second,
-												  session->enc_write_frame.data,
-												  &session->enc_write_frame.datalen,
-												  &session->enc_write_frame.rate, &flag);
-				
-				switch (status) {
-				case SWITCH_STATUS_RESAMPLE:
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "fixme 2\n");
-				case SWITCH_STATUS_SUCCESS:
-					write_frame = &session->enc_write_frame;
-					break;
-				case SWITCH_STATUS_NOOP:
-					write_frame = enc_frame;
-					status = SWITCH_STATUS_SUCCESS;
-					break;
-				default:
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec %s encoder error!\n",
-										  session->read_codec->codec_interface->interface_name);
-					write_frame = NULL;
-					return status;
-				}
-				if (flag & SFF_CNG) {
-					switch_set_flag(write_frame, SFF_CNG);
-				}
-				status = perform_write(session, write_frame, timeout, io_flag, stream_id);
-				return status;
-			} else {
-				switch_size_t used = switch_buffer_inuse(session->raw_write_buffer);
-				uint32_t bytes = session->write_codec->implementation->bytes_per_frame;
-				switch_size_t frames = (used / bytes);
-				
-				status = SWITCH_STATUS_SUCCESS;
-				if (!frames) {
-					return status;
-				} else {
-					switch_size_t x;
-					for (x = 0; x < frames; x++) {
-						if ((session->raw_write_frame.datalen = (uint32_t)
-							 switch_buffer_read(session->raw_write_buffer, session->raw_write_frame.data, bytes)) != 0) {
-							enc_frame = &session->raw_write_frame;
-							session->raw_write_frame.rate = session->write_codec->implementation->samples_per_second;
-							session->enc_write_frame.datalen = session->enc_write_frame.buflen;
-
-
-							status = switch_core_codec_encode(session->write_codec,
-															  frame->codec,
-															  enc_frame->data,
-															  enc_frame->datalen,
-															  frame->codec->implementation->samples_per_second,
-															  session->enc_write_frame.data,
-															  &session->enc_write_frame.datalen,
-															  &session->enc_write_frame.rate, &flag);
-
-							
-							switch (status) {
-							case SWITCH_STATUS_RESAMPLE:
-								write_frame = &session->enc_write_frame;
-								if (!session->read_resampler) {
-									status = switch_resample_create(&session->read_resampler,
-																	frame->codec->implementation->samples_per_second,
-																	frame->codec->implementation->bytes_per_frame * 20,
-																	session->write_codec->implementation->
-																	samples_per_second,
-																	session->write_codec->implementation->
-																	bytes_per_frame * 20, session->pool);
-								}
-								break;
-							case SWITCH_STATUS_SUCCESS:
-								write_frame = &session->enc_write_frame;
-								break;
-							case SWITCH_STATUS_NOOP:
-								write_frame = enc_frame;
-								status = SWITCH_STATUS_SUCCESS;
-								break;
-							default:
-								switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec %s encoder error %d!\n",
-													  session->read_codec->codec_interface->interface_name, status);
-								write_frame = NULL;
-								return status;
-							}
-
-							if (session->read_resampler) {
-								short *data = write_frame->data;
-
-								session->read_resampler->from_len = switch_short_to_float(data,
-																						  session->read_resampler->from,
-																						  (int) write_frame->datalen /
-																						  2);
-								session->read_resampler->to_len = (uint32_t)
-									switch_resample_process(session->read_resampler, session->read_resampler->from,
-															session->read_resampler->from_len,
-															session->read_resampler->to,
-															session->read_resampler->to_size, 0);
-								switch_float_to_short(session->read_resampler->to, data, write_frame->datalen * 2);
-								write_frame->samples = session->read_resampler->to_len;
-								write_frame->datalen = session->read_resampler->to_len * 2;
-								write_frame->rate = session->read_resampler->to_rate;
-							}
-							if (flag & SFF_CNG) {
-								switch_set_flag(write_frame, SFF_CNG);
-							}
-							if ((status = perform_write(session, write_frame, timeout, io_flag, stream_id)) != SWITCH_STATUS_SUCCESS) {
-								break;
-							}
-						}
-					}
-					return status;
-				}
-			}
-		}
-	} else {
-		do_write = 1;
-	}
-
- done:
-	if (do_write) {
-		return perform_write(session, frame, timeout, io_flag, stream_id);
-	}
-
-	return status;
-}
-
-static char *SIG_NAMES[] = {
-	"NONE",
-	"KILL",
-	"XFER",
-    "BREAK",
-	NULL
-};
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_perform_kill_channel(switch_core_session_t *session, 
-                                                                         const char *file, 
-                                                                         const char *func, 
-                                                                         int line, 
-                                                                         switch_signal_t sig)
-{
-	switch_io_event_hook_kill_channel_t *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-	
-	switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, SWITCH_LOG_INFO, "Kill %s [%s]\n", switch_channel_get_name(session->channel), SIG_NAMES[sig]);
-	
-	if (session->endpoint_interface->io_routines->kill_channel) {
-		if ((status = session->endpoint_interface->io_routines->kill_channel(session, sig)) == SWITCH_STATUS_SUCCESS) {
-			for (ptr = session->event_hooks.kill_channel; ptr; ptr = ptr->next) {
-				if ((status = ptr->kill_channel(session, sig)) != SWITCH_STATUS_SUCCESS) {
-					break;
-				}
-			}
-		}
-	}
-
-	return status;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_waitfor_read(switch_core_session_t *session, int timeout, int stream_id)
-{
-	switch_io_event_hook_waitfor_read_t *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (session->endpoint_interface->io_routines->waitfor_read) {
-		if ((status =
-			 session->endpoint_interface->io_routines->waitfor_read(session, timeout,
-																	stream_id)) == SWITCH_STATUS_SUCCESS) {
-			for (ptr = session->event_hooks.waitfor_read; ptr; ptr = ptr->next) {
-				if ((status = ptr->waitfor_read(session, timeout, stream_id)) != SWITCH_STATUS_SUCCESS) {
-					break;
-				}
-			}
-		}
-	}
-
-	return status;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_waitfor_write(switch_core_session_t *session, int timeout,
-																int stream_id)
-{
-	switch_io_event_hook_waitfor_write_t *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (session->endpoint_interface->io_routines->waitfor_write) {
-		if ((status =
-			 session->endpoint_interface->io_routines->waitfor_write(session, timeout,
-																	 stream_id)) == SWITCH_STATUS_SUCCESS) {
-			for (ptr = session->event_hooks.waitfor_write; ptr; ptr = ptr->next) {
-				if ((status = ptr->waitfor_write(session, timeout, stream_id)) != SWITCH_STATUS_SUCCESS) {
-					break;
-				}
-			}
-		}
-	}
-
-	return status;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_send_dtmf(switch_core_session_t *session, char *dtmf)
-{
-	switch_io_event_hook_send_dtmf_t *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (session->endpoint_interface->io_routines->send_dtmf) {
-        if (strchr(dtmf, 'w') || strchr(dtmf, 'W')) {
-            char *d;
-            for (d = dtmf; d && *d; d++) {
-				char digit[2] = {0};
-                
-                if (*d == 'w') {
-                    switch_yield(500000);
-                    continue;
-                } else if (*d == 'W') {
-                    switch_yield(1000000);
-                    continue;
-                }
-
-                digit[0] = *d;
-                if ((status = session->endpoint_interface->io_routines->send_dtmf(session, digit)) != SWITCH_STATUS_SUCCESS) {
-                    return status;
-                }
-            }
-        } else {
-            status = session->endpoint_interface->io_routines->send_dtmf(session, dtmf);
-        }
-
-        if (status == SWITCH_STATUS_SUCCESS) {
-            for (ptr = session->event_hooks.send_dtmf; ptr; ptr = ptr->next) {
-                if ((status = ptr->send_dtmf(session, dtmf)) != SWITCH_STATUS_SUCCESS) {
-                    break;
-                }
-            }
-        }
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_outgoing(switch_core_session_t *session,
-																		  switch_outgoing_channel_hook_t outgoing_channel)
-{
-	switch_io_event_hook_outgoing_channel_t *hook, *ptr;
-
-	assert(outgoing_channel != NULL);
-	if ((hook = switch_core_session_alloc(session, sizeof(*hook))) != 0) {
-		hook->outgoing_channel = outgoing_channel;
-		if (!session->event_hooks.outgoing_channel) {
-			session->event_hooks.outgoing_channel = hook;
-		} else {
-			for (ptr = session->event_hooks.outgoing_channel; ptr && ptr->next; ptr = ptr->next);
-			ptr->next = hook;
-
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_answer_channel(switch_core_session_t *session,
-																				switch_answer_channel_hook_t
-																				answer_channel)
-{
-	switch_io_event_hook_answer_channel_t *hook, *ptr;
-
-	assert(answer_channel != NULL);
-	if ((hook = switch_core_session_alloc(session, sizeof(*hook))) != 0) {
-		hook->answer_channel = answer_channel;
-		if (!session->event_hooks.answer_channel) {
-			session->event_hooks.answer_channel = hook;
-		} else {
-			for (ptr = session->event_hooks.answer_channel; ptr && ptr->next; ptr = ptr->next);
-			ptr->next = hook;
-
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_read_frame(switch_core_session_t *session,
-																			switch_read_frame_hook_t read_frame)
-{
-	switch_io_event_hook_read_frame_t *hook, *ptr;
-
-	assert(read_frame != NULL);
-	if ((hook = switch_core_session_alloc(session, sizeof(*hook))) != 0) {
-		hook->read_frame = read_frame;
-		if (!session->event_hooks.read_frame) {
-			session->event_hooks.read_frame = hook;
-		} else {
-			for (ptr = session->event_hooks.read_frame; ptr && ptr->next; ptr = ptr->next);
-			ptr->next = hook;
-
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_write_frame(switch_core_session_t *session,
-																			 switch_write_frame_hook_t write_frame)
-{
-	switch_io_event_hook_write_frame_t *hook, *ptr;
-
-	assert(write_frame != NULL);
-	if ((hook = switch_core_session_alloc(session, sizeof(*hook))) != 0) {
-		hook->write_frame = write_frame;
-		if (!session->event_hooks.write_frame) {
-			session->event_hooks.write_frame = hook;
-		} else {
-			for (ptr = session->event_hooks.write_frame; ptr && ptr->next; ptr = ptr->next);
-			ptr->next = hook;
-
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_kill_channel(switch_core_session_t *session,
-																			  switch_kill_channel_hook_t kill_channel)
-{
-	switch_io_event_hook_kill_channel_t *hook, *ptr;
-
-	assert(kill_channel != NULL);
-	if ((hook = switch_core_session_alloc(session, sizeof(*hook))) != 0) {
-		hook->kill_channel = kill_channel;
-		if (!session->event_hooks.kill_channel) {
-			session->event_hooks.kill_channel = hook;
-		} else {
-			for (ptr = session->event_hooks.kill_channel; ptr && ptr->next; ptr = ptr->next);
-			ptr->next = hook;
-
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_waitfor_read(switch_core_session_t *session,
-																			  switch_waitfor_read_hook_t waitfor_read)
-{
-	switch_io_event_hook_waitfor_read_t *hook, *ptr;
-
-	assert(waitfor_read != NULL);
-	if ((hook = switch_core_session_alloc(session, sizeof(*hook))) != 0) {
-		hook->waitfor_read = waitfor_read;
-		if (!session->event_hooks.waitfor_read) {
-			session->event_hooks.waitfor_read = hook;
-		} else {
-			for (ptr = session->event_hooks.waitfor_read; ptr && ptr->next; ptr = ptr->next);
-			ptr->next = hook;
-
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_waitfor_write(switch_core_session_t *session,
-																			   switch_waitfor_write_hook_t waitfor_write)
-{
-	switch_io_event_hook_waitfor_write_t *hook, *ptr;
-
-	assert(waitfor_write != NULL);
-	if ((hook = switch_core_session_alloc(session, sizeof(*hook))) != 0) {
-		hook->waitfor_write = waitfor_write;
-		if (!session->event_hooks.waitfor_write) {
-			session->event_hooks.waitfor_write = hook;
-		} else {
-			for (ptr = session->event_hooks.waitfor_write; ptr && ptr->next; ptr = ptr->next);
-			ptr->next = hook;
-
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_session_add_event_hook_send_dtmf(switch_core_session_t *session,
-																		   switch_send_dtmf_hook_t send_dtmf)
-{
-	switch_io_event_hook_send_dtmf_t *hook, *ptr;
-
-	assert(send_dtmf != NULL);
-	if ((hook = switch_core_session_alloc(session, sizeof(*hook))) != 0) {
-		hook->send_dtmf = send_dtmf;
-		if (!session->event_hooks.send_dtmf) {
-			session->event_hooks.send_dtmf = hook;
-		} else {
-			for (ptr = session->event_hooks.send_dtmf; ptr && ptr->next; ptr = ptr->next);
-			ptr->next = hook;
-
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_core_new_memory_pool(switch_memory_pool_t **pool)
-{
-
-	assert(runtime.memory_pool != NULL);
-
-	if ((apr_pool_create(pool, NULL)) != SWITCH_STATUS_SUCCESS) {
-		*pool = NULL;
-		return SWITCH_STATUS_MEMERR;
-	}
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_destroy_memory_pool(switch_memory_pool_t **pool)
-{
-	apr_pool_destroy(*pool);
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_channel_t *) switch_core_session_get_channel(switch_core_session_t *session)
-{
-	return session->channel;
-}
-
-static void switch_core_standard_on_init(switch_core_session_t *session)
-{
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Standard INIT %s\n", switch_channel_get_name(session->channel));
-}
-
-static void switch_core_standard_on_hangup(switch_core_session_t *session)
-{
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Standard HANGUP %s, cause: %s\n", switch_channel_get_name(session->channel),switch_channel_cause2str(switch_channel_get_cause(session->channel)));
-
-}
-
-static void switch_core_standard_on_ring(switch_core_session_t *session)
-{
-	switch_dialplan_interface_t *dialplan_interface = NULL;
-	switch_caller_profile_t *caller_profile;
-	switch_caller_extension_t *extension = NULL;
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Standard RING %s\n", switch_channel_get_name(session->channel));
-
-	if ((caller_profile = switch_channel_get_caller_profile(session->channel)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't get profile!\n");
-		switch_channel_hangup(session->channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-        return;
-	} else {
-		char *dp[25];
-        char *dpstr;
-		int argc, x, count = 0;
-
-		if (!switch_strlen_zero(caller_profile->dialplan)) {
-            if ((dpstr = switch_core_session_strdup(session, caller_profile->dialplan))) {
-                argc = switch_separate_string(dpstr, ',', dp, (sizeof(dp) / sizeof(dp[0]))); 
-                for (x = 0; x < argc; x++) {
-                    char *dpname = dp[x];
-                    char *dparg = NULL;
-
-                    if (dpname) {
-                        if ((dparg = strchr(dpname, ':'))) {
-                            *dparg++ = '\0';
-                        }
-                    }
-                    if (!(dialplan_interface = switch_loadable_module_get_dialplan_interface(dpname))) {
-                        continue;
-                    }
-
-                    count++;
-
-                    if ((extension = dialplan_interface->hunt_function(session, dparg)) != 0) {
-                        switch_channel_set_caller_extension(session->channel, extension);
-                        return;
-                    }
-                }
-            }
-        }
-
-		if (!count) {
-			if (switch_channel_test_flag(session->channel, CF_OUTBOUND)) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "No Dialplan, changing state to HOLD\n");
-				switch_channel_set_state(session->channel, CS_HOLD);
-				return;
-			} 
-		}
-	}
-
-	if (!extension) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "No Route, Aborting\n");
-        switch_channel_hangup(session->channel, SWITCH_CAUSE_NO_ROUTE_DESTINATION);
-    }
-}
-
-static void switch_core_standard_on_execute(switch_core_session_t *session)
-{
-	switch_caller_extension_t *extension;
-	switch_event_t *event;
-	const switch_application_interface_t *application_interface;
-
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Standard EXECUTE\n");
-	if ((extension = switch_channel_get_caller_extension(session->channel)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No Extension!\n");
-		switch_channel_hangup(session->channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-		return;
-	}
-
-	while (switch_channel_get_state(session->channel) == CS_EXECUTE && extension->current_application) {
-		char *expanded = NULL;
-
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Execute %s(%s)\n",
-							  extension->current_application->application_name,
-							  switch_str_nil(extension->current_application->application_data));
-		if (
-			(application_interface =
-			 switch_loadable_module_get_application_interface(extension->current_application->application_name)) == 0) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Application %s\n",
-								  extension->current_application->application_name);
-			switch_channel_hangup(session->channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			return;
-		}
-
-		if (!application_interface->application_function) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No Function for %s\n",
-								  extension->current_application->application_name);
-			switch_channel_hangup(session->channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			return;
-		}
-		
-		if ((expanded = switch_channel_expand_variables(session->channel, extension->current_application->application_data)) != 
-			extension->current_application->application_data) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Expanded String %s(%s)\n",
-							  extension->current_application->application_name,
-							  expanded);
-		}
-
-		if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_EXECUTE) == SWITCH_STATUS_SUCCESS) {
-			switch_channel_event_set_data(session->channel, event);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application", "%s", extension->current_application->application_name);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application-Data-Orig", "%s", extension->current_application->application_data);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application-Data", "%s", expanded);
-			switch_event_fire(&event);
-		}
-		
-
-		if (switch_channel_get_variable(session->channel, "presence_id")) {
-			char *arg = switch_mprintf("%s(%s)", extension->current_application->application_name, expanded);
-			if (arg) {
-				switch_channel_presence(session->channel, "unknown", arg);
-				switch_safe_free(arg);
-			}
-		}
-
-		application_interface->application_function(session, expanded);
-
-		if (expanded != extension->current_application->application_data) {
-			switch_safe_free(expanded);
-		}
-		extension->current_application = extension->current_application->next;
-	}
-	
-	if (switch_channel_get_state(session->channel) == CS_EXECUTE) {
-		switch_channel_hangup(session->channel, SWITCH_CAUSE_NORMAL_CLEARING);
-	}
-}
-
-static void switch_core_standard_on_loopback(switch_core_session_t *session)
-{
-	switch_frame_t *frame;
-	int stream_id;
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Standard LOOPBACK\n");
-
-	while (switch_channel_get_state(session->channel) == CS_LOOPBACK) {
-		for (stream_id = 0; stream_id < session->stream_count; stream_id++) {
-			if (switch_core_session_read_frame(session, &frame, -1, stream_id) == SWITCH_STATUS_SUCCESS) {
-				switch_core_session_write_frame(session, frame, -1, stream_id);
-			}
-		}
-	}
-}
-
-static void switch_core_standard_on_transmit(switch_core_session_t *session)
-{
-	assert(session != NULL);
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Standard TRANSMIT\n");
-}
-
-static void switch_core_standard_on_hold(switch_core_session_t *session)
-{
-	assert(session != NULL);
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Standard HOLD\n");
-}
-
-static void switch_core_standard_on_hibernate(switch_core_session_t *session)
-{
-	assert(session != NULL);
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Standard HIBERNATE\n");
-}
-
-SWITCH_DECLARE(void) switch_core_session_signal_state_change(switch_core_session_t *session)
-{
-
-	/* If trylock fails the signal is already awake so we needn't bother */
-	if (switch_mutex_trylock(session->mutex) == SWITCH_STATUS_SUCCESS) {
-		switch_thread_cond_signal(session->cond);
-		switch_mutex_unlock(session->mutex);
-	} 
-	
-}
-
-SWITCH_DECLARE(unsigned int) switch_core_session_running(switch_core_session_t *session)
-{
-	return session->thread_running;
-}
-#ifdef CRASH_PROT
-#if defined (__GNUC__) && defined (LINUX)
-#include <execinfo.h>
-#include <stdio.h>
-#include <stdlib.h>
-#define STACK_LEN 10
-
-/* Obtain a backtrace and print it to stdout. */
-static void print_trace (void)
-{
-	void *array[STACK_LEN];
-	size_t size;
-	char **strings;
-	size_t i;
-
-	size = backtrace (array, STACK_LEN);
-	strings = backtrace_symbols (array, size);
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Obtained %zd stack frames.\n", size);
-	
-	for (i = 0; i < size; i++) {
-		switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_CRIT, "%s\n", strings[i]);
-	}
-
-	free (strings);
-}
-#else
-static void print_trace (void)
-{
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Trace not avaliable =(\n");
-}
-#endif
-
-
-static void handle_fatality(int sig)
-{
-	switch_thread_id_t thread_id;
-	jmp_buf *env;
-
-	if (sig && (thread_id = switch_thread_self()) && (env = (jmp_buf *) apr_hash_get(runtime.stack_table, &thread_id, sizeof(thread_id)))) {
-		print_trace();
-		longjmp(*env, sig);
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Caught signal %d for unmapped thread!", sig);
-		abort();
-	}
-}
-#endif
-
-SWITCH_DECLARE(void) switch_core_session_run(switch_core_session_t *session)
-{
-	switch_channel_state_t state = CS_NEW, laststate = CS_HANGUP, midstate = CS_DONE, endstate;
-	const switch_endpoint_interface_t *endpoint_interface;
-	const switch_state_handler_table_t *driver_state_handler = NULL;
-	const switch_state_handler_table_t *application_state_handler = NULL;
-
-#ifdef CRASH_PROT
-	switch_thread_id_t thread_id = switch_thread_self();
-	jmp_buf env;
-	int sig;
-
-	signal(SIGSEGV, handle_fatality);
-	signal(SIGFPE, handle_fatality);
-#ifndef WIN32
-	signal(SIGBUS, handle_fatality);
-#endif
-
-	if ((sig = setjmp(env)) != 0) {
-		switch_event_t *event;
-
-		if (switch_event_create(&event, SWITCH_EVENT_SESSION_CRASH) == SWITCH_STATUS_SUCCESS) {
-			switch_channel_event_set_data(session->channel, event);
-			switch_event_fire(&event);
-		}
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Thread has crashed for channel %s\n", switch_channel_get_name(session->channel));
-		switch_channel_hangup(session->channel, SWITCH_CAUSE_CRASH);
-	} else {
-		apr_hash_set(runtime.stack_table, &thread_id, sizeof(thread_id), &env);
-	}
-#endif
-	/*
-	   Life of the channel. you have channel and pool in your session
-	   everywhere you go you use the session to malloc with
-	   switch_core_session_alloc(session, <size>)
-
-	   The enpoint module gets the first crack at implementing the state
-	   if it wants to, it can cancel the default behaviour by returning SWITCH_STATUS_FALSE
-
-	   Next comes the channel's event handler table that can be set by an application
-	   which also can veto the next behaviour in line by returning SWITCH_STATUS_FALSE
-
-	   Finally the default state behaviour is called.
-
-
-	 */
-	assert(session != NULL);
-	
-	session->thread_running = 1;
-	endpoint_interface = session->endpoint_interface;
-	assert(endpoint_interface != NULL);
-
-	driver_state_handler = endpoint_interface->state_handler;
-	assert(driver_state_handler != NULL);
-
-	switch_mutex_lock(session->mutex);
-
-	while ((state = switch_channel_get_state(session->channel)) != CS_DONE) {
-        uint8_t exception = 0;        
-        if (switch_channel_test_flag(session->channel, CF_REPEAT_STATE)) {
-            switch_channel_clear_flag(session->channel, CF_REPEAT_STATE);
-            exception = 1;
-        }
-		if (state != laststate || state == CS_HANGUP || exception) {
-			int index = 0;
-			int proceed = 1;
-			midstate = state;
-
-			switch (state) {
-			case CS_NEW:		/* Just created, Waiting for first instructions */
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "(%s) State NEW\n", switch_channel_get_name(session->channel));
-				break;
-			case CS_DONE:
-				goto done;
-			case CS_HANGUP:	/* Deactivate and end the thread */
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "(%s) State HANGUP\n", switch_channel_get_name(session->channel));
-				if (!driver_state_handler->on_hangup ||
-					(driver_state_handler->on_hangup &&
-					 driver_state_handler->on_hangup(session) == SWITCH_STATUS_SUCCESS &&
-					 midstate == switch_channel_get_state(session->channel))) {
-					while((application_state_handler = switch_channel_get_state_handler(session->channel, index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_hangup ||
-							(application_state_handler->on_hangup &&
-							 application_state_handler->on_hangup(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					index = 0;
-					while(proceed && (application_state_handler = switch_core_get_state_handler(index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_hangup ||
-							(application_state_handler->on_hangup &&
-							 application_state_handler->on_hangup(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-
-					if (proceed) {
-						switch_core_standard_on_hangup(session);
-					}
-				}
-				goto done;
-			case CS_INIT:		/* Basic setup tasks */
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "(%s) State INIT\n", switch_channel_get_name(session->channel));
-				if (!driver_state_handler->on_init ||
-					(driver_state_handler->on_init &&
-					 driver_state_handler->on_init(session) == SWITCH_STATUS_SUCCESS &&
-					 midstate == switch_channel_get_state(session->channel))) {
-					while((application_state_handler = switch_channel_get_state_handler(session->channel, index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_init ||
-							(application_state_handler->on_init &&
-							 application_state_handler->on_init(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					index = 0;
-					while(proceed && (application_state_handler = switch_core_get_state_handler(index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_init ||
-							(application_state_handler->on_init &&
-							 application_state_handler->on_init(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					if (proceed) {
-						switch_core_standard_on_init(session);
-					}
-				}
-				break;
-			case CS_RING:		/* Look for a dialplan and find something to do */
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "(%s) State RING\n", switch_channel_get_name(session->channel));
-				if (!driver_state_handler->on_ring ||
-					(driver_state_handler->on_ring &&
-					 driver_state_handler->on_ring(session) == SWITCH_STATUS_SUCCESS &&
-					 midstate == switch_channel_get_state(session->channel))) {
-					while((application_state_handler = switch_channel_get_state_handler(session->channel, index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_ring ||
-							(application_state_handler->on_ring &&
-							 application_state_handler->on_ring(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					index = 0;
-					while(proceed && (application_state_handler = switch_core_get_state_handler(index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_ring ||
-							(application_state_handler->on_ring &&
-							 application_state_handler->on_ring(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					if (proceed) {
-						switch_core_standard_on_ring(session);
-					}
-				}
-				break;
-			case CS_EXECUTE:	/* Execute an Operation */
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "(%s) State EXECUTE\n", switch_channel_get_name(session->channel));
-				if (!driver_state_handler->on_execute ||
-					(driver_state_handler->on_execute &&
-					 driver_state_handler->on_execute(session) == SWITCH_STATUS_SUCCESS &&
-					 midstate == switch_channel_get_state(session->channel))) {
-					while((application_state_handler = switch_channel_get_state_handler(session->channel, index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_execute ||
-							(application_state_handler->on_execute &&
-							 application_state_handler->on_execute(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					index = 0;
-					while(proceed && (application_state_handler = switch_core_get_state_handler(index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_execute ||
-							(application_state_handler->on_execute &&
-							 application_state_handler->on_execute(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					if (proceed) {
-						switch_core_standard_on_execute(session);
-					}
-				}
-				break;
-			case CS_LOOPBACK:	/* loop all data back to source */
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "(%s) State LOOPBACK\n", switch_channel_get_name(session->channel));
-				if (!driver_state_handler->on_loopback ||
-					(driver_state_handler->on_loopback &&
-					 driver_state_handler->on_loopback(session) == SWITCH_STATUS_SUCCESS &&
-					 midstate == switch_channel_get_state(session->channel))) {
-					while((application_state_handler = switch_channel_get_state_handler(session->channel, index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_loopback ||
-							(application_state_handler->on_loopback &&
-							 application_state_handler->on_loopback(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					index = 0;
-					while(proceed && (application_state_handler = switch_core_get_state_handler(index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_loopback ||
-							(application_state_handler->on_loopback &&
-							 application_state_handler->on_loopback(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					if (proceed) {
-						switch_core_standard_on_loopback(session);
-					}
-				}
-				break;
-			case CS_TRANSMIT:	/* send/recieve data to/from another channel */
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "(%s) State TRANSMIT\n", switch_channel_get_name(session->channel));
-				if (!driver_state_handler->on_transmit ||
-					(driver_state_handler->on_transmit &&
-					 driver_state_handler->on_transmit(session) == SWITCH_STATUS_SUCCESS &&
-					 midstate == switch_channel_get_state(session->channel))) {
-
-					while((application_state_handler = switch_channel_get_state_handler(session->channel, index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_transmit ||
-							(application_state_handler->on_transmit &&
-							 application_state_handler->on_transmit(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					index = 0;
-					while(proceed && (application_state_handler = switch_core_get_state_handler(index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_transmit ||
-							(application_state_handler->on_transmit &&
-							 application_state_handler->on_transmit(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					if (proceed) {
-						switch_core_standard_on_transmit(session);
-					}
-				}
-				break;
-			case CS_HOLD:	/* wait in limbo */
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "(%s) State HOLD\n", switch_channel_get_name(session->channel));
-				if (!driver_state_handler->on_hold ||
-					(driver_state_handler->on_hold &&
-					 driver_state_handler->on_hold(session) == SWITCH_STATUS_SUCCESS &&
-					 midstate == switch_channel_get_state(session->channel))) {
-
-					while((application_state_handler = switch_channel_get_state_handler(session->channel, index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_hold ||
-							(application_state_handler->on_hold &&
-							 application_state_handler->on_hold(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					index = 0;
-					while(proceed && (application_state_handler = switch_core_get_state_handler(index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_hold ||
-							(application_state_handler->on_hold &&
-							 application_state_handler->on_hold(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					if (proceed) {
-						switch_core_standard_on_hold(session);
-					}
-				}
-				break;
-			case CS_HIBERNATE:	/* wait in limbo */
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "(%s) State HIBERNATE\n", switch_channel_get_name(session->channel));
-				if (!driver_state_handler->on_hibernate ||
-					(driver_state_handler->on_hibernate &&
-					 driver_state_handler->on_hibernate(session) == SWITCH_STATUS_SUCCESS &&
-					 midstate == switch_channel_get_state(session->channel))) {
-
-					while((application_state_handler = switch_channel_get_state_handler(session->channel, index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_hibernate ||
-							(application_state_handler->on_hibernate &&
-							 application_state_handler->on_hibernate(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					index = 0;
-					while(proceed && (application_state_handler = switch_core_get_state_handler(index++)) != 0) {
-						if (!application_state_handler || !application_state_handler->on_hibernate ||
-							(application_state_handler->on_hibernate &&
-							 application_state_handler->on_hibernate(session) == SWITCH_STATUS_SUCCESS &&
-							 midstate == switch_channel_get_state(session->channel))) {
-							proceed++;
-							continue;
-						} else {
-							proceed = 0;
-							break;
-						}
-					}
-					if (proceed) {
-						switch_core_standard_on_hibernate(session);
-					}
-				}
-				break;
-			}
-
-			if (midstate == CS_DONE) {
-				break;
-			}
-
-			laststate = midstate;
-		}
-		
-
-		endstate = switch_channel_get_state(session->channel);
-
-
-		if (midstate == endstate) {
-			switch_thread_cond_wait(session->cond, session->mutex);
-		}
-
-	}
- done:
-	switch_mutex_unlock(session->mutex);
-
-#ifdef CRASH_PROT
-	apr_hash_set(runtime.stack_table, &thread_id, sizeof(thread_id), NULL);
-#endif
-	session->thread_running = 0;
-
-}
-
-SWITCH_DECLARE(void) switch_core_session_destroy(switch_core_session_t **session)
-{
-	switch_memory_pool_t *pool;
-	switch_event_t *event;
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Close Channel %s\n", switch_channel_get_name((*session)->channel));
-
-	switch_mutex_lock(runtime.session_table_mutex);
-	switch_core_hash_delete(runtime.session_table, (*session)->uuid_str);
-	if (runtime.session_count) {
-		runtime.session_count--;
-	}
-	switch_mutex_unlock(runtime.session_table_mutex);
-
-	if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_DESTROY) == SWITCH_STATUS_SUCCESS) {
-		switch_channel_event_set_data((*session)->channel, event);
-		switch_event_fire(&event);
-	}
-
-	switch_core_media_bug_remove_all(*session);
-	switch_buffer_destroy(&(*session)->raw_read_buffer);
-	switch_buffer_destroy(&(*session)->raw_write_buffer);
-	switch_channel_uninit((*session)->channel);
-
-	pool = (*session)->pool;
-	*session = NULL;
-	apr_pool_destroy(pool);
-	pool = NULL;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_hash_init(switch_hash_t **hash, switch_memory_pool_t *pool)
-{
-	assert(pool != NULL);
-
-	if ((*hash = apr_hash_make(pool)) != 0) {
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_GENERR;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_hash_destroy(switch_hash_t *hash)
-{
-	assert(hash != NULL);
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_hash_insert_dup(switch_hash_t *hash, const char *key, const void *data)
-{
-	apr_hash_set(hash, switch_core_strdup(apr_hash_pool_get(hash), key), APR_HASH_KEY_STRING, data);
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_hash_insert(switch_hash_t *hash, const char *key, const void *data)
-{
-	apr_hash_set(hash, key, APR_HASH_KEY_STRING, data);
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_core_hash_delete(switch_hash_t *hash, const char *key)
-{
-	apr_hash_set(hash, key, APR_HASH_KEY_STRING, NULL);
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(void *) switch_core_hash_find(switch_hash_t *hash, const char *key)
-{
-	return apr_hash_get(hash, key, APR_HASH_KEY_STRING);
-}
-
-/* This function abstracts the thread creation for modules by allowing you to pass a function ptr and
-   a void object and trust that that the function will be run in a thread with arg  This lets
-   you request and activate a thread without giving up any knowledge about what is in the thread
-   neither the core nor the calling module know anything about each other.
-
-   This thread is expected to never exit until the application exits so the func is responsible
-   to make sure that is the case.
-
-   The typical use for this is so switch_loadable_module.c can start up a thread for each module
-   passing the table of module methods as a session obj into the core without actually allowing
-   the core to have any clue and keeping switch_loadable_module.c from needing any thread code.
-
-*/
-
-SWITCH_DECLARE(void) switch_core_launch_thread(switch_thread_start_t func, void *obj, switch_memory_pool_t *pool)
-{
-	switch_thread_t *thread;
-	switch_threadattr_t *thd_attr = NULL;
-	switch_core_thread_session_t *ts;
-	int mypool;
-
-	mypool = pool ? 0 : 1;
-
-	if (!pool && switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Could not allocate memory pool\n");
-		return;
-	}
-
-	switch_threadattr_create(&thd_attr, pool);
-	switch_threadattr_detach_set(thd_attr, 1);
-
-	if ((ts = switch_core_alloc(pool, sizeof(*ts))) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Could not allocate memory\n");
-	} else {
-		if (mypool) {
-			ts->pool = pool;
-		}
-		ts->objs[0] = obj;
-		switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-		switch_thread_create(&thread, thd_attr, func, ts, pool);
-	}
-
-}
-
-static void *SWITCH_THREAD_FUNC switch_core_session_thread(switch_thread_t *thread, void *obj)
-{
-	switch_core_session_t *session = obj;
-	session->thread = thread;
-
-
-
-	switch_core_session_run(session);
-	switch_core_media_bug_remove_all(session);
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Session %u (%s) Locked, Waiting on external entities\n", session->id, switch_channel_get_name(session->channel));
-	switch_core_session_write_lock(session);
-    switch_set_flag(session, SSF_DESTROYED);
-	switch_core_session_rwunlock(session);
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Session %u (%s) Ended\n", session->id, switch_channel_get_name(session->channel));
-	switch_core_session_destroy(&session);
-	return NULL;
-}
-
-
-SWITCH_DECLARE(void) switch_core_session_thread_launch(switch_core_session_t *session)
-{
-	switch_thread_t *thread;
-	switch_threadattr_t *thd_attr;;
-	switch_threadattr_create(&thd_attr, session->pool);
-	switch_threadattr_detach_set(thd_attr, 1);
-
-	if (! session->thread_running) {
-		switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-		if (switch_thread_create(&thread, thd_attr, switch_core_session_thread, session, session->pool) != SWITCH_STATUS_SUCCESS) {
-			switch_core_session_destroy(&session);
-		}
-	}
-}
-
-
-SWITCH_DECLARE(void) switch_core_session_launch_thread(switch_core_session_t *session, switch_thread_start_t func,
-													   void *obj)
-{
-	switch_thread_t *thread;
-	switch_threadattr_t *thd_attr = NULL;
-	switch_threadattr_create(&thd_attr, session->pool);
-	switch_threadattr_detach_set(thd_attr, 1);
-
-	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-	switch_thread_create(&thread, thd_attr, func, obj, session->pool);
-
-}
-
-
-SWITCH_DECLARE(void *) switch_core_alloc(switch_memory_pool_t *pool, switch_size_t memory)
-{
-	void *ptr = NULL;
-	assert(pool != NULL);
-
-#ifdef DEBUG_ALLOC
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Allocate %d\n", memory);
-	//assert(memory < 600000);
-#endif
-
-	if ((ptr = apr_palloc(pool, memory)) != 0) {
-		memset(ptr, 0, memory);
-	}
-	return ptr;
-}
-
-SWITCH_DECLARE(switch_core_session_t *) switch_core_session_request(const switch_endpoint_interface_t *endpoint_interface,
-																  switch_memory_pool_t *pool)
-{
-	switch_memory_pool_t *usepool;
-	switch_core_session_t *session;
-	switch_uuid_t uuid;
-	uint32_t count = 0;
-
-	assert(endpoint_interface != NULL);
-
-	switch_mutex_lock(runtime.session_table_mutex);
-	count = runtime.session_count;
-	switch_mutex_unlock(runtime.session_table_mutex);
-
-	if ((count + 1) > runtime.session_limit) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Over Session Limit!\n");
-		return NULL;
-	}
-
-	if (runtime.no_new_sessions || runtime.shutting_down) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Read my lips: no new sessions!\n");
-		return NULL;
-	}
-
-	if (pool) {
-		usepool = pool;
-	} else if (switch_core_new_memory_pool(&usepool) != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Could not allocate memory pool\n");
-		return NULL;
-	}
-
-	if ((session = switch_core_alloc(usepool, sizeof(switch_core_session_t))) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Could not allocate session\n");
-		apr_pool_destroy(usepool);
-		return NULL;
-	}
+	switch_core_measure_time(switch_core_uptime(), &duration);
 
-	if (switch_channel_alloc(&session->channel, usepool) != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate channel structure\n");
-		apr_pool_destroy(usepool);
-		return NULL;
-	}
+	if (switch_event_create(&event, SWITCH_EVENT_HEARTBEAT) == SWITCH_STATUS_SUCCESS) {
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Event-Info", "System Ready");
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Up-Time",
+								"%u year%s, "
+								"%u day%s, "
+								"%u hour%s, "
+								"%u minute%s, "
+								"%u second%s, "
+								"%u millisecond%s, "
+								"%u microsecond%s\n",
+								duration.yr, duration.yr == 1 ? "" : "s",
+								duration.day, duration.day == 1 ? "" : "s",
+								duration.hr, duration.hr == 1 ? "" : "s",
+								duration.min, duration.min == 1 ? "" : "s",
+								duration.sec, duration.sec == 1 ? "" : "s",
+								duration.ms, duration.ms == 1 ? "" : "s", duration.mms, duration.mms == 1 ? "" : "s");
 
-	switch_channel_init(session->channel, session, CS_NEW, 0);
+		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Session-Count", "%u", switch_core_session_count());
+		switch_event_fire(&event);
+	}
+}
 
-	/* The session *IS* the pool you may not alter it because you have no idea how
-	   its all private it will be passed to the thread run function */
+static void heartbeat_callback(switch_scheduler_task_t *task)
+{
+	send_heartbeat();
 
-	switch_uuid_get(&uuid);
-	switch_uuid_format(session->uuid_str, &uuid);
+	/* reschedule this task */
+	task->runtime += 20;
+}
 
-	session->pool = usepool;
-	session->endpoint_interface = endpoint_interface;
 
-	session->raw_write_frame.data = session->raw_write_buf;
-	session->raw_write_frame.buflen = sizeof(session->raw_write_buf);
-	session->raw_read_frame.data = session->raw_read_buf;
-	session->raw_read_frame.buflen = sizeof(session->raw_read_buf);
-
-
-	session->enc_write_frame.data = session->enc_write_buf;
-	session->enc_write_frame.buflen = sizeof(session->enc_write_buf);
-	session->enc_read_frame.data = session->enc_read_buf;
-	session->enc_read_frame.buflen = sizeof(session->enc_read_buf);
-
-	switch_mutex_init(&session->mutex, SWITCH_MUTEX_NESTED, session->pool);
-	switch_thread_rwlock_create(&session->bug_rwlock, session->pool);
-	switch_thread_cond_create(&session->cond, session->pool);
-	switch_thread_rwlock_create(&session->rwlock, session->pool);
-
-	snprintf(session->name, sizeof(session->name), "%u", session->id);
-	switch_mutex_lock(runtime.session_table_mutex);
-	session->id = runtime.session_id++;
-	switch_core_hash_insert(runtime.session_table, session->uuid_str, session);
-	runtime.session_count++;
-	switch_mutex_unlock(runtime.session_table_mutex);
+SWITCH_DECLARE(switch_status_t) switch_core_set_console(char *console)
+{
+	if ((runtime.console = fopen(console, "a")) == 0) {
+		fprintf(stderr, "Cannot open output file %s.\n", console);
+		return SWITCH_STATUS_FALSE;
+	}
 
-	return session;
+	return SWITCH_STATUS_SUCCESS;
 }
 
-SWITCH_DECLARE(uint32_t) switch_core_session_count(void)
+SWITCH_DECLARE(FILE *) switch_core_get_console(void)
 {
-	return runtime.session_count;
+	return runtime.console;
 }
 
-SWITCH_DECLARE(switch_core_session_t *) switch_core_session_request_by_name(char *endpoint_name, switch_memory_pool_t *pool)
+SWITCH_DECLARE(FILE *) switch_core_data_channel(switch_text_channel_t channel)
 {
-	const switch_endpoint_interface_t *endpoint_interface;
+	FILE *handle = stdout;
 
-	if ((endpoint_interface = switch_loadable_module_get_endpoint_interface(endpoint_name)) == 0) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not locate channel type %s\n", endpoint_name);
-		return NULL;
+	switch (channel) {
+	case SWITCH_CHANNEL_ID_LOG:
+	case SWITCH_CHANNEL_ID_LOG_CLEAN:
+		handle = runtime.console;
+		break;
+	default:
+		handle = runtime.console;
+		break;
 	}
 
-	return switch_core_session_request(endpoint_interface, pool);
+	return handle;
 }
 
-static switch_status_t switch_core_db_persistant_execute_trans(switch_core_db_t *db, char *sql, uint32_t retries)
+SWITCH_DECLARE(int) switch_core_add_state_handler(const switch_state_handler_table_t *state_handler)
 {
-	char *errmsg;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-	uint8_t forever = 0;
-	unsigned begin_retries = 100;
-	uint8_t again = 0;
-
-	if (!retries) {
-		forever = 1;
-		retries = 1000;
+	int index = runtime.state_handler_index++;
+
+	if (runtime.state_handler_index >= SWITCH_MAX_STATE_HANDLERS) {
+		return -1;
 	}
 
- again:
+	runtime.state_handlers[index] = state_handler;
+	return index;
+}
 
-	while(begin_retries > 0) {
-		again = 0;
-		
-		switch_core_db_exec(
-							db,
-							"begin transaction",
-							NULL,
-							NULL,
-							&errmsg
-							);
-	
-        if (errmsg) {
-			begin_retries--;
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "SQL ERR [%s]\n", errmsg);
-			if (strstr(errmsg, "cannot start a transaction within a transaction")) {
-				again = 1;
-			}
-            switch_core_db_free(errmsg);
+SWITCH_DECLARE(const switch_state_handler_table_t *) switch_core_get_state_handler(int index)
+{
 
-			if (again) {
-				switch_core_db_exec(db, "end transaction", NULL, NULL, &errmsg);
-				goto again;
-			}
+	if (index > SWITCH_MAX_STATE_HANDLERS || index > runtime.state_handler_index) {
+		return NULL;
+	}
 
-            switch_yield(100000);
+	return runtime.state_handlers[index];
+}
 
-			if(begin_retries == 0) {
-				goto done;
-			} 
-        } else {
-            break;
-        }
 
-	}
+SWITCH_DECLARE(char *) switch_core_get_variable(char *varname)
+{
+	return (char *) switch_core_hash_find(runtime.global_vars, varname);
+}
 
-	while(retries > 0) {
+SWITCH_DECLARE(void) switch_core_set_variable(char *varname, char *value)
+{
+	switch_core_hash_insert(runtime.global_vars, switch_core_strdup(runtime.memory_pool, varname), switch_core_strdup(runtime.memory_pool, value));
+}
 
+SWITCH_DECLARE(char *) switch_core_get_uuid(void)
+{
+	return runtime.uuid_str;
+}
 
 
-		switch_core_db_exec(
-							db,
-							sql,
-							NULL,
-							NULL,
-							&errmsg
-							);		
-		if (errmsg) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "SQL ERR [%s]\n", errmsg);
-			switch_core_db_free(errmsg);
-			switch_yield(100000);
-			retries--;
-			if (retries == 0 && forever) {
-				retries = 1000;
-				continue;
-			}
-		} else {
-			status = SWITCH_STATUS_SUCCESS;
+static void *switch_core_service_thread(switch_thread_t * thread, void *obj)
+{
+	switch_core_thread_session_t *data = obj;
+	switch_core_session_t *session = data->objs[0];
+	int *stream_id_p = data->objs[1];
+	switch_channel_t *channel;
+	switch_frame_t *read_frame;
+	int stream_id = *stream_id_p;
+
+	assert(thread != NULL);
+	assert(session != NULL);
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
+
+	switch_channel_set_flag(channel, CF_SERVICE);
+	while (data->running > 0) {
+		switch (switch_core_session_read_frame(session, &read_frame, -1, stream_id)) {
+		case SWITCH_STATUS_SUCCESS:
+		case SWITCH_STATUS_TIMEOUT:
+		case SWITCH_STATUS_BREAK:
 			break;
+		default:
+			data->running = -1;
+			continue;
 		}
 	}
 
-
- done:
-
-	switch_core_db_exec(
-						db,
-						"end transaction",
-						NULL,
-						NULL,
-						&errmsg
-						);
-
-	return status;
+	switch_channel_clear_flag(channel, CF_SERVICE);
+	data->running = 0;
+	return NULL;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_core_db_persistant_execute(switch_core_db_t *db, char *sql, uint32_t retries)
+/* Either add a timeout here or make damn sure the thread cannot get hung somehow (my preference) */
+SWITCH_DECLARE(void) switch_core_thread_session_end(switch_core_thread_session_t *thread_session)
 {
-	char *errmsg;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-	uint8_t forever = 0;
-
-	if (!retries) {
-		forever = 1;
-		retries = 1000;
-	}
+	if (thread_session->running > 0) {
+		thread_session->running = -1;
 
-	while(retries > 0) {
-		switch_core_db_exec(
-							db,
-							sql,
-							NULL,
-							NULL,
-							&errmsg
-							);		
-		if (errmsg) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "SQL ERR [%s]\n", errmsg);
-			switch_core_db_free(errmsg);
-			switch_yield(100000);
-			retries--;
-			if (retries == 0 && forever) {
-				retries = 1000;
-				continue;
-			}
-		} else {
-			status = SWITCH_STATUS_SUCCESS;
-			break;
+		while (thread_session->running) {
+			switch_yield(1000);
 		}
 	}
-
-	return status;
 }
 
-#ifdef DO_EVENTS
-#define SQLLEN 1024 * 64
-static void *SWITCH_THREAD_FUNC switch_core_sql_thread(switch_thread_t *thread, void *obj)
+SWITCH_DECLARE(void) switch_core_service_session(switch_core_session_t *session, switch_core_thread_session_t *thread_session, int stream_id)
 {
-	void *pop;
-	uint32_t itterations = 0;
-	uint8_t trans = 0, nothing_in_queue = 0;
-	uint32_t target = 1000;
-	switch_size_t len = 0, sql_len = SQLLEN;
-	char *sqlbuf = (char *) malloc(sql_len);
-	char *sql;
-	switch_size_t newlen;
-	uint32_t loops = 0;
-	
-	if (!runtime.event_db) {
-		runtime.event_db = switch_core_db_handle();
-	}
-	switch_queue_create(&runtime.sql_queue, SWITCH_SQL_QUEUE_LEN, runtime.memory_pool);
-
-
+	thread_session->running = 1;
+	thread_session->objs[0] = session;
+	thread_session->objs[1] = &stream_id;
+	switch_core_session_launch_thread(session, switch_core_service_thread, thread_session);
+}
 
-	for(;;) {
-		if (switch_queue_trypop(runtime.sql_queue, &pop) == SWITCH_STATUS_SUCCESS) {
-			sql = (char *) pop;
 
-			if (sql) {
-				newlen = strlen(sql) + 2;
-				
-				if (itterations == 0) {
-					trans = 1;
-				}
+/* This function abstracts the thread creation for modules by allowing you to pass a function ptr and
+   a void object and trust that that the function will be run in a thread with arg  This lets
+   you request and activate a thread without giving up any knowledge about what is in the thread
+   neither the core nor the calling module know anything about each other.
 
-				/* ignore abnormally large strings sql strings as potential buffer overflow */
-				if (newlen < SQLLEN) {
-					itterations++;
-					if (len + newlen > sql_len) {
-						sql_len = len + SQLLEN;
-						if (!(sqlbuf = realloc(sqlbuf, sql_len))) {
-							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "SQL thread ending on mem err\n");
-							break;
-						}
-					}
-					sprintf(sqlbuf + len, "%s;\n", sql); 
-					len += newlen;
+   This thread is expected to never exit until the application exits so the func is responsible
+   to make sure that is the case.
 
-				}
-				switch_core_db_free(sql);
-			} else {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "SQL thread ending\n");
-				break;
-			}
-		} else {
-			nothing_in_queue = 1;
-		}
+   The typical use for this is so switch_loadable_module.c can start up a thread for each module
+   passing the table of module methods as a session obj into the core without actually allowing
+   the core to have any clue and keeping switch_loadable_module.c from needing any thread code.
 
+*/
 
-		if (trans && ((itterations == target) || nothing_in_queue)) {
-			if (switch_core_db_persistant_execute_trans(runtime.event_db, sqlbuf, 1000) != SWITCH_STATUS_SUCCESS) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "SQL thread unable to commit transaction, records lost!\n");
-			}
-			itterations = 0;
-			trans = 0;
-			nothing_in_queue = 0;
-			len = 0;
-			*sqlbuf = '\0';
-		}
+SWITCH_DECLARE(void) switch_core_launch_thread(switch_thread_start_t func, void *obj, switch_memory_pool_t *pool)
+{
+	switch_thread_t *thread;
+	switch_threadattr_t *thd_attr = NULL;
+	switch_core_thread_session_t *ts;
+	int mypool;
 
-		if (loops++ >= 5000) {
-			switch_event_t *event;
-			switch_core_time_duration_t duration;
-
-			switch_core_measure_time(switch_core_uptime(), &duration);
-
-			if (switch_event_create(&event, SWITCH_EVENT_HEARTBEAT) == SWITCH_STATUS_SUCCESS) {
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Event-Info", "System Ready");
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Up-Time", 
-										"%u year%s, "
-										"%u day%s, "
-										"%u hour%s, "
-										"%u minute%s, "
-										"%u second%s, "
-										"%u millisecond%s, "
-										"%u microsecond%s\n",
-										duration.yr, duration.yr == 1 ? "" : "s",
-										duration.day, duration.day == 1 ? "" : "s",
-										duration.hr, duration.hr == 1 ? "" : "s",
-										duration.min, duration.min == 1 ? "" : "s",
-										duration.sec, duration.sec == 1 ? "" : "s",
-										duration.ms, duration.ms == 1 ? "" : "s",
-										duration.mms, duration.mms == 1 ? "" : "s"
-										);
+	mypool = pool ? 0 : 1;
 
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Session-Count", "%u", switch_core_session_count());
-				switch_event_fire(&event);
-			}
-			
-			loops = 0;
-		}
-		
-		if (nothing_in_queue) {
-			switch_yield(1000);
-		}
+	if (!pool && switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Could not allocate memory pool\n");
+		return;
 	}
 
-
-	free(sqlbuf);
-	return NULL;
-}
-
-
-static void switch_core_sql_thread_launch(void)
-{
-	switch_thread_t *thread;
-	switch_threadattr_t *thd_attr;;
-	
-	assert(runtime.memory_pool != NULL);
-
-	switch_threadattr_create(&thd_attr, runtime.memory_pool);
+	switch_threadattr_create(&thd_attr, pool);
 	switch_threadattr_detach_set(thd_attr, 1);
-	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-	switch_thread_create(&thread, thd_attr, switch_core_sql_thread, NULL, runtime.memory_pool);
-	
-}
-
-static void core_event_handler(switch_event_t *event)
-{
-	char *sql = NULL;
 
-	switch (event->event_id) {
-	case SWITCH_EVENT_CHANNEL_DESTROY:
-		sql = switch_mprintf("delete from channels where uuid='%s'", switch_event_get_header(event, "unique-id"));
-		break;
-	case SWITCH_EVENT_CHANNEL_CREATE:
-		sql = switch_mprintf("insert into channels (uuid,created,name,state) values('%q','%q','%q','%q')",
-									 switch_event_get_header(event, "unique-id"),
-									 switch_event_get_header(event, "event-date-local"),
-									 switch_event_get_header(event, "channel-name"),
-									 switch_event_get_header(event, "channel-state")
-									 );
-		break;
-	case SWITCH_EVENT_CODEC:
-		sql = switch_mprintf("update channels set read_codec='%q',read_rate='%q',write_codec='%q',write_rate='%q' where uuid='%q'",
-									 switch_event_get_header(event, "channel-read-codec-name"),
-									 switch_event_get_header(event, "channel-read-codec-rate"),
-									 switch_event_get_header(event, "channel-write-codec-name"),
-									 switch_event_get_header(event, "channel-write-codec-rate"),
-									 switch_event_get_header(event, "unique-id"));
-		break;
-	case SWITCH_EVENT_CHANNEL_EXECUTE:
-		sql = switch_mprintf("update channels set application='%q',application_data='%q' where uuid='%q'",
-									 switch_event_get_header(event, "application"),
-									 switch_event_get_header(event, "application-data"),
-									 switch_event_get_header(event, "unique-id")
-									 );
-		break;
-	case SWITCH_EVENT_CHANNEL_STATE:
-		if (event) {
-			char *state = switch_event_get_header(event, "channel-state-number");
-			switch_channel_state_t state_i = atoi(state);
-
-			switch(state_i) {
-			case CS_HANGUP:
-			case CS_DONE:
-				break;
-			case CS_RING:
-				sql = switch_mprintf("update channels set state='%s',cid_name='%q',cid_num='%q',ip_addr='%s',dest='%q'"
-											 "where uuid='%s'",
-											 switch_event_get_header(event, "channel-state"),
-											 switch_event_get_header(event, "caller-caller-id-name"),
-											 switch_event_get_header(event, "caller-caller-id-number"),
-											 switch_event_get_header(event, "caller-network-addr"),
-											 switch_event_get_header(event, "caller-destination-number"),
-											 switch_event_get_header(event, "unique-id")
-											 );
-				break;
-			default:
-				sql = switch_mprintf("update channels set state='%s' where uuid='%s'", 
-											 switch_event_get_header(event, "channel-state"),
-											 switch_event_get_header(event, "unique-id")
-											 );
-				break;
-			}
-		
-		}
-		break;
-	case SWITCH_EVENT_CHANNEL_BRIDGE:
-		sql = switch_mprintf("insert into calls values ('%s','%q','%q','%q','%q','%s','%q','%q','%q','%q','%s')",
-									 switch_event_get_header(event, "event-calling-function"),
-									 switch_event_get_header(event, "caller-caller-id-name"),
-									 switch_event_get_header(event, "caller-caller-id-number"),
-									 switch_event_get_header(event, "caller-destination-number"),
-									 switch_event_get_header(event, "caller-channel-name"),
-									 switch_event_get_header(event, "caller-unique-id"),
-									 switch_event_get_header(event, "originatee-caller-id-name"),
-									 switch_event_get_header(event, "originatee-caller-id-number"),
-									 switch_event_get_header(event, "originatee-destination-number"),
-									 switch_event_get_header(event, "originatee-channel-name"),
-									 switch_event_get_header(event, "originatee-unique-id")
-									 );
-		break;
-	case SWITCH_EVENT_CHANNEL_UNBRIDGE:
-		sql = switch_mprintf("delete from calls where caller_uuid='%s'", switch_event_get_header(event, "caller-unique-id"));
-		break;
-	case SWITCH_EVENT_SHUTDOWN:
-		sql = switch_mprintf("delete from channels;delete from interfaces;delete from calls");
-		break;
-	case SWITCH_EVENT_LOG:
-		return;
-	case SWITCH_EVENT_MODULE_LOAD:
-		{
-			const char *type = switch_event_get_header(event, "type");
-			const char *name = switch_event_get_header(event, "name");
-			const char *description = switch_event_get_header(event, "description");
-			const char *syntax = switch_event_get_header(event, "syntax");
-			if(!switch_strlen_zero(type) && !switch_strlen_zero(name)) {
-				sql = switch_mprintf("insert into interfaces (type,name,description,syntax) values('%q','%q','%q','%q')",
-											 type,
-											 name,
-											 switch_str_nil(description),
-											 switch_str_nil(syntax)
-											 );
-			}
-		break;
+	if ((ts = switch_core_alloc(pool, sizeof(*ts))) == 0) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Could not allocate memory\n");
+	} else {
+		if (mypool) {
+			ts->pool = pool;
 		}
-	default:
-		break;
+		ts->objs[0] = obj;
+		switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
+		switch_thread_create(&thread, thd_attr, func, ts, pool);
 	}
 
-	if (sql) {
-		switch_queue_push(runtime.sql_queue, sql);
-		sql = NULL;
-	}
 }
-#endif
 
 SWITCH_DECLARE(void) switch_core_set_globals(void)
 {
-#ifdef WIN32
 #define BUFSIZE 1024
-    char lpPathBuffer[BUFSIZE];
-	DWORD dwBufSize=BUFSIZE;
-	char exePath[1024];
+#ifdef WIN32
+	char lpPathBuffer[BUFSIZE];
+	DWORD dwBufSize = BUFSIZE;
+	char base_dir[1024];
 	char *lastbacklash;
-	GetModuleFileName( NULL, exePath, BUFSIZE );
-	lastbacklash = strrchr( exePath, '\\');
-	exePath[(lastbacklash - exePath + 1)] = '\0';
+	GetModuleFileName(NULL, base_dir, BUFSIZE);
+	lastbacklash = strrchr(base_dir, '\\');
+	base_dir[(lastbacklash - base_dir)] = '\0';
+#else
+	char base_dir[1024] = SWITCH_PREFIX_DIR;
+#endif
+
 	if (!SWITCH_GLOBAL_dirs.base_dir && (SWITCH_GLOBAL_dirs.base_dir = (char *) malloc(BUFSIZE))) {
-		snprintf(SWITCH_GLOBAL_dirs.base_dir, BUFSIZE, "%s", exePath);
+		switch_snprintf(SWITCH_GLOBAL_dirs.base_dir, BUFSIZE, "%s", base_dir);
 	}
+
 	if (!SWITCH_GLOBAL_dirs.mod_dir && (SWITCH_GLOBAL_dirs.mod_dir = (char *) malloc(BUFSIZE))) {
-		snprintf(SWITCH_GLOBAL_dirs.mod_dir, BUFSIZE, "%smod", exePath);
+#ifdef SWITCH_MOD_DIR
+		switch_snprintf(SWITCH_GLOBAL_dirs.mod_dir, BUFSIZE, "%s", SWITCH_MOD_DIR);
+#else
+		switch_snprintf(SWITCH_GLOBAL_dirs.mod_dir, BUFSIZE, "%s%smod", base_dir, SWITCH_PATH_SEPARATOR);
+#endif
 	}
+
 	if (!SWITCH_GLOBAL_dirs.conf_dir && (SWITCH_GLOBAL_dirs.conf_dir = (char *) malloc(BUFSIZE))) {
-		snprintf(SWITCH_GLOBAL_dirs.conf_dir, BUFSIZE, "%sconf", exePath);
+#ifdef SWITCH_CONF_DIR
+		switch_snprintf(SWITCH_GLOBAL_dirs.conf_dir, BUFSIZE, "%s", SWITCH_CONF_DIR);
+#else
+		switch_snprintf(SWITCH_GLOBAL_dirs.conf_dir, BUFSIZE, "%s%sconf", base_dir, SWITCH_PATH_SEPARATOR);
+#endif
 	}
+
 	if (!SWITCH_GLOBAL_dirs.log_dir && (SWITCH_GLOBAL_dirs.log_dir = (char *) malloc(BUFSIZE))) {
-		snprintf(SWITCH_GLOBAL_dirs.log_dir, BUFSIZE, "%slog", exePath);
+#ifdef SWITCH_LOG_DIR
+		switch_snprintf(SWITCH_GLOBAL_dirs.log_dir, BUFSIZE, "%s", SWITCH_LOG_DIR);
+#else
+		switch_snprintf(SWITCH_GLOBAL_dirs.log_dir, BUFSIZE, "%s%slog", base_dir, SWITCH_PATH_SEPARATOR);
+#endif
 	}
+
 	if (!SWITCH_GLOBAL_dirs.db_dir && (SWITCH_GLOBAL_dirs.db_dir = (char *) malloc(BUFSIZE))) {
-		snprintf(SWITCH_GLOBAL_dirs.db_dir, BUFSIZE, "%sdb", exePath);
+#ifdef SWITCH_DB_DIR
+		switch_snprintf(SWITCH_GLOBAL_dirs.db_dir, BUFSIZE, "%s", SWITCH_DB_DIR);
+#else
+		switch_snprintf(SWITCH_GLOBAL_dirs.db_dir, BUFSIZE, "%s%sdb", base_dir, SWITCH_PATH_SEPARATOR);
+#endif
 	}
+
 	if (!SWITCH_GLOBAL_dirs.script_dir && (SWITCH_GLOBAL_dirs.script_dir = (char *) malloc(BUFSIZE))) {
-		snprintf(SWITCH_GLOBAL_dirs.script_dir, BUFSIZE, "%sscripts", exePath);
+#ifdef SWITCH_SCRIPT_DIR
+		switch_snprintf(SWITCH_GLOBAL_dirs.script_dir, BUFSIZE, "%s", SWITCH_SCRIPT_DIR);
+#else
+		switch_snprintf(SWITCH_GLOBAL_dirs.script_dir, BUFSIZE, "%s%sscripts", base_dir, SWITCH_PATH_SEPARATOR);
+#endif
 	}
+
 	if (!SWITCH_GLOBAL_dirs.htdocs_dir && (SWITCH_GLOBAL_dirs.htdocs_dir = (char *) malloc(BUFSIZE))) {
-		snprintf(SWITCH_GLOBAL_dirs.htdocs_dir, BUFSIZE, "%shtdocs", exePath);
-	}
-	if (!SWITCH_GLOBAL_dirs.htdocs_dir && (SWITCH_GLOBAL_dirs.grammar_dir = (char *) malloc(BUFSIZE))) {
-		snprintf(SWITCH_GLOBAL_dirs.grammar_dir, BUFSIZE, "%sgrammar", exePath);
+#ifdef SWITCH_HTDOCS_DIR
+		switch_snprintf(SWITCH_GLOBAL_dirs.htdocs_dir, BUFSIZE, "%s", SWITCH_HTDOCS_DIR);
+#else
+		switch_snprintf(SWITCH_GLOBAL_dirs.htdocs_dir, BUFSIZE, "%s%shtdocs", base_dir, SWITCH_PATH_SEPARATOR);
+#endif
 	}
+
+	if (!SWITCH_GLOBAL_dirs.grammar_dir && (SWITCH_GLOBAL_dirs.grammar_dir = (char *) malloc(BUFSIZE))) {
+#ifdef SWITCH_GRAMMAR_DIR
+		switch_snprintf(SWITCH_GLOBAL_dirs.grammar_dir, BUFSIZE, "%s", SWITCH_GRAMMAR_DIR);
 #else
-	SWITCH_GLOBAL_dirs.base_dir = SWITCH_PREFIX_DIR;
-	SWITCH_GLOBAL_dirs.mod_dir = SWITCH_MOD_DIR;
-	if(!SWITCH_GLOBAL_dirs.conf_dir) SWITCH_GLOBAL_dirs.conf_dir = SWITCH_CONF_DIR;
-	if(!SWITCH_GLOBAL_dirs.log_dir) SWITCH_GLOBAL_dirs.log_dir = SWITCH_LOG_DIR;
-	if(!SWITCH_GLOBAL_dirs.db_dir) SWITCH_GLOBAL_dirs.db_dir = SWITCH_DB_DIR;
-	SWITCH_GLOBAL_dirs.script_dir = SWITCH_SCRIPT_DIR;
-	SWITCH_GLOBAL_dirs.htdocs_dir = SWITCH_HTDOCS_DIR;
-	SWITCH_GLOBAL_dirs.grammar_dir = SWITCH_GRAMMAR_DIR;
+		switch_snprintf(SWITCH_GLOBAL_dirs.grammar_dir, BUFSIZE, "%s%sgrammar", base_dir, SWITCH_PATH_SEPARATOR);
 #endif
+	}
+
+	if (!SWITCH_GLOBAL_dirs.temp_dir && (SWITCH_GLOBAL_dirs.temp_dir = (char *) malloc(BUFSIZE))) {
 #ifdef SWITCH_TEMP_DIR
-	SWITCH_GLOBAL_dirs.temp_dir = SWITCH_TEMP_DIR;
+		switch_snprintf(SWITCH_GLOBAL_dirs.temp_dir, BUFSIZE, "%s", SWITCH_TEMP_DIR);
 #else
 #ifdef WIN32
-	GetTempPath(dwBufSize, lpPathBuffer);
-	if (!SWITCH_GLOBAL_dirs.temp_dir && (SWITCH_GLOBAL_dirs.temp_dir = (char *) malloc(BUFSIZE))) {
-		snprintf(SWITCH_GLOBAL_dirs.temp_dir, BUFSIZE, "%s", lpPathBuffer);
-	}
+		GetTempPath(dwBufSize, lpPathBuffer);
+		switch_snprintf(SWITCH_GLOBAL_dirs.temp_dir, BUFSIZE, "%s", lpPathBuffer);
 #else
-	SWITCH_GLOBAL_dirs.temp_dir = "/tmp/";
+		switch_snprintf(SWITCH_GLOBAL_dirs.temp_dir, BUFSIZE, "%s", "/tmp/");
 #endif
 #endif
-}
-
-
-SWITCH_DECLARE(uint32_t) switch_core_session_limit(uint32_t new_limit)
-{
-	if (new_limit) {
-		runtime.session_limit = new_limit;
 	}
-	
-	return runtime.session_limit;
+
 }
 
 
 SWITCH_DECLARE(int32_t) set_high_priority(void)
 {
 #ifdef __linux__
-	struct sched_param sched = {0};
+	struct sched_param sched = { 0 };
 	sched.sched_priority = 1;
 	if (sched_setscheduler(0, SCHED_RR, &sched)) {
-        sched.sched_priority = 0;
-        if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
+		sched.sched_priority = 0;
+		if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
 			return -1;
 		}
 	}
@@ -4244,7 +373,7 @@
 #define USE_MLOCKALL
 #ifdef HAVE_MLOCKALL
 #ifdef USE_MLOCKALL
-	mlockall(MCL_CURRENT|MCL_FUTURE);
+	mlockall(MCL_CURRENT | MCL_FUTURE);
 #endif
 #endif
 	return 0;
@@ -4260,15 +389,15 @@
 		bg = 0;
 #ifdef WIN32
 		snprintf(path, sizeof(path), "Global\\Freeswitch.%d", getpid());
-		shutdown_event = CreateEvent(NULL, FALSE, FALSE, path);		
+		shutdown_event = CreateEvent(NULL, FALSE, FALSE, path);
 		WaitForSingleObject(shutdown_event, INFINITE);
 #else
 		runtime.running = 1;
-		while(runtime.running) {
+		while (runtime.running) {
 			switch_yield(1000000);
 		}
 #endif
-	}  else {
+	} else {
 		/* wait for console input */
 		switch_console_loop();
 	}
@@ -4280,25 +409,26 @@
 	switch_xml_t xml = NULL, cfg = NULL;
 	switch_uuid_t uuid;
 	memset(&runtime, 0, sizeof(runtime));
-	runtime.session_limit = 1000;
-
-	switch_core_set_globals();
 
 	/* INIT APR and Create the pool context */
 	if (apr_initialize() != SWITCH_STATUS_SUCCESS) {
-		apr_terminate();
 		*err = "FATAL ERROR! Could not initilize APR\n";
 		return SWITCH_STATUS_MEMERR;
 	}
 
-	if (apr_pool_create(&runtime.memory_pool, NULL) != SWITCH_STATUS_SUCCESS) {
-		apr_terminate();
-		*err = "FATAL ERROR! Could not allocate memory pool\n";
+	if (!(runtime.memory_pool = switch_core_memory_init())) {
+		*err = "FATAL ERROR! Could noat allocate memory pool\n";
 		return SWITCH_STATUS_MEMERR;
 	}
+	assert(runtime.memory_pool != NULL);
 
+	switch_core_set_globals();
+	switch_core_session_init(runtime.memory_pool);
+	switch_core_state_machine_init(runtime.memory_pool);
 	switch_core_hash_init(&runtime.global_vars, runtime.memory_pool);
 
+
+
 	if (switch_xml_init(runtime.memory_pool, err) != SWITCH_STATUS_SUCCESS) {
 		apr_terminate();
 		return SWITCH_STATUS_MEMERR;
@@ -4307,14 +437,20 @@
 
 	if ((xml = switch_xml_open_cfg("switch.conf", &cfg, NULL))) {
 		switch_xml_t settings, param;
-		
+
 		if ((settings = switch_xml_child(cfg, "settings"))) {
 			for (param = switch_xml_child(settings, "param"); param; param = param->next) {
 				const char *var = switch_xml_attr_soft(param, "name");
 				const char *val = switch_xml_attr_soft(param, "value");
-				
+
 				if (!strcasecmp(var, "max-sessions")) {
-					runtime.session_limit = atoi(val);
+					switch_core_session_limit(atoi(val));
+				}
+				else if (!strcasecmp(var, "rtp-start-port")) {
+					switch_rtp_set_start_port((switch_port_t)atoi(val));
+				}
+				else if (!strcasecmp(var, "rtp-end-port")) {
+					switch_rtp_set_end_port((switch_port_t)atoi(val));
 				}
 			}
 		}
@@ -4335,7 +471,7 @@
 
 	*err = NULL;
 
-	if(console) {
+	if (console) {
 		if (*console != '/') {
 			char path[265];
 			snprintf(path, sizeof(path), "%s%s%s", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, console);
@@ -4352,82 +488,17 @@
 
 	assert(runtime.memory_pool != NULL);
 	switch_log_init(runtime.memory_pool);
-
-#ifdef DO_EVENTS
-	switch_core_sql_thread_launch();
-#endif
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Allocated memory pool. Sessions are %u bytes\n", (uint32_t)sizeof(switch_core_session_t));
 	switch_event_init(runtime.memory_pool);
-	switch_rtp_init(runtime.memory_pool);
-
-	/* Activate SQL database */
-	if ((runtime.db = switch_core_db_handle()) == 0 ) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening DB!\n");
-	} else {
-		char create_channels_sql[] =
-			"CREATE TABLE channels (\n"
-			"   uuid  VARCHAR(255),\n"
-			"   created  VARCHAR(255),\n"
-			"   name  VARCHAR(255),\n"
-			"   state  VARCHAR(255),\n"
-			"   cid_name  VARCHAR(255),\n"
-			"   cid_num  VARCHAR(255),\n"
-			"   ip_addr  VARCHAR(255),\n"
-			"   dest  VARCHAR(255),\n"
-			"   application  VARCHAR(255),\n"
-			"   application_data  VARCHAR(255),\n"
-			"   read_codec  VARCHAR(255),\n"
-			"   read_rate  VARCHAR(255),\n"
-			"   write_codec  VARCHAR(255),\n"
-			"   write_rate  VARCHAR(255)\n"
-			");\n";
-		char create_calls_sql[] =
-			"CREATE TABLE calls (\n"
-			"   function  VARCHAR(255),\n"
-			"   caller_cid_name  VARCHAR(255),\n"
-			"   caller_cid_num   VARCHAR(255),\n"
-			"   caller_dest_num  VARCHAR(255),\n"
-			"   caller_chan_name VARCHAR(255),\n"
-			"   caller_uuid      VARCHAR(255),\n"
-			"   callee_cid_name  VARCHAR(255),\n"
-			"   callee_cid_num   VARCHAR(255),\n"
-			"   callee_dest_num  VARCHAR(255),\n"
-			"   callee_chan_name VARCHAR(255),\n"
-			"   callee_uuid      VARCHAR(255)\n"
-			");\n";
-		char create_interfaces_sql[] =
-			"CREATE TABLE interfaces (\n"
-			"   type             VARCHAR(255),\n"
-			"   name             VARCHAR(255),\n"
-			"   description      VARCHAR(255),\n"
-			"   syntax           VARCHAR(255)\n"
-			");\n";
-
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Opening DB\n");
-		switch_core_db_exec(runtime.db, "drop table channels", NULL, NULL, NULL);
-		switch_core_db_exec(runtime.db, "drop table calls", NULL, NULL, NULL);
-		switch_core_db_exec(runtime.db, "drop table interfaces", NULL, NULL, NULL);
-		switch_core_db_exec(runtime.db, create_channels_sql, NULL, NULL, NULL);
-		switch_core_db_exec(runtime.db, create_calls_sql, NULL, NULL, NULL);
-		switch_core_db_exec(runtime.db, create_interfaces_sql, NULL, NULL, NULL);
-#ifdef DO_EVENTS		
-		if (switch_event_bind("core_db", SWITCH_EVENT_ALL, SWITCH_EVENT_SUBCLASS_ANY, core_event_handler, NULL) !=
-			SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't bind event handler!\n");
-		}
-#endif
-	}
 
-	runtime.session_id = 1;
+	switch_core_sqldb_start(runtime.memory_pool);
+	switch_rtp_init(runtime.memory_pool);
 	runtime.running = 1;
-	switch_core_hash_init(&runtime.session_table, runtime.memory_pool);
-	switch_mutex_init(&runtime.session_table_mutex, SWITCH_MUTEX_NESTED, runtime.memory_pool);
-#ifdef CRASH_PROT
-	switch_core_hash_init(&runtime.stack_table, runtime.memory_pool);
-#endif
+
+	switch_scheduler_task_thread_start();
 	runtime.initiated = switch_time_now();
 
+	switch_scheduler_add_task(time(NULL), heartbeat_callback, "heartbeat", "core", 0, NULL, SSHF_NONE | SSHF_NO_DEL);
+
 
 	switch_uuid_get(&uuid);
 	switch_uuid_format(runtime.uuid_str, &uuid);
@@ -4438,7 +509,7 @@
 #ifdef SIGPIPE
 static void handle_SIGPIPE(int sig)
 {
-	if(sig);
+	if (sig);
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Sig Pipe!\n");
 	return;
 }
@@ -4447,7 +518,7 @@
 #ifdef SIGPOLL
 static void handle_SIGPOLL(int sig)
 {
-	if(sig);
+	if (sig);
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Sig Poll!\n");
 	return;
 }
@@ -4456,7 +527,7 @@
 #ifdef SIGIO
 static void handle_SIGIO(int sig)
 {
-	if(sig);
+	if (sig);
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Sig I/O!\n");
 	return;
 }
@@ -4497,7 +568,7 @@
 #ifdef TRAP_BUS
 	signal(SIGBUS, handle_SIGBUS);
 #endif
-	
+
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Bringing up environment.\n");
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Loading Modules.\n");
 	if (switch_loadable_module_init() != SWITCH_STATUS_SUCCESS) {
@@ -4511,26 +582,28 @@
 		switch_event_fire(&event);
 	}
 
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "\nFreeSWITCH Version %s Started.\nCrash Protection [%s]\nMax Sessions[%u]\n\n", SWITCH_VERSION_FULL, __CP, switch_core_session_limit(0));
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE,
+					  "\nFreeSWITCH Version %s Started.\nCrash Protection [%s]\nMax Sessions[%u]\n\n", SWITCH_VERSION_FULL, __CP,
+					  switch_core_session_limit(0));
 	return SWITCH_STATUS_SUCCESS;
 
 }
 
 SWITCH_DECLARE(void) switch_core_measure_time(switch_time_t total_ms, switch_core_time_duration_t *duration)
 {
-    switch_time_t temp = total_ms / 1000;
+	switch_time_t temp = total_ms / 1000;
 	memset(duration, 0, sizeof(*duration));
-	duration->mms = (uint32_t)(total_ms % 1000);
-	duration->ms = (uint32_t)(temp % 1000);
-    temp = temp / 1000;
-    duration->sec = (uint32_t)(temp % 60);
-    temp = temp / 60;
-    duration->min = (uint32_t)(temp % 60);
+	duration->mms = (uint32_t) (total_ms % 1000);
+	duration->ms = (uint32_t) (temp % 1000);
+	temp = temp / 1000;
+	duration->sec = (uint32_t) (temp % 60);
+	temp = temp / 60;
+	duration->min = (uint32_t) (temp % 60);
 	temp = temp / 60;
-	duration->hr = (uint32_t)(temp % 24);
+	duration->hr = (uint32_t) (temp % 24);
 	temp = temp / 24;
-	duration->day = (uint32_t)(temp % 365);
-	duration->yr = (uint32_t)(temp / 365);
+	duration->day = (uint32_t) (temp % 365);
+	duration->yr = (uint32_t) (temp / 365);
 }
 
 SWITCH_DECLARE(switch_time_t) switch_core_uptime(void)
@@ -4538,7 +611,7 @@
 	return switch_time_now() - runtime.initiated;
 }
 
-SWITCH_DECLARE(int32_t) switch_core_session_ctl(switch_session_ctl_t cmd, uint32_t *val)
+SWITCH_DECLARE(int32_t) switch_core_session_ctl(switch_session_ctl_t cmd, uint32_t * val)
 {
 
 	if (runtime.shutting_down) {
@@ -4563,6 +636,12 @@
 	return 0;
 }
 
+SWITCH_DECLARE(switch_bool_t) switch_core_ready(void)
+{
+	return (runtime.shutting_down || runtime.no_new_sessions) ? SWITCH_FALSE : SWITCH_TRUE;
+}
+
+
 SWITCH_DECLARE(switch_status_t) switch_core_destroy(void)
 {
 	switch_event_t *event;
@@ -4573,6 +652,7 @@
 	runtime.shutting_down = 1;
 	runtime.no_new_sessions = 1;
 
+
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "End existing sessions\n");
 	switch_core_session_hupall(SWITCH_CAUSE_SYSTEM_SHUTDOWN);
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Clean up modules.\n");
@@ -4580,53 +660,39 @@
 
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Closing Event Engine.\n");
 	switch_event_shutdown();
-	
-	switch_queue_push(runtime.sql_queue, NULL);
 
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Waiting for unfinished SQL transactions\n");
-	while (switch_queue_size(runtime.sql_queue) > 0) {
-		switch_yield(10000);
-	}
-	switch_core_db_close(runtime.db);
-	switch_core_db_close(runtime.event_db);
+	switch_core_sqldb_stop();
+	switch_scheduler_task_thread_stop();
+
 	switch_xml_destroy();
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Finalizing Shutdown.\n");
 	switch_log_shutdown();
-	
-	if(runtime.console != stdout && runtime.console != stderr) {
+
+
+
+	if (runtime.console != stdout && runtime.console != stderr) {
 		fclose(runtime.console);
 		runtime.console = NULL;
 	}
 
-    switch_yield(1000000);
-
-#ifdef WIN32
-	free(SWITCH_GLOBAL_dirs.base_dir);
-	free(SWITCH_GLOBAL_dirs.mod_dir);
-	free(SWITCH_GLOBAL_dirs.conf_dir);
-	free(SWITCH_GLOBAL_dirs.log_dir);
-	free(SWITCH_GLOBAL_dirs.db_dir);
-	free(SWITCH_GLOBAL_dirs.script_dir);
-	free(SWITCH_GLOBAL_dirs.htdocs_dir);
-	free(SWITCH_GLOBAL_dirs.grammar_dir);
-	free(SWITCH_GLOBAL_dirs.temp_dir);
-#endif
+	switch_safe_free(SWITCH_GLOBAL_dirs.base_dir);
+	switch_safe_free(SWITCH_GLOBAL_dirs.mod_dir);
+	switch_safe_free(SWITCH_GLOBAL_dirs.conf_dir);
+	switch_safe_free(SWITCH_GLOBAL_dirs.log_dir);
+	switch_safe_free(SWITCH_GLOBAL_dirs.db_dir);
+	switch_safe_free(SWITCH_GLOBAL_dirs.script_dir);
+	switch_safe_free(SWITCH_GLOBAL_dirs.htdocs_dir);
+	switch_safe_free(SWITCH_GLOBAL_dirs.grammar_dir);
+	switch_safe_free(SWITCH_GLOBAL_dirs.temp_dir);
 
 	if (runtime.memory_pool) {
 		apr_pool_destroy(runtime.memory_pool);
-		//apr_terminate();
+		/* apr_terminate(); */
 	}
 
 	return SWITCH_STATUS_SUCCESS;
 }
 
-SWITCH_DECLARE(uint8_t) switch_core_session_compare(switch_core_session_t *a, switch_core_session_t *b)
-{
-	assert(a != NULL);
-	assert(b != NULL);
-
-	return (uint8_t)(a->endpoint_interface == b->endpoint_interface);
-}
 
 /* For Emacs:
  * Local Variables:

Modified: freeswitch/branches/cparker/src/switch_event.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_event.c	(original)
+++ freeswitch/branches/cparker/src/switch_event.c	Tue Apr 24 10:14:28 2007
@@ -41,10 +41,10 @@
 static switch_mutex_t *EVENT_QUEUE_HAVEMORE_MUTEX = NULL;
 static switch_thread_cond_t *EVENT_QUEUE_CONDITIONAL = NULL;
 static switch_memory_pool_t *RUNTIME_POOL = NULL;
-//static switch_memory_pool_t *APOOL = NULL;
-//static switch_memory_pool_t *BPOOL = NULL;
+/* static switch_memory_pool_t *APOOL = NULL; */
+/* static switch_memory_pool_t *BPOOL = NULL; */
 static switch_memory_pool_t *THRUNTIME_POOL = NULL;
-static switch_queue_t *EVENT_QUEUE[3] = {0,0,0};
+static switch_queue_t *EVENT_QUEUE[3] = { 0, 0, 0 };
 static int POOL_COUNT_MAX = SWITCH_CORE_QUEUE_LEN;
 
 static switch_hash_t *CUSTOM_HASH = NULL;
@@ -126,12 +126,19 @@
 	"PRESENCE_IN",
 	"PRESENCE_OUT",
 	"PRESENCE_PROBE",
+	"MESSAGE_WAITING",
+	"MESSAGE_QUERY",
 	"ROSTER",
 	"CODEC",
 	"BACKGROUND_JOB",
 	"DETECTED_SPEECH",
 	"PRIVATE_COMMAND",
 	"HEARTBEAT",
+	"TRAP",
+	"ADD_SCHEDULE",
+	"DEL_SCHEDULE",
+	"EXE_SCHEDULE",
+	"RE_SCHEDULE",
 	"ALL"
 };
 
@@ -175,13 +182,13 @@
 	return match;
 }
 
-static void *SWITCH_THREAD_FUNC switch_event_thread(switch_thread_t *thread, void *obj)
+static void *SWITCH_THREAD_FUNC switch_event_thread(switch_thread_t * thread, void *obj)
 {
 	switch_event_t *out_event = NULL;
 	switch_queue_t *queue = NULL;
-	switch_queue_t *queues[3] = {0,0,0};
+	switch_queue_t *queues[3] = { 0, 0, 0 };
 	void *pop;
-	int i, len[3] = {0,0,0};
+	int i, len[3] = { 0, 0, 0 };
 
 	assert(thread != NULL);
 	assert(obj == NULL);
@@ -191,14 +198,14 @@
 	assert(EVENT_QUEUE_HAVEMORE_MUTEX != NULL);
 	assert(EVENT_QUEUE_CONDITIONAL != NULL);
 	THREAD_RUNNING = 1;
-	
+
 	queues[0] = EVENT_QUEUE[SWITCH_PRIORITY_HIGH];
 	queues[1] = EVENT_QUEUE[SWITCH_PRIORITY_NORMAL];
 	queues[2] = EVENT_QUEUE[SWITCH_PRIORITY_LOW];
 
 	switch_mutex_lock(EVENT_QUEUE_MUTEX);
-	
-	for(;;) {
+
+	for (;;) {
 		int any;
 
 
@@ -207,43 +214,45 @@
 		len[0] = switch_queue_size(EVENT_QUEUE[SWITCH_PRIORITY_HIGH]);
 		any = len[1] + len[2] + len[0];
 
-	
+
 		if (!any) {
-			//lock on havemore so we are the only ones poking at it while we check it
-			//see if we saw anything in the queues or have a check again flag
+			/* lock on havemore so we are the only ones poking at it while we check it
+			 * see if we saw anything in the queues or have a check again flag
+			 */
 			switch_mutex_lock(EVENT_QUEUE_HAVEMORE_MUTEX);
-			if(!EVENT_QUEUE_HAVEMORE) {
-				//See if we need to quit
+			if (!EVENT_QUEUE_HAVEMORE) {
+				/* See if we need to quit */
 				if (THREAD_RUNNING != 1) {
-					//give up our lock
+					/* give up our lock */
 					switch_mutex_unlock(EVENT_QUEUE_HAVEMORE_MUTEX);
 
-					//Game over
+					/* game over */
 					break;
 				}
 
-				//give up our lock
+				/* give up our lock */
 				switch_mutex_unlock(EVENT_QUEUE_HAVEMORE_MUTEX);
 
-				//wait until someone tells us we have something to do
+				/* wait until someone tells us we have something to do */
 				switch_thread_cond_wait(EVENT_QUEUE_CONDITIONAL, EVENT_QUEUE_MUTEX);
 			} else {
-				//Caught a race, one of the queues was updated after we looked at it
-				//reset our flag
+				/* Caught a race, one of the queues was updated after we looked at it 
+				 * reset our flag
+				 */
 				EVENT_QUEUE_HAVEMORE = 0;
 
-				//Give up our lock
+				/* give up our lock */
 				switch_mutex_unlock(EVENT_QUEUE_HAVEMORE_MUTEX);
 			}
 
-			//go grab some events
+			/* go grab some events */
 			continue;
 		}
 
-		for(i = 0; i < 3; i++) {
+		for (i = 0; i < 3; i++) {
 			if (len[i]) {
 				queue = queues[i];
-				while(queue) {
+				while (queue) {
 					if (switch_queue_trypop(queue, &pop) == SWITCH_STATUS_SUCCESS) {
 						out_event = pop;
 						switch_event_deliver(&out_event);
@@ -304,14 +313,14 @@
 	switch_event_types_t x;
 	assert(BLOCK != NULL);
 	assert(RUNTIME_POOL != NULL);
-	
+
 	for (x = 0; x <= SWITCH_EVENT_ALL; x++) {
-		if (!strcasecmp(name, EVENT_NAMES[x])) {
+		if ((strlen(name) > 13 && !strcasecmp(name + 13, EVENT_NAMES[x])) || !strcasecmp(name, EVENT_NAMES[x])) {
 			*type = x;
 			return SWITCH_STATUS_SUCCESS;
 		}
 	}
-	
+
 	return SWITCH_STATUS_FALSE;
 
 }
@@ -348,24 +357,27 @@
 	if (THREAD_RUNNING > 0) {
 		THREAD_RUNNING = -1;
 
-		//Lock on havemore to make sure he event thread, if currently running
-		// doesn't check the HAVEMORE flag before we set it
+		/* lock on havemore to make sure he event thread, if currently running
+		 * doesn't check the HAVEMORE flag before we set it
+		 */
 		switch_mutex_lock(EVENT_QUEUE_HAVEMORE_MUTEX);
-		//See if the event thread is sitting
-		if(switch_mutex_trylock(EVENT_QUEUE_MUTEX) == SWITCH_STATUS_SUCCESS) {
-			//we don't need havemore anymore, the thread was sitting already
+		/* see if the event thread is sitting */
+		if (switch_mutex_trylock(EVENT_QUEUE_MUTEX) == SWITCH_STATUS_SUCCESS) {
+			/* we don't need havemore anymore, the thread was sitting already */
 			switch_mutex_unlock(EVENT_QUEUE_HAVEMORE_MUTEX);
 
-			//wake up the event thread
+			/* wake up the event thread */
 			switch_thread_cond_signal(EVENT_QUEUE_CONDITIONAL);
 
-			//give up our lock
+			/* give up our lock */
 			switch_mutex_unlock(EVENT_QUEUE_MUTEX);
-		} else { // it wasn't waiting which means we might have updated a queue it already looked at
-			//set a flag so it knows to read the queues again
+		} else {
+			/* it wasn't waiting which means we might have updated a queue it already looked at
+			 * set a flag so it knows to read the queues again
+			 */
 			EVENT_QUEUE_HAVEMORE = 1;
 
-			//variable updated, give up the mutex
+			/* variable updated, give up the mutex */
 			switch_mutex_unlock(EVENT_QUEUE_HAVEMORE_MUTEX);
 		}
 
@@ -388,20 +400,21 @@
 	switch_threadattr_detach_set(thd_attr, 1);
 
 	assert(pool != NULL);
-	RUNTIME_POOL = pool;
-
+	THRUNTIME_POOL = RUNTIME_POOL = pool;
 
+	/*
 	if (switch_core_new_memory_pool(&THRUNTIME_POOL) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Could not allocate memory pool\n");
 		return SWITCH_STATUS_MEMERR;
 	}
-	/*
-	if (switch_core_new_memory_pool(&BPOOL) != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Could not allocate memory pool\n");
-		return SWITCH_STATUS_MEMERR;
-	}
 	*/
-	//THRUNTIME_POOL = APOOL;
+	/*
+	   if (switch_core_new_memory_pool(&BPOOL) != SWITCH_STATUS_SUCCESS) {
+	   switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Could not allocate memory pool\n");
+	   return SWITCH_STATUS_MEMERR;
+	   }
+	 */
+	/* THRUNTIME_POOL = APOOL; */
 	switch_queue_create(&EVENT_QUEUE[0], POOL_COUNT_MAX + 10, THRUNTIME_POOL);
 	switch_queue_create(&EVENT_QUEUE[1], POOL_COUNT_MAX + 10, THRUNTIME_POOL);
 	switch_queue_create(&EVENT_QUEUE[2], POOL_COUNT_MAX + 10, THRUNTIME_POOL);
@@ -423,9 +436,7 @@
 
 }
 
-SWITCH_DECLARE(switch_status_t) switch_event_create_subclass(switch_event_t **event,
-														   switch_event_types_t event_id,
-														   const char *subclass_name)
+SWITCH_DECLARE(switch_status_t) switch_event_create_subclass(switch_event_t **event, switch_event_types_t event_id, const char *subclass_name)
 {
 
 	if (event_id != SWITCH_EVENT_CUSTOM && subclass_name) {
@@ -476,8 +487,7 @@
 	return NULL;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_event_add_header(switch_event_t *event, switch_stack_t stack, const char *header_name,
-													  const char *fmt, ...)
+SWITCH_DECLARE(switch_status_t) switch_event_add_header(switch_event_t *event, switch_stack_t stack, const char *header_name, const char *fmt, ...)
 {
 	int ret = 0;
 	char data[2048];
@@ -526,12 +536,7 @@
 	va_list ap;
 	if (fmt) {
 		va_start(ap, fmt);
-#ifdef HAVE_VASPRINTF
-		ret = vasprintf(&data, fmt, ap);
-#else
-		data = (char *) malloc(2048);
-		ret = vsnprintf(data, 2048, fmt, ap);
-#endif
+		ret = switch_vasprintf(&data, fmt, ap);
 		va_end(ap);
 
 		if (ret == -1) {
@@ -612,8 +617,8 @@
 	switch_event_header_t *hp;
 	switch_size_t llen = 0, dlen = 0, blocksize = 512, encode_len = 1536, new_len = 0;
 	char *buf;
-    char *encode_buf = NULL; /* used for url encoding of variables to make sure unsafe things stay out of the serialzed copy */
-	
+	char *encode_buf = NULL;	/* used for url encoding of variables to make sure unsafe things stay out of the serialzed copy */
+
 	*str = NULL;
 
 	dlen = blocksize * 2;
@@ -622,55 +627,55 @@
 		return SWITCH_STATUS_MEMERR;
 	}
 
-    /* go ahead and give ourselves some space to work with, should save a few reallocs */
-    if(!(encode_buf = malloc(encode_len))) {
-        return SWITCH_STATUS_MEMERR;
-    }
+	/* go ahead and give ourselves some space to work with, should save a few reallocs */
+	if (!(encode_buf = malloc(encode_len))) {
+		return SWITCH_STATUS_MEMERR;
+	}
 
-    //switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "hit serialze!.\n");
+	/* switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "hit serialze!.\n"); */
 	for (hp = event->headers; hp; hp = hp->next) {
-        /*
-         * grab enough memory to store 3x the string (url encode takes one char and turns it into %XX)
-         * so we could end up with a string that is 3 times the original's length, unlikely but rather
-         * be safe than destroy the string, also add one for the null.  And try to be smart about using 
-         * the memory, allocate and only reallocate if we need more.  This avoids an alloc, free CPU
-         * destroying loop.
-         */
-
-        new_len = (strlen(hp->value) * 3) + 1;
-
-        if(encode_len < new_len) {
-            char* tmp;
-	        //switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Allocing %d was %d.\n", ((strlen(hp->value) * 3) + 1), encode_len);
-            /* we can use realloc for initial alloc as well, if encode_buf is zero it treats it as a malloc */
-
-            /* keep track of the size of our allocation */
-            encode_len = new_len;
-            
-            if(!(tmp = realloc(encode_buf, encode_len))) {
-                /* oh boy, ram's gone, give back what little we grabbed and bail */
-                switch_safe_free(buf);
-                switch_safe_free(encode_buf);
-                return SWITCH_STATUS_MEMERR;
-            }
-            
-            encode_buf = tmp;
-        }
+		/*
+		 * grab enough memory to store 3x the string (url encode takes one char and turns it into %XX)
+		 * so we could end up with a string that is 3 times the original's length, unlikely but rather
+		 * be safe than destroy the string, also add one for the null.  And try to be smart about using 
+		 * the memory, allocate and only reallocate if we need more.  This avoids an alloc, free CPU
+		 * destroying loop.
+		 */
+
+		new_len = (strlen(hp->value) * 3) + 1;
+
+		if (encode_len < new_len) {
+			char *tmp;
+			/* switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Allocing %d was %d.\n", ((strlen(hp->value) * 3) + 1), encode_len); */
+			/* we can use realloc for initial alloc as well, if encode_buf is zero it treats it as a malloc */
+
+			/* keep track of the size of our allocation */
+			encode_len = new_len;
+
+			if (!(tmp = realloc(encode_buf, encode_len))) {
+				/* oh boy, ram's gone, give back what little we grabbed and bail */
+				switch_safe_free(buf);
+				switch_safe_free(encode_buf);
+				return SWITCH_STATUS_MEMERR;
+			}
+
+			encode_buf = tmp;
+		}
 
-        /* handle any bad things in the string like newlines : etc that screw up the serialized format */
-        switch_url_encode(hp->value, encode_buf, encode_len - 1);
+		/* handle any bad things in the string like newlines : etc that screw up the serialized format */
+		switch_url_encode(hp->value, encode_buf, encode_len - 1);
 
 		llen = strlen(hp->name) + strlen(encode_buf) + 8;
-		
+
 		if ((len + llen) > dlen) {
 			char *m;
 			dlen += (blocksize + (len + llen));
 			if ((m = realloc(buf, dlen))) {
 				buf = m;
 			} else {
-                /* we seem to be out of memory trying to resize the serialize string, give back what we already have and give up */
+				/* we seem to be out of memory trying to resize the serialize string, give back what we already have and give up */
 				switch_safe_free(buf);
-                switch_safe_free(encode_buf);
+				switch_safe_free(encode_buf);
 				return SWITCH_STATUS_MEMERR;
 			}
 		}
@@ -680,8 +685,8 @@
 
 	}
 
-    /* we are done with the memory we used for encoding, give it back */
-    switch_safe_free(encode_buf);
+	/* we are done with the memory we used for encoding, give it back */
+	switch_safe_free(encode_buf);
 
 	if (event->body) {
 		int blen = (int) strlen(event->body);
@@ -692,7 +697,7 @@
 		} else {
 			llen += 5;
 		}
-		
+
 		if ((len + llen) > dlen) {
 			char *m;
 			dlen += (blocksize + (len + llen));
@@ -703,7 +708,7 @@
 				return SWITCH_STATUS_MEMERR;
 			}
 		}
-		
+
 		if (blen) {
 			snprintf(buf + len, dlen - len, "Content-Length: %d\n\n%s", blen, event->body);
 		} else {
@@ -714,7 +719,7 @@
 	}
 
 	*str = buf;
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -725,13 +730,13 @@
 
 	if ((header = switch_xml_add_child_d(xml, "header", offset))) {
 		switch_xml_set_attr_d(header, "name", name);
-		switch_xml_set_attr_d(header, "value", value);	
+		switch_xml_set_attr_d(header, "value", value);
 	}
 
 	return header;
 }
 
-SWITCH_DECLARE(switch_xml_t) switch_event_xmlize(switch_event_t *event, const char *fmt, ...)
+SWITCH_DECLARE(switch_xml_t) switch_event_xmlize(switch_event_t *event, const char *fmt,...)
 {
 	switch_event_header_t *hp;
 	char *data = NULL, *body = NULL;
@@ -758,7 +763,7 @@
 		}
 	}
 
-	
+
 	for (hp = event->headers; hp; hp = hp->next) {
 		add_xml_header(xml, hp->name, hp->value, off++);
 	}
@@ -782,7 +787,7 @@
 			}
 		}
 	}
-	
+
 	if (data) {
 		free(data);
 	}
@@ -791,8 +796,7 @@
 }
 
 
-SWITCH_DECLARE(switch_status_t) switch_event_fire_detailed(char *file, char *func, int line, switch_event_t **event,
-														 void *user_data)
+SWITCH_DECLARE(switch_status_t) switch_event_fire_detailed(char *file, char *func, int line, switch_event_t **event, void *user_data)
 {
 
 	switch_time_exp_t tm;
@@ -834,35 +838,38 @@
 
 	switch_queue_push(EVENT_QUEUE[(*event)->priority], *event);
 
-	//Lock on havemore to make sure he event thread, if currently running
-	// doesn't check the HAVEMORE flag before we set it
+	/* lock on havemore to make sure he event thread, if currently running
+	 * doesn't check the HAVEMORE flag before we set it
+	 */
 	switch_mutex_lock(EVENT_QUEUE_HAVEMORE_MUTEX);
-	//See if the event thread is sitting
-	if(switch_mutex_trylock(EVENT_QUEUE_MUTEX) == SWITCH_STATUS_SUCCESS) {
-		//we don't need havemore anymore, the thread was sitting already
+	/* see if the event thread is sitting */
+	if (switch_mutex_trylock(EVENT_QUEUE_MUTEX) == SWITCH_STATUS_SUCCESS) {
+		/* we don't need havemore anymore, the thread was sitting already */
 		switch_mutex_unlock(EVENT_QUEUE_HAVEMORE_MUTEX);
 
-		//wake up the event thread
+		/* wake up the event thread */
 		switch_thread_cond_signal(EVENT_QUEUE_CONDITIONAL);
 
-		//give up our lock
+		/* give up our lock */
 		switch_mutex_unlock(EVENT_QUEUE_MUTEX);
-	} else { // it wasn't waiting which means we might have updated a queue it already looked at
-		//set a flag so it knows to read the queues again
+	} else {
+		/* it wasn't waiting which means we might have updated a queue it already looked at
+		 * set a flag so it knows to read the queues again
+		 */
 		EVENT_QUEUE_HAVEMORE = 1;
 
-		//variable updated, give up the mutex
+		/* variable updated, give up the mutex */
 		switch_mutex_unlock(EVENT_QUEUE_HAVEMORE_MUTEX);
 	}
-		
+
 
 	*event = NULL;
 
 	return SWITCH_STATUS_SUCCESS;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_event_bind(char *id, switch_event_types_t event, char *subclass_name,
-												switch_event_callback_t callback, void *user_data)
+SWITCH_DECLARE(switch_status_t) switch_event_bind(char *id, switch_event_types_t event, char *subclass_name, switch_event_callback_t callback,
+												  void *user_data)
 {
 	switch_event_node_t *event_node;
 	switch_event_subclass_t *subclass = NULL;

Modified: freeswitch/branches/cparker/src/switch_ivr.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_ivr.c	(original)
+++ freeswitch/branches/cparker/src/switch_ivr.c	Tue Apr 24 10:14:28 2007
@@ -34,15 +34,8 @@
  */
 #include <switch.h>
 #include <switch_ivr.h>
-#include <libteletone.h>
 
-static const switch_state_handler_table_t audio_bridge_peer_state_handlers;
-static const switch_state_handler_table_t originate_state_handlers;
 
-typedef enum {
-	IDX_CANCEL = -2,
-	IDX_NADA = -1
-} abort_t;
 
 SWITCH_DECLARE(switch_status_t) switch_ivr_sleep(switch_core_session_t *session, uint32_t ms)
 {
@@ -51,15 +44,15 @@
 	switch_time_t start, now, done = switch_time_now() + (ms * 1000);
 	switch_frame_t *read_frame;
 	int32_t left, elapsed;
-	
+
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 	start = switch_time_now();
 
-	for(;;) {
+	for (;;) {
 		now = switch_time_now();
-		elapsed = (int32_t)((now - start) / 1000);
+		elapsed = (int32_t) ((now - start) / 1000);
 		left = ms - elapsed;
 
 		if (!switch_channel_ready(channel)) {
@@ -71,8 +64,8 @@
 			break;
 		}
 
-		if (switch_channel_test_flag(channel, CF_SERVICE) || 
-            (!switch_channel_test_flag(channel, CF_ANSWERED) && !switch_channel_test_flag(channel, CF_EARLY_MEDIA))) {
+		if (switch_channel_test_flag(channel, CF_SERVICE) ||
+			(!switch_channel_test_flag(channel, CF_ANSWERED) && !switch_channel_test_flag(channel, CF_EARLY_MEDIA))) {
 			switch_yield(1000);
 		} else {
 			status = switch_core_session_read_frame(session, &read_frame, left, 0);
@@ -81,65 +74,287 @@
 			}
 		}
 	}
-	
+
 
 	return status;
 }
 
 
+static void *SWITCH_THREAD_FUNC unicast_thread_run(switch_thread_t *thread, void *obj)
+{
+	switch_unicast_conninfo_t *conninfo = (switch_unicast_conninfo_t *) obj;
+	switch_size_t len;
+	switch_channel_t *channel;
+
+	if (!conninfo) {
+		return NULL;
+	}
+
+	channel = switch_core_session_get_channel(conninfo->session);
+	
+	while(switch_test_flag(conninfo, SUF_READY) && switch_test_flag(conninfo, SUF_THREAD_RUNNING)) {
+		len = conninfo->write_frame.buflen;
+		if (switch_socket_recv(conninfo->socket, conninfo->write_frame.data, &len) != SWITCH_STATUS_SUCCESS || len == 0) {
+			break;
+		}
+		conninfo->write_frame.datalen = (uint32_t)len;
+		conninfo->write_frame.samples = conninfo->write_frame.datalen / 2;
+		switch_core_session_write_frame(conninfo->session, &conninfo->write_frame, -1, conninfo->stream_id);
+	}
+	
+	switch_clear_flag_locked(conninfo, SUF_READY);
+	switch_clear_flag_locked(conninfo, SUF_THREAD_RUNNING);
+
+	return NULL;
+}
+
+static void unicast_thread_launch(switch_unicast_conninfo_t *conninfo)
+{
+	switch_thread_t *thread;
+	switch_threadattr_t *thd_attr = NULL;
+
+	switch_threadattr_create(&thd_attr, switch_core_session_get_pool(conninfo->session));
+	switch_threadattr_detach_set(thd_attr, 1);
+	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
+	switch_set_flag_locked(conninfo, SUF_THREAD_RUNNING);
+	switch_thread_create(&thread, thd_attr, unicast_thread_run, conninfo, switch_core_session_get_pool(conninfo->session));
+}
+
+SWITCH_DECLARE(switch_status_t) switch_ivr_deactivate_unicast(switch_core_session_t *session)
+{
+	switch_channel_t *channel;
+	switch_unicast_conninfo_t *conninfo;
+	int sanity = 0;
+	
+	channel = switch_core_session_get_channel(session);
+    assert(channel != NULL);
+
+	if (switch_channel_test_flag(channel, CF_UNICAST)) {
+		if ((conninfo = switch_channel_get_private(channel, "unicast"))) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Shutting down unicast connection\n");
+			switch_clear_flag_locked(conninfo, SUF_READY);
+			switch_socket_shutdown(conninfo->socket, SWITCH_SHUTDOWN_READWRITE);
+			while(switch_test_flag(conninfo, SUF_THREAD_RUNNING)) {
+				switch_yield(10000);
+				if (++sanity >= 10000) {
+					break;
+				}
+			}
+			if (conninfo->read_codec.implementation) {
+				switch_core_codec_destroy(&conninfo->read_codec);
+			}
+			switch_socket_close(conninfo->socket);
+		}
+		switch_channel_clear_flag(channel, CF_UNICAST);
+		return SWITCH_STATUS_SUCCESS;
+	}
+	
+	return SWITCH_STATUS_FALSE;
+	
+}
+
+SWITCH_DECLARE(switch_status_t) switch_ivr_activate_unicast(switch_core_session_t *session, 
+															char *local_ip,
+															switch_port_t local_port,
+															char *remote_ip,
+															switch_port_t remote_port,
+															char *transport,
+															char *flags)
+{
+	switch_channel_t *channel;
+	switch_unicast_conninfo_t *conninfo;
+	switch_codec_t *read_codec;
+
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
+
+	conninfo = switch_core_session_alloc(session, sizeof(*conninfo));
+	assert(conninfo != NULL);
+
+	conninfo->local_ip = switch_core_session_strdup(session, local_ip);
+	conninfo->local_port = local_port;
+
+	conninfo->remote_ip = switch_core_session_strdup(session, remote_ip);
+	conninfo->remote_port = remote_port;
+	conninfo->session = session;
+	
+	if (!strcasecmp(transport, "udp")) {
+		conninfo->type = AF_INET;
+		conninfo->transport = SOCK_DGRAM;
+	} else if (!strcasecmp(transport, "tcp")) {
+		conninfo->type = AF_INET;
+		conninfo->transport = SOCK_STREAM;
+	} else {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid transport %s\n", transport);
+		goto fail;
+	}
+
+	if (flags) {
+		if (strstr(flags, "native")) {
+			switch_set_flag(conninfo, SUF_NATIVE);
+		}
+	}
+
+	switch_mutex_init(&conninfo->flag_mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
+	
+	read_codec = switch_core_session_get_read_codec(session);
+	
+	if (!switch_test_flag(conninfo, SUF_NATIVE)) {
+		if (switch_core_codec_init(&conninfo->read_codec,
+								   "L16",
+								   NULL,
+								   read_codec->implementation->samples_per_second,
+								   read_codec->implementation->microseconds_per_frame / 1000,
+								   1, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
+								   NULL, switch_core_session_get_pool(session)) == SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
+							  "Raw Codec Activation Success L16@%uhz 1 channel %dms\n",
+							  read_codec->implementation->samples_per_second, read_codec->implementation->microseconds_per_frame / 1000);
+		} else {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Failed L16@%uhz 1 channel %dms\n",
+							  read_codec->implementation->samples_per_second, read_codec->implementation->microseconds_per_frame / 1000);
+			goto fail;
+		}
+	}
+
+	conninfo->write_frame.data = conninfo->write_frame_data;
+	conninfo->write_frame.buflen = sizeof(conninfo->write_frame_data);
+	conninfo->write_frame.codec = switch_test_flag(conninfo, SUF_NATIVE) ? read_codec : &conninfo->read_codec;
+	
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "connect %s:%d->%s:%d\n",
+					  conninfo->local_ip, conninfo->local_port, conninfo->remote_ip, conninfo->remote_port);
+
+	if (switch_sockaddr_info_get(&conninfo->local_addr,
+								 conninfo->local_ip, SWITCH_UNSPEC, conninfo->local_port, 0, 
+								 switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
+		goto fail;
+	}
+	
+	if (switch_sockaddr_info_get(&conninfo->remote_addr, 
+								 conninfo->remote_ip, SWITCH_UNSPEC, conninfo->remote_port, 0,
+								 switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
+		goto fail;
+	}
+	
+	if (switch_socket_create(&conninfo->socket, AF_INET, SOCK_DGRAM, 0, switch_core_session_get_pool(session)) == SWITCH_STATUS_SUCCESS) {
+		if (switch_socket_bind(conninfo->socket, conninfo->local_addr) != SWITCH_STATUS_SUCCESS) {
+			goto fail;
+		}
+	} else {
+		goto fail;
+	}
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Created unicast connection %s:%d->%s:%d\n",
+					  conninfo->local_ip, conninfo->local_port, conninfo->remote_ip, conninfo->remote_port);
+	switch_channel_set_private(channel, "unicast", conninfo);
+	switch_channel_set_flag(channel, CF_UNICAST);
+	switch_set_flag_locked(conninfo, SUF_READY);
+	return SWITCH_STATUS_SUCCESS;
+
+ fail:
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Failure creating unicast connection %s:%d->%s:%d\n",
+					  conninfo->local_ip, conninfo->local_port, conninfo->remote_ip, conninfo->remote_port);
+	return SWITCH_STATUS_FALSE;	
+
+
+}
+
 SWITCH_DECLARE(switch_status_t) switch_ivr_parse_event(switch_core_session_t *session, switch_event_t *event)
 {
 	switch_channel_t *channel = switch_core_session_get_channel(session);
 	char *cmd = switch_event_get_header(event, "call-command");
 	unsigned long cmd_hash;
-	apr_ssize_t hlen = APR_HASH_KEY_STRING;
-	unsigned long CMD_EXECUTE = apr_hashfunc_default("execute", &hlen);
-	unsigned long CMD_HANGUP = apr_hashfunc_default("hangup", &hlen);
-	unsigned long CMD_NOMEDIA = apr_hashfunc_default("nomedia", &hlen);
-	
-    assert(channel != NULL);
+	switch_ssize_t hlen = SWITCH_HASH_KEY_STRING;
+	unsigned long CMD_EXECUTE = switch_hashfunc_default("execute", &hlen);
+	unsigned long CMD_HANGUP = switch_hashfunc_default("hangup", &hlen);
+	unsigned long CMD_NOMEDIA = switch_hashfunc_default("nomedia", &hlen);
+	unsigned long CMD_UNICAST = switch_hashfunc_default("unicast", &hlen);
+
+	assert(channel != NULL);
 	assert(event != NULL);
 
 	if (switch_strlen_zero(cmd)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Command!\n");
-        return SWITCH_STATUS_FALSE;
-    }
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Command!\n");
+		return SWITCH_STATUS_FALSE;
+	}
 
 	hlen = (switch_size_t) strlen(cmd);
-	cmd_hash = apr_hashfunc_default(cmd, &hlen);
+	cmd_hash = switch_hashfunc_default(cmd, &hlen);
 
 	switch_channel_set_flag(channel, CF_EVENT_PARSE);
-	
 
-    if (cmd_hash == CMD_EXECUTE) {
-        const switch_application_interface_t *application_interface;
-        char *app_name = switch_event_get_header(event, "execute-app-name");
-        char *app_arg = switch_event_get_header(event, "execute-app-arg");
-						
-        if (app_name && app_arg) {
-            if ((application_interface = switch_loadable_module_get_application_interface(app_name))) {
-                if (application_interface->application_function) {
-                    application_interface->application_function(session, app_arg);
-                }
-            }
-        }
-    } else if (cmd_hash == CMD_HANGUP) {
-        char *cause_name = switch_event_get_header(event, "hangup-cause");
-        switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
-
-        if (cause_name) {
-            cause = switch_channel_str2cause(cause_name);
-        }
-
-        switch_channel_hangup(channel, cause);
-    } else if (cmd_hash == CMD_NOMEDIA) {
-        char *uuid = switch_event_get_header(event, "nomedia-uuid");
-        switch_ivr_nomedia(uuid, SMF_REBRIDGE);
-    } 
-	
+
+	if (cmd_hash == CMD_EXECUTE) {
+		const switch_application_interface_t *application_interface;
+		char *app_name = switch_event_get_header(event, "execute-app-name");
+		char *app_arg = switch_event_get_header(event, "execute-app-arg");
+		char *loop_h = switch_event_get_header(event, "loops");
+		int loops = 1;
+	
+		if (loop_h) {
+			loops = atoi(loop_h);
+		}
+
+		if (app_name && app_arg) {
+			if ((application_interface = switch_loadable_module_get_application_interface(app_name))) {
+				if (application_interface->application_function) {
+					int x;
+					switch_channel_set_flag(channel, CF_BROADCAST);
+					for (x = 0; x < loops || loops < 0; x++) {
+						switch_core_session_exec(session, application_interface, app_arg);
+						if (!switch_channel_test_flag(channel, CF_BROADCAST)) {
+							break;
+						}
+					}
+					switch_channel_clear_flag(channel, CF_BROADCAST);					
+				}
+			}
+		}
+	} else if (cmd_hash == CMD_UNICAST) {
+		char *local_ip = switch_event_get_header(event, "local_ip");
+		char *local_port = switch_event_get_header(event, "local_port");
+		char *remote_ip = switch_event_get_header(event, "remote_ip");
+		char *remote_port = switch_event_get_header(event, "remote_port");
+		char *transport = switch_event_get_header(event, "transport");
+		char *flags = switch_event_get_header(event, "flags");
+
+		if (switch_strlen_zero(local_ip)) {
+			local_ip = "127.0.0.1";
+		}
+		if (switch_strlen_zero(remote_ip)) {
+			remote_ip = "127.0.0.1";
+		}
+		if (switch_strlen_zero(local_port)) {
+			local_port = "8025";
+		}
+		if (switch_strlen_zero(remote_port)) {
+			remote_port = "8026";
+		}
+		if (switch_strlen_zero(transport)) {
+			transport = "udp";
+		}
+
+		switch_ivr_activate_unicast(session, local_ip, (switch_port_t)atoi(local_port), remote_ip, (switch_port_t)atoi(remote_port), transport, flags);
+
+	} else if (cmd_hash == CMD_HANGUP) {
+		char *cause_name = switch_event_get_header(event, "hangup-cause");
+		switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
+
+		if (cause_name) {
+			cause = switch_channel_str2cause(cause_name);
+		}
+
+		switch_channel_hangup(channel, cause);
+	} else if (cmd_hash == CMD_NOMEDIA) {
+		char *uuid = switch_event_get_header(event, "nomedia-uuid");
+		switch_ivr_nomedia(uuid, SMF_REBRIDGE);
+	}
+
 
 	switch_channel_clear_flag(channel, CF_EVENT_PARSE);
-    return SWITCH_STATUS_SUCCESS;
+	return SWITCH_STATUS_SUCCESS;
 
 }
 
@@ -147,12 +362,13 @@
 {
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
 	switch_channel_t *channel;
-	switch_frame_t *frame;
+	switch_frame_t *read_frame;
 	int stream_id = 0;
 	switch_event_t *event;
-	
+	switch_unicast_conninfo_t *conninfo = NULL;
+	switch_codec_t *read_codec = switch_core_session_get_read_codec(session);
 	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);	
+	assert(channel != NULL);
 
 	switch_channel_answer(channel);
 
@@ -163,29 +379,95 @@
 
 	switch_channel_set_flag(channel, CF_CONTROLLED);
 	while (switch_channel_ready(channel) && switch_channel_test_flag(channel, CF_CONTROLLED)) {
-        
-        if ((status = switch_core_session_read_frame(session, &frame, -1, stream_id)) == SWITCH_STATUS_SUCCESS) {
-            if (!SWITCH_READ_ACCEPTABLE(status)) {
-                break;
-            }
-            
-            if (switch_core_session_dequeue_private_event(session, &event) == SWITCH_STATUS_SUCCESS) {
-                switch_ivr_parse_event(session, event);
+
+		if ((status = switch_core_session_read_frame(session, &read_frame, -1, stream_id)) == SWITCH_STATUS_SUCCESS) {
+			if (!SWITCH_READ_ACCEPTABLE(status)) {
+				break;
+			}
+			
+			if (switch_channel_test_flag(channel, CF_UNICAST)) {
+				if (!conninfo) {
+					if (!(conninfo = switch_channel_get_private(channel, "unicast"))) {
+						switch_channel_clear_flag(channel, CF_UNICAST);
+					}
+					
+					if (conninfo) {
+						unicast_thread_launch(conninfo);
+					}
+				}
+				
+				if (conninfo) {
+					switch_size_t len = 0;
+					uint32_t flags = 0;
+					switch_byte_t decoded[SWITCH_RECOMMENDED_BUFFER_SIZE];
+					uint32_t rate = read_codec->implementation->samples_per_second;
+					uint32_t dlen = sizeof(decoded);
+					switch_status_t status;
+					switch_byte_t *sendbuf = NULL;
+					uint32_t sendlen = 0;
+
+					if (switch_test_flag(read_frame, SFF_CNG)) {
+						sendlen = read_codec->implementation->bytes_per_frame;
+						memset(decoded, 255, sendlen);
+						sendbuf = decoded;
+						status = SWITCH_STATUS_SUCCESS;
+					} else {
+						if (switch_test_flag(conninfo, SUF_NATIVE)) {
+							status = SWITCH_STATUS_NOOP;
+						} else {
+							status = switch_core_codec_decode(
+															  read_codec,
+															  &conninfo->read_codec,
+															  read_frame->data,
+															  read_frame->datalen,
+															  read_codec->implementation->samples_per_second,
+															  decoded, &dlen, &rate, &flags);
+						}
+						switch (status) {
+						case SWITCH_STATUS_NOOP:
+						case SWITCH_STATUS_BREAK:
+							sendbuf = read_frame->data;
+							sendlen = read_frame->datalen;
+							status = SWITCH_STATUS_SUCCESS;
+							break;
+						case SWITCH_STATUS_SUCCESS:
+							sendbuf = decoded;
+							sendlen = dlen;
+							status = SWITCH_STATUS_SUCCESS;
+							break;
+						default:
+							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Codec Error\n");
+							switch_ivr_deactivate_unicast(session);
+							break;
+						}
+					}
+
+					if (status == SWITCH_STATUS_SUCCESS) {
+						len = sendlen;
+						if (switch_socket_sendto(conninfo->socket, conninfo->remote_addr, 0, (void *)sendbuf, &len) != SWITCH_STATUS_SUCCESS) {
+							switch_ivr_deactivate_unicast(session);
+						}
+					}
+				}
+			}
+			
+			if (switch_core_session_dequeue_private_event(session, &event) == SWITCH_STATUS_SUCCESS) {
+				switch_ivr_parse_event(session, event);
 				switch_channel_event_set_data(switch_core_session_get_channel(session), event);
-                switch_event_fire(&event);
-            }
+				switch_event_fire(&event);
+			}
 
 			if (switch_channel_has_dtmf(channel)) {
-                char dtmf[128];
-                switch_channel_dequeue_dtmf(channel, dtmf, sizeof(dtmf));
+				char dtmf[128];
+				switch_channel_dequeue_dtmf(channel, dtmf, sizeof(dtmf));
 				if (args && args->input_callback) {
 					if ((status = args->input_callback(session, dtmf, SWITCH_INPUT_TYPE_DTMF, args->buf, args->buflen)) != SWITCH_STATUS_SUCCESS) {
 						break;
 					}
 				}
-            }
+			}
 
-            if (switch_core_session_dequeue_event(session, &event) == SWITCH_STATUS_SUCCESS) {
+			if (switch_core_session_dequeue_event(session, &event) == SWITCH_STATUS_SUCCESS) {
 				if (args && args->input_callback) {
 					if ((status = args->input_callback(session, event, SWITCH_INPUT_TYPE_EVENT, args->buf, args->buflen)) != SWITCH_STATUS_SUCCESS) {
 						break;
@@ -194,9 +476,9 @@
 					switch_channel_event_set_data(channel, event);
 					switch_event_fire(&event);
 				}
-            }
-        }
-		
+			}
+		}
+
 	}
 	switch_channel_clear_flag(channel, CF_CONTROLLED);
 
@@ -205,12 +487,14 @@
 		switch_event_fire(&event);
 	}
 
+	if (switch_channel_test_flag(channel, CF_UNICAST)) {
+		switch_ivr_deactivate_unicast(session);
+	}
+
 	return status;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_collect_digits_callback(switch_core_session_t *session,
-                                                                   switch_input_args_t *args,
-																   uint32_t timeout)
+SWITCH_DECLARE(switch_status_t) switch_ivr_collect_digits_callback(switch_core_session_t *session, switch_input_args_t *args, uint32_t timeout)
 {
 	switch_channel_t *channel;
 	switch_status_t status = SWITCH_STATUS_SUCCESS;
@@ -228,13 +512,13 @@
 		started = switch_time_now();
 	}
 
-	while(switch_channel_ready(channel)) {
+	while (switch_channel_ready(channel)) {
 		switch_frame_t *read_frame;
 		switch_event_t *event;
 		char dtmf[128];
 
 		if (timeout) {
-			elapsed = (uint32_t)((switch_time_now() - started) / 1000);
+			elapsed = (uint32_t) ((switch_time_now() - started) / 1000);
 			if (elapsed >= timeout) {
 				break;
 			}
@@ -251,7 +535,7 @@
 		}
 
 		if (switch_core_session_dequeue_event(session, &event) == SWITCH_STATUS_SUCCESS) {
-			status = args->input_callback(session, event, SWITCH_INPUT_TYPE_EVENT, args->buf, args->buflen);			
+			status = args->input_callback(session, event, SWITCH_INPUT_TYPE_EVENT, args->buf, args->buflen);
 			switch_event_destroy(&event);
 		}
 
@@ -277,12 +561,9 @@
 SWITCH_DECLARE(switch_status_t) switch_ivr_collect_digits_count(switch_core_session_t *session,
 																char *buf,
 																uint32_t buflen,
-																uint32_t maxdigits,
-																const char *terminators,
-																char *terminator,
-																uint32_t timeout)
+																uint32_t maxdigits, const char *terminators, char *terminator, uint32_t timeout)
 {
-	uint32_t i = 0, x =  (uint32_t) strlen(buf);
+	uint32_t i = 0, x = (uint32_t) strlen(buf);
 	switch_channel_t *channel;
 	switch_status_t status = SWITCH_STATUS_FALSE;
 	switch_time_t started = 0;
@@ -295,7 +576,7 @@
 		*terminator = '\0';
 
 	if (!switch_strlen_zero(terminators)) {
-		for (i = 0 ; i < x; i++) {
+		for (i = 0; i < x; i++) {
 			if (strchr(terminators, buf[i]) && terminator != NULL) {
 				*terminator = buf[i];
 				return SWITCH_STATUS_SUCCESS;
@@ -307,27 +588,27 @@
 		started = switch_time_now();
 	}
 
-	while(switch_channel_ready(channel)) {
+	while (switch_channel_ready(channel)) {
 		switch_frame_t *read_frame;
 		switch_event_t *event;
 
 		if (timeout) {
-			elapsed = (uint32_t)((switch_time_now() - started) / 1000);
+			elapsed = (uint32_t) ((switch_time_now() - started) / 1000);
 			if (elapsed >= timeout) {
 				break;
 			}
 		}
-		
+
 		if (switch_core_session_dequeue_private_event(session, &event) == SWITCH_STATUS_SUCCESS) {
 			switch_ivr_parse_event(session, event);
 			switch_event_destroy(&event);
 		}
-		
+
 		if (switch_channel_has_dtmf(channel)) {
 			char dtmf[128];
 
 			switch_channel_dequeue_dtmf(channel, dtmf, maxdigits);
-			for(i =0 ; i < (uint32_t) strlen(dtmf); i++) {
+			for (i = 0; i < (uint32_t) strlen(dtmf); i++) {
 
 				if (!switch_strlen_zero(terminators) && strchr(terminators, dtmf[i]) && terminator != NULL) {
 					*terminator = dtmf[i];
@@ -356,4569 +637,514 @@
 }
 
 
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_record_file(switch_core_session_t *session, 
-                                                       switch_file_handle_t *fh,
-                                                       char *file,
-                                                       switch_input_args_t *args,
-                                                       uint32_t limit)
+SWITCH_DECLARE(switch_status_t) switch_ivr_hold(switch_core_session_t *session)
 {
+	switch_core_session_message_t msg = { 0 };
 	switch_channel_t *channel;
-    char dtmf[128];
-	switch_file_handle_t lfh = {0};
-	switch_frame_t *read_frame;
-	switch_codec_t codec, *read_codec;
-	char *codec_name;
-	switch_status_t status = SWITCH_STATUS_SUCCESS;
-	char *p;
-	const char *vval;
-    time_t start = 0;
-	uint32_t org_silence_hits = 0;
 
-	if (!fh) {
-		fh = &lfh;
-	}
+	msg.message_id = SWITCH_MESSAGE_INDICATE_HOLD;
+	msg.from = __FILE__;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
-
-	read_codec = switch_core_session_get_read_codec(session);
-	assert(read_codec != NULL);
-
-	fh->channels = read_codec->implementation->number_of_channels;
-	fh->samplerate = read_codec->implementation->samples_per_second;
-
-
-	if (switch_core_file_open(fh,
-							  file,
-							  SWITCH_FILE_FLAG_WRITE | SWITCH_FILE_DATA_SHORT,
-							  switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
-		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-		switch_core_session_reset(session);
-		return SWITCH_STATUS_GENERR;
-	}
-
-	switch_channel_answer(channel);
-
-	if ((p = switch_channel_get_variable(channel, "RECORD_TITLE"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_TITLE, vval);
-		switch_channel_set_variable(channel, "RECORD_TITLE", NULL);
-	}
+	assert(channel != NULL);
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_COPYRIGHT"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_COPYRIGHT, vval);
-		switch_channel_set_variable(channel, "RECORD_COPYRIGHT", NULL);
-	}
+	switch_channel_set_flag(channel, CF_HOLD);
+	switch_channel_set_flag(channel, CF_SUSPEND);
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_SOFTWARE"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_SOFTWARE, vval);
-		switch_channel_set_variable(channel, "RECORD_SOFTWARE", NULL);
-	}
+	switch_core_session_receive_message(session, &msg);
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_ARTIST"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_ARTIST, vval);
-		switch_channel_set_variable(channel, "RECORD_ARTIST", NULL);
-	}
+	return SWITCH_STATUS_SUCCESS;
+}
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_COMMENT"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_COMMENT, vval);
-		switch_channel_set_variable(channel, "RECORD_COMMENT", NULL);
-	}
+SWITCH_DECLARE(switch_status_t) switch_ivr_hold_uuid(char *uuid)
+{
+	switch_core_session_t *session;
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_DATE"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_DATE, vval);
-		switch_channel_set_variable(channel, "RECORD_DATE", NULL);
-	}
-	
-	codec_name = "L16";
-	if (switch_core_codec_init(&codec,
-							   codec_name,
-							   NULL,
-							   read_codec->implementation->samples_per_second,
-							   read_codec->implementation->microseconds_per_frame / 1000,
-							   read_codec->implementation->number_of_channels,
-							   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-							   NULL, switch_core_session_get_pool(session)) == SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activated\n");
-		switch_core_session_set_read_codec(session, &codec);		
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Raw Codec Activation Failed %s@%uhz %u channels %dms\n",
-							  codec_name, fh->samplerate, fh->channels, read_codec->implementation->microseconds_per_frame / 1000);
-		switch_core_file_close(fh);
-		switch_core_session_reset(session);
-		return SWITCH_STATUS_GENERR;
-	}
-	
-    if (limit) {
-        start = time(NULL);
-    }
-
-    if (fh->thresh) {
-        if (fh->silence_hits) {
-			fh->silence_hits = fh->samplerate * fh->silence_hits / read_codec->implementation->samples_per_frame;
-		} else {
-            fh->silence_hits = fh->samplerate * 3 / read_codec->implementation->samples_per_frame;
-        }
-		org_silence_hits = fh->silence_hits;
+	if ((session = switch_core_session_locate(uuid))) {
+		switch_ivr_hold(session);
+		switch_core_session_rwunlock(session);
 	}
 
-	while(switch_channel_ready(channel)) {
-		switch_size_t len;
-		switch_event_t *event;
-
-        if (switch_core_session_dequeue_private_event(session, &event) == SWITCH_STATUS_SUCCESS) {
-			switch_ivr_parse_event(session, event);
-			switch_event_destroy(&event);
-		}
-
-        if (start && (time(NULL) - start) > limit) {
-            break;
-        }
-
-		if (args && (args->input_callback || args->buf || args->buflen)) {
-			/*
-			  dtmf handler function you can hook up to be executed when a digit is dialed during playback 
-			  if you return anything but SWITCH_STATUS_SUCCESS the playback will stop.
-			*/
-			if (switch_channel_has_dtmf(channel)) {
-				if (!args->input_callback && !args->buf) {
-					status = SWITCH_STATUS_BREAK;
-					break;
-				}
-				switch_channel_dequeue_dtmf(channel, dtmf, sizeof(dtmf));
-				if (args->input_callback) {
-					status = args->input_callback(session, dtmf, SWITCH_INPUT_TYPE_DTMF, args->buf, args->buflen);
-				} else {
-					switch_copy_string((char *)args->buf, dtmf, args->buflen);
-					status = SWITCH_STATUS_BREAK;
-				}
-			}
+	return SWITCH_STATUS_SUCCESS;
+}
 
-			if (args->input_callback) {
-				if (switch_core_session_dequeue_event(session, &event) == SWITCH_STATUS_SUCCESS) {
-					status = args->input_callback(session, event, SWITCH_INPUT_TYPE_EVENT, args->buf, args->buflen);			
-					switch_event_destroy(&event);
-				}
-			}
+SWITCH_DECLARE(switch_status_t) switch_ivr_unhold(switch_core_session_t *session)
+{
+	switch_core_session_message_t msg = { 0 };
+	switch_channel_t *channel;
 
+	msg.message_id = SWITCH_MESSAGE_INDICATE_UNHOLD;
+	msg.from = __FILE__;
 
-			if (status != SWITCH_STATUS_SUCCESS) {
-				break;
-			}
-		}
-		
-		status = switch_core_session_read_frame(session, &read_frame, -1, 0);
-		if (!SWITCH_READ_ACCEPTABLE(status)) {
-			break;
-		}
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-        if (fh->thresh) {
-            int16_t *fdata = (int16_t *) read_frame->data;
-            uint32_t samples = read_frame->datalen / sizeof(*fdata);
-            uint32_t score, count = 0, j = 0;
-            double energy = 0;
-
-            for (count = 0; count < samples; count++) {
-                energy += abs(fdata[j]);
-                j += read_codec->implementation->number_of_channels;
-            }
-		
-            score = (uint32_t)(energy / samples);
-            if (score < fh->thresh) {
-                if (!--fh->silence_hits) {
-                    break;
-                }
-			} else {
-				fh->silence_hits = org_silence_hits;
-			}
-        }
+	switch_channel_clear_flag(channel, CF_HOLD);
+	switch_channel_clear_flag(channel, CF_SUSPEND);
 
-		if (!switch_test_flag(fh, SWITCH_FILE_PAUSE)) {
-			len = (switch_size_t) read_frame->datalen / 2;
-			switch_core_file_write(fh, read_frame->data, &len);
-		}
-	}
+	switch_core_session_receive_message(session, &msg);
 
-	switch_core_session_set_read_codec(session, read_codec);
-	switch_core_file_close(fh);
-	switch_core_session_reset(session);
-	return status;
+	return SWITCH_STATUS_SUCCESS;
 }
 
-static void record_callback(switch_media_bug_t *bug, void *user_data, switch_abc_type_t type)
+SWITCH_DECLARE(switch_status_t) switch_ivr_unhold_uuid(char *uuid)
 {
-	switch_file_handle_t *fh = (switch_file_handle_t *) user_data;
-	uint8_t data[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-	switch_frame_t frame = {0};
+	switch_core_session_t *session;
 
-	frame.data = data;
-	frame.buflen = SWITCH_RECCOMMENDED_BUFFER_SIZE;
-	
-	switch(type) {
-	case SWITCH_ABC_TYPE_INIT:
-		break;
-	case SWITCH_ABC_TYPE_CLOSE:
-        if (fh) {
-            switch_core_file_close(fh);
-        }
-        break;
-	case SWITCH_ABC_TYPE_READ:
-		if (fh) {
-			switch_size_t len;
-
-			if (switch_core_media_bug_read(bug, &frame) == SWITCH_STATUS_SUCCESS) {
-				len = (switch_size_t) frame.datalen / 2;
-				switch_core_file_write(fh, frame.data, &len);
-			}
-		}
-		break;
-	case SWITCH_ABC_TYPE_WRITE:
-    default:
-		break;
+	if ((session = switch_core_session_locate(uuid))) {
+		switch_ivr_unhold(session);
+		switch_core_session_rwunlock(session);
 	}
+
+	return SWITCH_STATUS_SUCCESS;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_stop_record_session(switch_core_session_t *session, char *file) 
+SWITCH_DECLARE(switch_status_t) switch_ivr_media(char *uuid, switch_media_flag_t flags)
 {
-	switch_media_bug_t *bug;
-	switch_channel_t *channel = switch_core_session_get_channel(session);
+	char *other_uuid = NULL;
+	switch_channel_t *channel, *other_channel = NULL;
+	switch_core_session_t *session, *other_session;
+	switch_core_session_message_t msg = { 0 };
+	switch_status_t status = SWITCH_STATUS_GENERR;
+	uint8_t swap = 0;
 
-	assert(channel != NULL);
-	if ((bug = switch_channel_get_private(channel, file))) {
-		switch_channel_set_private(channel, file, NULL);
-		switch_core_media_bug_remove(session, &bug);
-		return SWITCH_STATUS_SUCCESS;
-	}
-	
-	return SWITCH_STATUS_FALSE;
-	
-}
+	msg.message_id = SWITCH_MESSAGE_INDICATE_MEDIA;
+	msg.from = __FILE__;
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_record_session(switch_core_session_t *session, char *file,  switch_file_handle_t *fh)
-{
-	switch_channel_t *channel;
-	switch_codec_t *read_codec;
-	char *p;
-	const char *vval;
-	switch_media_bug_t *bug;
-	switch_status_t status;
-
-	if (!fh) {
-		if (!(fh = switch_core_session_alloc(session, sizeof(*fh)))) {
-			return SWITCH_STATUS_MEMERR;
+	if ((session = switch_core_session_locate(uuid))) {
+		channel = switch_core_session_get_channel(session);
+		assert(channel != NULL);
+		if ((flags & SMF_REBRIDGE) && !switch_channel_test_flag(channel, CF_ORIGINATOR)) {
+			swap = 1;
 		}
-	}
-
-	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
-
-    read_codec = switch_core_session_get_read_codec(session);
-    assert(read_codec != NULL);
-
-    fh->channels = read_codec->implementation->number_of_channels;
-    fh->samplerate = read_codec->implementation->samples_per_second;
-
-
-    if (switch_core_file_open(fh,
-                              file,
-                              SWITCH_FILE_FLAG_WRITE | SWITCH_FILE_DATA_SHORT,
-                              switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
-        switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-        switch_core_session_reset(session);
-        return SWITCH_STATUS_GENERR;
-    }
-
-    switch_channel_answer(channel);
-
-	if ((p = switch_channel_get_variable(channel, "RECORD_TITLE"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_TITLE, vval);
-		switch_channel_set_variable(channel, "RECORD_TITLE", NULL);
-	}
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_COPYRIGHT"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_COPYRIGHT, vval);
-		switch_channel_set_variable(channel, "RECORD_COPYRIGHT", NULL);
-	}
+		if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
+			status = SWITCH_STATUS_SUCCESS;
+			switch_channel_clear_flag(channel, CF_NOMEDIA);
+			switch_core_session_receive_message(session, &msg);
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_SOFTWARE"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_SOFTWARE, vval);
-		switch_channel_set_variable(channel, "RECORD_SOFTWARE", NULL);
-	}
+			if ((flags & SMF_REBRIDGE)
+				&& (other_uuid = switch_channel_get_variable(channel, SWITCH_SIGNAL_BRIDGE_VARIABLE))
+				&& (other_session = switch_core_session_locate(other_uuid))) {
+				other_channel = switch_core_session_get_channel(other_session);
+				assert(other_channel != NULL);
+				switch_core_session_receive_message(other_session, &msg);
+				switch_channel_clear_state_handler(other_channel, NULL);
+				switch_core_session_rwunlock(other_session);
+			}
+			if (other_channel) {
+				switch_channel_clear_state_handler(channel, NULL);
+			}
+		}
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_ARTIST"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_ARTIST, vval);
-		switch_channel_set_variable(channel, "RECORD_ARTIST", NULL);
-	}
+		switch_core_session_rwunlock(session);
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_COMMENT"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_COMMENT, vval);
-		switch_channel_set_variable(channel, "RECORD_COMMENT", NULL);
+		if (other_channel) {
+			if (swap) {
+				switch_ivr_uuid_bridge(other_uuid, uuid);
+			} else {
+				switch_ivr_uuid_bridge(uuid, other_uuid);
+			}
+		}
 	}
 
-	if ((p = switch_channel_get_variable(channel, "RECORD_DATE"))) {
-		vval = (const char *) switch_core_session_strdup(session, p);
-		switch_core_file_set_string(fh, SWITCH_AUDIO_COL_STR_DATE, vval);
-		switch_channel_set_variable(channel, "RECORD_DATE", NULL);
-	}
+	return status;
+}
 
-	
 
-	if ((status = switch_core_media_bug_add(session,
-											record_callback,
-											fh,
-											SMBF_BOTH,
-											&bug)) != SWITCH_STATUS_SUCCESS) {
-		switch_core_file_close(fh);
-		return status;
-	}
+SWITCH_DECLARE(switch_status_t) switch_ivr_nomedia(char *uuid, switch_media_flag_t flags)
+{
+	char *other_uuid;
+	switch_channel_t *channel, *other_channel = NULL;
+	switch_core_session_t *session, *other_session = NULL;
+	switch_core_session_message_t msg = { 0 };
+	switch_status_t status = SWITCH_STATUS_GENERR;
+	uint8_t swap = 0;
 
-	switch_channel_set_private(channel, file, bug);
-	
-	return SWITCH_STATUS_SUCCESS;
-}
+	msg.message_id = SWITCH_MESSAGE_INDICATE_NOMEDIA;
+	msg.from = __FILE__;
 
-typedef struct {
-	switch_core_session_t *session;
-	teletone_dtmf_detect_state_t dtmf_detect;
-} switch_inband_dtmf_t;
+	if ((session = switch_core_session_locate(uuid))) {
+		status = SWITCH_STATUS_SUCCESS;
+		channel = switch_core_session_get_channel(session);
+		assert(channel != NULL);
 
-static void inband_dtmf_callback(switch_media_bug_t *bug, void *user_data, switch_abc_type_t type)
-{
-	switch_inband_dtmf_t *pvt = (switch_inband_dtmf_t *) user_data;
-	uint8_t data[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-	switch_frame_t frame = {0};
-	char digit_str[80];
-	switch_channel_t *channel = switch_core_session_get_channel(pvt->session);
+		if ((flags & SMF_REBRIDGE) && !switch_channel_test_flag(channel, CF_ORIGINATOR)) {
+			swap = 1;
+		}
 
-	assert(channel != NULL);
-	frame.data = data;
-	frame.buflen = SWITCH_RECCOMMENDED_BUFFER_SIZE;
+		if ((flags & SMF_FORCE) || !switch_channel_test_flag(channel, CF_NOMEDIA)) {
+			switch_channel_set_flag(channel, CF_NOMEDIA);
+			switch_core_session_receive_message(session, &msg);
+			if ((flags & SMF_REBRIDGE) && (other_uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) &&
+				(other_session = switch_core_session_locate(other_uuid))) {
+				other_channel = switch_core_session_get_channel(other_session);
+				assert(other_channel != NULL);
+				switch_core_session_receive_message(other_session, &msg);
+				switch_channel_clear_state_handler(other_channel, NULL);
 
-	switch(type) {
-		case SWITCH_ABC_TYPE_INIT:
-			break;
-		case SWITCH_ABC_TYPE_CLOSE:
-			break;
-		case SWITCH_ABC_TYPE_READ:
-			if (switch_core_media_bug_read(bug, &frame) == SWITCH_STATUS_SUCCESS) {
-				teletone_dtmf_detect(&pvt->dtmf_detect, frame.data, frame.samples);
-				teletone_dtmf_get(&pvt->dtmf_detect, digit_str, sizeof(digit_str));
-				if(digit_str[0]) {
-					switch_channel_queue_dtmf(channel, digit_str);
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "DTMF DETECTED: [%s]\n", digit_str);
+			}
+			if (other_channel) {
+				switch_channel_clear_state_handler(channel, NULL);
+				if (swap) {
+					switch_ivr_signal_bridge(other_session, session);
+				} else {
+					switch_ivr_signal_bridge(session, other_session);
 				}
+				switch_core_session_rwunlock(other_session);
 			}
-			break;
-		case SWITCH_ABC_TYPE_WRITE:
-		default:
-			break;
-	}
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_stop_inband_dtmf_session(switch_core_session_t *session) 
-{
-	switch_media_bug_t *bug;
-	switch_channel_t *channel = switch_core_session_get_channel(session);
-
-	assert(channel != NULL);
-	if ((bug = switch_channel_get_private(channel, "dtmf"))) {
-		switch_channel_set_private(channel, "dtmf", NULL);
-		switch_core_media_bug_remove(session, &bug);
-		return SWITCH_STATUS_SUCCESS;
+		}
+		switch_core_session_rwunlock(session);
 	}
 
-	return SWITCH_STATUS_FALSE;
-
+	return status;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_inband_dtmf_session(switch_core_session_t *session)
+SWITCH_DECLARE(switch_status_t) switch_ivr_session_transfer(switch_core_session_t *session, char *extension, char *dialplan, char *context)
 {
 	switch_channel_t *channel;
-	switch_codec_t *read_codec;
-	switch_media_bug_t *bug;
-	switch_status_t status;
-	switch_inband_dtmf_t *pvt;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	read_codec = switch_core_session_get_read_codec(session);
-	assert(read_codec != NULL);
-
-	if (!(pvt = switch_core_session_alloc(session, sizeof(*pvt)))) {
-		return SWITCH_STATUS_MEMERR;
-	}
+	switch_caller_profile_t *profile, *new_profile;
+	switch_core_session_message_t msg = { 0 };
+	switch_core_session_t *other_session;
+	switch_channel_t *other_channel = NULL;
+	char *uuid = NULL;
 
-	teletone_dtmf_detect_init(&pvt->dtmf_detect, read_codec->implementation->samples_per_second);
+	assert(session != NULL);
+	assert(extension != NULL);
 
-	pvt->session = session;
+	switch_core_session_reset(session);
 
-	switch_channel_answer(channel);	
 
-	if ((status = switch_core_media_bug_add(session,
-		inband_dtmf_callback,
-		pvt,
-		SMBF_READ_STREAM,
-		&bug)) != SWITCH_STATUS_SUCCESS) {
-			return status;
-	}
+	channel = switch_core_session_get_channel(session);
+	assert(channel != NULL);
 
-	switch_channel_set_private(channel, "dtmf", bug);
+	/* clear all state handlers */
+	switch_channel_clear_state_handler(channel, NULL);
 
-	return SWITCH_STATUS_SUCCESS;
-}
+	if ((profile = switch_channel_get_caller_profile(channel))) {
+		new_profile = switch_caller_profile_clone(session, profile);
+		new_profile->destination_number = switch_core_session_strdup(session, extension);
 
-struct speech_thread_handle {
-	switch_core_session_t *session;
-	switch_asr_handle_t *ah;
-	switch_media_bug_t *bug;
-	switch_mutex_t *mutex;
-	switch_thread_cond_t *cond;
-	switch_memory_pool_t *pool;
-};
+		if (!switch_strlen_zero(dialplan)) {
+			new_profile->dialplan = switch_core_session_strdup(session, dialplan);
+		} else {
+			dialplan = new_profile->dialplan;
+		}
 
-static void *SWITCH_THREAD_FUNC speech_thread(switch_thread_t *thread, void *obj)
-{
-	struct speech_thread_handle *sth = (struct speech_thread_handle *) obj;
-	switch_channel_t *channel = switch_core_session_get_channel(sth->session);
-	switch_asr_flag_t flags = SWITCH_ASR_FLAG_NONE;
-	switch_status_t status;
+		if (!switch_strlen_zero(context)) {
+			new_profile->context = switch_core_session_strdup(session, context);
+		} else {
+			context = new_profile->context;
+		}
 
-	switch_thread_cond_create(&sth->cond, sth->pool);
-	switch_mutex_init(&sth->mutex, SWITCH_MUTEX_NESTED, sth->pool);
-	
 
-	switch_core_session_read_lock(sth->session);
-	switch_mutex_lock(sth->mutex);
-	
-	while (switch_channel_ready(channel) && !switch_test_flag(sth->ah, SWITCH_ASR_FLAG_CLOSED)) {
-		char *xmlstr = NULL;
-		
-		switch_thread_cond_wait(sth->cond, sth->mutex);
-		if (switch_core_asr_check_results(sth->ah, &flags) == SWITCH_STATUS_SUCCESS) {
-			switch_event_t *event;
+		switch_channel_set_variable(channel, SWITCH_SIGNAL_BOND_VARIABLE, NULL);
+		if ((uuid = switch_channel_get_variable(channel, SWITCH_SIGNAL_BOND_VARIABLE))
+			&& (other_session = switch_core_session_locate(uuid))) {
+			switch_channel_set_variable(other_channel, SWITCH_SIGNAL_BOND_VARIABLE, NULL);
+			switch_core_session_rwunlock(other_session);
+		}
 
-			status = switch_core_asr_get_results(sth->ah, &xmlstr, &flags);
-		
-			if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
-				goto done;
-			}
+		if ((uuid = switch_channel_get_variable(channel, SWITCH_SIGNAL_BRIDGE_VARIABLE))
+			&& (other_session = switch_core_session_locate(uuid))) {
+			other_channel = switch_core_session_get_channel(other_session);
+			assert(other_channel != NULL);
 
+			switch_channel_set_variable(channel, SWITCH_SIGNAL_BRIDGE_VARIABLE, NULL);
+			switch_channel_set_variable(other_channel, SWITCH_SIGNAL_BRIDGE_VARIABLE, NULL);
 
-			if (switch_event_create(&event, SWITCH_EVENT_DETECTED_SPEECH) == SWITCH_STATUS_SUCCESS) {
-				if (status == SWITCH_STATUS_SUCCESS) {
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Speech-Type", "detected-speech");
-					switch_event_add_body(event, "%s", xmlstr);
-				} else {
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Speech-Type", "begin-speaking");
-				}
+			switch_channel_set_variable(channel, SWITCH_BRIDGE_VARIABLE, NULL);
+			switch_channel_set_variable(other_channel, SWITCH_BRIDGE_VARIABLE, NULL);
 
-				if (switch_test_flag(sth->ah, SWITCH_ASR_FLAG_FIRE_EVENTS)) {
-					switch_event_t *dup;
+			switch_channel_hangup(other_channel, SWITCH_CAUSE_BLIND_TRANSFER);
+			switch_ivr_media(uuid, SMF_NONE);
 
-					if (switch_event_dup(&dup, event) == SWITCH_STATUS_SUCCESS) {
-						switch_event_fire(&dup);
-					}
-						
-				}
-				
-				if (switch_core_session_queue_event(sth->session, &event) != SWITCH_STATUS_SUCCESS) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Event queue failed!\n");
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "delivery-failure", "true");
-					switch_event_fire(&event);
-				}
-			}
-			
-			switch_safe_free(xmlstr);
+			switch_core_session_rwunlock(other_session);
 		}
-	}
- done:
-	
-	switch_mutex_unlock(sth->mutex);
-	switch_core_session_rwunlock(sth->session);
-
-	return NULL;
-}
-
-static void speech_callback(switch_media_bug_t *bug, void *user_data, switch_abc_type_t type)
-{
-	struct speech_thread_handle *sth = (struct speech_thread_handle *) user_data;
-	uint8_t data[SWITCH_RECCOMMENDED_BUFFER_SIZE];
-	switch_frame_t frame = {0};
-	switch_asr_flag_t flags = SWITCH_ASR_FLAG_NONE;
 
-	frame.data = data;
-	frame.buflen = SWITCH_RECCOMMENDED_BUFFER_SIZE;
-	
-	switch(type) {
-	case SWITCH_ABC_TYPE_INIT: {
-		switch_thread_t *thread;
-		switch_threadattr_t *thd_attr = NULL;
-
-		switch_threadattr_create(&thd_attr, sth->pool);
-		switch_threadattr_detach_set(thd_attr, 1);
-		switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-        switch_thread_create(&thread, thd_attr, speech_thread, sth, sth->pool);
-		
-	}
-		break;
-	case SWITCH_ABC_TYPE_CLOSE: {
-		switch_core_asr_close(sth->ah, &flags);
-		switch_mutex_lock(sth->mutex);
-		switch_thread_cond_signal(sth->cond);
-		switch_mutex_unlock(sth->mutex);
-    }
-        break;
-	case SWITCH_ABC_TYPE_READ:
-		if (sth->ah) {
-			if (switch_core_media_bug_read(bug, &frame) == SWITCH_STATUS_SUCCESS) {
-				if (switch_core_asr_feed(sth->ah, frame.data, frame.datalen, &flags) != SWITCH_STATUS_SUCCESS) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error Feeding Data\n");
-					return;
-				}
-				if (switch_core_asr_check_results(sth->ah, &flags) == SWITCH_STATUS_SUCCESS) {
-					switch_mutex_lock(sth->mutex);
-					switch_thread_cond_signal(sth->cond);
-					switch_mutex_unlock(sth->mutex);
-				}
-			}
-		}
-		break;
-	case SWITCH_ABC_TYPE_WRITE:
-    default:
-		break;
-	}
-}
+		switch_channel_set_caller_profile(channel, new_profile);
+		switch_channel_set_flag(channel, CF_TRANSFER);
+		switch_channel_set_state(channel, CS_RING);
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_stop_detect_speech(switch_core_session_t *session) 
-{
-	switch_channel_t *channel = switch_core_session_get_channel(session);
-	struct speech_thread_handle *sth;
+		msg.message_id = SWITCH_MESSAGE_INDICATE_TRANSFER;
+		msg.from = __FILE__;
+		switch_core_session_receive_message(session, &msg);
 
-	assert(channel != NULL);
-	if ((sth = switch_channel_get_private(channel, SWITCH_SPEECH_KEY))) {
-		switch_channel_set_private(channel, SWITCH_SPEECH_KEY, NULL);
-		switch_core_media_bug_remove(session, &sth->bug);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Transfer %s to %s[%s@%s]\n", switch_channel_get_name(channel), dialplan, extension,
+						  context);
 		return SWITCH_STATUS_SUCCESS;
 	}
-	
-	return SWITCH_STATUS_FALSE;
-	
-}
-
-
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_pause_detect_speech(switch_core_session_t *session) 
-{
-	switch_channel_t *channel = switch_core_session_get_channel(session);
-	struct speech_thread_handle *sth;
-
-	assert(channel != NULL);
-	if ((sth = switch_channel_get_private(channel, SWITCH_SPEECH_KEY))) {
-		switch_core_asr_pause(sth->ah);
-		return SWITCH_STATUS_SUCCESS;
-	}
-	
 	return SWITCH_STATUS_FALSE;
-	
 }
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_resume_detect_speech(switch_core_session_t *session) 
+SWITCH_DECLARE(switch_status_t) switch_ivr_transfer_variable(switch_core_session_t *sessa, switch_core_session_t *sessb, char *var)
 {
-	switch_channel_t *channel = switch_core_session_get_channel(session);
-	struct speech_thread_handle *sth;
+	switch_channel_t *chana = switch_core_session_get_channel(sessa);
+	switch_channel_t *chanb = switch_core_session_get_channel(sessb);
+	char *val = NULL;
+	uint8_t prefix = 0;
 
-	assert(channel != NULL);
-	if ((sth = switch_channel_get_private(channel, SWITCH_SPEECH_KEY))) {
-		switch_core_asr_resume(sth->ah);
-		return SWITCH_STATUS_SUCCESS;
+	if (var && *var == '~') {
+		var++;
+		prefix = 1;
 	}
-	
-	return SWITCH_STATUS_FALSE;
-	
-}
-
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_detect_speech_load_grammar(switch_core_session_t *session, char *grammar, char *path) 
-{
-	switch_channel_t *channel = switch_core_session_get_channel(session);
-	switch_asr_flag_t flags = SWITCH_ASR_FLAG_NONE;
-	struct speech_thread_handle *sth;
 
-	assert(channel != NULL);
-	if ((sth = switch_channel_get_private(channel, SWITCH_SPEECH_KEY))) {		
-		if (switch_core_asr_load_grammar(sth->ah, grammar, path) != SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error loading Grammar\n");
-			switch_core_asr_close(sth->ah, &flags);
-			switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			return SWITCH_STATUS_FALSE;
+	if (var && !prefix) {
+		if ((val = switch_channel_get_variable(chana, var))) {
+			switch_channel_set_variable(chanb, var, val);
 		}
+	} else {
+		switch_hash_index_t *hi;
+		void *vval;
+		const void *vvar;
 
-		return SWITCH_STATUS_SUCCESS;
+		for (hi = switch_channel_variable_first(chana, switch_core_session_get_pool(sessa)); hi; hi = switch_hash_next(hi)) {
+			switch_hash_this(hi, &vvar, NULL, &vval);
+			if (vvar && vval && (!prefix || (var && !strncmp((char *) vvar, var, strlen(var))))) {
+				switch_channel_set_variable(chanb, (char *) vvar, (char *) vval);
+			}
+		}
 	}
 
-	return SWITCH_STATUS_FALSE;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_detect_speech_unload_grammar(switch_core_session_t *session, char *grammar) 
-{
-	switch_channel_t *channel = switch_core_session_get_channel(session);
-	switch_asr_flag_t flags = SWITCH_ASR_FLAG_NONE;
-	struct speech_thread_handle *sth;
-
-	assert(channel != NULL);
-	if ((sth = switch_channel_get_private(channel, SWITCH_SPEECH_KEY))) {		
-		if (switch_core_asr_unload_grammar(sth->ah, grammar) != SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error unloading Grammar\n");
-			switch_core_asr_close(sth->ah, &flags);
-			switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			return SWITCH_STATUS_FALSE;
-		}
-
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_FALSE;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_detect_speech(switch_core_session_t *session,
-														 char *mod_name,
-														 char *grammar,
-														 char *path,
-														 char *dest,
-														 switch_asr_handle_t *ah)
-{
-	switch_channel_t *channel;
-	switch_codec_t *read_codec;
-	switch_status_t status;
-	switch_asr_flag_t flags = SWITCH_ASR_FLAG_NONE;
-	struct speech_thread_handle *sth;
-	char *val;
-
-	if (!ah) {
-		if (!(ah = switch_core_session_alloc(session, sizeof(*ah)))) {
-			return SWITCH_STATUS_MEMERR;
-		}
-	}
-
-	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
-
-    read_codec = switch_core_session_get_read_codec(session);
-    assert(read_codec != NULL);
-
-
-	if ((val = switch_channel_get_variable(channel, "fire_asr_events"))) {
-		switch_set_flag(ah, SWITCH_ASR_FLAG_FIRE_EVENTS);
-	}
-
-	if ((sth = switch_channel_get_private(channel, SWITCH_SPEECH_KEY))) {
-		if (switch_core_asr_load_grammar(sth->ah, grammar, path) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error loading Grammar\n");
-            switch_core_asr_close(sth->ah, &flags);
-            return SWITCH_STATUS_FALSE;
-        }
-
-        return SWITCH_STATUS_SUCCESS;
-	}
-	
-	if (switch_core_asr_open(ah, 
-							 mod_name,
-							 "L16",
-							 read_codec->implementation->samples_per_second,
-							 dest,
-							 &flags,
-							 switch_core_session_get_pool(session)) == SWITCH_STATUS_SUCCESS) {
-
-		if (switch_core_asr_load_grammar(ah, grammar, path) != SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Error loading Grammar\n");
-			switch_core_asr_close(ah, &flags);
-			switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			return SWITCH_STATUS_FALSE;
-		}
-	} else {
-		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-		return SWITCH_STATUS_FALSE;
-	}
-
-
-	sth = switch_core_session_alloc(session, sizeof(*sth));
-	sth->pool = switch_core_session_get_pool(session);
-	sth->session = session;
-	sth->ah = ah;
-	
-	if ((status = switch_core_media_bug_add(session,
-											speech_callback,
-											sth,
-											SMBF_READ_STREAM,
-											&sth->bug)) != SWITCH_STATUS_SUCCESS) {
-		switch_core_asr_close(ah, &flags);
-		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-		return status;
-	}
-
-	switch_channel_set_private(channel, SWITCH_SPEECH_KEY, sth);
-	
-	return SWITCH_STATUS_SUCCESS;
-}
-
-#define FILE_STARTSAMPLES 1024 * 32
-#define FILE_BLOCKSIZE 1024 * 8
-#define FILE_BUFSIZE 1024 * 64
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_play_file(switch_core_session_t *session, 
-                                                     switch_file_handle_t *fh,
-                                                     char *file,
-                                                     switch_input_args_t *args)
-{
-	switch_channel_t *channel;
-	int16_t abuf[FILE_STARTSAMPLES];
-	char dtmf[128];
-	uint32_t interval = 0, samples = 0, framelen, sample_start = 0;
-	uint32_t ilen = 0;
-	switch_size_t olen = 0, llen = 0;
-	switch_frame_t write_frame = {0};
-	switch_timer_t timer;
-	switch_core_thread_session_t thread_session;
-	switch_codec_t codec;
-	switch_memory_pool_t *pool = switch_core_session_get_pool(session);
-	char *codec_name;
-	int stream_id = 0;
-	switch_status_t status = SWITCH_STATUS_SUCCESS;
-	switch_file_handle_t lfh;
-	switch_codec_t *read_codec = switch_core_session_get_read_codec(session);
-	const char *p;
-	char *title = "", *copyright = "", *software = "", *artist = "", *comment = "", *date = "";
-	uint8_t asis = 0;
-	char *ext;
-    char *prefix;
-    char *timer_name;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-    prefix = switch_channel_get_variable(channel, "sound_prefix");
-    timer_name = switch_channel_get_variable(channel, "timer_name");
-	
-	if (file) {
-        if (prefix && *file != '/' && *file != '\\' && *(file+1) != ':') {
-            char *new_file;
-            uint32_t len;
-            len = (uint32_t)strlen(file) + (uint32_t)strlen(prefix) + 10;
-            new_file = switch_core_session_alloc(session, len);
-            snprintf(new_file, len, "%s/%s", prefix, file);
-            file = new_file;
-        }
-
-		if ((ext = strrchr(file, '.'))) {
-			ext++;
-		} else {
-			char *new_file;
-			uint32_t len;
-			ext = read_codec->implementation->iananame;
-			len = (uint32_t)strlen(file) + (uint32_t)strlen(ext) + 2;
-			new_file = switch_core_session_alloc(session, len);
-			snprintf(new_file, len, "%s.%s", file, ext);
-			file = new_file;
-			asis = 1;
-		}
-	}
-
-	if (!fh) {
-		fh = &lfh;
-		memset(fh, 0, sizeof(lfh));
-	}
-
-
-	if (fh->samples > 0) {
-		sample_start = fh->samples;
-		fh->samples = 0;
-	}
-
-	if (switch_core_file_open(fh,
-							  file,
-							  SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT,
-							  switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
-		switch_core_session_reset(session);
-		return SWITCH_STATUS_NOTFOUND;
-	}
-	if (switch_test_flag(fh, SWITCH_FILE_NATIVE)) {
-		asis = 1;
-	}
-
-
-	write_frame.data = abuf;
-	write_frame.buflen = sizeof(abuf);
-
-    if (sample_start > 0) {
-        uint32_t pos = 0;
-        switch_core_file_seek(fh, &pos, sample_start, SEEK_CUR);
-    }
-	
-	if (switch_core_file_get_string(fh, SWITCH_AUDIO_COL_STR_TITLE, &p) == SWITCH_STATUS_SUCCESS) {
-		title = switch_core_session_strdup(session, p);
-		switch_channel_set_variable(channel, "RECORD_TITLE", p);
-	}
-	
-	if (switch_core_file_get_string(fh, SWITCH_AUDIO_COL_STR_COPYRIGHT, &p) == SWITCH_STATUS_SUCCESS) {
-		copyright = switch_core_session_strdup(session, p);
-		switch_channel_set_variable(channel, "RECORD_COPYRIGHT", p);
-	}
-	
-	if (switch_core_file_get_string(fh, SWITCH_AUDIO_COL_STR_SOFTWARE, &p) == SWITCH_STATUS_SUCCESS) {
-		software = switch_core_session_strdup(session, p);
-		switch_channel_set_variable(channel, "RECORD_SOFTWARE", p);
-	}
-	
-	if (switch_core_file_get_string(fh, SWITCH_AUDIO_COL_STR_ARTIST, &p) == SWITCH_STATUS_SUCCESS) {
-		artist = switch_core_session_strdup(session, p);
-		switch_channel_set_variable(channel, "RECORD_ARTIST", p);
-	}
-	
-	if (switch_core_file_get_string(fh, SWITCH_AUDIO_COL_STR_COMMENT, &p) == SWITCH_STATUS_SUCCESS) {
-		comment = switch_core_session_strdup(session, p);
-		switch_channel_set_variable(channel, "RECORD_COMMENT", p);
-	}
-	
-	if (switch_core_file_get_string(fh, SWITCH_AUDIO_COL_STR_DATE, &p) == SWITCH_STATUS_SUCCESS) {
-		date = switch_core_session_strdup(session, p);
-		switch_channel_set_variable(channel, "RECORD_DATE", p);
-	}
-#if 0
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, 
-					  "OPEN FILE %s %uhz %u channels\n"
-					  "TITLE=%s\n"
-					  "COPYRIGHT=%s\n"
-					  "SOFTWARE=%s\n"
-					  "ARTIST=%s\n"
-					  "COMMENT=%s\n"
-					  "DATE=%s\n", file, fh->samplerate, fh->channels,
-					  title,
-					  copyright,
-					  software,
-					  artist,
-					  comment,
-					  date);
-#endif
-
-	assert(read_codec != NULL);
-	interval = read_codec->implementation->microseconds_per_frame / 1000;
-
-	if (!fh->audio_buffer) {
-		switch_buffer_create_dynamic(&fh->audio_buffer, FILE_BLOCKSIZE, FILE_BUFSIZE, 0);
-		if (!fh->audio_buffer) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "setup buffer failed\n");
-
-			switch_core_file_close(fh);
-			switch_core_session_reset(session);
-			
-			return SWITCH_STATUS_GENERR;
-		}
-	} 
-
-	if (asis) {
-		write_frame.codec = read_codec;
-		samples = read_codec->implementation->samples_per_frame;
-		framelen = read_codec->implementation->encoded_bytes_per_frame;
-	} else {
-		codec_name = "L16";
-
-		if (switch_core_codec_init(&codec,
-								   codec_name,
-								   NULL,
-								   fh->samplerate,
-								   interval,
-								   fh->channels,
-								   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-								   NULL, pool) == SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG,
-							  SWITCH_LOG_DEBUG,
-							  "Codec Activated %s@%uhz %u channels %dms\n",
-							  codec_name,
-							  fh->samplerate,
-							  fh->channels,
-							  interval);
-
-			write_frame.codec = &codec;
-		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Failed %s@%uhz %u channels %dms\n",
-							  codec_name, fh->samplerate, fh->channels, interval);
-			switch_core_file_close(fh);
-			switch_core_session_reset(session);
-			return SWITCH_STATUS_GENERR;
-		}
-		samples = codec.implementation->samples_per_frame;
-		framelen = codec.implementation->bytes_per_frame;
-	}
-
-
-	if (timer_name) {
-		uint32_t len;
-
-		len = samples * 2;
-		if (switch_core_timer_init(&timer, timer_name, interval, samples, pool) != SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "setup timer failed!\n");
-			switch_core_codec_destroy(&codec);
-			switch_core_file_close(fh);
-			switch_core_session_reset(session);
-			return SWITCH_STATUS_GENERR;
-		}
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "setup timer success %u bytes per %d ms!\n", len, interval);
-	}
-	write_frame.rate = fh->samplerate;
-
-	if (timer_name) {
-		/* start a thread to absorb incoming audio */
-		for (stream_id = 0; stream_id < switch_core_session_get_stream_count(session); stream_id++) {
-			switch_core_service_session(session, &thread_session, stream_id);
-		}
-	}
-
-	ilen = samples;
-
-	while(switch_channel_ready(channel)) {
-		int done = 0;
-		int do_speed = 1;
-		int last_speed = -1;
-		switch_event_t *event;
-	
-
-		if (switch_core_session_dequeue_private_event(session, &event) == SWITCH_STATUS_SUCCESS) {
-			switch_ivr_parse_event(session, event);
-			switch_event_destroy(&event);
-		}
-
-		if (args && (args->input_callback || args->buf || args->buflen)) {
-			/*
-			  dtmf handler function you can hook up to be executed when a digit is dialed during playback 
-			  if you return anything but SWITCH_STATUS_SUCCESS the playback will stop.
-			*/
-			if (switch_channel_has_dtmf(channel)) {
-				if (!args->input_callback && !args->buf) {
-					status = SWITCH_STATUS_BREAK;
-					done = 1;
-					break;
-				}
-				switch_channel_dequeue_dtmf(channel, dtmf, sizeof(dtmf));
-				if (args->input_callback) {
-					status = args->input_callback(session, dtmf, SWITCH_INPUT_TYPE_DTMF, args->buf, args->buflen);
-				} else {
-					switch_copy_string((char *)args->buf, dtmf, args->buflen);
-					status = SWITCH_STATUS_BREAK;
-				}
-			}
-
-			if (args->input_callback) {
-				if (switch_core_session_dequeue_event(session, &event) == SWITCH_STATUS_SUCCESS) {
-					status = args->input_callback(session, event, SWITCH_INPUT_TYPE_EVENT, args->buf, args->buflen);			
-					switch_event_destroy(&event);
-				}
-			}
-			
-			if (status != SWITCH_STATUS_SUCCESS) {
-				done = 1;
-				break;
-			}
-		}
-		
-		if (switch_test_flag(fh, SWITCH_FILE_PAUSE)) {
-			memset(abuf, 0, framelen);
-			olen = ilen;
-            do_speed = 0;
-		} else if (fh->audio_buffer && (switch_buffer_inuse(fh->audio_buffer) > (switch_size_t)(framelen))) {
-			switch_buffer_read(fh->audio_buffer, abuf, framelen);
-			olen = asis ? framelen : ilen;
-			do_speed = 0;
-		} else {
-			olen = sizeof(abuf);
-			if (!asis) {
-				olen /= 2;
-			}
-			switch_core_file_read(fh, abuf, &olen);
-			switch_buffer_write(fh->audio_buffer, abuf, asis ? olen : olen * 2);
-			olen = switch_buffer_read(fh->audio_buffer, abuf, framelen);
-			if (!asis) {
-				olen /= 2;
-			} 
-		}
-
-		if (done || olen <= 0) {
-			break;
-		}
-
-		if (!asis) {
-			if (fh->speed > 2) {
-				fh->speed = 2;
-			} else if (fh->speed < -2) {
-				fh->speed = -2;
-			}
-		}
-		
-		if (!asis && fh->audio_buffer && last_speed > -1 && last_speed != fh->speed) {
-			switch_buffer_zero(fh->audio_buffer);
-		}
-
-		
-		if (!asis && fh->speed && do_speed) {
-			float factor = 0.25f * abs(fh->speed);
-			switch_size_t newlen, supplement, step;
-			short *bp = write_frame.data;
-			switch_size_t wrote = 0;
-			
-			
-			supplement = (int) (factor * olen);
-			newlen = (fh->speed > 0) ? olen - supplement : olen + supplement;
-			step = (fh->speed > 0) ? (newlen / supplement) : (olen / supplement);
-			
-			while ((wrote + step) < newlen) {
-				switch_buffer_write(fh->audio_buffer, bp, step * 2);
-				wrote += step;
-				bp += step;
-				if (fh->speed > 0) {
-					bp++;
-				} else {
-					float f;
-					short s;
-					f = (float)(*bp + *(bp+1) + *(bp-1));
-					f /= 3;
-					s = (short) f;
-					switch_buffer_write(fh->audio_buffer, &s, 2);
-					wrote++;
-				}
-			}
-			if (wrote < newlen) {
-				switch_size_t r = newlen - wrote;
-				switch_buffer_write(fh->audio_buffer, bp, r*2);
-				wrote += r;
-			}
-			last_speed = fh->speed;
-			continue;
-		}
-		if (olen < llen) {
-            uint8_t *dp = (uint8_t *) write_frame.data;
-            memset(dp + (int)olen, 0, (int)(llen - olen));
-            olen = llen;
-        }
-
-		write_frame.datalen = (uint32_t)(olen * (asis ? 1 : 2));
-		write_frame.samples = (uint32_t)olen;
-
-		llen = olen;
-
-
-#ifndef WIN32
-#if __BYTE_ORDER == __BIG_ENDIAN
-		if (!asis) {switch_swap_linear(write_frame.data, (int) write_frame.datalen / 2);}
-#endif
-#endif
-		stream_id = 0; 
-
-        status = switch_core_session_write_frame(session, &write_frame, -1, stream_id);
-        
-        if (status == SWITCH_STATUS_MORE_DATA) {
-            status = SWITCH_STATUS_SUCCESS;
-            continue;
-        } else if (status != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Bad Write\n");
-            done = 1;
-            break;
-        }
-
-        if (done) {
-            break;
-        }
-    
-		
-		if (timer_name) {
-			if (switch_core_timer_next(&timer) < 0) {
-				break;
-			}
-		} else { /* time off the channel (if you must) */
-			switch_frame_t *read_frame;
-			switch_status_t status; 
-			while (switch_channel_ready(channel) && switch_channel_test_flag(channel, CF_HOLD)) {
-				switch_yield(10000);
-			}
-			status = switch_core_session_read_frame(session, &read_frame, -1, 0);
-			if (!SWITCH_READ_ACCEPTABLE(status)) {
-				break;
-			}
-		}
-	}
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "done playing file\n");
-	switch_core_file_close(fh);
-	switch_buffer_destroy(&fh->audio_buffer);
-	if (!asis) {
-		switch_core_codec_destroy(&codec);
-	}
-	if (timer_name) {
-		/* End the audio absorbing thread */
-		switch_core_thread_session_end(&thread_session);
-		switch_core_timer_destroy(&timer);
-	}
-
-	switch_core_session_reset(session);
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_regex_match(char *target, char *expression) {
-	const char* error	= NULL;		//Used to hold any errors
-	int error_offset	= 0;		//Holds the offset of an error
-	pcre* pcre_prepared	= NULL;		//Holds the compiled regex
-	int match_count		= 0;		//Number of times the regex was matched
-	int offset_vectors[2];			//not used, but has to exist or pcre won't even try to find a match
-	
-	//Compile the expression
-	pcre_prepared = pcre_compile(expression, 0, &error, &error_offset, NULL);
-
-	//See if there was an error in the expression
-	if (error != NULL) {
-		//Clean up after ourselves
-		if (pcre_prepared) {
-			pcre_free(pcre_prepared);
-			pcre_prepared = NULL;
-		}	       
-
-		//Note our error	
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Regular Expression Error expression[%s] error[%s] location[%d]\n", expression, error, error_offset);
-
-		//We definitely didn't match anything
-		return SWITCH_STATUS_FALSE;
-	}
-
-	//So far so good, run the regex
-	match_count = pcre_exec(pcre_prepared, NULL, target, (int) strlen(target), 0, 0, offset_vectors, sizeof(offset_vectors) / sizeof(offset_vectors[0]));
-
-	//Clean up
-	if (pcre_prepared) {
-		pcre_free(pcre_prepared);
-		pcre_prepared = NULL;
-	}
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "number of matches: %d\n", match_count);
-
-	//Was it a match made in heaven?
-	if (match_count > 0) {
-		return SWITCH_STATUS_SUCCESS;
-	} else {
-		return SWITCH_STATUS_FALSE;
-	}
-}
-
-SWITCH_DECLARE(switch_status_t) switch_play_and_get_digits(switch_core_session_t *session,
-														   uint32_t min_digits,
-														   uint32_t max_digits,
-														   uint32_t max_tries,
-														   uint32_t timeout,
-														   char* valid_terminators,
-														   char* prompt_audio_file,
-														   char* bad_input_audio_file,
-														   void* digit_buffer,
-														   uint32_t digit_buffer_length,
-														   char* digits_regex) 
-{
-
-	char terminator;			//used to hold terminator recieved from  
-	switch_channel_t *channel;	//the channel contained in session
-	switch_status_t status;		//used to recieve state out of called functions
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "switch_play_and_get_digits(session, %d, %d, %d, %d, %s, %s, %s, digit_buffer, %d, %s)\n", min_digits, max_digits, max_tries, timeout, valid_terminators, prompt_audio_file, bad_input_audio_file, digit_buffer_length, digits_regex);
-
-	//Get the channel
-	channel = switch_core_session_get_channel(session);
-
-	//Make sure somebody is home
-	assert(channel != NULL);
-
-	//Answer the channel if it hasn't already been answered
-	switch_channel_answer(channel);
-
-	//Start pestering the user for input
-	for(;(switch_channel_get_state(channel) == CS_EXECUTE) && max_tries > 0; max_tries--) {
-        switch_input_args_t args = {0};
-		//make the buffer so fresh and so clean clean
-		memset(digit_buffer, 0, digit_buffer_length);
-        
-        args.buf = digit_buffer;
-        args.buflen = digit_buffer_length;
-		//Play the file
-		status = switch_ivr_play_file(session, NULL, prompt_audio_file, &args);
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "play gave up %s", (char *) digit_buffer);
-
-		//Make sure we made it out alive
-		if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
-			switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
-			break;
-		}
-
-		//we only get one digit out of playback, see if thats all we needed and what we got
-		if (max_digits == 1 && status == SWITCH_STATUS_BREAK) {
-			//Check the digit if we have a regex
-			if (digits_regex != NULL) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Checking regex [%s] on [%s]\n", digits_regex, (char *) digit_buffer);
-
-				//Make sure the digit is allowed
-				if (switch_regex_match(digit_buffer, digits_regex) == SWITCH_STATUS_SUCCESS) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Match found!\n");
-					//jobs done
-					break;
-				} else {
-					//See if a bad input prompt was specified, if so, play it
-					if (strlen(bad_input_audio_file) > 0) {
-						status = switch_ivr_play_file(session, NULL, bad_input_audio_file, NULL);
-
-						//Make sure we made it out alive
-						if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
-							switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
-							break;
-						}
-					}
-				}
-			} else {
-				//jobs done
-				break;
-			}
-		}
-
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Calling more digits try %d\n", max_tries);
-
-		//Try to grab some more digits for the timeout period
-		status = switch_ivr_collect_digits_count(session, digit_buffer, digit_buffer_length, max_digits, valid_terminators, &terminator, timeout);
-
-		//Make sure we made it out alive
-		if (status != SWITCH_STATUS_SUCCESS) {
-			//Bail
-			switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
-			break;
-		}
-
-		//see if we got enough
-		if (min_digits <= strlen(digit_buffer)) {
-			//See if we need to test a regex
-			if (digits_regex != NULL) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Checking regex [%s] on [%s]\n", digits_regex, (char *) digit_buffer);
-				//Test the regex
-				if (switch_regex_match(digit_buffer, digits_regex) == SWITCH_STATUS_SUCCESS) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Match found!\n");
-					//Jobs done
-					return SWITCH_STATUS_SUCCESS;
-				} else {
-					//See if a bad input prompt was specified, if so, play it
-					if (strlen(bad_input_audio_file) > 0) {
-						status = switch_ivr_play_file(session, NULL, bad_input_audio_file, NULL);
-
-						//Make sure we made it out alive
-						if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
-							switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
-							break;
-						}
-					}
-				}
-			} else {
-				//Jobs done
-				return SWITCH_STATUS_SUCCESS;
-			}
-		}
-	}
-
-	//if we got here, we got no digits or lost the channel
-	digit_buffer = "\0";
-	return SWITCH_STATUS_FALSE;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_speak_text_handle(switch_core_session_t *session, 
-															 switch_speech_handle_t *sh,
-															 switch_codec_t *codec,
-															 switch_timer_t *timer,
-															 char *text,
-                                                             switch_input_args_t *args)
-{
-	switch_channel_t *channel;
-	short abuf[960];
-	char dtmf[128];
-	uint32_t len = 0;
-	switch_size_t ilen = 0;
-	switch_frame_t write_frame = {0};
-	int x;
-	int stream_id = 0;
-	int done = 0;
-	int lead_in_out = 10;
-	switch_status_t status = SWITCH_STATUS_SUCCESS;
-	switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
-	uint32_t rate = 0, samples = 0;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	if (!sh) {
-		return SWITCH_STATUS_FALSE;
-	}
-
-	switch_channel_answer(channel);
-
-	write_frame.data = abuf;
-	write_frame.buflen = sizeof(abuf);
-
-	samples = (uint32_t)(sh->rate / 50);
-	len = samples * 2;
-
-	flags = 0;
-	switch_sleep(200000);
-	switch_core_speech_feed_tts(sh, text, &flags);
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Speaking text: %s\n", text);
-
-	write_frame.rate = sh->rate;
-
-	memset(write_frame.data, 0, len);
-	write_frame.datalen = len;
-	write_frame.samples = len / 2;
-	write_frame.codec = codec;
-
-	for( x = 0; !done && x < lead_in_out; x++) {
-        if (switch_core_session_write_frame(session, &write_frame, -1, stream_id) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Bad Write\n");
-            done = 1;
-            break;
-        }		
-	}
-
-	ilen = len;
-	while(switch_channel_ready(channel)) {
-		switch_event_t *event;
-
-		if (switch_core_session_dequeue_private_event(session, &event) == SWITCH_STATUS_SUCCESS) {
-			switch_ivr_parse_event(session, event);
-			switch_event_destroy(&event);
-		}
-
-		if (args && (args->input_callback || args->buf || args->buflen)) {
-			/*
-			dtmf handler function you can hook up to be executed when a digit is dialed during playback 
-			if you return anything but SWITCH_STATUS_SUCCESS the playback will stop.
-			*/
-			if (switch_channel_has_dtmf(channel)) {
-				if (!args->input_callback && !args->buf) {
-					status = SWITCH_STATUS_BREAK;
-					done = 1;
-					break;
-				}
-				if (args->buf && !strcasecmp(args->buf, "_break_")) {
-					status = SWITCH_STATUS_BREAK;
-				} else {
-					switch_channel_dequeue_dtmf(channel, dtmf, sizeof(dtmf));
-					if (args->input_callback) {
-						status = args->input_callback(session, dtmf, SWITCH_INPUT_TYPE_DTMF, args->buf, args->buflen);
-					} else {
-						switch_copy_string((char *)args->buf, dtmf, args->buflen);
-						status = SWITCH_STATUS_BREAK;
-					}
-				}
-			}
-
-			if (args->input_callback) {
-				if (switch_core_session_dequeue_event(session, &event) == SWITCH_STATUS_SUCCESS) {
-					status = args->input_callback(session, event, SWITCH_INPUT_TYPE_EVENT, args->buf, args->buflen);			
-					switch_event_destroy(&event);
-				}
-			}
-
-			if (status != SWITCH_STATUS_SUCCESS) {
-				done = 1;
-				break;
-			}
-		}
-
-		if (switch_test_flag(sh, SWITCH_SPEECH_FLAG_PAUSE)) {
-			if (timer) {
-				if ((x = switch_core_timer_next(timer)) < 0) {
-					break;
-				}
-			} else {
-				switch_frame_t *read_frame;
-				switch_status_t status = switch_core_session_read_frame(session, &read_frame, -1, 0);
-
-				while (switch_channel_ready(channel) && switch_channel_test_flag(channel, CF_HOLD)) {
-					switch_yield(10000);
-				}
-
-				if (!SWITCH_READ_ACCEPTABLE(status)) {
-					break;
-				}
-			}
-			continue;
-		}
-
-		flags = SWITCH_SPEECH_FLAG_BLOCKING;
-		status = switch_core_speech_read_tts(sh,
-			abuf,
-			&ilen,
-			&rate,
-			&flags);
-
-		if (status != SWITCH_STATUS_SUCCESS) {
-			for( x = 0; !done && x < lead_in_out; x++) {
-                if (switch_core_session_write_frame(session, &write_frame, -1, stream_id) != SWITCH_STATUS_SUCCESS) {
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Bad Write\n");
-                    done = 1;
-                    break;
-                }
-			}
-			if (status == SWITCH_STATUS_BREAK) {
-				status = SWITCH_STATUS_SUCCESS;
-			}
-			done = 1;
-		}
-
-		if (done) {
-			break;
-		}
-
-		write_frame.datalen = (uint32_t)ilen;
-		write_frame.samples = (uint32_t)(ilen / 2);
-
-        if (switch_core_session_write_frame(session, &write_frame, -1, stream_id) != SWITCH_STATUS_SUCCESS) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Bad Write\n");
-            done = 1;
-            break;
-        }
-
-        if (done) {
-            break;
-        }
-
-		if (timer) {
-			if ((x = switch_core_timer_next(timer)) < 0) {
-				break;
-			}
-		} else { /* time off the channel (if you must) */
-			switch_frame_t *read_frame;
-			switch_status_t status = switch_core_session_read_frame(session, &read_frame, -1, 0);
-
-			while (switch_channel_ready(channel) && switch_channel_test_flag(channel, CF_HOLD)) {
-				switch_yield(10000);
-			}
-
-			if (!SWITCH_READ_ACCEPTABLE(status)) {
-				break;
-			}
-		}
-
-	}
-
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "done speaking text\n");
-	flags = 0;	
-	switch_core_speech_flush_tts(sh);
-	return status;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_speak_text(switch_core_session_t *session, 
-													  char *tts_name,
-													  char *voice_name,
-													  uint32_t rate,
-													  char *text,
-                                                      switch_input_args_t *args)
-{
-	switch_channel_t *channel;
-	int interval = 0;
-	uint32_t samples = 0;
-	uint32_t len = 0;
-	switch_frame_t write_frame = {0};
-	switch_timer_t timer;
-	switch_core_thread_session_t thread_session;
-	switch_codec_t codec;
-	switch_memory_pool_t *pool = switch_core_session_get_pool(session);
-	char *codec_name;
-	int stream_id = 0;
-	switch_status_t status = SWITCH_STATUS_SUCCESS;
-	switch_speech_handle_t sh;
-	switch_speech_flag_t flags = SWITCH_SPEECH_FLAG_NONE;
-	switch_codec_t *read_codec;
-    char *timer_name;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-    timer_name = switch_channel_get_variable(channel, "timer_name");
-
-	if (rate == 0) {
-		read_codec = switch_core_session_get_read_codec(session);
-		rate = read_codec->implementation->samples_per_second;
-	}
-
-	memset(&sh, 0, sizeof(sh));
-	if (switch_core_speech_open(&sh,
-								tts_name,
-								voice_name,
-								(uint32_t)rate,
-								&flags,
-								switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid TTS module!\n");
-		switch_core_session_reset(session);
-		return SWITCH_STATUS_FALSE;
-	}
-		
-	switch_channel_answer(channel);
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "OPEN TTS %s\n", tts_name);
-	
-	interval = 20;
-	samples = (uint32_t)(rate / 50);
-	len = samples * 2;
-
-	codec_name = "L16";
-
-	if (switch_core_codec_init(&codec,
-							   codec_name,
-							   NULL,
-							   (int)rate,
-							   interval,
-							   1,
-							   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-							   NULL, pool) == SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activated\n");
-		write_frame.codec = &codec;
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Failed %s@%uhz 1 channel %dms\n",
-							  codec_name, rate, interval);
-		flags = 0;
-		switch_core_speech_close(&sh, &flags);
-		switch_core_session_reset(session);
-		return SWITCH_STATUS_GENERR;
-	}
-
-	if (timer_name) {
-		if (switch_core_timer_init(&timer, timer_name, interval, (int)samples, pool) != SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "setup timer failed!\n");
-			switch_core_codec_destroy(&codec);
-			flags = 0;
-			switch_core_speech_close(&sh, &flags);
-
-			switch_core_session_reset(session);
-			return SWITCH_STATUS_GENERR;
-		}
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "setup timer success %u bytes per %d ms!\n", len, interval);
-
-		/* start a thread to absorb incoming audio */
-		for (stream_id = 0; stream_id < switch_core_session_get_stream_count(session); stream_id++) {
-			switch_core_service_session(session, &thread_session, stream_id);
-		}
-	}
-
-	status = switch_ivr_speak_text_handle(session, &sh, &codec, timer_name ? &timer : NULL, text, args);
-	flags = 0;	
-	switch_core_speech_close(&sh, &flags);
-	switch_core_codec_destroy(&codec);
-
-	if (timer_name) {
-		/* End the audio absorbing thread */
-		switch_core_thread_session_end(&thread_session);
-		switch_core_timer_destroy(&timer);
-	}
-
-	switch_core_session_reset(session);
-	return status;
-}
-
-
-/* Bridge Related Stuff*/
-/*********************************************************************************/
-struct audio_bridge_data {
-	switch_core_session_t *session_a;
-	switch_core_session_t *session_b;
-	int running;
-};
-
-static void *audio_bridge_thread(switch_thread_t *thread, void *obj)
-{
-	switch_core_thread_session_t *his_thread, *data = obj;
-	int *stream_id_p;
-	int stream_id = 0, pre_b = 0, ans_a = 0, ans_b = 0, originator = 0;
-	switch_input_callback_function_t input_callback;
-	switch_core_session_message_t *message, msg = {0};
-	void *user_data;
-
-	switch_channel_t *chan_a, *chan_b;
-	switch_frame_t *read_frame;
-	switch_core_session_t *session_a, *session_b;
-
-	assert(!thread || thread);
-
-	session_a = data->objs[0];
-	session_b = data->objs[1];
-
-	stream_id_p = data->objs[2];
-	input_callback = data->input_callback;
-	user_data = data->objs[4];
-	his_thread = data->objs[5];
-
-	if (stream_id_p) {
-		stream_id = *stream_id_p;
-	}
-
-	chan_a = switch_core_session_get_channel(session_a);
-	chan_b = switch_core_session_get_channel(session_b);
-
-	ans_a = switch_channel_test_flag(chan_a, CF_ANSWERED);
-	if ((originator = switch_channel_test_flag(chan_a, CF_ORIGINATOR))) {
-		pre_b = switch_channel_test_flag(chan_a, CF_EARLY_MEDIA);
-		ans_b = switch_channel_test_flag(chan_b, CF_ANSWERED);
-	}
-	switch_core_session_read_lock(session_a);
-	switch_core_session_read_lock(session_b);
-
-	switch_channel_set_flag(chan_a, CF_BRIDGED);
-
-	while (switch_channel_ready(chan_a) && data->running > 0 && his_thread->running > 0) {
-		switch_channel_state_t b_state = switch_channel_get_state(chan_b);
-		switch_status_t status;
-		switch_event_t *event;
-
-		switch (b_state) {
-		case CS_HANGUP:
-		case CS_DONE:
-			switch_mutex_lock(data->mutex);
-			data->running = -1;
-			switch_mutex_unlock(data->mutex);
-			continue;
-		default:
-			break;
-		}
-
-		if (switch_channel_test_flag(chan_a, CF_TRANSFER)) {
-			switch_channel_clear_flag(chan_a, CF_HOLD);
-			switch_channel_clear_flag(chan_a, CF_SUSPEND);
-			break;
-		}
-		
-		if (switch_core_session_dequeue_private_event(session_a, &event) == SWITCH_STATUS_SUCCESS) {
-			switch_channel_set_flag(chan_b, CF_SUSPEND);
-			switch_ivr_parse_event(session_a, event);
-			switch_channel_clear_flag(chan_b, CF_SUSPEND);
-			switch_event_destroy(&event);
-		}
-
-		/* if 1 channel has DTMF pass it to the other */
-		if (switch_channel_has_dtmf(chan_a)) {
-			char dtmf[128];
-			switch_channel_dequeue_dtmf(chan_a, dtmf, sizeof(dtmf));
-			switch_core_session_send_dtmf(session_b, dtmf);
-			
-			if (input_callback) {
-				if (input_callback(session_a, dtmf, SWITCH_INPUT_TYPE_DTMF, user_data, 0) != SWITCH_STATUS_SUCCESS) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "%s ended call via DTMF\n", switch_channel_get_name(chan_a));
-					switch_mutex_lock(data->mutex);
-					data->running = -1;
-					switch_mutex_unlock(data->mutex);
-					break;
-				}
-			}
-		}
-
-		if (switch_core_session_dequeue_event(session_a, &event) == SWITCH_STATUS_SUCCESS) {
-			if (input_callback) {
-				status = input_callback(session_a, event, SWITCH_INPUT_TYPE_EVENT, user_data, 0);
-			}
-
-			if (event->event_id != SWITCH_EVENT_MESSAGE || switch_core_session_receive_event(session_b, &event) != SWITCH_STATUS_SUCCESS) {
-				switch_event_destroy(&event);
-			}
-
-		}
-
-		if (switch_core_session_dequeue_message(session_b, &message) == SWITCH_STATUS_SUCCESS) {
-			switch_core_session_receive_message(session_a, message);
-			if (switch_test_flag(message, SCSMF_DYNAMIC)) {
-				switch_safe_free(message);
-			} else {
-				message = NULL;
-			}
-		}
-
-		if (!ans_a && originator) {
-
-			if (!ans_b && switch_channel_test_flag(chan_b, CF_ANSWERED)) {
-				switch_channel_answer(chan_a);
-				ans_a++;
-			} else if (!pre_b && switch_channel_test_flag(chan_b, CF_EARLY_MEDIA)) {
-				if (switch_channel_pre_answer(chan_a) == SWITCH_STATUS_SUCCESS) {
-					pre_b++;
-				}
-			}
-			if (!pre_b) {
-				switch_yield(10000);
-				continue;
-			}
-		}
-
-
-		if (switch_channel_test_flag(chan_a, CF_SUSPEND) || switch_channel_test_flag(chan_b, CF_SUSPEND)) {
-			switch_yield(10000);
-			continue;
-		}
-
-		/* read audio from 1 channel and write it to the other */
-		status = switch_core_session_read_frame(session_a, &read_frame, -1, stream_id);
-
-		if (SWITCH_READ_ACCEPTABLE(status)) {
-			if (status != SWITCH_STATUS_BREAK && !switch_channel_test_flag(chan_a, CF_HOLD)) {
-				if (switch_core_session_write_frame(session_b, read_frame, -1, stream_id) != SWITCH_STATUS_SUCCESS) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "write: %s Bad Frame....[%u] Bubye!\n",
-									  switch_channel_get_name(chan_b), read_frame->datalen);
-					switch_mutex_lock(data->mutex);
-					data->running = -1;
-					switch_mutex_unlock(data->mutex);
-				}
-			} 
-		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "read: %s Bad Frame.... Bubye!\n", switch_channel_get_name(chan_a));
-			switch_mutex_lock(data->mutex);
-			data->running = -1;
-			switch_mutex_unlock(data->mutex);
-		}
-	}
-
-    switch_core_session_kill_channel(session_b, SWITCH_SIG_BREAK);
-	
-	msg.message_id = SWITCH_MESSAGE_INDICATE_UNBRIDGE;
-	msg.from = __FILE__;
-	switch_core_session_receive_message(session_a, &msg);
-
-	switch_channel_set_variable(chan_a, SWITCH_BRIDGE_VARIABLE, NULL);
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "BRIDGE THREAD DONE [%s]\n", switch_channel_get_name(chan_a));
-
-	switch_channel_clear_flag(chan_a, CF_BRIDGED);
-	switch_mutex_lock(data->mutex);
-	data->running = 0;
-	switch_mutex_unlock(data->mutex);
-
-	switch_core_session_rwunlock(session_a);
-	switch_core_session_rwunlock(session_b);
-	return NULL;
-}
-
-static switch_status_t audio_bridge_on_loopback(switch_core_session_t *session)
-{
-	switch_channel_t *channel = NULL;
-	void *arg;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	if ((arg = switch_channel_get_private(channel, "_bridge_"))) {
-		switch_channel_set_private(channel, "_bridge_", NULL);
-		audio_bridge_thread(NULL, (void *) arg);
-	} else {
-		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-	}
-	switch_channel_clear_state_handler(channel, &audio_bridge_peer_state_handlers);
-
-	if (!switch_channel_test_flag(channel, CF_TRANSFER)) {
-		switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
-	}
-	
-	return SWITCH_STATUS_FALSE;
-}
-
-
-static switch_status_t audio_bridge_on_ring(switch_core_session_t *session)
-{
-	switch_channel_t *channel = NULL;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "CUSTOM RING\n");
-
-	/* put the channel in a passive state so we can loop audio to it */
-	switch_channel_set_state(channel, CS_HOLD);
-	return SWITCH_STATUS_FALSE;
-}
-
-static switch_status_t audio_bridge_on_hold(switch_core_session_t *session)
-{
-	switch_channel_t *channel = NULL;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "CUSTOM HOLD\n");
-
-	/* put the channel in a passive state so we can loop audio to it */
-	return SWITCH_STATUS_FALSE;
-}
-
-static const switch_state_handler_table_t audio_bridge_peer_state_handlers = {
-	/*.on_init */ NULL,
-	/*.on_ring */ audio_bridge_on_ring,
-	/*.on_execute */ NULL,
-	/*.on_hangup */ NULL,
-	/*.on_loopback */ audio_bridge_on_loopback,
-	/*.on_transmit */ NULL,
-	/*.on_hold */ audio_bridge_on_hold,
-};
-
-
-
-static switch_status_t originate_on_ring(switch_core_session_t *session)
-{
-	switch_channel_t *channel = NULL;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	/* put the channel in a passive state so we can loop audio to it */
-
-	/* clear this handler so it only works once (next time (a.k.a. Transfer) we will do the real ring state) */
-	switch_channel_clear_state_handler(channel, &originate_state_handlers);
-
-	switch_channel_set_state(channel, CS_HOLD);
-
-	return SWITCH_STATUS_FALSE;
-}
-
-static const switch_state_handler_table_t originate_state_handlers = {
-	/*.on_init */ NULL,
-	/*.on_ring */ originate_on_ring,
-	/*.on_execute */ NULL,
-	/*.on_hangup */ NULL,
-	/*.on_loopback */ NULL,
-	/*.on_transmit */ NULL,
-	/*.on_hold */ NULL
-};
-
-
-static switch_status_t uuid_bridge_on_transmit(switch_core_session_t *session)
-{
-	switch_channel_t *channel = NULL;
-	switch_core_session_t *other_session;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "CUSTOM TRANSMIT\n");
-	switch_channel_clear_state_handler(channel, NULL);
-
-
-	if (!switch_channel_test_flag(channel, CF_ORIGINATOR)) {
-		return SWITCH_STATUS_FALSE;
-	}
-
-	if ((other_session = switch_channel_get_private(channel, SWITCH_UUID_BRIDGE))) {
-		switch_channel_t *other_channel = switch_core_session_get_channel(other_session);
-		switch_channel_state_t state = switch_channel_get_state(other_channel);
-		switch_channel_state_t mystate = switch_channel_get_state(channel);
-		switch_event_t *event;
-		uint8_t ready_a, ready_b;
-		switch_caller_profile_t *profile, *new_profile;
-
-
-		switch_channel_clear_flag(channel, CF_TRANSFER);
-		switch_channel_set_private(channel, SWITCH_UUID_BRIDGE, NULL);
-
-		while (mystate <= CS_HANGUP && state <= CS_HANGUP && !switch_channel_test_flag(other_channel, CF_TAGGED)) {
-			switch_yield(1000);
-			state = switch_channel_get_state(other_channel);
-			mystate = switch_channel_get_state(channel);
-		}
-
-		switch_channel_clear_flag(other_channel, CF_TRANSFER);
-		switch_channel_clear_flag(other_channel, CF_TAGGED);
-		
-
-		switch_core_session_reset(session);
-		switch_core_session_reset(other_session);
-		
-		ready_a = switch_channel_ready(channel);
-		ready_b = switch_channel_ready(other_channel);
-
-		if (!ready_a || !ready_b) {
-			if (!ready_a) {
-				switch_channel_hangup(other_channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			}
-
-			if (!ready_b) {
-				switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			}
-			return SWITCH_STATUS_FALSE;
-		}
-		
-		/* add another profile to both sessions for CDR's sake */
-		if ((profile = switch_channel_get_caller_profile(channel))) {
-			new_profile = switch_caller_profile_clone(session, profile);
-			new_profile->destination_number = switch_core_session_strdup(session, switch_core_session_get_uuid(other_session));
-			switch_channel_set_caller_profile(channel, new_profile);
-		} 
-
-		if ((profile = switch_channel_get_caller_profile(other_channel))) {
-			new_profile = switch_caller_profile_clone(other_session, profile);
-			new_profile->destination_number = switch_core_session_strdup(other_session, switch_core_session_get_uuid(session));
-			switch_channel_set_caller_profile(other_channel, new_profile);
-		} 
-
-		/* fire events that will change the data table from "show channels" */
-		if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_EXECUTE) == SWITCH_STATUS_SUCCESS) {
-			switch_channel_event_set_data(channel, event);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application", "uuid_bridge");
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application-Data", "%s", switch_core_session_get_uuid(other_session));
-			switch_event_fire(&event);
-		}
-
-		if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_EXECUTE) == SWITCH_STATUS_SUCCESS) {
-			switch_channel_event_set_data(other_channel, event);
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application", "uuid_bridge");
-			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application-Data", "%s", switch_core_session_get_uuid(session));
-			switch_event_fire(&event);
-		}
-
-		switch_ivr_multi_threaded_bridge(session, other_session, NULL, NULL, NULL);
-	} else {
-		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-	}
-
-
-
-	return SWITCH_STATUS_FALSE;
-}
-
-static const switch_state_handler_table_t uuid_bridge_state_handlers = {
-	/*.on_init */ NULL,
-	/*.on_ring */ NULL,
-	/*.on_execute */ NULL,
-	/*.on_hangup */ NULL,
-	/*.on_loopback */ NULL,
-	/*.on_transmit */ uuid_bridge_on_transmit,
-	/*.on_hold */ NULL
-};
-
-struct key_collect {
-	char *key;
-	char *file;
-	switch_core_session_t *session;
-};
-
-
-static void *SWITCH_THREAD_FUNC collect_thread_run(switch_thread_t *thread, void *obj)
-{
-	struct key_collect *collect = (struct key_collect *) obj;
-	switch_channel_t *channel = switch_core_session_get_channel(collect->session);
-	char buf[10] = "";
-	char *p, term;
-
-
-	if (!strcasecmp(collect->key, "exec")) {
-		char *data;
-		const switch_application_interface_t *application_interface;
-		char *app_name, *app_data;
-
-		if (!(data = collect->file)) {
-			goto wbreak;
-		}
-
-		app_name = data;
-
-		if ((app_data = strchr(app_name, ' '))) {
-			*app_data++ = '\0';
-		}
-		
-		if ((application_interface = switch_loadable_module_get_application_interface(app_name)) == 0) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Application %s\n", app_name);
-			switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			goto wbreak;
-		}
-
-		if (!application_interface->application_function) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No Function for %s\n", app_name);
-			switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-			goto wbreak;
-		}
-
-		application_interface->application_function(collect->session, app_data);
-		if (switch_channel_get_state(channel) < CS_HANGUP) {
-			switch_channel_set_flag(channel, CF_WINNER);
-		}
-		goto wbreak;
-	}
-
-	if (!switch_channel_ready(channel)) {
-		switch_channel_hangup(channel, SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER);
-		goto wbreak;
-	}
-
-	while(switch_channel_ready(channel)) {
-		memset(buf, 0, sizeof(buf));
-
-		if (collect->file) {
-            switch_input_args_t args = {0};
-            args.buf = buf;
-            args.buflen = sizeof(buf);
-			switch_ivr_play_file(collect->session, NULL, collect->file, &args);
-		} else {
-			switch_ivr_collect_digits_count(collect->session, buf, sizeof(buf), 1, "", &term, 0);
-		}
-
-		for(p = buf; *p; p++) {
-			if (*collect->key == *p) {
-				switch_channel_set_flag(channel, CF_WINNER);
-				goto wbreak;
-			}
-		}
-	}
- wbreak:
-
-	return NULL;
-}
-
-static void launch_collect_thread(struct key_collect *collect)
-{
-	switch_thread_t *thread;
-	switch_threadattr_t *thd_attr = NULL;
-	
-	switch_threadattr_create(&thd_attr, switch_core_session_get_pool(collect->session));
-	switch_threadattr_detach_set(thd_attr, 1);
-	switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
-	switch_thread_create(&thread, thd_attr, collect_thread_run, collect, switch_core_session_get_pool(collect->session));
-}
-
-static uint8_t check_channel_status(switch_channel_t **peer_channels,
-									switch_core_session_t **peer_sessions,
-									uint32_t len,
-									int32_t *idx,
-									uint32_t *hups,
-									char *file,
-									char *key,
-									uint8_t early_ok,
-									uint8_t *ring_ready)
-{
-
-	uint32_t i;
-	*hups = 0;
-	*idx = IDX_NADA;
-	
-	for (i = 0; i < len; i++) {
-		if (!peer_channels[i]) {
-			continue;
-		}
-		if (!*ring_ready && switch_channel_test_flag(peer_channels[i], CF_RING_READY)) {
-			*ring_ready = 1;
-		}
-		if (switch_channel_get_state(peer_channels[i]) >= CS_HANGUP) {
-			(*hups)++;
-		} else if ((switch_channel_test_flag(peer_channels[i], CF_ANSWERED) || 
-                    (early_ok && len == 1 && switch_channel_test_flag(peer_channels[i], CF_EARLY_MEDIA))) && 
-				   !switch_channel_test_flag(peer_channels[i], CF_TAGGED)) {
-
-			if (key) {
-				struct key_collect *collect;
-				
-				if ((collect = switch_core_session_alloc(peer_sessions[i], sizeof(*collect)))) {
-					switch_channel_set_flag(peer_channels[i], CF_TAGGED);
-					collect->key = key;
-					if (file) {
-						collect->file = switch_core_session_strdup(peer_sessions[i], file);
-					}
-				
-					collect->session = peer_sessions[i];
-					launch_collect_thread(collect);
-				}
-			} else {
-				*idx = i;
-				return 0;
-					
-			}
-		} else if (switch_channel_test_flag(peer_channels[i], CF_WINNER)) {
-			*idx = i;
-			return 0;
-		}
-	}
-
-	if (*hups == len) {
-		return 0;
-	} else {
-		return 1;
-	}
-	
-}
-
-struct ringback {
-	switch_buffer_t *audio_buffer;
-    switch_buffer_t *loop_buffer;
-	teletone_generation_session_t ts;	
-	switch_file_handle_t fhb;
-	switch_file_handle_t *fh;
-	uint8_t asis;
-};
-
-typedef struct ringback ringback_t;
-
-static int teletone_handler(teletone_generation_session_t *ts, teletone_tone_map_t *map)
-{
-	ringback_t *tto = ts->user_data;
-	int wrote;
-
-	if (!tto) {
-		return -1;
-	}
-	wrote = teletone_mux_tones(ts, map);
-	switch_buffer_write(tto->audio_buffer, ts->buffer, wrote * 2);
-
-	return 0;
-}
-
-#define MAX_PEERS 256
-SWITCH_DECLARE(switch_status_t) switch_ivr_originate(switch_core_session_t *session,
-													 switch_core_session_t **bleg,
-													 switch_call_cause_t *cause,
-													 char *bridgeto,
-													 uint32_t timelimit_sec,
-													 const switch_state_handler_table_t *table,
-													 char *cid_name_override,
-													 char *cid_num_override,
-													 switch_caller_profile_t *caller_profile_override
-													 )
-										  
-{
-	char *pipe_names[MAX_PEERS] = {0};
-	char *data = NULL;
-	switch_status_t status = SWITCH_STATUS_SUCCESS;
-	switch_channel_t *caller_channel = NULL;
-	char *peer_names[MAX_PEERS] = {0};
-	switch_core_session_t *peer_session, *peer_sessions[MAX_PEERS] = {0};
-	switch_caller_profile_t *caller_profiles[MAX_PEERS] = {0}, *caller_caller_profile;
-	char *chan_type = NULL, *chan_data;
-	switch_channel_t *peer_channel = NULL, *peer_channels[MAX_PEERS] = {0};
-	ringback_t ringback = {0};
-	time_t start;
-	switch_frame_t *read_frame = NULL;
-	switch_memory_pool_t *pool = NULL;
-	int r = 0, i, and_argc = 0, or_argc = 0;
-	int32_t idx = IDX_NADA;
-	switch_codec_t write_codec = {0};
-	switch_frame_t write_frame = {0};
-	uint8_t fdata[1024], pass = 0;
-	char *file = NULL, *key = NULL, *odata, *var;
-	switch_call_cause_t reason = SWITCH_CAUSE_UNALLOCATED;
-	uint8_t to = 0;
-	char *var_val, *vars = NULL, *ringback_data = NULL;
-	switch_codec_t *read_codec = NULL;
-	uint8_t sent_ring = 0, early_ok = 1;
-	switch_core_session_message_t *message = NULL;
-    switch_event_t *var_event = NULL;
-	uint8_t fail_on_single_reject = 0;
-	uint8_t ring_ready = 0;
-	write_frame.data = fdata;
-	
-	*bleg = NULL;
-	odata = strdup(bridgeto);
-	data = odata;
-
-    /* strip leading spaces */
-    while (data && *data && *data == ' ') {
-        data++;
-    }
-
-    if (*data == '{') {
-        vars = data + 1;
-        if (!(data = strchr(data, '}'))) {
-            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Parse Error!\n");
-            status = SWITCH_STATUS_GENERR;
-            goto done;
-        }
-        *data++ = '\0';
-    }
-
-    /* strip leading spaces (again)*/
-    while (data && *data && *data == ' ') {
-        data++;
-    }
-    
-    if (switch_strlen_zero(data)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Parse Error!\n");
-        status = SWITCH_STATUS_GENERR;
-        goto done;
-    }
-    
-    /* Some channel are created from an originating channel and some aren't so not all outgoing calls have a way to get params
-       so we will normalize dialstring params and channel variables (when there is an originator) into an event that we 
-       will use as a pseudo hash to consult for params as needed.
-     */
-    if (switch_event_create(&var_event, SWITCH_EVENT_MESSAGE) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n");
-        status = SWITCH_STATUS_MEMERR;
-        goto done;
-    }
-    
-	if (session) {
-        switch_hash_index_t *hi;
-        void *vval;
-        const void *vvar;
-        
-        caller_channel = switch_core_session_get_channel(session);
-		assert(caller_channel != NULL);
-
-        /* Copy all the channel variables into the event */
-        for (hi = switch_channel_variable_first(caller_channel, switch_core_session_get_pool(session)); hi; hi = switch_hash_next(hi)) {
-            switch_hash_this(hi, &vvar, NULL, &vval);
-            if (vvar && vval) {
-                switch_event_add_header(var_event, SWITCH_STACK_BOTTOM, (void *)vvar, "%s", (char *)vval);
-            }
-        }
-
-    }
-
-    if (vars) { /* Parse parameters specified from the dialstring */
-        char *var_array[1024] = {0};
-        int var_count = 0;
-        if ((var_count = switch_separate_string(vars, ',', var_array, (sizeof(var_array) / sizeof(var_array[0]))))) {
-            int x = 0;
-            for (x = 0; x < var_count; x++) {
-                char *inner_var_array[2];
-                int inner_var_count;
-                if ((inner_var_count = 
-                     switch_separate_string(var_array[x], '=', inner_var_array, (sizeof(inner_var_array) / sizeof(inner_var_array[0])))) == 2) {
-                    
-                    switch_event_add_header(var_event, SWITCH_STACK_BOTTOM, inner_var_array[0], "%s", inner_var_array[1]);
-                    if (caller_channel) {
-                        switch_channel_set_variable(caller_channel, inner_var_array[0], inner_var_array[1]);
-                    }
-                }
-            }
-        }
-    }
-
-
-    if (caller_channel) { /* ringback is only useful when there is an originator */
-		ringback_data = switch_channel_get_variable(caller_channel, "ringback");
-		switch_channel_set_variable(caller_channel, "originate_disposition", "failure");
-	}
-	
-    if ((var = switch_event_get_header(var_event, "group_confirm_key"))) {
-        key = switch_core_session_strdup(session, var);
-        if ((var = switch_event_get_header(var_event, "group_confirm_file"))) {
-            file = switch_core_session_strdup(session, var);
-        }
-    }
-
-	// When using the AND operator, the fail_on_single_reject flage may be set in order to indicate that a single
-	// rejections should terminate the attempt rather than a timeout, answer, or rejection by all.
-	if ((var = switch_event_get_header(var_event, "fail_on_single_reject")) && switch_true(var)) {
-		fail_on_single_reject = 1;
-	}
-
-	if (file && !strcmp(file, "undef")) {
-		file = NULL;
-	}
-
-    if ((var_val = switch_event_get_header(var_event, "ignore_early_media")) && switch_true(var_val)) {
-        early_ok = 0;
-    }
-
-    if (!cid_name_override) {
-        cid_name_override = switch_event_get_header(var_event, "origination_caller_id_name");
-    }
-
-    if (!cid_num_override) {
-        cid_num_override = switch_event_get_header(var_event, "origination_caller_id_number");
-    }
-                                                        
-
-	or_argc = switch_separate_string(data, '|', pipe_names, (sizeof(pipe_names) / sizeof(pipe_names[0])));
-
-	if (caller_channel && or_argc > 1 && !ringback_data) {
-		switch_channel_ring_ready(caller_channel);
-		sent_ring = 1;
-	}
-
-	for (r = 0; r < or_argc; r++) {
-		uint32_t hups;
-        reason = SWITCH_CAUSE_UNALLOCATED;
-		memset(peer_names, 0, sizeof(peer_names));
-		peer_session = NULL;
-		memset(peer_sessions, 0, sizeof(peer_sessions));
-		memset(peer_channels, 0, sizeof(peer_channels));
-		memset(caller_profiles, 0, sizeof(caller_profiles));
-		chan_type = NULL;
-		chan_data = NULL;
-		peer_channel = NULL;
-		start = 0;
-		read_frame = NULL;
-		pool = NULL;
-		pass = 0;
-		file = NULL;
-		key = NULL;
-		var = NULL;
-		to = 0;
-
-		and_argc = switch_separate_string(pipe_names[r], ',', peer_names, (sizeof(peer_names) / sizeof(peer_names[0])));
-	
-		if (caller_channel && !sent_ring && and_argc > 1 && !ringback_data) {
-			switch_channel_ring_ready(caller_channel);
-			sent_ring = 1;
-		}
-
-		for (i = 0; i < and_argc; i++) {
-		
-			chan_type = peer_names[i];
-			if ((chan_data = strchr(chan_type, '/')) != 0) {
-				*chan_data = '\0';
-				chan_data++;
-			}
-	
-			if (session) {
-				if (!switch_channel_ready(caller_channel)) {
-					status = SWITCH_STATUS_FALSE;
-					goto done;
-				}
-
-				caller_caller_profile = caller_profile_override ? caller_profile_override : switch_channel_get_caller_profile(caller_channel);
-                
-				if (!cid_name_override) {
-					cid_name_override = caller_caller_profile->caller_id_name;
-				}
-				if (!cid_num_override) {
-					cid_num_override = caller_caller_profile->caller_id_number;
-				}
-
-				caller_profiles[i] = switch_caller_profile_new(switch_core_session_get_pool(session),
-															   caller_caller_profile->username,
-															   caller_caller_profile->dialplan,
-															   cid_name_override,
-															   cid_num_override,
-															   caller_caller_profile->network_addr,
-															   NULL,
-															   NULL,
-															   caller_caller_profile->rdnis,
-															   caller_caller_profile->source,
-															   caller_caller_profile->context,
-															   chan_data);
-				caller_profiles[i]->flags = caller_caller_profile->flags;
-				pool = NULL;
-			} else {
-				if (!cid_name_override) {
-					cid_name_override = "FreeSWITCH";
-				}
-				if (!cid_num_override) {
-					cid_num_override = "0000000000";
-				}
-
-				if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "OH OH no pool\n");
-					status = SWITCH_STATUS_TERM;
-					goto done;
-				}
-
-				if (caller_profile_override) {
-					caller_profiles[i] = switch_caller_profile_new(pool,
-																   caller_profile_override->username,
-																   caller_profile_override->dialplan,
-																   caller_profile_override->caller_id_name,
-																   caller_profile_override->caller_id_number,
-																   caller_profile_override->network_addr, 
-																   caller_profile_override->ani,
-																   caller_profile_override->aniii,
-																   caller_profile_override->rdnis,
-																   caller_profile_override->source,
-																   caller_profile_override->context,
-																   chan_data);
-				} else {
-					caller_profiles[i] = switch_caller_profile_new(pool,
-																   NULL,
-																   NULL,
-																   cid_name_override,
-																   cid_num_override,
-																   NULL,
-																   NULL, 
-																   NULL,
-																   NULL,
-																   __FILE__,
-																   NULL,
-																   chan_data);
-				}
-			}
-
-			if ((reason = switch_core_session_outgoing_channel(session, chan_type, caller_profiles[i], &peer_sessions[i], pool)) != SWITCH_CAUSE_SUCCESS) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Create Outgoing Channel! cause: %s\n", switch_channel_cause2str(reason));
-				if (pool) {
-					switch_core_destroy_memory_pool(&pool);
-				}
-				caller_profiles[i] = NULL;
-				peer_channels[i] = NULL;
-				peer_sessions[i] = NULL;
-				continue;
-			}
-			
-			switch_core_session_read_lock(peer_sessions[i]);
-			pool = NULL;
-	
-			peer_channels[i] = switch_core_session_get_channel(peer_sessions[i]);
-			assert(peer_channels[i] != NULL);
-
-			if (!table) {
-				table = &originate_state_handlers;
-			}
-
-			if (table) {
-				switch_channel_add_state_handler(peer_channels[i], table);
-			}
-
-			if (switch_core_session_running(peer_sessions[i])) {
-				switch_channel_set_state(peer_channels[i], CS_RING);
-			} else {
-				switch_core_session_thread_launch(peer_sessions[i]);
-			}
-		}
-
-		time(&start);
-
-		for (;;) {
-			uint32_t valid_channels = 0;
-			for (i = 0; i < and_argc; i++) {
-				int state;
-
-				if (!peer_channels[i]) {
-					continue;
-				}
-				valid_channels++;
-				state = switch_channel_get_state(peer_channels[i]);
-			
-				if (state >= CS_HANGUP) {
-					goto notready;
-				} else if (state >= CS_RING) {
-					goto endfor1;
-				}
-		
-				if (caller_channel && !switch_channel_ready(caller_channel)) {
-					goto notready;
-				}
-				
-				if ((time(NULL) - start) > (time_t)timelimit_sec) {
-					to++;
-					idx = IDX_CANCEL;
-					goto notready;
-				}
-				switch_yield(1000);
-			}
-
-			if (valid_channels == 0) {
-				status = SWITCH_STATUS_GENERR;
-				goto done;
-			}
-
-		}
-	endfor1:
-
-		if (ringback_data && !switch_channel_test_flag(caller_channel, CF_ANSWERED) && !switch_channel_test_flag(caller_channel, CF_EARLY_MEDIA)) {
-			switch_channel_pre_answer(caller_channel);
-		}
-
-		if (session && (read_codec = switch_core_session_get_read_codec(session)) && 
-			(ringback_data || !switch_channel_test_flag(caller_channel, CF_NOMEDIA))) {
-
-			if (!(pass = (uint8_t)switch_test_flag(read_codec, SWITCH_CODEC_FLAG_PASSTHROUGH))) {
-				if (switch_core_codec_init(&write_codec,
-										   "L16",
-										   NULL,
-										   read_codec->implementation->samples_per_second,
-										   read_codec->implementation->microseconds_per_frame / 1000,
-										   1,
-										   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-										   NULL,
-										   pool) == SWITCH_STATUS_SUCCESS) {
-					
-					
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Success L16@%uhz 1 channel %dms\n",
-									  read_codec->implementation->samples_per_second,
-									  read_codec->implementation->microseconds_per_frame / 1000);
-					write_frame.codec = &write_codec;
-					write_frame.datalen = read_codec->implementation->bytes_per_frame;
-					write_frame.samples = write_frame.datalen / 2;
-					memset(write_frame.data, 255, write_frame.datalen);
-					
-					if (ringback_data) {
-						char *tmp_data = NULL;
-						
-						switch_buffer_create_dynamic(&ringback.audio_buffer, 512, 1024, 0);
-						switch_buffer_create_dynamic(&ringback.loop_buffer, 512, 1024, 0);
-
-						if (*ringback_data == '/') {
-							char *ext;
-							
-							if ((ext = strrchr(ringback_data, '.'))) {
-								switch_core_session_set_read_codec(session, &write_codec);
-								ext++;
-							} else {
-								ringback.asis++;
-								write_frame.codec = read_codec;
-								ext = read_codec->implementation->iananame;
-								tmp_data = switch_mprintf("%s.%s", ringback_data, ext);
-								ringback_data = tmp_data;
-							}
-
-							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Play Ringback File [%s]\n", ringback_data);
-
-							ringback.fhb.channels = read_codec->implementation->number_of_channels;
-							ringback.fhb.samplerate = read_codec->implementation->samples_per_second;
-							if (switch_core_file_open(&ringback.fhb,
-													  ringback_data,
-													  SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT,
-													  switch_core_session_get_pool(session)) != SWITCH_STATUS_SUCCESS) {
-								switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Playing File\n");
-								switch_safe_free(tmp_data);
-								goto notready;
-							}
-							ringback.fh = &ringback.fhb;
-
-							
-						} else {
-							teletone_init_session(&ringback.ts, 0, teletone_handler, &ringback);
-							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Play Ringback Tone [%s]\n", ringback_data);
-							//ringback.ts.debug = 1;
-							//ringback.ts.debug_stream = switch_core_get_console();
-							if (teletone_run(&ringback.ts, ringback_data)) {
-								switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Playing Tone\n");
-								teletone_destroy_session(&ringback.ts);
-								switch_buffer_destroy(&ringback.audio_buffer);
-								switch_buffer_destroy(&ringback.loop_buffer);
-								ringback_data = NULL;
-							}
-						}
-						switch_safe_free(tmp_data);
-					}
-				} else {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Codec Error!");
-					switch_channel_hangup(caller_channel, SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE);
-					read_codec = NULL;
-				}
-			}
-		}
-        
-        if (ringback_data) {
-            early_ok = 0;
-        }
-
-        while ((!caller_channel || switch_channel_ready(caller_channel)) && 
-			   check_channel_status(peer_channels, peer_sessions, and_argc, &idx, &hups, file, key, early_ok, &ring_ready)) {
-
-			// When the AND operator is being used, and fail_on_single_reject is set, a hangup indicates that the call should fail.
-			if ((to = (uint8_t)((time(NULL) - start) >= (time_t)timelimit_sec)) || (fail_on_single_reject && hups)) {
-				idx = IDX_CANCEL;
-				goto notready;
-			}
-
-			if (peer_sessions[0] && switch_core_session_dequeue_message(peer_sessions[0], &message) == SWITCH_STATUS_SUCCESS) {
-				if (session && !ringback_data && or_argc == 1 && and_argc == 1) { /* when there is only 1 channel to call and bridge and no ringback */
-					switch_core_session_receive_message(session, message);
-				}
-				
-				if (switch_test_flag(message, SCSMF_DYNAMIC)) {
-					switch_safe_free(message);
-				} else {
-					message = NULL;
-				}
-			}
-
-			/* read from the channel while we wait if the audio is up on it */
-			if (session && (ringback_data || !switch_channel_test_flag(caller_channel, CF_NOMEDIA)) && 
-				(switch_channel_test_flag(caller_channel, CF_ANSWERED) || switch_channel_test_flag(caller_channel, CF_EARLY_MEDIA))) {
-				switch_status_t status = switch_core_session_read_frame(session, &read_frame, 1000, 0);
-			
-				if (!SWITCH_READ_ACCEPTABLE(status)) {
-					break;
-				}
-				
-				if (ring_ready && read_frame && !pass && !switch_test_flag(read_frame, SFF_CNG) && read_frame->datalen > 1) {
-					if (ringback.fh) {
-						uint8_t abuf[1024];
-						switch_size_t mlen, olen;
-						unsigned int pos = 0;
-
-						if (ringback.asis) {
-							mlen = read_frame->datalen;
-						} else {
-							mlen = read_frame->datalen  / 2;
-						}
-
-						olen = mlen;
-						switch_core_file_read(ringback.fh, abuf, &olen);
-						
-						if (olen == 0) {
-							olen = mlen;
-							ringback.fh->speed = 0;
-							switch_core_file_seek(ringback.fh, &pos, 0, SEEK_SET);
-							switch_core_file_read(ringback.fh, abuf, &olen);
-							if (olen == 0) {
-								break;
-							}
-						}
-						write_frame.data = abuf;
-						write_frame.datalen = (uint32_t) (ringback.asis ? olen : olen * 2);
-						if (switch_core_session_write_frame(session, &write_frame, 1000, 0) != SWITCH_STATUS_SUCCESS) {
-							break;
-						}
-					} else if (ringback.audio_buffer) {
-						if ((write_frame.datalen = (uint32_t)switch_buffer_read(ringback.audio_buffer,
-																				write_frame.data,
-																				write_frame.codec->implementation->bytes_per_frame)) <= 0) {
-							switch_buffer_t *tmp;
-							tmp = ringback.audio_buffer;
-							ringback.audio_buffer = ringback.loop_buffer;
-							ringback.loop_buffer = tmp;
-							if ((write_frame.datalen = (uint32_t)switch_buffer_read(ringback.audio_buffer,
-																					write_frame.data,
-																					write_frame.codec->implementation->bytes_per_frame)) <= 0) {
-								break;
-							}
-						}
-					}
-
-					if (switch_core_session_write_frame(session, &write_frame, 1000, 0) != SWITCH_STATUS_SUCCESS) {
-						break;
-					}
-					if (ringback.loop_buffer) {
-						switch_buffer_write(ringback.loop_buffer, write_frame.data, write_frame.datalen);
-					}
-				}
-
-			} else {
-				switch_yield(1000);
-			}
-		
-		}
-
-	notready:
-
-		if (caller_channel && !switch_channel_ready(caller_channel)) {
-			idx = IDX_CANCEL;
-		}
-
-		if (session && (ringback_data || !switch_channel_test_flag(caller_channel, CF_NOMEDIA))) {
-			switch_core_session_reset(session);
-		}
-
-		for (i = 0; i < and_argc; i++) {
-			if (!peer_channels[i]) {
-				continue;
-			}
-			if (i != idx) {
-				if (idx == IDX_CANCEL) {
-					if (to) {
-						reason = SWITCH_CAUSE_NO_ANSWER;
-                    } else {
-                        reason = SWITCH_CAUSE_ORIGINATOR_CANCEL;
-                    }
-				} else {
-					if (to) {
-						reason = SWITCH_CAUSE_NO_ANSWER;
-					} else if (and_argc > 1) {
-						reason = SWITCH_CAUSE_LOSE_RACE;
-					} else {
-						reason = SWITCH_CAUSE_NO_ANSWER;
-					}
-				}
-
-				
-				switch_channel_hangup(peer_channels[i], reason);
-			}
-		}
-
-
-		if (idx > IDX_NADA) {
-			peer_session = peer_sessions[idx];
-			peer_channel = peer_channels[idx];
-		} else {
-			status = SWITCH_STATUS_FALSE;
-			goto done;
-		}
-
-		if (caller_channel) {
-			if (switch_channel_test_flag(peer_channel, CF_ANSWERED)) {
-				switch_channel_answer(caller_channel);
-			} else if (switch_channel_test_flag(peer_channel, CF_EARLY_MEDIA)) {
-				switch_channel_pre_answer(caller_channel);
-			}
-		}
-
-		if (switch_channel_test_flag(peer_channel, CF_ANSWERED) || switch_channel_test_flag(peer_channel, CF_EARLY_MEDIA)) {
-			*bleg = peer_session;
-			status = SWITCH_STATUS_SUCCESS;
-		} else {
-			status = SWITCH_STATUS_FALSE;
-		}
-
-	done:
-		*cause = SWITCH_CAUSE_UNALLOCATED;
-        
-        if (var_event) {
-			if (peer_channel && !caller_channel) { /* install the vars from the {} params */
-                switch_event_header_t *header;
-                for (header = var_event->headers; header; header = header->next) {
-                    switch_channel_set_variable(peer_channel, header->name, header->value);
-                }
-            }
-            switch_event_destroy(&var_event);
-        }
-
-		if (status == SWITCH_STATUS_SUCCESS) {
-			if (caller_channel) {
-				switch_channel_set_variable(caller_channel, "originate_disposition", "call accepted");
-			} 
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Originate Resulted in Success: [%s]\n", switch_channel_get_name(peer_channel));
-            *cause = SWITCH_CAUSE_SUCCESS;
-            
-		} else {
-			if (peer_channel) {
-				*cause = switch_channel_get_cause(peer_channel);
-			} else {
-				for (i = 0; i < and_argc; i++) {
-					if (!peer_channels[i]) {
-						continue;
-					}
-                    *cause = switch_channel_get_cause(peer_channels[i]);
-					break;
-				}
-			}
-
-            if (!*cause) {
-                if (reason) {
-                    *cause = reason;
-                } else if (caller_channel) {
-                    *cause = switch_channel_get_cause(caller_channel);
-                } else {
-                    *cause = SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER;
-                }
-            }
-
-			if (idx == IDX_CANCEL) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Originate Cancelled by originator termination Cause: %d [%s]\n",
-								  *cause, switch_channel_cause2str(*cause));
-                
-			} else {
-                switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Originate Resulted in Error Cause: %d [%s]\n",
-								  *cause, switch_channel_cause2str(*cause));
-			}
-		}
-        
-        if (caller_channel) {
-            switch_channel_set_variable(caller_channel, "originate_disposition", switch_channel_cause2str(*cause));
-        }
-
-		if (!pass && write_codec.implementation) {
-			switch_core_codec_destroy(&write_codec);
-		}
-
-		if (ringback.fh) {
-			switch_core_file_close(ringback.fh);
-			ringback.fh = NULL;
-			if (read_codec && !ringback.asis) {
-				switch_core_session_set_read_codec(session, read_codec);
-				switch_core_session_reset(session);
-			}
-		} else if (ringback.audio_buffer) {
-			teletone_destroy_session(&ringback.ts);
-			switch_buffer_destroy(&ringback.audio_buffer);
-			switch_buffer_destroy(&ringback.loop_buffer);
-		}
-
-		for (i = 0; i < and_argc; i++) {
-			if (!peer_channels[i]) {
-				continue;
-			}
-			switch_core_session_rwunlock(peer_sessions[i]);
-		}
-
-		if (status == SWITCH_STATUS_SUCCESS) {
-			break;
-		}
-	}
-
-	switch_safe_free(odata);
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_hold(switch_core_session_t *session)
-{
-	switch_core_session_message_t msg = {0};
-	switch_channel_t *channel;
-
-	msg.message_id = SWITCH_MESSAGE_INDICATE_HOLD;
-	msg.from = __FILE__;
-	
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-		
-	switch_channel_set_flag(channel, CF_HOLD);
-	switch_channel_set_flag(channel, CF_SUSPEND);
-
-	switch_core_session_receive_message(session, &msg);
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_hold_uuid(char *uuid)
-{
-	switch_core_session_t *session;
-
-	if ((session = switch_core_session_locate(uuid))) {
-		switch_ivr_hold(session);
-		switch_core_session_rwunlock(session);
-	}
-	
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_unhold(switch_core_session_t *session)
-{
-	switch_core_session_message_t msg = {0};
-	switch_channel_t *channel;
-		
-	msg.message_id = SWITCH_MESSAGE_INDICATE_UNHOLD;
-	msg.from = __FILE__;
-	
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-		
-	switch_channel_clear_flag(channel, CF_HOLD);
-	switch_channel_clear_flag(channel, CF_SUSPEND);
-	
-	switch_core_session_receive_message(session, &msg);
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_unhold_uuid(char *uuid)
-{
-	switch_core_session_t *session;
-
-	if ((session = switch_core_session_locate(uuid))) {
-		switch_ivr_unhold(session);
-		switch_core_session_rwunlock(session);
-	}
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_broadcast(char *uuid, char *path, switch_media_flag_t flags)
-{
-    switch_channel_t *channel;
-	int nomedia;
-	switch_core_session_t *session, *master;
-	switch_event_t *event;
-	switch_core_session_t *other_session = NULL;
-	char *other_uuid = NULL;
-
-	if ((session = switch_core_session_locate(uuid))) {
-		char *app;
-		master = session;
-
-		channel = switch_core_session_get_channel(session);
-		assert(channel != NULL);
-
-		if ((nomedia = switch_channel_test_flag(channel, CF_NOMEDIA))) {
-			switch_ivr_media(uuid, SMF_REBRIDGE);
-		}
-		
-		if (!strncasecmp(path, "speak:", 6)) {
-			path += 6;
-			app = "speak";
-		} else {
-			app = "playback";
-		}
-		
-		if ((flags & SMF_ECHO_BLEG) && (other_uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE))
-			&& (other_session = switch_core_session_locate(other_uuid))) {
-			if (switch_event_create(&event, SWITCH_EVENT_MESSAGE) == SWITCH_STATUS_SUCCESS) {
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "call-command", "execute");
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "execute-app-name", "%s", app);
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "execute-app-arg", "%s", path);
-				switch_core_session_queue_private_event(other_session, &event);
-			}
-			switch_core_session_rwunlock(other_session);
-			master = other_session;
-			other_session = NULL;
-		}
-		
-		if ((flags & SMF_ECHO_ALEG)) {
-			if (switch_event_create(&event, SWITCH_EVENT_MESSAGE) == SWITCH_STATUS_SUCCESS) {
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "call-command", "execute");
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "execute-app-name", "%s", app);
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "execute-app-arg", "%s", path);
-				switch_core_session_queue_private_event(session, &event);
-			}
-			master = session;
-		}
-
-		if (nomedia) {
-			if (switch_event_create(&event, SWITCH_EVENT_MESSAGE) == SWITCH_STATUS_SUCCESS) {
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "call-command", "nomedia");
-				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "nomedia-uuid", "%s", uuid);
-				switch_core_session_queue_private_event(master, &event);
-			}
-		}
-		
-		switch_core_session_rwunlock(session);
-	}
-	return SWITCH_STATUS_SUCCESS;
-	
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_media(char *uuid, switch_media_flag_t flags)
-{
-	char *other_uuid = NULL;
-	switch_channel_t *channel, *other_channel = NULL;
-    switch_core_session_t *session, *other_session;
-	switch_core_session_message_t msg = {0};
-	switch_status_t status = SWITCH_STATUS_GENERR;
-	uint8_t swap = 0;
-
-	msg.message_id = SWITCH_MESSAGE_INDICATE_MEDIA;
-	msg.from = __FILE__;
-
-	if ((session = switch_core_session_locate(uuid))) {
-		channel = switch_core_session_get_channel(session);
-		assert(channel != NULL);
-		if ((flags & SMF_REBRIDGE) && !switch_channel_test_flag(channel, CF_ORIGINATOR)) {
-			swap = 1;
-		}
-		
-		if (switch_channel_test_flag(channel, CF_NOMEDIA)) {
-			status = SWITCH_STATUS_SUCCESS;
-			switch_channel_clear_flag(channel, CF_NOMEDIA);
-			switch_core_session_receive_message(session, &msg);
-
-			if ((flags & SMF_REBRIDGE) && (other_uuid = switch_channel_get_variable(channel, SWITCH_SIGNAL_BRIDGE_VARIABLE)) 
-				&& (other_session = switch_core_session_locate(other_uuid))) {
-				other_channel = switch_core_session_get_channel(other_session);
-				assert(other_channel != NULL);
-				switch_core_session_receive_message(other_session, &msg);
-				switch_channel_clear_state_handler(other_channel, NULL);
-				switch_core_session_rwunlock(other_session);
-			}
-			if (other_channel) {
-				switch_channel_clear_state_handler(channel, NULL);
-			}
-		}
-		
-		switch_core_session_rwunlock(session);
-
-		if (other_channel) {
-			if (swap) {
-				switch_ivr_uuid_bridge(other_uuid, uuid);
-			} else {
-				switch_ivr_uuid_bridge(uuid, other_uuid);
-			}
-		}
-	}
-
-	return status;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_nomedia(char *uuid, switch_media_flag_t flags)
-{
-	char *other_uuid;
-	switch_channel_t *channel, *other_channel = NULL;
-    switch_core_session_t *session, *other_session = NULL;
-	switch_core_session_message_t msg = {0};
-	switch_status_t status = SWITCH_STATUS_GENERR;
-	uint8_t swap = 0;
-
-	msg.message_id = SWITCH_MESSAGE_INDICATE_NOMEDIA;
-	msg.from = __FILE__;
-
-	if ((session = switch_core_session_locate(uuid))) {
-		status = SWITCH_STATUS_SUCCESS;
-		channel = switch_core_session_get_channel(session);
-		assert(channel != NULL);
-
-		if ((flags & SMF_REBRIDGE) && !switch_channel_test_flag(channel, CF_ORIGINATOR)) {
-			swap = 1;
-		}
-
-		if ((flags & SMF_FORCE) || !switch_channel_test_flag(channel, CF_NOMEDIA)) {
-			switch_channel_set_flag(channel, CF_NOMEDIA);
-			switch_core_session_receive_message(session, &msg);
-			if ((flags & SMF_REBRIDGE) && (other_uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) &&
-				(other_session = switch_core_session_locate(other_uuid))) {
-				other_channel = switch_core_session_get_channel(other_session);
-				assert(other_channel != NULL);
-				switch_core_session_receive_message(other_session, &msg);
-				switch_channel_clear_state_handler(other_channel, NULL);
-
-			}
-			if (other_channel) {
-				switch_channel_clear_state_handler(channel, NULL);
-				if (swap) {
-					switch_ivr_signal_bridge(other_session, session);
-				} else {
-					switch_ivr_signal_bridge(session, other_session);
-				}
-				switch_core_session_rwunlock(other_session);
-			}
-		}
-		switch_core_session_rwunlock(session);
-	}
-
-	return status;
-}
-
-static switch_status_t signal_bridge_on_hibernate(switch_core_session_t *session)
-{
-	switch_channel_t *channel = NULL;
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-	switch_channel_clear_flag(channel, CF_TRANSFER);
-
-	switch_channel_set_variable(channel, SWITCH_BRIDGE_VARIABLE, switch_channel_get_variable(channel, SWITCH_SIGNAL_BRIDGE_VARIABLE));
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static switch_status_t signal_bridge_on_hangup(switch_core_session_t *session)
-{
-	char *uuid;
-	switch_channel_t *channel = NULL;
-    switch_core_session_t *other_session;
-	switch_event_t *event;
-
-    channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
-
-	if (switch_channel_test_flag(channel, CF_ORIGINATOR)) {
-		switch_channel_clear_flag(channel, CF_ORIGINATOR);
-		if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_UNBRIDGE) == SWITCH_STATUS_SUCCESS) {
-			switch_channel_event_set_data(channel, event);
-			switch_event_fire(&event);
-		}
-	}
-
-
-	if ((uuid = switch_channel_get_variable(channel, SWITCH_BRIDGE_VARIABLE)) && (other_session = switch_core_session_locate(uuid))) {
-		switch_channel_t *other_channel = NULL;
-
-		other_channel = switch_core_session_get_channel(other_session);
-		assert(other_channel != NULL);
-
-		switch_channel_hangup(other_channel, switch_channel_get_cause(channel));
-		switch_core_session_rwunlock(other_session);
-	}
-
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-static const switch_state_handler_table_t signal_bridge_state_handlers = {
-	/*.on_init */ NULL,
-	/*.on_ring */ NULL,
-	/*.on_execute */ NULL,
-	/*.on_hangup */ signal_bridge_on_hangup,
-	/*.on_loopback */ NULL,
-	/*.on_transmit */ NULL,
-	/*.on_hold */ NULL,
-	/*.on_hibernate*/ signal_bridge_on_hibernate
-};
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_signal_bridge(switch_core_session_t *session, switch_core_session_t *peer_session)
-{
-	switch_channel_t *caller_channel, *peer_channel;
-	switch_event_t *event;
-
-	caller_channel = switch_core_session_get_channel(session);
-	assert(caller_channel != NULL);
-
-	peer_channel = switch_core_session_get_channel(peer_session);
-	assert(peer_channel != NULL);
-
-	switch_channel_set_flag(caller_channel, CF_ORIGINATOR);
-
-	switch_channel_clear_state_handler(caller_channel, NULL);
-	switch_channel_clear_state_handler(peer_channel, NULL);
-
-	switch_channel_add_state_handler(caller_channel, &signal_bridge_state_handlers);
-	switch_channel_add_state_handler(peer_channel, &signal_bridge_state_handlers);
-
-
-	/* fire events that will change the data table from "show channels" */
-	if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_EXECUTE) == SWITCH_STATUS_SUCCESS) {
-		switch_channel_event_set_data(caller_channel, event);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application", "signal_bridge");
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application-Data", "%s", switch_core_session_get_uuid(peer_session));
-		switch_event_fire(&event);
-	}
-
-	if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_EXECUTE) == SWITCH_STATUS_SUCCESS) {
-		switch_channel_event_set_data(peer_channel, event);
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application", "signal_bridge");
-		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Application-Data", "%s", switch_core_session_get_uuid(session));
-		switch_event_fire(&event);
-	}
-
-	if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_BRIDGE) == SWITCH_STATUS_SUCCESS) {
-		switch_channel_event_set_data(caller_channel, event);
-		switch_event_fire(&event);
-	}
-	
-	switch_channel_set_state_flag(caller_channel, CF_TRANSFER);
-	switch_channel_set_state_flag(peer_channel, CF_TRANSFER);
-
-
-	switch_channel_set_variable(caller_channel, SWITCH_SIGNAL_BRIDGE_VARIABLE, switch_core_session_get_uuid(peer_session));
-	switch_channel_set_variable(peer_channel, SWITCH_SIGNAL_BRIDGE_VARIABLE, switch_core_session_get_uuid(session));
-
-	switch_channel_set_state(caller_channel, CS_HIBERNATE);
-	switch_channel_set_state(peer_channel, CS_HIBERNATE);
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_multi_threaded_bridge(switch_core_session_t *session, 
-																 switch_core_session_t *peer_session,
-																 switch_input_callback_function_t input_callback,
-																 void *session_data,
-																 void *peer_session_data)
-	 
-
-															   
-{
-	switch_core_thread_session_t *this_audio_thread, *other_audio_thread;
-	switch_channel_t *caller_channel, *peer_channel;
-	int stream_id = 0;
-	switch_status_t status = SWITCH_STATUS_SUCCESS;
-	
-	caller_channel = switch_core_session_get_channel(session);
-	assert(caller_channel != NULL);
-
-	switch_channel_set_flag(caller_channel, CF_ORIGINATOR);
-
-	peer_channel = switch_core_session_get_channel(peer_session);
-	assert(peer_channel != NULL);
-
-	other_audio_thread = switch_core_session_alloc(peer_session, sizeof(switch_core_thread_session_t));
-	this_audio_thread = switch_core_session_alloc(peer_session, sizeof(switch_core_thread_session_t));
-
-	other_audio_thread->objs[0] = session;
-	other_audio_thread->objs[1] = peer_session;
-	other_audio_thread->objs[2] = &stream_id;
-	other_audio_thread->input_callback = input_callback;
-	other_audio_thread->objs[4] = session_data;
-	other_audio_thread->objs[5] = this_audio_thread;
-	other_audio_thread->running = 5;
-	switch_mutex_init(&other_audio_thread->mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session));
-
-	this_audio_thread->objs[0] = peer_session;
-	this_audio_thread->objs[1] = session;
-	this_audio_thread->objs[2] = &stream_id;
-	this_audio_thread->input_callback = input_callback;
-	this_audio_thread->objs[4] = peer_session_data;
-	this_audio_thread->objs[5] = other_audio_thread;
-	this_audio_thread->running = 2;
-	switch_mutex_init(&this_audio_thread->mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(peer_session));
-
-	switch_channel_add_state_handler(peer_channel, &audio_bridge_peer_state_handlers);
-
-	if (switch_channel_test_flag(peer_channel, CF_ANSWERED) && !switch_channel_test_flag(caller_channel, CF_ANSWERED)) {
-		switch_channel_answer(caller_channel);
-	}
-
-	if (switch_channel_test_flag(peer_channel, CF_ANSWERED) || switch_channel_test_flag(peer_channel, CF_EARLY_MEDIA)) {
-		switch_event_t *event;
-		switch_core_session_message_t msg = {0};
-		
-		switch_channel_set_state(peer_channel, CS_HOLD);
-
-		if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_BRIDGE) == SWITCH_STATUS_SUCCESS) {
-			switch_channel_event_set_data(caller_channel, event);
-			switch_event_fire(&event);
-		}
-		
-		if (switch_core_session_read_lock(peer_session) == SWITCH_STATUS_SUCCESS) {
-			switch_channel_set_variable(caller_channel, SWITCH_BRIDGE_VARIABLE, switch_core_session_get_uuid(peer_session));
-			switch_channel_set_variable(peer_channel, SWITCH_BRIDGE_VARIABLE, switch_core_session_get_uuid(session));
-
-			msg.message_id = SWITCH_MESSAGE_INDICATE_BRIDGE;
-			msg.from = __FILE__;
-			msg.pointer_arg = session;
-
-			switch_core_session_receive_message(peer_session, &msg);
-
-			if (!msg.pointer_arg) {
-				status = SWITCH_STATUS_FALSE;
-				switch_core_session_rwunlock(peer_session);
-				goto done;
-			}
-
-			msg.pointer_arg = peer_session;
-			switch_core_session_receive_message(session, &msg);
-
-			if (!msg.pointer_arg) {
-				status = SWITCH_STATUS_FALSE;
-				switch_core_session_rwunlock(peer_session);
-				goto done;
-			}
-
-			
-			switch_channel_set_private(peer_channel, "_bridge_", other_audio_thread);
-			switch_channel_set_state(peer_channel, CS_LOOPBACK);
-			audio_bridge_thread(NULL, (void *) this_audio_thread);
-
-			if (switch_event_create(&event, SWITCH_EVENT_CHANNEL_UNBRIDGE) == SWITCH_STATUS_SUCCESS) {
-				switch_channel_event_set_data(caller_channel, event);
-				switch_event_fire(&event);
-			}
-
-            this_audio_thread->objs[0] = NULL;
-			this_audio_thread->objs[1] = NULL;
-			this_audio_thread->objs[2] = NULL;
-			this_audio_thread->input_callback = NULL;
-			this_audio_thread->objs[4] = NULL;
-			this_audio_thread->objs[5] = NULL;
-			switch_mutex_lock(this_audio_thread->mutex);
-			this_audio_thread->running = 0;
-			switch_mutex_unlock(this_audio_thread->mutex);
-			
-			switch_channel_clear_flag(caller_channel, CF_ORIGINATOR);
-
-			if (other_audio_thread->running > 0) {
-				switch_mutex_lock(other_audio_thread->mutex);
-				other_audio_thread->running = -1;
-				switch_mutex_unlock(other_audio_thread->mutex);
-				while (other_audio_thread->running) {
-					switch_yield(1000);
-				}
-			}
-
-			switch_core_session_rwunlock(peer_session);
-			
-		} else {
-			status = SWITCH_STATUS_FALSE;
-		}
-	} else {
-		status = SWITCH_STATUS_FALSE;
-	}
-
-	if (status != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Bridge Failed %s->%s\n", 
-						  switch_channel_get_name(caller_channel),
-						  switch_channel_get_name(peer_channel)
-						  );
-		switch_channel_hangup(peer_channel, SWITCH_CAUSE_NO_ANSWER);
-	} 
-
- done:
-
-    if (switch_channel_get_state(caller_channel) < CS_HANGUP && 
-        switch_true(switch_channel_get_variable(caller_channel, SWITCH_HANGUP_AFTER_BRIDGE_VARIABLE))) {
-        switch_channel_hangup(caller_channel, switch_channel_get_cause(peer_channel));
-    }
-
-	return status;
-}
-
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_uuid_bridge(char *originator_uuid, char *originatee_uuid)
-{
-	switch_core_session_t *originator_session, *originatee_session;
-	switch_channel_t *originator_channel, *originatee_channel;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if ((originator_session = switch_core_session_locate(originator_uuid))) {
-		if ((originatee_session = switch_core_session_locate(originatee_uuid))) { 
-			originator_channel = switch_core_session_get_channel(originator_session);
-			originatee_channel = switch_core_session_get_channel(originatee_session);
-
-			/* override transmit state for originator_channel to bridge to originatee_channel 
-			 * install pointer to originatee_session into originator_channel
-			 * set CF_TRANSFER on both channels and change state to CS_TRANSMIT to
-			 * inturrupt anything they are already doing.
-			 * originatee_session will fall asleep and originator_session will bridge to it
-			 */
-			
-			switch_channel_clear_state_handler(originator_channel, NULL);
-			switch_channel_clear_state_handler(originatee_channel, NULL);
-			switch_channel_set_flag(originator_channel, CF_ORIGINATOR);
-			switch_channel_add_state_handler(originator_channel, &uuid_bridge_state_handlers);
-			switch_channel_add_state_handler(originatee_channel, &uuid_bridge_state_handlers);
-			switch_channel_set_flag(originatee_channel, CF_TAGGED);
-			switch_channel_set_private(originator_channel, SWITCH_UUID_BRIDGE, originatee_session);
-
-			/* switch_channel_set_state_flag sets flags you want to be set when the next state change happens */
-			switch_channel_set_state_flag(originator_channel, CF_TRANSFER);
-			switch_channel_set_state_flag(originatee_channel, CF_TRANSFER);
-
-			/* release the read locks we have on the channels */
-			switch_core_session_rwunlock(originator_session);
-			switch_core_session_rwunlock(originatee_session);
-
-			/* change the states and let the chips fall where they may */
-			switch_channel_set_state(originator_channel, CS_TRANSMIT);
-			switch_channel_set_state(originatee_channel, CS_TRANSMIT);
-
-			status = SWITCH_STATUS_SUCCESS;
-			
-			while(switch_channel_get_state(originatee_channel) < CS_HANGUP && switch_channel_test_flag(originatee_channel, CF_TAGGED)) {
-				switch_yield(20000);
-			}
-		} else {
-			switch_core_session_rwunlock(originator_session);
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "no channel for originatee uuid %s\n", originatee_uuid);
-		}
-	} else {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "no channel for originator uuid %s\n", originator_uuid);
-	}
-
-	return status;
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_session_transfer(switch_core_session_t *session, char *extension, char *dialplan, char *context)
-{
-	switch_channel_t *channel;
-	switch_caller_profile_t *profile, *new_profile;
-	switch_core_session_message_t msg = {0};
-	switch_core_session_t *other_session;
-	char *uuid = NULL;
-
-	assert(session != NULL);
-	assert(extension != NULL);
-
-	switch_core_session_reset(session);
-
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	/* clear all state handlers */
-	switch_channel_clear_state_handler(channel, NULL);
-
-	if ((profile = switch_channel_get_caller_profile(channel))) {
-		new_profile = switch_caller_profile_clone(session, profile);
-		new_profile->destination_number = switch_core_session_strdup(session, extension);
-
-		if (!switch_strlen_zero(dialplan)) {
-			new_profile->dialplan = switch_core_session_strdup(session, dialplan);
-		} else {
-			dialplan = new_profile->dialplan;
-		}
-
-		if (!switch_strlen_zero(context)) {
-			new_profile->context = switch_core_session_strdup(session, context);
-		} else {
-			context = new_profile->context;
-		}
-
-		if ((uuid = switch_channel_get_variable(channel, SWITCH_SIGNAL_BRIDGE_VARIABLE)) && (other_session = switch_core_session_locate(uuid))) {
-			switch_channel_t *other_channel = NULL;
-
-			other_channel = switch_core_session_get_channel(other_session);
-			assert(other_channel != NULL);
-			
-			switch_channel_set_variable(channel, SWITCH_SIGNAL_BRIDGE_VARIABLE, NULL);
-			switch_channel_set_variable(other_channel, SWITCH_SIGNAL_BRIDGE_VARIABLE, NULL);
-
-			switch_channel_hangup(other_channel, SWITCH_CAUSE_BLIND_TRANSFER);
-			switch_ivr_media(uuid, SMF_NONE);
-			
-			switch_core_session_rwunlock(other_session);
-		}
-
-		switch_channel_set_caller_profile(channel, new_profile);
-		switch_channel_set_flag(channel, CF_TRANSFER);
-		switch_channel_set_state(channel, CS_RING);
-
-		msg.message_id = SWITCH_MESSAGE_INDICATE_TRANSFER;
-		msg.from = __FILE__;
-		switch_core_session_receive_message(session, &msg);
-
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Transfer %s to %s[%s@%s]\n", 
-						  switch_channel_get_name(channel), dialplan, extension, context); 
-		return SWITCH_STATUS_SUCCESS;
-	} 
-
-	return SWITCH_STATUS_FALSE;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_transfer_variable(switch_core_session_t *sessa, switch_core_session_t *sessb, char *var)
-{
-	switch_channel_t *chana = switch_core_session_get_channel(sessa);
-	switch_channel_t *chanb = switch_core_session_get_channel(sessb);
-	char *val = NULL;
-	uint8_t prefix = 0;
-
-	if (var && *var == '~') {
-		var++;
-		prefix = 1;
-	}
-
-
-	if (var && !prefix) {
-		if ((val = switch_channel_get_variable(chana, var))) {
-			switch_channel_set_variable(chanb, var, val);
-		}
-	} else {
-		switch_hash_index_t *hi;
-		void *vval;
-		const void *vvar;
-
-		for (hi = switch_channel_variable_first(chana, switch_core_session_get_pool(sessa)); hi; hi = switch_hash_next(hi)) {
-			switch_hash_this(hi, &vvar, NULL, &vval);
-			if (vvar && vval && (!prefix || (var && !strncmp((char *)vvar, var, strlen(var))))) {
-				switch_channel_set_variable(chanb, (char *) vvar, (char *) vval);
-			}
-		}
-	}
-
-	return SWITCH_STATUS_SUCCESS;
-}
-
-/******************************************************************************************************/
-
-struct switch_ivr_digit_stream_parser {
-	int pool_auto_created;
-	switch_memory_pool_t *pool;
-	switch_hash_t *hash;
-	switch_size_t maxlen;
-	switch_size_t minlen;
-	char terminator;
-	unsigned int digit_timeout_ms;
-};
-
-struct switch_ivr_digit_stream {
-	char *digits;
-	switch_time_t last_digit_time;
-};
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_new(switch_memory_pool_t *pool, switch_ivr_digit_stream_parser_t **parser)
-{	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if(parser != NULL) {
-		int pool_auto_created = 0;
-
-		// if the caller didn't provide a pool, make one
-		if (pool == NULL) {
-			switch_core_new_memory_pool(&pool);
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "created a memory pool\n");
-			if (pool != NULL) {
-				pool_auto_created = 1;
-			}
-		}
-
-		// if we have a pool, make a parser object
-		if (pool != NULL) {
-			*parser = (switch_ivr_digit_stream_parser_t *)switch_core_alloc(pool,sizeof(switch_ivr_digit_stream_parser_t));
-		}
-
-		// if we have parser object, initialize it for the caller
-		if (*parser != NULL) {
-			memset(*parser,0,sizeof(switch_ivr_digit_stream_parser_t));
-			(*parser)->pool_auto_created = pool_auto_created;
-			(*parser)->pool = pool;
-			(*parser)->digit_timeout_ms = 1000;
-			switch_core_hash_init(&(*parser)->hash,(*parser)->pool);
-
-			status = SWITCH_STATUS_SUCCESS;
-		} else {
-			status = SWITCH_STATUS_MEMERR;
-			// if we can't create a parser object,clean up the pool if we created it
-			if (pool != NULL && pool_auto_created) {
-				switch_core_destroy_memory_pool(&pool);
-			}
-		}
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_destroy(switch_ivr_digit_stream_parser_t *parser)
-{	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (parser != NULL) {
-		if (parser->hash != NULL) {
-			switch_core_hash_destroy(parser->hash);
-			parser->hash = NULL;
-		}
-		// free the memory pool if we created it
-		if (parser->pool_auto_created && parser->pool != NULL) {
-			status = switch_core_destroy_memory_pool(&parser->pool);
-		}
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_new(switch_ivr_digit_stream_parser_t *parser, switch_ivr_digit_stream_t **stream)
-{	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	// if we have a paser object memory pool and a stream object pointer that is null
-	if (parser != NULL && parser->pool && stream != NULL && *stream == NULL) {
-		*stream = (switch_ivr_digit_stream_t *)switch_core_alloc(parser->pool,sizeof(switch_ivr_digit_stream_t));
-		if (*stream != NULL) {
-			memset(*stream,0,sizeof(switch_ivr_digit_stream_t));
-			status = SWITCH_STATUS_SUCCESS;
-		}
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_destroy(switch_ivr_digit_stream_t *stream)
-{	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (stream == NULL && stream->digits != NULL) {
-		free(stream->digits);
-		stream->digits = NULL;
-		status = SWITCH_STATUS_SUCCESS;
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_set_event(switch_ivr_digit_stream_parser_t *parser, char *digits, void *data)
-{	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (parser != NULL && digits != NULL && *digits && parser->hash != NULL) {
-
-		status = switch_core_hash_insert_dup(parser->hash,digits,data);
-		if (status == SWITCH_STATUS_SUCCESS) {
-			switch_size_t len = strlen(digits);
-
-			// if we don't have a terminator, then we have to try and
-			// figure out when a digit set is completed, therefore we
-			// keep track of the min and max digit lengths
-			if (parser->terminator == '\0') {
-				if (len > parser->maxlen) {
-					parser->maxlen = len;
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "max len %u\n", (uint32_t) parser->maxlen);
-				}
-				if (parser->minlen == 0 || len < parser->minlen) {
-					parser->minlen = len;
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "min len %u\n", (uint32_t) parser->minlen);
-				}
-			} else {
-				// since we have a terminator, reset min and max
-				parser->minlen = 0;
-				parser->maxlen = 0;
-			}
-
-		}
-	}
-	if (status != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "unable to add hash for '%s'\n",digits);
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_del_event(switch_ivr_digit_stream_parser_t *parser, char *digits)
-{	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (parser != NULL && digits != NULL && *digits) {
-		status = switch_core_hash_delete(parser->hash,digits);
-	}
-
-	if (status != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "unable to del hash for '%s'\n",digits);
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(void *) switch_ivr_digit_stream_parser_feed(switch_ivr_digit_stream_parser_t *parser, switch_ivr_digit_stream_t *stream, char digit)
-{	void *result = NULL;
-
-	if (parser != NULL && stream != NULL) {
-		switch_size_t len = (stream->digits != NULL ? strlen(stream->digits) : 0);
-
-		// handle new digit arrivals
-		if(digit != '\0') {
-
-			// if it's not a terminator digit, add it to the collected digits
-			if (digit != parser->terminator) {
-				// if collected digits length >= the max length of the keys
-				// in the hash table, then left shift the digit string
-				if (len > 0 && parser->maxlen != 0 && len >= parser->maxlen) {
-					char *src = stream->digits + 1;
-					char *dst = stream->digits;
-
-					while (*src) {
-						*(dst++) = *(src++);
-					}
-					*dst = digit;
-				} else {
-					stream->digits = realloc(stream->digits,len+2);
-					*(stream->digits+(len++)) = digit;
-					*(stream->digits+len) = '\0';
-					stream->last_digit_time = switch_time_now() / 1000;
-				}
-			}
-		}
-
-		// don't allow collected digit string testing if there are varying sized keys until timeout
-		if ( parser->maxlen - parser->minlen > 0
-			&& (switch_time_now() / 1000) - stream->last_digit_time < parser->digit_timeout_ms
-		) {
-			len = 0;
-		}
-
-		// if we have digits to test
-		if (len) {
-			result = switch_core_hash_find(parser->hash, stream->digits);
-			// if we matched the digit string, or this digit is the terminator
-			// reset the collected digits for next digit string
-			if (result != NULL || parser->terminator == digit) {
-				free(stream->digits);
-				stream->digits = NULL;
-			}
-		}
-}
-
-	return result;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_reset(switch_ivr_digit_stream_t *stream)
-{	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (stream != NULL && stream->digits != NULL) {
-		free(stream->digits);
-		stream->digits = NULL;
-		stream->last_digit_time = 0;
-		status = SWITCH_STATUS_SUCCESS;
-	}
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_set_terminator(switch_ivr_digit_stream_parser_t *parser, char digit)
-{	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (parser != NULL) {
-		parser->terminator = digit;
-		// since we have a terminator, reset min and max
-		parser->minlen = 0;
-		parser->maxlen = 0;
-		status = SWITCH_STATUS_SUCCESS;
-	}
-
-	return status;
-}
-
-/******************************************************************************************************/
-
-struct switch_ivr_menu_action;
-
-struct switch_ivr_menu {
-	char *name;
-	char *greeting_sound;
-	char *short_greeting_sound;
-	char *invalid_sound;
-	char *exit_sound;
-	char *tts_engine;
-	char *tts_voice;
-	char *phrase_lang;
-	char *buf;
-	char *ptr;
-	int max_failures;
-	int timeout;
-	uint32_t inlen;
-	uint32_t flags;
-	struct switch_ivr_menu_action *actions;
-	struct switch_ivr_menu *next;
-	switch_memory_pool_t *pool;
-};
-
-struct switch_ivr_menu_action {
-	switch_ivr_menu_action_function_t *function;
-	switch_ivr_action_t ivr_action;
-	char *arg;
-	char *bind;
-	struct switch_ivr_menu_action *next;
-};
-
-static switch_ivr_menu_t *switch_ivr_menu_find(switch_ivr_menu_t *stack, const char *name) {
-	switch_ivr_menu_t *ret;
-	for(ret = stack; ret ; ret = ret->next) {
-		if (!name || !strcmp(ret->name, name))
-			break;
-	}
-	return ret;
-}
-
-static void switch_ivr_menu_stack_add(switch_ivr_menu_t **top, switch_ivr_menu_t *bottom) 
-{
-	switch_ivr_menu_t *ptr;
-
-	for(ptr = *top ; ptr && ptr->next ; ptr = ptr->next);
-
-	if (ptr) {
-		ptr->next = bottom;
-	} else {
-		*top = bottom;
-	}
-
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_init(switch_ivr_menu_t **new_menu,
-													 switch_ivr_menu_t *main,
-													 const char *name, 
-													 const char *greeting_sound, 
-													 const char *short_greeting_sound,
-													 const char *invalid_sound, 
-													 const char *exit_sound,
-													 const char *tts_engine,
-													 const char *tts_voice,
-													 const char *phrase_lang,
-													 int timeout,
-													 int max_failures, 
-													 switch_memory_pool_t *pool)
-{
-	switch_ivr_menu_t *menu;
-	uint8_t newpool = 0;
-
-	if (!pool) {
-		if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "OH OH no pool\n");
-			return SWITCH_STATUS_MEMERR;
-		}
-		newpool = 1;
-	}
-	
-	if (!(menu = switch_core_alloc(pool, sizeof(*menu)))) {
-		if (newpool) {
-			switch_core_destroy_memory_pool(&pool);
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error!\n");
-			return SWITCH_STATUS_MEMERR;
-		}
-	}
-
-	menu->pool = pool;
-
-	if (!switch_strlen_zero(name)) {
-		menu->name = switch_core_strdup(menu->pool, name);
-	}
-
-	if (!switch_strlen_zero(greeting_sound)) {
-		menu->greeting_sound = switch_core_strdup(menu->pool, greeting_sound);
-	}
-
-	if (!switch_strlen_zero(short_greeting_sound)) {
-		menu->short_greeting_sound = switch_core_strdup(menu->pool, short_greeting_sound);
-	}
-
-	if (!switch_strlen_zero(invalid_sound)) {
-		menu->invalid_sound = switch_core_strdup(menu->pool, invalid_sound);
-	}
-
-	if (!switch_strlen_zero(exit_sound)) {
-		menu->exit_sound = switch_core_strdup(menu->pool, exit_sound);
-	}
-
-	if (!switch_strlen_zero(tts_engine)) {
-		menu->tts_engine = switch_core_strdup(menu->pool, tts_engine);
-	}
-
-	if (!switch_strlen_zero(tts_voice)) {
-		menu->tts_voice = switch_core_strdup(menu->pool, tts_voice);
-	}
-
-	if (!switch_strlen_zero(phrase_lang)) {
-		menu->phrase_lang = switch_core_strdup(menu->pool, phrase_lang);
-	}
-
-	menu->max_failures = max_failures;
-
-	menu->timeout = timeout;
-
-	menu->actions = NULL;
-
-	if (newpool) {
-		menu->flags |= SWITCH_IVR_MENU_FLAG_FREEPOOL;
-	}
-
-	if (menu->timeout <= 0) {
-		menu->timeout = 10000;
-	}
-
-	if (main) {
-		switch_ivr_menu_stack_add(&main, menu);
-	} else {
-		menu->flags |= SWITCH_IVR_MENU_FLAG_STACK;
-	}
-	
-	*new_menu = menu;
-	
-	return SWITCH_STATUS_SUCCESS;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_bind_action(switch_ivr_menu_t *menu, switch_ivr_action_t ivr_action, const char *arg, const char *bind)
-{
-	switch_ivr_menu_action_t *action;
-	uint32_t len;
-
-	if ((action = switch_core_alloc(menu->pool, sizeof(*action)))) {
-		action->bind = switch_core_strdup(menu->pool, bind);
-		action->next = menu->actions;
-		action->arg = switch_core_strdup(menu->pool, arg);
-		len = (uint32_t)strlen(action->bind) + 1;
-		if (len > menu->inlen) {
-			menu->inlen = len;
-		}
-		action->ivr_action = ivr_action;
-		menu->actions = action;
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_bind_function(switch_ivr_menu_t *menu, switch_ivr_menu_action_function_t *function, const char *arg, const char *bind)
-{
-	switch_ivr_menu_action_t *action;
-	uint32_t len;
-
-	if ((action = switch_core_alloc(menu->pool, sizeof(*action)))) {
-		action->bind = switch_core_strdup(menu->pool,bind);
-		action->next = menu->actions;
-		action->arg = switch_core_strdup(menu->pool, arg);
-		len = (uint32_t)strlen(action->bind) + 1;
-		if (len > menu->inlen) {
-			menu->inlen = len;
-		}
-		action->function = function;
-		menu->actions = action;
-		return SWITCH_STATUS_SUCCESS;
-	}
-
-	return SWITCH_STATUS_MEMERR;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_free(switch_ivr_menu_t *stack) 
-{
-	switch_status_t status = SWITCH_STATUS_FALSE;
-
-	if (stack != NULL && stack->pool != NULL) {
-		if (switch_test_flag(stack, SWITCH_IVR_MENU_FLAG_STACK) && switch_test_flag(stack, SWITCH_IVR_MENU_FLAG_FREEPOOL)) {
-			switch_memory_pool_t *pool = stack->pool;
-			status = switch_core_destroy_memory_pool(&pool);
-		} else {
-			status = SWITCH_STATUS_SUCCESS;
-		}
-	}
-
-	return status;
-}
-
-static switch_status_t play_or_say(switch_core_session_t *session, switch_ivr_menu_t *menu, char *sound, uint32_t need)
-{
-	char terminator;
-	uint32_t len;
-	char *ptr;
-	switch_status_t status = SWITCH_STATUS_FALSE;
-	switch_input_args_t args= {0};
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "play_or_say sound=[%s]\n",sound);
-
-	if (session != NULL && menu != NULL && !switch_strlen_zero(sound)) {
-		memset(menu->buf, 0, menu->inlen);
-		menu->ptr = menu->buf;
-
-		if (!need) {
-			len = 1;
-			ptr = NULL;
-		} else {
-			len = menu->inlen;
-			ptr = menu->ptr;
-		}
-		args.buf = ptr;
-		args.buflen = len;
-
-		if (*sound == '/' || *sound == '\\') {
-			status = switch_ivr_play_file(session, NULL, sound, &args);
-		} else {
-			if (strlen(sound) > 4 && strncmp(sound, "say:", 4) == 0) {
-				if (menu->tts_engine && menu->tts_voice) {
-					status = switch_ivr_speak_text(session, menu->tts_engine, menu->tts_voice, 0, sound+4, &args);
-				} else {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No TTS engine to play sound\n");
-				}
-			} else {
-				if (strlen(sound) > 7 && strncmp(sound, "phrase:", 7) == 0) {
-						status = switch_ivr_phrase_macro(session, sound+7, "", menu->phrase_lang, &args);
-				} else {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "play_or_say: no player for [%s]. Use say: or phrase:\n", sound);
-				}
-			}
-		}
-
-		if (need) {
-			menu->ptr += strlen(menu->buf);
-			if (strlen(menu->buf) < need) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "waiting for %u digits\n",need);
-				status = switch_ivr_collect_digits_count(session, menu->ptr, menu->inlen - strlen(menu->buf), need, "#", &terminator, menu->timeout);
-			}
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "digits '%s'\n",menu->buf);
-		}
-	}
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "play_or_say returning [%d]\n",status);
-
-	return status;
-}
-
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_execute(switch_core_session_t *session, switch_ivr_menu_t *stack, char *name, void *obj)
-{
-	int reps = 0, errs = 0, match = 0, running = 1;
-	char *greeting_sound = NULL, *aptr = NULL;
-	char arg[512];
-	switch_ivr_action_t todo = SWITCH_IVR_ACTION_DIE;
-	switch_ivr_menu_action_t *ap;
-	switch_ivr_menu_t *menu;
-	switch_channel_t *channel;
-	switch_status_t status = SWITCH_STATUS_SUCCESS;
-
-	if (session == NULL || stack == NULL || switch_strlen_zero(name)) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid menu context\n");
-		return SWITCH_STATUS_FALSE;
-	}
-
-	channel = switch_core_session_get_channel(session);
-	assert(channel != NULL);
-
-	if (!(menu = switch_ivr_menu_find(stack, name))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Menu!\n");
-		return SWITCH_STATUS_FALSE;
-	}
-	
-	if (!(menu->buf = malloc(menu->inlen))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No Memory!\n");
-		return SWITCH_STATUS_FALSE;
-	}
-	
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Executing IVR menu %s\n", menu->name);
-
-	for (reps = 0 ; (running && status == SWITCH_STATUS_SUCCESS && errs < menu->max_failures) ; reps++) {
-		if (!switch_channel_ready(channel)) {
-			break;
-		}
-
-		if (reps > 0 && menu->short_greeting_sound) {
-			greeting_sound = menu->short_greeting_sound;
-		} else {
-			greeting_sound = menu->greeting_sound;
-		}
-
-		match = 0;
-		aptr = NULL;
-
-		memset(arg, 0, sizeof(arg));
-
-		memset(menu->buf, 0, menu->inlen);
-		status = play_or_say(session, menu, greeting_sound, menu->inlen - 1);
-
-		if (!switch_strlen_zero(menu->buf)) {
-			for(ap = menu->actions; ap ; ap = ap->next) {
-				if (!strcmp(menu->buf, ap->bind)) {
-					char *membuf;
-                    
-					match++;
-					errs = 0;
-					if (ap->function) {
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "IVR function on menu '%s' matched '%s' param '%s'\n", menu->name, menu->buf, ap->arg);
-						todo = ap->function(menu, ap->arg, arg, sizeof(arg), obj);
-						aptr = arg;
-					} else {
-						todo = ap->ivr_action;
-						aptr = ap->arg;
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "IVR action on menu '%s' matched '%s' param '%s'\n", menu->name, menu->buf,aptr);
-					}
-
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "switch_ivr_menu_execute todo=[%d]\n", todo);
-
-					switch(todo) {
-					case SWITCH_IVR_ACTION_DIE:
-						status = SWITCH_STATUS_FALSE;
-						break;
-					case SWITCH_IVR_ACTION_PLAYSOUND:
-						status = switch_ivr_play_file(session, NULL, aptr, NULL);
-						break;
-					case SWITCH_IVR_ACTION_SAYTEXT:
-						status = switch_ivr_speak_text(session, menu->tts_engine, menu->tts_voice, 0, aptr, NULL);
-						break;
-					case SWITCH_IVR_ACTION_SAYPHRASE:
-						status = switch_ivr_phrase_macro(session, aptr, "", menu->phrase_lang, NULL);
-						break;
-					case SWITCH_IVR_ACTION_TRANSFER:
-						switch_ivr_session_transfer(session, aptr, NULL, NULL);
-						running = 0;
-						break;
-					case SWITCH_IVR_ACTION_EXECMENU:
-						reps = -1;
-						status = switch_ivr_menu_execute(session, stack, aptr, obj);
-						break;
-					case SWITCH_IVR_ACTION_EXECAPP: {
-						const switch_application_interface_t *application_interface;
-
-						if ((membuf = strdup(aptr))) {
-							char *app_name = membuf;
-							char *app_arg = strchr(app_name, ' ');
-
-							if (app_arg) {
-								*app_arg = '\0';
-								app_arg++;
-							}
-
-							if (app_name && app_arg) {
-								if ((application_interface = switch_loadable_module_get_application_interface(app_name))) {
-									if (application_interface->application_function) {
-										application_interface->application_function(session, app_arg);
-									}
-								}
-							}
-						}
-					}
-						break;
-					case SWITCH_IVR_ACTION_BACK:
-						running = 0;
-						status = SWITCH_STATUS_SUCCESS;
-						break;
-					case SWITCH_IVR_ACTION_TOMAIN:
-						switch_set_flag(stack, SWITCH_IVR_MENU_FLAG_FALLTOMAIN);
-						status = SWITCH_STATUS_BREAK;
-						break;
-					case SWITCH_IVR_ACTION_NOOP:
-						status = SWITCH_STATUS_SUCCESS;
-						break;
-					default:
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Invalid TODO!\n");
-						break;
-					}
-				}
-			}
-
-
-			if (switch_test_flag(menu, SWITCH_IVR_MENU_FLAG_STACK)) { // top level
-				if (switch_test_flag(stack, SWITCH_IVR_MENU_FLAG_FALLTOMAIN)) { // catch the fallback and recover
-					switch_clear_flag(stack, SWITCH_IVR_MENU_FLAG_FALLTOMAIN);
-					status = SWITCH_STATUS_SUCCESS;
-					running = 1;
-					continue;
-				}
-			}
-		}
-		if (!match) {
-			if (*menu->buf) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "IVR menu '%s' caught invalid input '%s'\n", menu->name, menu->buf);
-				if (menu->invalid_sound) {
-					play_or_say(session, menu, menu->invalid_sound, 0);
-				}
-			}
-			else {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "IVR menu '%s' no input detected\n", menu->name);
-			}
-			errs++;
-			if (status == SWITCH_STATUS_SUCCESS) {
-				status = switch_ivr_sleep(session, 1000);
-			}
-			/* breaks are ok too */
-			if (SWITCH_STATUS_IS_BREAK(status)) {
-				status = SWITCH_STATUS_SUCCESS;
-			}
-		}
-	}
-
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "exit-sound '%s'\n",menu->exit_sound);
-	if (!switch_strlen_zero(menu->exit_sound)) {
-		play_or_say(session, menu, menu->exit_sound, 0);
-	}
-
-	switch_safe_free(menu->buf);
-
-	return status;
+	return SWITCH_STATUS_SUCCESS;
 }
 
 /******************************************************************************************************/
 
-typedef struct switch_ivr_menu_xml_map {
-	char *name;
-	switch_ivr_action_t action;
-	switch_ivr_menu_action_function_t *function;
-	struct switch_ivr_menu_xml_map *next;
-} switch_ivr_menu_xml_map_t;
-
-struct switch_ivr_menu_xml_ctx {
+struct switch_ivr_digit_stream_parser {
+	int pool_auto_created;
 	switch_memory_pool_t *pool;
-	struct switch_ivr_menu_xml_map *map;
-	int autocreated;
+	switch_hash_t *hash;
+	switch_size_t maxlen;
+	switch_size_t minlen;
+	char terminator;
+	unsigned int digit_timeout_ms;
 };
 
-static switch_ivr_menu_xml_map_t *switch_ivr_menu_stack_xml_find(switch_ivr_menu_xml_ctx_t *xml_ctx, char *name)
-{
-	switch_ivr_menu_xml_map_t *map = (xml_ctx != NULL ? xml_ctx->map : NULL);
-	int rc = -1;
-
-	while (map != NULL && (rc = strcasecmp(map->name,name)) != 0) {
-		map =  map->next;
-	}
-
-	return (rc == 0 ? map : NULL);
-}
+struct switch_ivr_digit_stream {
+	char *digits;
+	switch_time_t last_digit_time;
+};
 
-static switch_status_t switch_ivr_menu_stack_xml_add(switch_ivr_menu_xml_ctx_t *xml_ctx, char*name, int action, switch_ivr_menu_action_function_t *function)
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_new(switch_memory_pool_t *pool, switch_ivr_digit_stream_parser_t ** parser)
 {
 	switch_status_t status = SWITCH_STATUS_FALSE;
 
-	// if this action/function does not exist yet
-	if (xml_ctx != NULL && name != NULL && xml_ctx->pool != NULL && switch_ivr_menu_stack_xml_find(xml_ctx,name) == NULL) {
-		switch_ivr_menu_xml_map_t *map = switch_core_alloc(xml_ctx->pool,sizeof(switch_ivr_menu_xml_map_t));
-
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "switch_ivr_menu_stack_xml_add bindng '%s'\n",name);
-		// and we have memory
-		if (map != NULL) {
-			map->name = switch_core_strdup(xml_ctx->pool,name);
-			map->action = action;
-			map->function = function;
-
-			if (map->name != NULL) {
-				// insert map item at top of list
-				map->next = xml_ctx->map;
-				xml_ctx->map = map;
-				status = SWITCH_STATUS_SUCCESS;
-			} else {
-				status = SWITCH_STATUS_MEMERR;
+	if (parser != NULL) {
+		int pool_auto_created = 0;
+
+		// if the caller didn't provide a pool, make one
+		if (pool == NULL) {
+			switch_core_new_memory_pool(&pool);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "created a memory pool\n");
+			if (pool != NULL) {
+				pool_auto_created = 1;
 			}
+		}
+		// if we have a pool, make a parser object
+		if (pool != NULL) {
+			*parser = (switch_ivr_digit_stream_parser_t *) switch_core_alloc(pool, sizeof(switch_ivr_digit_stream_parser_t));
+		}
+		// if we have parser object, initialize it for the caller
+		if (*parser != NULL) {
+			memset(*parser, 0, sizeof(switch_ivr_digit_stream_parser_t));
+			(*parser)->pool_auto_created = pool_auto_created;
+			(*parser)->pool = pool;
+			(*parser)->digit_timeout_ms = 1000;
+			switch_core_hash_init(&(*parser)->hash, (*parser)->pool);
+
+			status = SWITCH_STATUS_SUCCESS;
 		} else {
 			status = SWITCH_STATUS_MEMERR;
+			// if we can't create a parser object,clean up the pool if we created it
+			if (pool != NULL && pool_auto_created) {
+				switch_core_destroy_memory_pool(&pool);
+			}
 		}
 	}
 
 	return status;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_xml_init(switch_ivr_menu_xml_ctx_t **xml_menu_ctx, switch_memory_pool_t *pool)
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_destroy(switch_ivr_digit_stream_parser_t * parser)
 {
-	switch_status_t status	= SWITCH_STATUS_FALSE;
-	int autocreated = 0;
+	switch_status_t status = SWITCH_STATUS_FALSE;
 
-	// build a memory pool ?
-	if (pool == NULL) {
-		status = switch_core_new_memory_pool(&pool);
-		autocreated = 1;
-	}
-
-	// allocate the xml context
-	if (xml_menu_ctx != NULL && pool != NULL) {
-		*xml_menu_ctx = switch_core_alloc(pool,sizeof(switch_ivr_menu_xml_ctx_t));
-		if (*xml_menu_ctx != NULL) {
-			(*xml_menu_ctx)->pool = pool;
-			(*xml_menu_ctx)->autocreated = autocreated;
-			(*xml_menu_ctx)->map = NULL;
-			status = SWITCH_STATUS_SUCCESS;
-		} else {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to alloc xml_ctx\n");
-			status = SWITCH_STATUS_FALSE;
+	if (parser != NULL) {
+		if (parser->hash != NULL) {
+			switch_core_hash_destroy(parser->hash);
+			parser->hash = NULL;
+		}
+		// free the memory pool if we created it
+		if (parser->pool_auto_created && parser->pool != NULL) {
+			status = switch_core_destroy_memory_pool(&parser->pool);
 		}
 	}
 
-	// build the standard/default xml menu handler mappings
-	if (status == SWITCH_STATUS_SUCCESS && xml_menu_ctx != NULL && *xml_menu_ctx != NULL) {
-		struct iam_s {
-			char *name;
-			switch_ivr_action_t action;
-		} iam [] = {
-			{"menu-exit",		SWITCH_IVR_ACTION_DIE},
-			{"menu-sub",		SWITCH_IVR_ACTION_EXECMENU},
-			{"menu-exec-api",	SWITCH_IVR_ACTION_EXECAPP},
-			{"menu-play-sound",	SWITCH_IVR_ACTION_PLAYSOUND},
-			{"menu-say-text",	SWITCH_IVR_ACTION_SAYTEXT},
-			{"menu-say-phrase",	SWITCH_IVR_ACTION_SAYPHRASE},
-			{"menu-back",		SWITCH_IVR_ACTION_BACK},
-			{"menu-top",		SWITCH_IVR_ACTION_TOMAIN},
-			{"menu-call-transfer",	SWITCH_IVR_ACTION_TRANSFER},
-		};
-		int iam_qty = (sizeof(iam)/sizeof(iam[0]));
-		int i;
+	return status;
+}
+
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_new(switch_ivr_digit_stream_parser_t * parser, switch_ivr_digit_stream_t ** stream)
+{
+	switch_status_t status = SWITCH_STATUS_FALSE;
 
-		for(i=0; i<iam_qty && status == SWITCH_STATUS_SUCCESS; i++) {
-			status = switch_ivr_menu_stack_xml_add(*xml_menu_ctx,iam[i].name,iam[i].action,NULL);
+	// if we have a paser object memory pool and a stream object pointer that is null
+	if (parser != NULL && parser->pool && stream != NULL && *stream == NULL) {
+		*stream = (switch_ivr_digit_stream_t *) switch_core_alloc(parser->pool, sizeof(switch_ivr_digit_stream_t));
+		if (*stream != NULL) {
+			memset(*stream, 0, sizeof(switch_ivr_digit_stream_t));
+			status = SWITCH_STATUS_SUCCESS;
 		}
 	}
 
 	return status;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_xml_add_custom(switch_ivr_menu_xml_ctx_t *xml_menu_ctx, char *name, switch_ivr_menu_action_function_t *function)
-{	
-	return switch_ivr_menu_stack_xml_add(xml_menu_ctx, name, -1, function);
-}
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_destroy(switch_ivr_digit_stream_t * stream)
+{
+	switch_status_t status = SWITCH_STATUS_FALSE;
+
+	if (stream == NULL && stream->digits != NULL) {
+		free(stream->digits);
+		stream->digits = NULL;
+		status = SWITCH_STATUS_SUCCESS;
+	}
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_menu_stack_xml_build(switch_ivr_menu_xml_ctx_t *xml_menu_ctx,
-                                                                switch_ivr_menu_t **menu_stack,
-                                                                switch_xml_t xml_menus,
-                                                                switch_xml_t xml_menu)
+	return status;
+}
 
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_set_event(switch_ivr_digit_stream_parser_t * parser, char *digits, void *data)
 {
-	switch_status_t status	= SWITCH_STATUS_FALSE;
+	switch_status_t status = SWITCH_STATUS_FALSE;
 
-	if (xml_menu_ctx != NULL && menu_stack  != NULL && xml_menu != NULL) {
-		const char *menu_name		= switch_xml_attr_soft(xml_menu,"name");		// if the attr doesn't exist, return ""
-		const char *greet_long	= switch_xml_attr(xml_menu,"greet-long");		// if the attr doesn't exist, return NULL
-		const char *greet_short	= switch_xml_attr(xml_menu,"greet-short");		// if the attr doesn't exist, return NULL
-		const char *invalid_sound	= switch_xml_attr(xml_menu,"invalid-sound");		// if the attr doesn't exist, return NULL
-		const char *exit_sound	= switch_xml_attr(xml_menu,"exit-sound");		// if the attr doesn't exist, return NULL
-		const char *tts_engine	= switch_xml_attr(xml_menu,"tts-engine");		// if the attr doesn't exist, return NULL
-		const char *tts_voice		= switch_xml_attr(xml_menu,"tts-voice");		// if the attr doesn't exist, return NULL
-		const char *phrase_lang		= switch_xml_attr(xml_menu,"phrase-lang");		// if the attr doesn't exist, return NULL
-		const char *timeout		= switch_xml_attr_soft(xml_menu,"timeout");		// if the attr doesn't exist, return ""
-		const char *max_failures	= switch_xml_attr_soft(xml_menu,"max-failures");	// if the attr doesn't exist, return ""
-		switch_ivr_menu_t *menu	= NULL;
-
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "building menu '%s'\n",menu_name);
-		status = switch_ivr_menu_init(&menu,
-									*menu_stack,
-									menu_name,
-									greet_long,
-									greet_short,
-									invalid_sound,
-									exit_sound,
-									tts_engine,
-									tts_voice,
-									phrase_lang,
-									atoi(timeout)*1000,
-									atoi(max_failures),
-									xml_menu_ctx->pool
-									);
-		// set the menu_stack for the caller
-		if (status == SWITCH_STATUS_SUCCESS && *menu_stack == NULL) {
-			*menu_stack = menu;
-		}
-
-		if (status == SWITCH_STATUS_SUCCESS && menu != NULL) {
-			switch_xml_t xml_kvp;
-
-			// build menu entries
-			for(xml_kvp = switch_xml_child(xml_menu, "entry"); xml_kvp != NULL && status == SWITCH_STATUS_SUCCESS; xml_kvp = xml_kvp->next) {
-				const char *action	= switch_xml_attr(xml_kvp, "action");
-				const char *digits	= switch_xml_attr(xml_kvp, "digits");
-				const char *param	= switch_xml_attr_soft(xml_kvp, "param");
-
-				if (!switch_strlen_zero(action) && !switch_strlen_zero(digits)) {
-					switch_ivr_menu_xml_map_t *xml_map = xml_menu_ctx->map;
-					int found = 0;
-
-					// find and appropriate xml handler
-					while(xml_map != NULL && !found) {
-						if (!(found = (strcasecmp(xml_map->name,action) == 0))) {
-							xml_map = xml_map->next;
-						}
-					}
+	if (parser != NULL && digits != NULL && *digits && parser->hash != NULL) {
 
-					if (found && xml_map != NULL) {
-						// do we need to build a new sub-menu ?
-						if (xml_map->action == SWITCH_IVR_ACTION_EXECMENU && switch_ivr_menu_find(*menu_stack, param) == NULL) {
-							if ((xml_menu = switch_xml_find_child(xml_menus, "menu", "name", param)) != NULL) {
-								status = switch_ivr_menu_stack_xml_build(xml_menu_ctx, menu_stack, xml_menus, xml_menu);
-							}
-						}
+		status = switch_core_hash_insert_dup(parser->hash, digits, data);
+		if (status == SWITCH_STATUS_SUCCESS) {
+			switch_size_t len = strlen(digits);
 
-						// finally bind the menu entry
-						if (status == SWITCH_STATUS_SUCCESS) {
-							if (xml_map->function != NULL) {
-								switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
-									"binding menu caller control '%s'/'%s' to '%s'\n", xml_map->name, param, digits);
-								status = switch_ivr_menu_bind_function(menu, xml_map->function, param, digits);
-							} else {
-								switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
-									"binding menu action '%s' to '%s'\n", xml_map->name, digits);
-								status = switch_ivr_menu_bind_action(menu, xml_map->action, param, digits);
-							}
-						}
-					}
-				} else {
-					status = SWITCH_STATUS_FALSE;
+			// if we don't have a terminator, then we have to try and
+			// figure out when a digit set is completed, therefore we
+			// keep track of the min and max digit lengths
+			if (parser->terminator == '\0') {
+				if (len > parser->maxlen) {
+					parser->maxlen = len;
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "max len %u\n", (uint32_t) parser->maxlen);
+				}
+				if (parser->minlen == 0 || len < parser->minlen) {
+					parser->minlen = len;
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "min len %u\n", (uint32_t) parser->minlen);
 				}
+			} else {
+				// since we have a terminator, reset min and max
+				parser->minlen = 0;
+				parser->maxlen = 0;
 			}
+
 		}
 	}
-
 	if (status != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unable to build xml menu\n");
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "unable to add hash for '%s'\n", digits);
 	}
 
 	return status;
 }
 
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_del_event(switch_ivr_digit_stream_parser_t * parser, char *digits)
+{
+	switch_status_t status = SWITCH_STATUS_FALSE;
 
-static char *SAY_METHOD_NAMES[] = {
-    "N/A",
-    "PRONOUNCED",
-    "ITERATED",
-    "COUNTED",
-    NULL
-};
-
-static char *SAY_TYPE_NAMES[] = {
-	"NUMBER",
-	"ITEMS",
-	"PERSONS",
-	"MESSAGES",
-	"CURRENCY",
-	"TIME_MEASUREMENT",
-	"CURRENT_DATE",
-	"CURRENT_TIME",
-	"CURRENT_DATE_TIME",
-	"TELEPHONE_NUMBER",
-	"TELEPHONE_EXTENSION",
-	"URL",
-    "IP_ADDRESS",
-	"EMAIL_ADDRESS",
-	"POSTAL_ADDRESS",
-	"ACCOUNT_NUMBER",
-	"NAME_SPELLED",
-	"NAME_PHONETIC",
-    NULL
-};
-
+	if (parser != NULL && digits != NULL && *digits) {
+		status = switch_core_hash_delete(parser->hash, digits);
+	}
 
-static switch_say_method_t get_say_method_by_name(char *name)
-{
-    int x = 0;
-    for (x = 0; SAY_METHOD_NAMES[x]; x++) {
-        if (!strcasecmp(SAY_METHOD_NAMES[x], name)) {
-            break;
-        }
-    }
+	if (status != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "unable to del hash for '%s'\n", digits);
+	}
 
-    return (switch_say_method_t) x;
+	return status;
 }
 
-static switch_say_method_t get_say_type_by_name(char *name)
+SWITCH_DECLARE(void *) switch_ivr_digit_stream_parser_feed(switch_ivr_digit_stream_parser_t * parser, switch_ivr_digit_stream_t * stream, char digit)
 {
-    int x = 0;
-    for (x = 0; SAY_TYPE_NAMES[x]; x++) {
-        if (!strcasecmp(SAY_TYPE_NAMES[x], name)) {
-            break;
-        }
-    }
-    
-    return (switch_say_method_t) x;
-}
-
+	void *result = NULL;
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_phrase_macro(switch_core_session_t *session,
-                                                        char *macro_name,
-                                                        char *data,
-                                                        char *lang,
-                                                        switch_input_args_t *args)
+	if (parser != NULL && stream != NULL) {
+		switch_size_t len = (stream->digits != NULL ? strlen(stream->digits) : 0);
 
-{
-	switch_xml_t cfg, xml = NULL, language, macros, macro, input, action;
-    char *lname = NULL, *mname = NULL, hint_data[1024] = "", enc_hint[1024] = "";
-    switch_status_t status = SWITCH_STATUS_GENERR;
-    char *old_sound_prefix = NULL, *sound_path = NULL, *tts_engine = NULL, *tts_voice = NULL, *chan_lang = NULL; 
-    switch_channel_t *channel;
-    uint8_t done = 0;
+		// handle new digit arrivals
+		if (digit != '\0') {
 
-    channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+			// if it's not a terminator digit, add it to the collected digits
+			if (digit != parser->terminator) {
+				// if collected digits length >= the max length of the keys
+				// in the hash table, then left shift the digit string
+				if (len > 0 && parser->maxlen != 0 && len >= parser->maxlen) {
+					char *src = stream->digits + 1;
+					char *dst = stream->digits;
 
-	if (!macro_name) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No phrase macro specified.\n");
-		return status;
+					while (*src) {
+						*(dst++) = *(src++);
+					}
+					*dst = digit;
+				} else {
+					stream->digits = realloc(stream->digits, len + 2);
+					*(stream->digits + (len++)) = digit;
+					*(stream->digits + len) = '\0';
+					stream->last_digit_time = switch_time_now() / 1000;
+				}
+			}
+		}
+		// don't allow collected digit string testing if there are varying sized keys until timeout
+		if (parser->maxlen - parser->minlen > 0 && (switch_time_now() / 1000) - stream->last_digit_time < parser->digit_timeout_ms) {
+			len = 0;
+		}
+		// if we have digits to test
+		if (len) {
+			result = switch_core_hash_find(parser->hash, stream->digits);
+			// if we matched the digit string, or this digit is the terminator
+			// reset the collected digits for next digit string
+			if (result != NULL || parser->terminator == digit) {
+				free(stream->digits);
+				stream->digits = NULL;
+			}
+		}
 	}
 
-	if (!lang) {
-        chan_lang = switch_channel_get_variable(channel, "default_language");
-        if (!chan_lang) {
-            chan_lang = "en";
-        } 
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "No language specified - Using [%s]\n", chan_lang);
-	} else {
-        chan_lang = lang;
-    }
-
-	if (!data) {
-		data = "";
-	}
+	return result;
+}
 
-    switch_url_encode(data, enc_hint, sizeof(enc_hint));
-    snprintf(hint_data, sizeof(hint_data), "macro_name=%s&lang=%s&data=%s", macro_name, chan_lang, enc_hint);
-    
-	if (switch_xml_locate("phrases", NULL, NULL, NULL, &xml, &cfg, hint_data) != SWITCH_STATUS_SUCCESS) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of phrases failed.\n");
-        goto done;
-	}
-
-    if (!(macros = switch_xml_child(cfg, "macros"))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "can't find macros tag.\n");
-        goto done;
-    }
-
-    if (!(language = switch_xml_child(macros, "language"))) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "can't find language tag.\n");
-        goto done;
-    }
-
-    while(language) {
-        if ((lname = (char *) switch_xml_attr(language, "name")) && !strcasecmp(lname, chan_lang)) {
-            break;
-        }
-        language = language->next;
-    }
-
-    if (!language) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "can't find language %s.\n", chan_lang);
-        goto done;
-    }
-
-    sound_path = (char *) switch_xml_attr_soft(language, "sound_path");
-    tts_engine = (char *) switch_xml_attr_soft(language, "tts_engine");
-    tts_voice = (char *) switch_xml_attr_soft(language, "tts_voice");
-
-    old_sound_prefix = switch_channel_get_variable(channel, "sound_prefix");    
-    switch_channel_set_variable(channel, "sound_prefix", sound_path);
-
-    if (!(macro = switch_xml_child(language, "macro"))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "can't find any macro tags.\n");
-        goto done;
-    }
-    
-    while(macro) {
-        if ((mname = (char *) switch_xml_attr(macro, "name")) && !strcasecmp(mname, macro_name)) {
-            break;
-        }
-        macro = macro->next;
-    }
-    
-    if (!macro) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "can't find macro %s.\n", macro_name);
-        goto done;
-    }
-
-    if (!(input = switch_xml_child(macro, "input"))) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "can't find any input tags.\n");
-        goto done;
-    }
-
-    switch_channel_pre_answer(channel);
-
-    while(input && !done) {
-        char *pattern = (char *) switch_xml_attr(input, "pattern");
-
-        if (pattern) {
-            pcre *re = NULL;
-            int proceed = 0, ovector[30];
-            char *substituted = NULL;
-            uint32_t len = 0;
-            char *odata = NULL;
-            char *expanded = NULL;
-            switch_xml_t match = NULL;
-            
-            if ((proceed = switch_perform_regex(data, pattern, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
-                match = switch_xml_child(input, "match");
-            } else {
-                match = switch_xml_child(input, "nomatch");
-            }
-
-            if (match) {
-				status = SWITCH_STATUS_SUCCESS;
-                for (action = switch_xml_child(match, "action"); action && status == SWITCH_STATUS_SUCCESS; action = action->next) {
-                    char *adata = (char *) switch_xml_attr_soft(action, "data");
-                    char *func = (char *) switch_xml_attr_soft(action, "function");
-
-                    if (strchr(pattern, '(') && strchr(adata, '$')) {
-                        len = (uint32_t)(strlen(data) + strlen(adata) + 10);
-                        if (!(substituted = malloc(len))) {
-                            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n");
-                            switch_clean_re(re);
-                            switch_safe_free(expanded);
-                            goto done;
-                        }
-                        memset(substituted, 0, len);
-                        switch_perform_substitution(re, proceed, adata, data, substituted, len, ovector);
-                        odata = substituted;
-                    } else {
-                        odata = adata;
-                    }
-                    
-                    expanded = switch_channel_expand_variables(channel, odata);
-
-                    if (expanded == odata) {
-                        expanded = NULL;
-                    } else {
-                        odata = expanded;
-                    }
-                    
-                    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Handle %s:[%s] (%s)\n", func, odata, chan_lang);
-
-                    if (!strcasecmp(func, "play-file")) {
-                        status = switch_ivr_play_file(session, NULL, odata, args);
-                    } else if (!strcasecmp(func, "break")) {
-                        done = 1;
-                        break;
-                    } else if (!strcasecmp(func, "execute")) {
-
-                    } else if (!strcasecmp(func, "say")) {
-                        switch_say_interface_t *si;
-                        if ((si = switch_loadable_module_get_say_interface(chan_lang))) {
-                            char *say_type = (char *) switch_xml_attr_soft(action, "type");
-                            char *say_method = (char *) switch_xml_attr_soft(action, "method");
-                            
-                            status = si->say_function(session, odata, get_say_type_by_name(say_type), get_say_method_by_name(say_method), args);
-                        } else {
-                            switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid SAY Interface [%s]!\n", chan_lang);
-                        }
-                    } else if (!strcasecmp(func, "speak-text")) {
-                        switch_codec_t *read_codec;
-                        if ((read_codec = switch_core_session_get_read_codec(session))) {
-                            
-                            status = switch_ivr_speak_text(session,
-														   tts_engine,
-														   tts_voice,
-														   read_codec->implementation->samples_per_second,
-														   odata,
-														   args);
-                        }
-                    }
-                }
-            }
-            
-            switch_clean_re(re);
-            switch_safe_free(expanded);
-            switch_safe_free(substituted);
-        }
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_reset(switch_ivr_digit_stream_t * stream)
+{
+	switch_status_t status = SWITCH_STATUS_FALSE;
 
-		if (status != SWITCH_STATUS_SUCCESS) {
-            done = 1;
-			break;
-		}
+	if (stream != NULL && stream->digits != NULL) {
+		free(stream->digits);
+		stream->digits = NULL;
+		stream->last_digit_time = 0;
+		status = SWITCH_STATUS_SUCCESS;
+	}
 
-        input = input->next;
-    }
+	return status;
+}
 
- done:
+SWITCH_DECLARE(switch_status_t) switch_ivr_digit_stream_parser_set_terminator(switch_ivr_digit_stream_parser_t * parser, char digit)
+{
+	switch_status_t status = SWITCH_STATUS_FALSE;
 
-	switch_channel_set_variable(channel, "sound_prefix", old_sound_prefix);
+	if (parser != NULL) {
+		parser->terminator = digit;
+		// since we have a terminator, reset min and max
+		parser->minlen = 0;
+		parser->maxlen = 0;
+		status = SWITCH_STATUS_SUCCESS;
+	}
 
-    if (xml) {
-        switch_xml_free(xml);
-    }
-    return status;
+	return status;
 }
 
-
 static int set_profile_data(switch_xml_t xml, switch_caller_profile_t *caller_profile, int off)
 {
 	switch_xml_t param;
@@ -4938,89 +1164,102 @@
 	}
 	switch_xml_set_txt(param, caller_profile->caller_id_name);
 
-    if (!(param = switch_xml_add_child_d(xml, "ani", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->ani);
-
-    if (!(param = switch_xml_add_child_d(xml, "aniii", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->aniii);
-
-    if (!(param = switch_xml_add_child_d(xml, "caller_id_number", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->caller_id_number);
-
-    if (!(param = switch_xml_add_child_d(xml, "network_addr", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->network_addr);
-
-    if (!(param = switch_xml_add_child_d(xml, "rdnis", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->rdnis);
-
-    if (!(param = switch_xml_add_child_d(xml, "destination_number", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->destination_number);
-
-    if (!(param = switch_xml_add_child_d(xml, "uuid", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->uuid);
-
-    if (!(param = switch_xml_add_child_d(xml, "source", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->source);
-
-    if (!(param = switch_xml_add_child_d(xml, "context", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->context);
-
-    if (!(param = switch_xml_add_child_d(xml, "chan_name", off++))) {
-        return -1;
-    }
-    switch_xml_set_txt(param, caller_profile->chan_name);
+	if (!(param = switch_xml_add_child_d(xml, "ani", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->ani);
+
+	if (!(param = switch_xml_add_child_d(xml, "aniii", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->aniii);
+
+	if (!(param = switch_xml_add_child_d(xml, "caller_id_number", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->caller_id_number);
+
+	if (!(param = switch_xml_add_child_d(xml, "network_addr", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->network_addr);
+
+	if (!(param = switch_xml_add_child_d(xml, "rdnis", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->rdnis);
+
+	if (!(param = switch_xml_add_child_d(xml, "destination_number", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->destination_number);
+
+	if (!(param = switch_xml_add_child_d(xml, "uuid", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->uuid);
+
+	if (!(param = switch_xml_add_child_d(xml, "source", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->source);
+
+	if (!(param = switch_xml_add_child_d(xml, "context", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->context);
+
+	if (!(param = switch_xml_add_child_d(xml, "chan_name", off++))) {
+		return -1;
+	}
+	switch_xml_set_txt(param, caller_profile->chan_name);
 
 	return 0;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_ivr_generate_xml_cdr(switch_core_session_t *session, switch_xml_t *xml_cdr)
+SWITCH_DECLARE(switch_status_t) switch_ivr_generate_xml_cdr(switch_core_session_t *session, switch_xml_t * xml_cdr)
 {
 	switch_channel_t *channel;
 	switch_caller_profile_t *caller_profile;
 	switch_hash_index_t *hi;
 	void *vval;
 	const void *vvar;
-	switch_xml_t variable,
-		variables,
-		cdr,
-		x_caller_profile,
-		x_caller_extension,
-		x_times,
-		time_tag,
-		x_application,
-		x_callflow;
+	switch_xml_t variable, variables, cdr, x_caller_profile, x_caller_extension, x_times, time_tag, 
+		x_application, x_callflow, x_inner_extension, x_apps;
+	switch_app_log_t *app_log;
+	
 	char tmp[512];
 	int cdr_off = 0, v_off = 0;
 
 	channel = switch_core_session_get_channel(session);
-    assert(channel != NULL);
+	assert(channel != NULL);
 
 	if (!(cdr = switch_xml_new("cdr"))) {
-        return SWITCH_STATUS_SUCCESS;
-    }
+		return SWITCH_STATUS_SUCCESS;
+	}
 
 	if (!(variables = switch_xml_add_child_d(cdr, "variables", cdr_off++))) {
 		goto error;
 	}
-	
+
+	if ((app_log = switch_core_session_get_app_log(session))) {
+		int app_off = 0;
+		switch_app_log_t *ap;
+		
+		if (!(x_apps = switch_xml_add_child_d(cdr, "app_log", cdr_off++))) {
+			goto error;
+		}
+		for(ap = app_log; ap; ap = ap->next) {
+
+			if (!(x_application = switch_xml_add_child_d(x_apps, "application", app_off++))) {
+				goto error;
+			}
+			
+			switch_xml_set_attr_d(x_application, "app_name", ap->app);
+			switch_xml_set_attr_d(x_application, "app_data", ap->arg);
+		}
+	}
+
 	for (hi = switch_channel_variable_first(channel, switch_core_session_get_pool(session)); hi; hi = switch_hash_next(hi)) {
 		switch_hash_this(hi, &vvar, NULL, &vval);
 		if (vvar && vval) {
@@ -5030,7 +1269,7 @@
 				switch_size_t dlen = strlen(value) * 3;
 
 				if ((data = switch_core_session_alloc(session, dlen))) {
-					switch_url_encode(value, data, dlen);					
+					switch_url_encode(value, data, dlen);
 					switch_xml_set_txt_d(variable, data);
 				}
 			}
@@ -5038,14 +1277,15 @@
 	}
 
 	caller_profile = switch_channel_get_caller_profile(channel);
-	
+
 	while (caller_profile) {
 		int cf_off = 0;
-		
+
 		if (!(x_callflow = switch_xml_add_child_d(cdr, "callflow", cdr_off++))) {
 			goto error;
 		}
-		
+		switch_xml_set_attr_d(x_callflow, "dialplan", caller_profile->dialplan);
+
 		if (caller_profile->caller_extension) {
 			switch_caller_application_t *ap;
 			int app_off = 0;
@@ -5059,7 +1299,7 @@
 				switch_xml_set_attr_d(x_caller_extension, "current_app", caller_profile->caller_extension->current_application->application_name);
 			}
 
-			for(ap = caller_profile->caller_extension->applications; ap; ap = ap->next) {
+			for (ap = caller_profile->caller_extension->applications; ap; ap = ap->next) {
 				if (!(x_application = switch_xml_add_child_d(x_caller_extension, "application", app_off++))) {
 					goto error;
 				}
@@ -5069,8 +1309,47 @@
 				switch_xml_set_attr_d(x_application, "app_name", ap->application_name);
 				switch_xml_set_attr_d(x_application, "app_data", ap->application_data);
 			}
+
+			if (caller_profile->caller_extension->children) {
+				switch_caller_profile_t *cp = NULL;
+				int i_off = 0;
+				for (cp = caller_profile->caller_extension->children; cp; cp = cp->next) {
+					switch_caller_application_t *ap;
+					int app_off = 0;
+					
+					if (!cp->caller_extension) {
+						continue;
+					}
+					if (!(x_inner_extension = switch_xml_add_child_d(x_caller_extension, "sub_extensions", i_off++))) {
+						goto error;
+					}				
+
+					if (!(x_caller_extension = switch_xml_add_child_d(x_inner_extension, "extension", cf_off++))) {
+						goto error;
+					}
+					switch_xml_set_attr_d(x_caller_extension, "name", cp->caller_extension->extension_name);
+					switch_xml_set_attr_d(x_caller_extension, "number", cp->caller_extension->extension_number);
+					switch_xml_set_attr_d(x_caller_extension, "dialplan", cp->dialplan);
+					if (cp->caller_extension->current_application) {
+						switch_xml_set_attr_d(x_caller_extension, "current_app", cp->caller_extension->current_application->application_name);
+					}
+				
+					for (ap = cp->caller_extension->applications; ap; ap = ap->next) {
+						if (!(x_application = switch_xml_add_child_d(x_caller_extension, "application", app_off++))) {
+							goto error;
+						}
+						if (ap == cp->caller_extension->current_application) {
+							switch_xml_set_attr_d(x_application, "last_executed", "true");
+						}
+						switch_xml_set_attr_d(x_application, "app_name", ap->application_name);
+						switch_xml_set_attr_d(x_application, "app_data", ap->application_data);
+					}
+				}
+			}
+
 		}
-		
+
+
 		if (!(x_caller_profile = switch_xml_add_child_d(x_callflow, "caller_profile", cf_off++))) {
 			goto error;
 		}
@@ -5099,41 +1378,44 @@
 			if (!(time_tag = switch_xml_add_child_d(x_times, "created_time", t_off++))) {
 				goto error;
 			}
-			snprintf(tmp, sizeof(tmp), "%"APR_TIME_T_FMT, caller_profile->times->created);
+			snprintf(tmp, sizeof(tmp), "%" SWITCH_TIME_T_FMT, caller_profile->times->created);
 			switch_xml_set_txt_d(time_tag, tmp);
 
 			if (!(time_tag = switch_xml_add_child_d(x_times, "answered_time", t_off++))) {
 				goto error;
 			}
-			snprintf(tmp, sizeof(tmp), "%"APR_TIME_T_FMT, caller_profile->times->answered);
+			snprintf(tmp, sizeof(tmp), "%" SWITCH_TIME_T_FMT, caller_profile->times->answered);
 			switch_xml_set_txt_d(time_tag, tmp);
 
 			if (!(time_tag = switch_xml_add_child_d(x_times, "hangup_time", t_off++))) {
 				goto error;
 			}
-			snprintf(tmp, sizeof(tmp), "%"APR_TIME_T_FMT, caller_profile->times->hungup);
+			snprintf(tmp, sizeof(tmp), "%" SWITCH_TIME_T_FMT, caller_profile->times->hungup);
 			switch_xml_set_txt_d(time_tag, tmp);
 
 			if (!(time_tag = switch_xml_add_child_d(x_times, "transfer_time", t_off++))) {
 				goto error;
 			}
-			snprintf(tmp, sizeof(tmp), "%"APR_TIME_T_FMT, caller_profile->times->transferred);
+			snprintf(tmp, sizeof(tmp), "%" SWITCH_TIME_T_FMT, caller_profile->times->transferred);
 			switch_xml_set_txt_d(time_tag, tmp);
 		}
 
 		caller_profile = caller_profile->next;
 	}
 
+
+
+
 	*xml_cdr = cdr;
-	
-	return SWITCH_STATUS_SUCCESS;	
 
- error:
+	return SWITCH_STATUS_SUCCESS;
+
+  error:
 
 	if (cdr) {
 		switch_xml_free(cdr);
 	}
-	
+
 	return SWITCH_STATUS_FALSE;
 }
 

Modified: freeswitch/branches/cparker/src/switch_loadable_module.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_loadable_module.c	(original)
+++ freeswitch/branches/cparker/src/switch_loadable_module.c	Tue Apr 24 10:14:28 2007
@@ -30,7 +30,15 @@
  *
  */
 #include <switch.h>
-#include <ctype.h>
+
+/* for apr_pstrcat */
+#include <apr_strings.h>
+
+/* for apr_env_get and apr_env_set */
+#include <apr_env.h>
+
+/* for apr file and directory handling */
+#include <apr_file_io.h>
 
 struct switch_loadable_module {
 	char *filename;
@@ -55,12 +63,13 @@
 	switch_hash_t *directory_hash;
 	switch_hash_t *chat_hash;
 	switch_hash_t *say_hash;
+	switch_hash_t *management_hash;
 	switch_memory_pool_t *pool;
 };
 
 static struct switch_loadable_module_container loadable_modules;
 
-static void *switch_loadable_module_exec(switch_thread_t *thread, void *obj)
+static void *switch_loadable_module_exec(switch_thread_t * thread, void *obj)
 {
 
 
@@ -87,8 +96,22 @@
 }
 
 
+static void switch_loadable_module_runtime(void)
+{
+	switch_hash_index_t *hi;
+	void *val;
+	switch_loadable_module_t *module;
 
+	for (hi = switch_hash_first(loadable_modules.pool, loadable_modules.module_hash); hi; hi = switch_hash_next(hi)) {
+		switch_hash_this(hi, NULL, NULL, &val);
+		module = (switch_loadable_module_t *) val;
 
+		if (module->switch_module_runtime) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Starting runtime thread for %s\n", module->module_interface->module_name);
+			switch_core_launch_thread(switch_loadable_module_exec, module, loadable_modules.pool);
+		}
+	}
+}
 
 static switch_status_t switch_loadable_module_process(char *key, switch_loadable_module_t *new_module)
 {
@@ -113,7 +136,7 @@
 		const switch_codec_interface_t *ptr;
 
 		for (ptr = new_module->module_interface->codec_interface; ptr; ptr = ptr->next) {
-			if (!ptr->interface_name)  {
+			if (!ptr->interface_name) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to load codec interface from %s due to no interface name.\n", key);
 			} else {
 				unsigned load_interface = 1;
@@ -124,14 +147,13 @@
 					}
 				}
 				if (!load_interface) {
-					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to load codec interface %s from %s due to no iana name in an implementation.\n", ptr->interface_name, key);
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+									  "Failed to load codec interface %s from %s due to no iana name in an implementation.\n", ptr->interface_name, key);
 				} else {
 					for (impl = ptr->implementations; impl; impl = impl->next) {
 						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
 										  "Adding Codec '%s' (%s) %dhz %dms\n",
-										  impl->iananame,
-										  ptr->interface_name,
-										  impl->samples_per_second, impl->microseconds_per_frame / 1000);
+										  impl->iananame, ptr->interface_name, impl->samples_per_second, impl->microseconds_per_frame / 1000);
 						if (!switch_core_hash_find(loadable_modules.codec_hash, impl->iananame)) {
 							switch_core_hash_insert(loadable_modules.codec_hash, impl->iananame, (const void *) ptr);
 						}
@@ -143,7 +165,7 @@
 					}
 				}
 			}
-		} 
+		}
 	}
 
 	if (new_module->module_interface->dialplan_interface) {
@@ -232,11 +254,11 @@
 				int i;
 				for (i = 0; ptr->extens[i]; i++) {
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Adding File Format '%s'\n", ptr->extens[i]);
-				if (switch_event_create(&event, SWITCH_EVENT_MODULE_LOAD) == SWITCH_STATUS_SUCCESS) {
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "type", "file");
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "name", "%s", ptr->extens[i]);
-					switch_event_fire(&event);
-				}
+					if (switch_event_create(&event, SWITCH_EVENT_MODULE_LOAD) == SWITCH_STATUS_SUCCESS) {
+						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "type", "file");
+						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "name", "%s", ptr->extens[i]);
+						switch_event_fire(&event);
+					}
 					switch_core_hash_insert(loadable_modules.file_hash, ptr->extens[i], (const void *) ptr);
 				}
 			}
@@ -332,7 +354,32 @@
 			}
 		}
 	}
-	
+
+	if (new_module->module_interface->management_interface) {
+		const switch_management_interface_t *ptr;
+
+		for (ptr = new_module->module_interface->management_interface; ptr; ptr = ptr->next) {
+			if (!ptr->relative_oid) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to load management interface from %s due to no interface name.\n", key);
+			} else {
+				if (switch_core_hash_find(loadable_modules.management_hash, ptr->relative_oid)) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+									  "Failed to load management interface %s. OID %s already exists\n", key, ptr->relative_oid);
+				} else {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
+									  "Adding Management interface '%s' OID[%s.%s]\n", key, FREESWITCH_OID_PREFIX, ptr->relative_oid);
+					switch_core_hash_insert(loadable_modules.management_hash, ptr->relative_oid, (const void *) ptr);
+					if (switch_event_create(&event, SWITCH_EVENT_MODULE_LOAD) == SWITCH_STATUS_SUCCESS) {
+						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "type", "management");
+						switch_event_add_header(event, SWITCH_STACK_BOTTOM, "name", "%s", ptr->relative_oid);
+						switch_event_fire(&event);
+					}
+				}
+
+			}
+		}
+	}
+
 
 	return SWITCH_STATUS_SUCCESS;
 
@@ -341,11 +388,11 @@
 static switch_status_t switch_loadable_module_load_file(char *filename, switch_loadable_module_t **new_module)
 {
 	switch_loadable_module_t *module = NULL;
-	apr_dso_handle_t *dso = NULL;
+	switch_dso_handle_t *dso = NULL;
 	apr_status_t status = SWITCH_STATUS_SUCCESS;
-	apr_dso_handle_sym_t load_function_handle = NULL;
-	apr_dso_handle_sym_t shutdown_function_handle = NULL;
-	apr_dso_handle_sym_t runtime_function_handle = NULL;
+	switch_dso_handle_sym_t load_function_handle = NULL;
+	switch_dso_handle_sym_t shutdown_function_handle = NULL;
+	switch_dso_handle_sym_t runtime_function_handle = NULL;
 	switch_module_load_t load_func_ptr = NULL;
 	int loading = 1;
 	const char *err = NULL;
@@ -355,17 +402,17 @@
 	assert(filename != NULL);
 
 	*new_module = NULL;
-	status = apr_dso_load(&dso, filename, loadable_modules.pool);
+	status = switch_dso_load(&dso, filename, loadable_modules.pool);
 
 	while (loading) {
 		if (status != APR_SUCCESS) {
-			apr_dso_error(dso, derr, sizeof(derr));
+			switch_dso_error(dso, derr, sizeof(derr));
 			err = derr;
 			break;
 		}
 
-		status = apr_dso_sym(&load_function_handle, dso, "switch_module_load");
-		load_func_ptr = (switch_module_load_t)(intptr_t) load_function_handle;
+		status = switch_dso_sym(&load_function_handle, dso, "switch_module_load");
+		load_func_ptr = (switch_module_load_t) (intptr_t) load_function_handle;
 
 		if (load_func_ptr == NULL) {
 			err = "Cannot locate symbol 'switch_module_load' please make sure this is a vaild module.";
@@ -387,7 +434,7 @@
 	}
 
 	if (err) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Error Loading module %s\n**%s**\n", filename, err);
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Loading module %s\n**%s**\n", filename, err);
 		return SWITCH_STATUS_GENERR;
 	}
 
@@ -395,17 +442,13 @@
 	module->module_interface = module_interface;
 	module->switch_module_load = load_func_ptr;
 
-	apr_dso_sym(&shutdown_function_handle, dso, "switch_module_shutdown");
-	module->switch_module_shutdown = (switch_module_shutdown_t)(intptr_t) shutdown_function_handle;
-	apr_dso_sym(&runtime_function_handle, dso, "switch_module_runtime");
-	module->switch_module_runtime = (switch_module_runtime_t)(intptr_t) runtime_function_handle;
+	switch_dso_sym(&shutdown_function_handle, dso, "switch_module_shutdown");
+	module->switch_module_shutdown = (switch_module_shutdown_t) (intptr_t) shutdown_function_handle;
+	switch_dso_sym(&runtime_function_handle, dso, "switch_module_runtime");
+	module->switch_module_runtime = (switch_module_runtime_t) (intptr_t) runtime_function_handle;
 
 	module->lib = dso;
 
-	if (module->switch_module_runtime) {
-		switch_core_launch_thread(switch_loadable_module_exec, module, loadable_modules.pool);
-	}
-
 	*new_module = module;
 	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Successfully Loaded [%s]\n", module_interface->module_name);
 
@@ -413,7 +456,7 @@
 
 }
 
-SWITCH_DECLARE(switch_status_t) switch_loadable_module_load_module(char *dir, char *fname)
+SWITCH_DECLARE(switch_status_t) switch_loadable_module_load_module(char *dir, char *fname, switch_bool_t runtime)
 {
 	switch_size_t len = 0;
 	char *path;
@@ -452,92 +495,95 @@
 		}
 	}
 
-    if (switch_core_hash_find(loadable_modules.module_hash, file)) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Module %s Already Loaded!\n", file);
-        return SWITCH_STATUS_FALSE;
-    }
+	if (switch_core_hash_find(loadable_modules.module_hash, file)) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Module %s Already Loaded!\n", file);
+		return SWITCH_STATUS_FALSE;
+	}
 
 	if ((status = switch_loadable_module_load_file(path, &new_module) == SWITCH_STATUS_SUCCESS)) {
-		return switch_loadable_module_process((char *) file, new_module);
-	} else {
-		return status;
+		if ((status = switch_loadable_module_process((char *) file, new_module)) == SWITCH_STATUS_SUCCESS && runtime) {
+			if (new_module->switch_module_runtime) {
+				switch_core_launch_thread(switch_loadable_module_exec, new_module, loadable_modules.pool);
+			}
+		}
 	}
+
+	return status;
+
 }
 
 SWITCH_DECLARE(switch_status_t) switch_loadable_module_build_dynamic(char *filename,
-																   switch_module_load_t switch_module_load,
-																   switch_module_runtime_t switch_module_runtime,
-																   switch_module_shutdown_t switch_module_shutdown)
-{ 
-	switch_loadable_module_t *module = NULL; 
-	switch_module_load_t load_func_ptr = NULL; 
-	int loading = 1; 
-	const char *err = NULL; 
-	switch_loadable_module_interface_t *module_interface = NULL; 
-
-	if ((module = switch_core_permanent_alloc(sizeof(switch_loadable_module_t))) == 0) { 
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Couldn't allocate memory\n"); 
-		return SWITCH_STATUS_GENERR; 
-	} 
-
-	while (loading) { 
-  		load_func_ptr = (switch_module_load_t) switch_module_load; 
-  
-		if (load_func_ptr == NULL) { 
-			err = "Cannot Load"; 
-			break; 
-		} 
-  
-		if (load_func_ptr(&module_interface, filename) != SWITCH_STATUS_SUCCESS) { 
-			err = "Module load routine returned an error"; 
-			module_interface = NULL; 
-			break; 
-		} 
-  
-		if ((module = switch_core_permanent_alloc(sizeof(switch_loadable_module_t))) == 0) { 
-			err = "Could not allocate memory\n"; 
-			break; 
-		} 
-  
-		loading = 0; 
-	}
-  
-	if (err) { 
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Error Loading module %s\n**%s**\n", filename, err); 
-		return SWITCH_STATUS_GENERR; 
-	} 
-  
-	module->filename = switch_core_permanent_strdup(filename); 
-	module->module_interface = module_interface; 
-	module->switch_module_load = load_func_ptr; 
-  
-	if (switch_module_shutdown) { 
-		module->switch_module_shutdown = switch_module_shutdown; 
-	} 
-	if (switch_module_runtime) { 
-		module->switch_module_runtime = switch_module_runtime; 
-	} 
-	if (module->switch_module_runtime) { 
-		switch_core_launch_thread(switch_loadable_module_exec, module, loadable_modules.pool); 
-	} 
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Successfully Loaded [%s]\n", module_interface->module_name); 
+																	 switch_module_load_t switch_module_load,
+																	 switch_module_runtime_t switch_module_runtime,
+																	 switch_module_shutdown_t switch_module_shutdown)
+{
+	switch_loadable_module_t *module = NULL;
+	switch_module_load_t load_func_ptr = NULL;
+	int loading = 1;
+	const char *err = NULL;
+	switch_loadable_module_interface_t *module_interface = NULL;
+
+	if ((module = switch_core_permanent_alloc(sizeof(switch_loadable_module_t))) == 0) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Couldn't allocate memory\n");
+		return SWITCH_STATUS_GENERR;
+	}
+
+	while (loading) {
+		load_func_ptr = (switch_module_load_t) switch_module_load;
+
+		if (load_func_ptr == NULL) {
+			err = "Cannot Load";
+			break;
+		}
+
+		if (load_func_ptr(&module_interface, filename) != SWITCH_STATUS_SUCCESS) {
+			err = "Module load routine returned an error";
+			module_interface = NULL;
+			break;
+		}
+
+		if ((module = switch_core_permanent_alloc(sizeof(switch_loadable_module_t))) == 0) {
+			err = "Could not allocate memory\n";
+			break;
+		}
+
+		loading = 0;
+	}
+
+	if (err) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Error Loading module %s\n**%s**\n", filename, err);
+		return SWITCH_STATUS_GENERR;
+	}
+
+	module->filename = switch_core_permanent_strdup(filename);
+	module->module_interface = module_interface;
+	module->switch_module_load = load_func_ptr;
+
+	if (switch_module_shutdown) {
+		module->switch_module_shutdown = switch_module_shutdown;
+	}
+	if (switch_module_runtime) {
+		module->switch_module_runtime = switch_module_runtime;
+	}
+	if (module->switch_module_runtime) {
+		switch_core_launch_thread(switch_loadable_module_exec, module, loadable_modules.pool);
+	}
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Successfully Loaded [%s]\n", module_interface->module_name);
 	return switch_loadable_module_process((char *) module->filename, module);
-} 
+}
 
 #ifdef WIN32
 static void switch_loadable_module_path_init()
 {
-	char *path =NULL, *working =NULL;
+	char *path = NULL, *working = NULL;
 	apr_dir_t *perl_dir_handle = NULL;
 
 	apr_env_get(&path, "path", loadable_modules.pool);
-	apr_filepath_get(&working, APR_FILEPATH_NATIVE , loadable_modules.pool);
+	apr_filepath_get(&working, APR_FILEPATH_NATIVE, loadable_modules.pool);
 
 	if (apr_dir_open(&perl_dir_handle, ".\\perl", loadable_modules.pool) == APR_SUCCESS) {
-			apr_dir_close(perl_dir_handle);
-			apr_env_set("path", 
-						apr_pstrcat(loadable_modules.pool, path, ";", working, "\\perl", NULL), 
-						loadable_modules.pool);
+		apr_dir_close(perl_dir_handle);
+		apr_env_set("path", apr_pstrcat(loadable_modules.pool, path, ";", working, "\\perl", NULL), loadable_modules.pool);
 	}
 }
 #endif
@@ -545,7 +591,7 @@
 SWITCH_DECLARE(switch_status_t) switch_loadable_module_init()
 {
 
-	apr_finfo_t finfo = {0};
+	apr_finfo_t finfo = { 0 };
 	apr_dir_t *module_dir_handle = NULL;
 	apr_int32_t finfo_flags = APR_FINFO_DIRENT | APR_FINFO_TYPE | APR_FINFO_NAME;
 	char *cf = "modules.conf";
@@ -585,6 +631,7 @@
 	switch_core_hash_init(&loadable_modules.directory_hash, loadable_modules.pool);
 	switch_core_hash_init(&loadable_modules.chat_hash, loadable_modules.pool);
 	switch_core_hash_init(&loadable_modules.say_hash, loadable_modules.pool);
+	switch_core_hash_init(&loadable_modules.management_hash, loadable_modules.pool);
 	switch_core_hash_init(&loadable_modules.dialplan_hash, loadable_modules.pool);
 
 	if ((xml = switch_xml_open_cfg(cf, &cfg, NULL))) {
@@ -597,12 +644,12 @@
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Invalid extension for %s\n", val);
 					continue;
 				}
-				switch_loadable_module_load_module((char *) SWITCH_GLOBAL_dirs.mod_dir, (char *) val);
+				switch_loadable_module_load_module((char *) SWITCH_GLOBAL_dirs.mod_dir, (char *) val, SWITCH_FALSE);
 				count++;
 			}
 		}
 		switch_xml_free(xml);
-		
+
 	} else {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "open of %s failed\n", cf);
 	}
@@ -617,12 +664,12 @@
 					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Invalid extension for %s\n", val);
 					continue;
 				}
-				switch_loadable_module_load_module((char *) SWITCH_GLOBAL_dirs.mod_dir, (char *) val);
+				switch_loadable_module_load_module((char *) SWITCH_GLOBAL_dirs.mod_dir, (char *) val, SWITCH_FALSE);
 				count++;
 			}
 		}
 		switch_xml_free(xml);
-		
+
 	} else {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "open of %s failed\n", pcf);
 	}
@@ -631,7 +678,7 @@
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "No modules loaded assuming 'load all'\n");
 		all = 1;
 	}
-	
+
 	if (all) {
 		if (apr_dir_open(&module_dir_handle, SWITCH_GLOBAL_dirs.mod_dir, loadable_modules.pool) != APR_SUCCESS) {
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Can't open directory: %s\n", SWITCH_GLOBAL_dirs.mod_dir);
@@ -657,11 +704,12 @@
 				continue;
 			}
 
-			switch_loadable_module_load_module((char *) SWITCH_GLOBAL_dirs.mod_dir, (char *) fname);
+			switch_loadable_module_load_module((char *) SWITCH_GLOBAL_dirs.mod_dir, (char *) fname, SWITCH_FALSE);
 		}
 		apr_dir_close(module_dir_handle);
 	}
 
+	switch_loadable_module_runtime();
 
 	return SWITCH_STATUS_SUCCESS;
 }
@@ -680,7 +728,7 @@
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "Stopping: %s\n", module->module_interface->module_name);
 			if (module->switch_module_shutdown() == SWITCH_STATUS_UNLOAD) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "%s unloaded.\n", module->module_interface->module_name);
-				apr_dso_unload(module->lib);
+				switch_dso_unload(module->lib);
 				module->lib = NULL;
 			} else {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "%s shutdown.\n", module->module_interface->module_name);
@@ -702,14 +750,14 @@
 	char altname[256] = "";
 	switch_codec_interface_t *codec;
 	switch_size_t x;
-	
+
 	if (!(codec = switch_core_hash_find(loadable_modules.codec_hash, name))) {
-		for(x = 0; x < strlen(name); x++) {
-			altname[x] = (char)toupper((int)name[x]);
+		for (x = 0; x < strlen(name); x++) {
+			altname[x] = (char) toupper((int) name[x]);
 		}
 		if (!(codec = switch_core_hash_find(loadable_modules.codec_hash, altname))) {
-			for(x = 0; x < strlen(name); x++) {
-				altname[x] = (char)tolower((int)name[x]);
+			for (x = 0; x < strlen(name); x++) {
+				altname[x] = (char) tolower((int) name[x]);
 			}
 			codec = switch_core_hash_find(loadable_modules.codec_hash, altname);
 		}
@@ -767,29 +815,33 @@
 	return switch_core_hash_find(loadable_modules.say_hash, name);
 }
 
-SWITCH_DECLARE(int) switch_loadable_module_get_codecs(switch_memory_pool_t *pool, const switch_codec_implementation_t **array,
-													  int arraylen)
+SWITCH_DECLARE(switch_management_interface_t *) switch_loadable_module_get_management_interface(char *relative_oid)
+{
+	return switch_core_hash_find(loadable_modules.management_hash, relative_oid);
+}
+
+SWITCH_DECLARE(int) switch_loadable_module_get_codecs(switch_memory_pool_t *pool, const switch_codec_implementation_t **array, int arraylen)
 {
 	switch_hash_index_t *hi;
 	void *val;
 	switch_codec_interface_t *codec_interface;
 	int i = 0;
-    const switch_codec_implementation_t *imp;
+	const switch_codec_implementation_t *imp;
 
 	for (hi = switch_hash_first(pool, loadable_modules.codec_hash); hi; hi = switch_hash_next(hi)) {
 		switch_hash_this(hi, NULL, NULL, &val);
 		codec_interface = (switch_codec_interface_t *) val;
-        /* Look for a 20ms implementation because it's the safest choice */
-        for (imp = codec_interface->implementations; imp; imp = imp->next) {
-            if (imp->microseconds_per_frame / 1000 == 20) {
-                array[i++] = imp;
-                goto found;
-            }
-        }
-        /* oh well we will use what we have */
+		/* Look for a 20ms implementation because it's the safest choice */
+		for (imp = codec_interface->implementations; imp; imp = imp->next) {
+			if (imp->microseconds_per_frame / 1000 == 20) {
+				array[i++] = imp;
+				goto found;
+			}
+		}
+		/* oh well we will use what we have */
 		array[i++] = codec_interface->implementations;
 
-    found:
+	  found:
 
 		if (i > arraylen) {
 			break;
@@ -800,14 +852,13 @@
 
 }
 
-SWITCH_DECLARE(int) switch_loadable_module_get_codecs_sorted(const switch_codec_implementation_t **array,
-															 int arraylen, char **prefs, int preflen)
+SWITCH_DECLARE(int) switch_loadable_module_get_codecs_sorted(const switch_codec_implementation_t **array, int arraylen, char **prefs, int preflen)
 {
 	int x, i = 0;
 	switch_codec_interface_t *codec_interface;
 	const switch_codec_implementation_t *imp;
 
-    for (x = 0; x < preflen; x++) {
+	for (x = 0; x < preflen; x++) {
 		char *cur, *last = NULL, *next = NULL, *name, *p, buf[256];
 		uint32_t interval = 0, rate = 0;
 
@@ -832,52 +883,52 @@
 			cur = next;
 		}
 
-        if ((codec_interface = switch_loadable_module_get_codec_interface(name)) != 0 ) {
-            /* If no specific codec interval is requested opt for 20ms above all else because lots of stuff assumes it */
-            if (!interval) {
-                for (imp = codec_interface->implementations; imp; imp = imp->next) {
-                    uint8_t match = 1;
-
-                    if ((uint32_t)(imp->microseconds_per_frame / 1000) != 20) {
-                        match = 0;
-                    }
-
-                    if (match && rate && (uint32_t)imp->samples_per_second != rate) {
-                        match = 0;
-                    }
-
-                    if (match) {
-                        array[i++] = imp;
-                        goto found;
-                    }
-                }
-            }
+		if ((codec_interface = switch_loadable_module_get_codec_interface(name)) != 0) {
+			/* If no specific codec interval is requested opt for 20ms above all else because lots of stuff assumes it */
+			if (!interval) {
+				for (imp = codec_interface->implementations; imp; imp = imp->next) {
+					uint8_t match = 1;
+
+					if ((uint32_t) (imp->microseconds_per_frame / 1000) != 20) {
+						match = 0;
+					}
+
+					if (match && rate && (uint32_t) imp->samples_per_second != rate) {
+						match = 0;
+					}
+
+					if (match) {
+						array[i++] = imp;
+						goto found;
+					}
+				}
+			}
 
-            /* Either looking for a specific interval or there was no interval specified and there wasn't one @20ms available*/
+			/* Either looking for a specific interval or there was no interval specified and there wasn't one @20ms available */
 			for (imp = codec_interface->implementations; imp; imp = imp->next) {
 				uint8_t match = 1;
 
-				if (interval && (uint32_t)(imp->microseconds_per_frame / 1000) != interval) {
+				if (interval && (uint32_t) (imp->microseconds_per_frame / 1000) != interval) {
 					match = 0;
 				}
 
-				if (match && rate && (uint32_t)imp->samples_per_second != rate) {
+				if (match && rate && (uint32_t) imp->samples_per_second != rate) {
 					match = 0;
 				}
 
 				if (match) {
 					array[i++] = imp;
-                    goto found;
+					goto found;
 				}
 			}
 
-        found:
+		  found:
 
-            if (i > arraylen) {
-                break;
-            }
-        }
-    }
+			if (i > arraylen) {
+				break;
+			}
+		}
+	}
 
 	return i;
 }
@@ -909,7 +960,7 @@
 	} else {
 		status = SWITCH_STATUS_FALSE;
 		stream->write_function(stream, "INVALID COMMAND [%s]", cmd);
-		//snprintf(retbuf, len, "INVALID COMMAND [%s]", cmd);
+		/* snprintf(retbuf, len, "INVALID COMMAND [%s]", cmd); */
 	}
 
 	if (stream->event) {

Modified: freeswitch/branches/cparker/src/switch_log.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_log.c	(original)
+++ freeswitch/branches/cparker/src/switch_log.c	Tue Apr 24 10:14:28 2007
@@ -33,14 +33,14 @@
 
 
 static const char *LEVELS[] = {
-	"EMERG"  , 
-	"ALERT"  , 
-	"CRIT"   , 
-	"ERR"    , 
-	"WARNING", 
-	"NOTICE" , 
-	"INFO"   , 
-	"DEBUG"  , 
+	"EMERG",
+	"ALERT",
+	"CRIT",
+	"ERR",
+	"WARNING",
+	"NOTICE",
+	"INFO",
+	"DEBUG",
 	"CONSOLE",
 	NULL
 };
@@ -69,7 +69,7 @@
 {
 	int x = 0;
 	switch_log_level_t level = SWITCH_LOG_DEBUG;
-	for(x = 0;;x++) {
+	for (x = 0;; x++) {
 		if (!LEVELS[x]) {
 			break;
 		}
@@ -91,7 +91,7 @@
 		return SWITCH_STATUS_MEMERR;
 	}
 
-	if ((uint8_t)level > MAX_LEVEL) {
+	if ((uint8_t) level > MAX_LEVEL) {
 		MAX_LEVEL = level;
 	}
 
@@ -111,30 +111,30 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static void *SWITCH_THREAD_FUNC log_thread(switch_thread_t *thread, void *obj)
+static void *SWITCH_THREAD_FUNC log_thread(switch_thread_t * thread, void *obj)
 {
 
 	/* To Be or Not To Be */
 	assert(obj == NULL || obj != NULL);
 	THREAD_RUNNING = 1;
 
-	while(THREAD_RUNNING == 1) {
+	while (THREAD_RUNNING == 1) {
 		void *pop = NULL;
 		switch_log_node_t *node = NULL;
 		switch_log_binding_t *binding;
-		
+
 		if (switch_queue_pop(LOG_QUEUE, &pop) != SWITCH_STATUS_SUCCESS) {
 			break;
 		}
-		
+
 		if (!pop) {
 			break;
 		}
-		
+
 		node = (switch_log_node_t *) pop;
 
 		switch_mutex_lock(BINDLOCK);
-		for(binding = BINDINGS; binding; binding = binding->next) {
+		for (binding = BINDINGS; binding; binding = binding->next) {
 			if (binding->level >= node->level) {
 				binding->function(node, node->level);
 			}
@@ -162,14 +162,15 @@
 	return NULL;
 }
 
-SWITCH_DECLARE(void) switch_log_printf(switch_text_channel_t channel, const char *file, const char *func, int line, switch_log_level_t level, const char *fmt, ...)
+SWITCH_DECLARE(void) switch_log_printf(switch_text_channel_t channel, const char *file, const char *func, int line,
+									   switch_log_level_t level, const char *fmt, ...)
 {
 	char *data = NULL;
 	char *new_fmt = NULL;
 	int ret = 0;
 	va_list ap;
 	FILE *handle;
-	const char *filep = (file ? switch_cut_path(file): "");
+	const char *filep = (file ? switch_cut_path(file) : "");
 	const char *funcp = (func ? func : "");
 	char *content = NULL;
 	switch_time_t now = switch_time_now();
@@ -186,19 +187,14 @@
 
 		switch_time_exp_lt(&tm, now);
 		switch_strftime(date, &retsize, sizeof(date), "%Y-%m-%d %T", &tm);
-		
-		len = (uint32_t)(strlen(extra_fmt) + strlen(date) + strlen(filep) + 32 + strlen(funcp) + strlen(fmt));
-		new_fmt = malloc(len+1);
+
+		len = (uint32_t) (strlen(extra_fmt) + strlen(date) + strlen(filep) + 32 + strlen(funcp) + strlen(fmt));
+		new_fmt = malloc(len + 1);
 		snprintf(new_fmt, len, extra_fmt, date, LEVELS[level], filep, line, funcp, 128, fmt);
 		fmt = new_fmt;
 	}
 
-#ifdef HAVE_VASPRINTF
-	ret = vasprintf(&data, fmt, ap);
-#else
-	data = (char *) malloc(2048);
-	ret = vsnprintf(data, 2048, fmt, ap);
-#endif
+	ret = switch_vasprintf(&data, fmt, ap);
 	va_end(ap);
 	if (ret == -1) {
 		fprintf(stderr, "Memory Error\n");
@@ -213,15 +209,15 @@
 		}
 
 		if (channel == SWITCH_CHANNEL_ID_EVENT) {
-				switch_event_t *event;
-				if (switch_event_running() == SWITCH_STATUS_SUCCESS && switch_event_create(&event, SWITCH_EVENT_LOG) == SWITCH_STATUS_SUCCESS) {
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-Data", "%s", data);
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-File", "%s", filep);
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-Function", "%s", funcp);
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-Line", "%d", line);
-					switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-Level", "%d", (int)level);
-					switch_event_fire(&event);
-				}
+			switch_event_t *event;
+			if (switch_event_running() == SWITCH_STATUS_SUCCESS && switch_event_create(&event, SWITCH_EVENT_LOG) == SWITCH_STATUS_SUCCESS) {
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-Data", "%s", data);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-File", "%s", filep);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-Function", "%s", funcp);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-Line", "%d", line);
+				switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Log-Level", "%d", (int) level);
+				switch_event_fire(&event);
+			}
 		} else {
 			if (level == SWITCH_LOG_CONSOLE || !LOG_QUEUE || !THREAD_RUNNING) {
 				fprintf(handle, "%s", data);
@@ -241,7 +237,7 @@
 				} else {
 					free(data);
 				}
-			} 
+			}
 		}
 	}
 

Modified: freeswitch/branches/cparker/src/switch_resample.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_resample.c	(original)
+++ freeswitch/branches/cparker/src/switch_resample.c	Tue Apr 24 10:14:28 2007
@@ -31,7 +31,12 @@
  */
 #include <switch.h>
 #include <switch_resample.h>
+#ifndef WIN32
+#include <switch_private.h>
+#endif
+#ifndef DISABLE_RESAMPLE
 #include <libresample.h>
+#endif
 #define NORMFACT (float)0x8000
 #define MAXSAMPLE (float)0x7FFF
 #define MAXSAMPLEC (char)0x7F
@@ -48,10 +53,12 @@
 
 
 SWITCH_DECLARE(switch_status_t) switch_resample_create(switch_audio_resampler_t **new_resampler,
-													 int from_rate,
-													 switch_size_t from_size,
-													 int to_rate, uint32_t to_size, switch_memory_pool_t *pool)
+													   int from_rate, switch_size_t from_size, int to_rate, uint32_t to_size, switch_memory_pool_t *pool)
 {
+#ifdef DISABLE_RESAMPLE
+	*new_resampler = NULL;
+	return SWITCH_STATUS_NOTIMPL;
+#else
 	switch_audio_resampler_t *resampler;
 	double lto_rate, lfrom_rate;
 
@@ -66,8 +73,8 @@
 	resampler->factor = (lto_rate / lfrom_rate);
 
 	resampler->resampler = resample_open(QUALITY, resampler->factor, resampler->factor);
-	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Activate Resampler %d->%d %f\n", resampler->from_rate,
-						  resampler->to_rate, resampler->factor);
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Activate Resampler %d->%d %f\n", resampler->from_rate, resampler->to_rate,
+					  resampler->factor);
 	resampler->from_size = from_size;
 	resampler->from = (float *) switch_core_alloc(pool, resampler->from_size);
 	resampler->to_size = to_size;
@@ -75,20 +82,22 @@
 
 	*new_resampler = resampler;
 	return SWITCH_STATUS_SUCCESS;
+#endif
 }
 
 
-SWITCH_DECLARE(uint32_t) switch_resample_process(switch_audio_resampler_t *resampler, float *src, int srclen, float *dst,
-											uint32_t dstlen, int last)
+SWITCH_DECLARE(uint32_t) switch_resample_process(switch_audio_resampler_t *resampler, float *src, int srclen, float *dst, uint32_t dstlen, int last)
 {
+#ifdef DISABLE_RESAMPLE
+	return 0;
+#else
 	int o = 0, srcused = 0, srcpos = 0, out = 0;
 
 	for (;;) {
 		int srcBlock = MIN(srclen - srcpos, srclen);
 		int lastFlag = (last && (srcBlock == srclen - srcpos));
-		o = resample_process(resampler->resampler, resampler->factor, &src[srcpos], srcBlock, lastFlag, &srcused,
-							 &dst[out], dstlen - out);
-		//printf("resampling %d/%d (%d) %d %f\n",  srcpos, srclen,  MIN(dstlen-out, dstlen), srcused, factor);
+		o = resample_process(resampler->resampler, resampler->factor, &src[srcpos], srcBlock, lastFlag, &srcused, &dst[out], dstlen - out);
+		/* printf("resampling %d/%d (%d) %d %f\n",  srcpos, srclen,  MIN(dstlen-out, dstlen), srcused, factor); */
 
 		srcpos += srcused;
 		if (o >= 0) {
@@ -99,11 +108,14 @@
 		}
 	}
 	return out;
+#endif
 }
 
 SWITCH_DECLARE(void) switch_resample_destroy(switch_audio_resampler_t *resampler)
 {
+#ifndef DISABLE_RESAMPLE
 	resample_close(resampler->resampler);
+#endif
 }
 
 
@@ -169,7 +181,7 @@
 
 	for (i = 0; i < len; i++) {
 		f[i] = (float) (s[i]) / NORMFACT;
-		//f[i] = (float) s[i];
+		/* f[i] = (float) s[i]; */
 	}
 	return len;
 }
@@ -183,10 +195,31 @@
 	}
 }
 
+SWITCH_DECLARE(void) switch_generate_sln_silence(int16_t *data, uint32_t samples, uint32_t divisor)
+{
+	int16_t rnd, x;
+	uint32_t i;
+	int sum_rnd = 0;
+
+	assert(divisor);
+
+	for (i = 0; i < samples; i++, sum_rnd = 0) {
+		for (x = 0; x < 7; x++) {
+			rnd = (int16_t) (rand() * sizeof(int16_t));
+			sum_rnd += rnd;
+		}
+		switch_normalize_to_16bit(sum_rnd);
+		*data = (int16_t) ((int16_t) sum_rnd / (int) divisor);
+
+		data++;
+	}
+}
+
+
 SWITCH_DECLARE(void) switch_change_sln_volume(int16_t *data, uint32_t samples, int32_t vol)
 {
-    double newrate = 0;
-    int div = 0;
+	double newrate = 0;
+	int div = 0;
 
 	switch_normalize_volume(vol);
 
@@ -211,7 +244,7 @@
 		for (x = 0; x < samples; x++) {
 			tmp = (int32_t) (div ? fp[x] / newrate : fp[x] * newrate);
 			switch_normalize_to_16bit(tmp);
-			fp[x] = (int16_t)tmp;
+			fp[x] = (int16_t) tmp;
 		}
 	}
 }

Modified: freeswitch/branches/cparker/src/switch_rtp.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_rtp.c	(original)
+++ freeswitch/branches/cparker/src/switch_rtp.c	Tue Apr 24 10:14:28 2007
@@ -24,6 +24,7 @@
  * Contributor(s):
  * 
  * Anthony Minessale II <anthmct at yahoo.com>
+ * Marcel Barbulescu <marcelbarbulescu at gmail.com>
  *
  *
  * switch_rtp.c -- RTP
@@ -46,11 +47,12 @@
 #define rtp_header_len 12
 #define RTP_START_PORT 16384
 #define RTP_END_PORT 32768
-#define SWITCH_RTP_CNG_PAYLOAD 13
 #define MAX_KEY_LEN      64
 #define MASTER_KEY_LEN   30
 #define RTP_MAGIC_NUMBER 42
 
+static switch_port_t START_PORT = RTP_START_PORT;
+static switch_port_t END_PORT = RTP_END_PORT;
 static switch_port_t NEXT_PORT = RTP_START_PORT;
 static switch_mutex_t *port_lock = NULL;
 
@@ -67,8 +69,8 @@
 
 
 typedef struct {
-	srtp_hdr_t header;        
-	char body[SWITCH_RTP_MAX_BUF_LEN];  
+	srtp_hdr_t header;
+	char body[SWITCH_RTP_MAX_BUF_LEN];
 } rtp_msg_t;
 
 
@@ -106,6 +108,7 @@
 	unsigned char out_digit_packet[4];
 	unsigned int out_digit_sofar;
 	unsigned int out_digit_dur;
+	uint16_t in_digit_seq;
 	uint16_t out_digit_seq;
 	uint32_t out_digit_ssrc;
 	int32_t timestamp_dtmf;
@@ -126,17 +129,16 @@
 	switch_sockaddr_t *remote_addr;
 	rtp_msg_t recv_msg;
 	srtp_ctx_t *recv_ctx;
-	
+
 	uint16_t seq;
 	uint16_t rseq;
 	switch_payload_t payload;
 	switch_payload_t rpayload;
-	
 	switch_rtp_invalid_handler_t invalid_handler;
 	void *private_data;
-
 	uint32_t ts;
 	uint32_t last_write_ts;
+	uint32_t last_write_samplecount;
 	uint16_t last_write_seq;
 	uint32_t last_write_ssrc;
 	uint32_t flags;
@@ -145,25 +147,27 @@
 
 	char *ice_user;
 	char *user_ice;
-    char *timer_name;
+	char *timer_name;
 	switch_time_t last_stun;
-	uint32_t packet_size;
-	uint32_t conf_packet_size;
-	uint32_t rpacket_size;
-	switch_time_t last_read;
+	uint32_t samples_per_interval;
+	uint32_t conf_samples_per_interval;
+	uint32_t rsamples_per_interval;
 	uint32_t ms_per_packet;
 	uint32_t remote_port;
 	uint8_t stuncount;
 	struct switch_rtp_vad_data vad_data;
 	struct switch_rtp_rfc2833_data dtmf_data;
 	switch_payload_t te;
+	switch_payload_t cng_pt;
 	switch_mutex_t *flag_mutex;
 	switch_timer_t timer;
 	uint8_t ready;
+	uint8_t cn;
 	switch_time_t last_time;
 };
 
 static int global_init = 0;
+static int rtp_common_write(switch_rtp_t *rtp_session, void *data, uint32_t datalen, switch_payload_t payload, switch_frame_flag_t *flags);
 
 static switch_status_t ice_out(switch_rtp_t *rtp_session)
 {
@@ -172,13 +176,13 @@
 	assert(rtp_session->ice_user != NULL);
 
 	if (rtp_session->stuncount == 0) {
-		uint8_t buf[256] = {0};
+		uint8_t buf[256] = { 0 };
 		switch_stun_packet_t *packet;
 		unsigned int elapsed;
 		switch_size_t bytes;
 
 		if (rtp_session->last_stun) {
-			elapsed = (unsigned int)((switch_time_now() - rtp_session->last_stun) / 1000);
+			elapsed = (unsigned int) ((switch_time_now() - rtp_session->last_stun) / 1000);
 
 			if (elapsed > 30000) {
 				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No stun for a long time (PUNT!)\n");
@@ -189,7 +193,7 @@
 		packet = switch_stun_packet_build_header(SWITCH_STUN_BINDING_REQUEST, NULL, buf);
 		switch_stun_packet_attribute_add_username(packet, rtp_session->ice_user, 32);
 		bytes = switch_stun_packet_length(packet);
-		switch_socket_sendto(rtp_session->sock, rtp_session->remote_addr, 0, (void *)packet, &bytes);
+		switch_socket_sendto(rtp_session->sock, rtp_session->remote_addr, 0, (void *) packet, &bytes);
 		rtp_session->stuncount = 25;
 	} else {
 		rtp_session->stuncount--;
@@ -201,18 +205,18 @@
 {
 	switch_stun_packet_t *packet;
 	switch_stun_packet_attribute_t *attr;
-	char username[33] = {0};
-	unsigned char buf[512] = {0};
+	char username[33] = { 0 };
+	unsigned char buf[512] = { 0 };
 
 	memcpy(buf, data, len);
 	packet = switch_stun_packet_parse(buf, sizeof(buf));
 	rtp_session->last_stun = switch_time_now();
-	
+
 
 	switch_stun_packet_first_attribute(packet, attr);
 
 	do {
-		switch(attr->type) {
+		switch (attr->type) {
 		case SWITCH_STUN_ATTR_MAPPED_ADDRESS:
 			if (attr->type) {
 				char ip[16];
@@ -221,32 +225,32 @@
 			}
 			break;
 		case SWITCH_STUN_ATTR_USERNAME:
-			if(attr->type) {
+			if (attr->type) {
 				switch_stun_packet_attribute_get_username(attr, username, 32);
 			}
 			break;
 		}
 	} while (switch_stun_packet_next_attribute(attr));
 
-	//printf("[%s] [%s] [%s]\n", rtp_session->user_ice, username, !strcmp(rtp_session->user_ice, username) ? "yes" : "no");
-	if ((packet->header.type == SWITCH_STUN_BINDING_REQUEST)  && !strcmp(rtp_session->user_ice, username)) {
+	/* printf("[%s] [%s] [%s]\n", rtp_session->user_ice, username, !strcmp(rtp_session->user_ice, username) ? "yes" : "no"); */
+	if ((packet->header.type == SWITCH_STUN_BINDING_REQUEST) && !strcmp(rtp_session->user_ice, username)) {
 		uint8_t buf[512];
 		switch_stun_packet_t *rpacket;
 		char *remote_ip;
 		switch_size_t bytes;
 		char ipbuf[25];
-		
+
 		memset(buf, 0, sizeof(buf));
 		rpacket = switch_stun_packet_build_header(SWITCH_STUN_BINDING_RESPONSE, packet->header.id, buf);
 		switch_stun_packet_attribute_add_username(rpacket, username, 32);
-		//switch_sockaddr_ip_get(&remote_ip, rtp_session->from_addr);
+		/* switch_sockaddr_ip_get(&remote_ip, rtp_session->from_addr); */
 
 		remote_ip = switch_get_addr(ipbuf, sizeof(ipbuf), rtp_session->from_addr);
-		
 
-		switch_stun_packet_attribute_add_binded_address(rpacket, remote_ip, rtp_session->from_addr->port);
+
+		switch_stun_packet_attribute_add_binded_address(rpacket, remote_ip, switch_sockaddr_get_port(rtp_session->from_addr));
 		bytes = switch_stun_packet_length(rpacket);
-		switch_socket_sendto(rtp_session->sock, rtp_session->from_addr, 0, (void*)rpacket, &bytes);
+		switch_socket_sendto(rtp_session->sock, rtp_session->from_addr, 0, (void *) rpacket, &bytes);
 	}
 }
 
@@ -257,9 +261,46 @@
 		return;
 	}
 
-  srtp_init();
-  switch_mutex_init(&port_lock, SWITCH_MUTEX_NESTED, pool);
-  global_init = 1;
+	srtp_init();
+	switch_mutex_init(&port_lock, SWITCH_MUTEX_NESTED, pool);
+	global_init = 1;
+}
+
+SWITCH_DECLARE(switch_port_t) switch_rtp_set_start_port(switch_port_t port)
+{
+	if (port) {
+		if (port_lock) {
+			switch_mutex_lock(port_lock);
+		}
+		if (NEXT_PORT == START_PORT) {
+			NEXT_PORT = port;
+		}
+		START_PORT = port;
+		if (NEXT_PORT < START_PORT) {
+			NEXT_PORT = START_PORT;
+		}
+		if (port_lock) {
+			switch_mutex_unlock(port_lock);
+		}
+        }
+        return START_PORT;
+}
+
+SWITCH_DECLARE(switch_port_t) switch_rtp_set_end_port(switch_port_t port)
+{
+	if (port) {
+		if (port_lock) {
+			switch_mutex_lock(port_lock);
+		}
+		END_PORT = port;
+		if (NEXT_PORT > END_PORT) {
+			NEXT_PORT = START_PORT;
+		}
+		if (port_lock) {
+			switch_mutex_unlock(port_lock);
+		}
+        }
+        return END_PORT;
 }
 
 SWITCH_DECLARE(switch_port_t) switch_rtp_request_port(void)
@@ -269,8 +310,8 @@
 	switch_mutex_lock(port_lock);
 	port = NEXT_PORT;
 	NEXT_PORT += 2;
-	if (NEXT_PORT > RTP_END_PORT) {
-		NEXT_PORT = RTP_START_PORT;
+	if (NEXT_PORT > END_PORT) {
+		NEXT_PORT = START_PORT;
 	}
 	switch_mutex_unlock(port_lock);
 	return port;
@@ -281,8 +322,10 @@
 {
 	switch_socket_t *new_sock = NULL, *old_sock = NULL;
 	switch_status_t status = SWITCH_STATUS_FALSE;
+	char o[5] = "TEST", i[5] = "";
+	switch_size_t len;
 	*err = NULL;
-	
+
 	if (switch_sockaddr_info_get(&rtp_session->local_addr, host, SWITCH_UNSPEC, port, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS) {
 		*err = "Local Address Error!";
 		goto done;
@@ -291,7 +334,7 @@
 	if (rtp_session->sock) {
 		switch_rtp_kill_socket(rtp_session);
 	}
-	
+
 	if (switch_socket_create(&new_sock, AF_INET, SOCK_DGRAM, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS) {
 		*err = "Socket Error!";
 		goto done;
@@ -307,12 +350,20 @@
 		goto done;
 	}
 
+	len = sizeof(i);
+	switch_socket_sendto(new_sock, rtp_session->local_addr, 0, (void *) o, &len);
+	switch_socket_recvfrom(rtp_session->from_addr, new_sock, 0, (void *) i, &len);
+
+	if (!len) {
+		goto done;
+	}
+
 	old_sock = rtp_session->sock;
 	rtp_session->sock = new_sock;
 	new_sock = NULL;
 
 	if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_USE_TIMER) || switch_test_flag(rtp_session, SWITCH_RTP_FLAG_NOBLOCK)) {
-		switch_socket_opt_set(rtp_session->sock, APR_SO_NONBLOCK, TRUE);
+		switch_socket_opt_set(rtp_session->sock, SWITCH_SO_NONBLOCK, TRUE);
 		switch_set_flag_locked(rtp_session, SWITCH_RTP_FLAG_NOBLOCK);
 	}
 
@@ -320,7 +371,7 @@
 	*err = "Success";
 	switch_set_flag_locked(rtp_session, SWITCH_RTP_FLAG_IO);
 
- done:
+  done:
 
 	if (status != SWITCH_STATUS_SUCCESS) {
 		rtp_session->ready = 0;
@@ -353,12 +404,9 @@
 
 SWITCH_DECLARE(switch_status_t) switch_rtp_create(switch_rtp_t **new_rtp_session,
 												  switch_payload_t payload,
-												  uint32_t packet_size,
+												  uint32_t samples_per_interval,
 												  uint32_t ms_per_packet,
-												  switch_rtp_flag_t flags, 
-												  char *crypto_key,
-												  char *timer_name,
-												  const char **err,
+												  switch_rtp_flag_t flags, char *crypto_key, char *timer_name, const char **err,
 												  switch_memory_pool_t *pool)
 {
 	switch_rtp_t *rtp_session = NULL;
@@ -367,8 +415,8 @@
 	uint32_t ssrc = rand() & 0xffff;
 
 	*new_rtp_session = NULL;
-	
-	if (packet_size > SWITCH_RTP_MAX_BUF_LEN) {
+
+	if (samples_per_interval > SWITCH_RTP_MAX_BUF_LEN) {
 		*err = "Packet Size Too Large!";
 		return SWITCH_STATUS_FALSE;
 	}
@@ -389,7 +437,7 @@
 	switch_buffer_create_dynamic(&rtp_session->dtmf_data.dtmf_buffer, 128, 128, 0);
 	/* for from address on recvfrom calls */
 	switch_sockaddr_info_get(&rtp_session->from_addr, NULL, SWITCH_UNSPEC, 0, 0, rtp_session->pool);
-	
+
 	memset(&policy, 0, sizeof(policy));
 	if (crypto_key) {
 		int len;
@@ -397,9 +445,9 @@
 		switch_set_flag_locked(rtp_session, SWITCH_RTP_FLAG_SECURE);
 		crypto_policy_set_rtp_default(&policy.rtp);
 		crypto_policy_set_rtcp_default(&policy.rtcp);
-		policy.ssrc.type  = ssrc_any_inbound;
+		policy.ssrc.type = ssrc_any_inbound;
 		policy.ssrc.value = ssrc;
-		policy.key  = (uint8_t *) key;
+		policy.key = (uint8_t *) key;
 		policy.next = NULL;
 		policy.rtp.sec_serv = sec_serv_conf_and_auth;
 		policy.rtcp.sec_serv = sec_serv_none;
@@ -407,56 +455,54 @@
 		/*
 		 * read key from hexadecimal on command line into an octet string
 		 */
-		len = hex_string_to_octet_string(key, crypto_key, MASTER_KEY_LEN*2);
-    
+		len = hex_string_to_octet_string(key, crypto_key, MASTER_KEY_LEN * 2);
+
 		/* check that hex string is the right length */
-		if (len < MASTER_KEY_LEN*2) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, 
-								  "error: too few digits in key/salt "
-								  "(should be %d hexadecimal digits, found %d)\n",
-								  MASTER_KEY_LEN*2, len);
+		if (len < MASTER_KEY_LEN * 2) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+							  "error: too few digits in key/salt " "(should be %d hexadecimal digits, found %d)\n", MASTER_KEY_LEN * 2, len);
 			*err = "Crypt Error";
 			return SWITCH_STATUS_FALSE;
-		} 
-		if (strlen(crypto_key) > MASTER_KEY_LEN*2) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, 
-								  "error: too many digits in key/salt "
-								  "(should be %d hexadecimal digits, found %u)\n",
-								  MASTER_KEY_LEN*2, (unsigned)strlen(crypto_key));
+		}
+		if (strlen(crypto_key) > MASTER_KEY_LEN * 2) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+							  "error: too many digits in key/salt "
+							  "(should be %d hexadecimal digits, found %u)\n", MASTER_KEY_LEN * 2, (unsigned) strlen(crypto_key));
 			*err = "Crypt Error";
 			return SWITCH_STATUS_FALSE;
 		}
-    
-		//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "set master key/salt to %s/", octet_string_hex_string(key, 16));
-		//switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_DEBUG, "%s\n", octet_string_hex_string(key+16, 14));
+
+		/* switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "set master key/salt to %s/", octet_string_hex_string(key, 16));
+		 * switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_DEBUG, "%s\n", octet_string_hex_string(key+16, 14));
+		 */
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Activating Secure RTP!\n");
 	}
 
-	rtp_session->send_msg.header.ssrc    = htonl(ssrc);
-	rtp_session->send_msg.header.ts      = 0;
-	rtp_session->send_msg.header.seq     = (uint16_t) rand();
-	rtp_session->send_msg.header.m       = 0;
-	rtp_session->send_msg.header.pt      = (switch_payload_t)htonl(payload);
+	rtp_session->seq = (uint16_t) rand();
+	rtp_session->send_msg.header.ssrc = htonl(ssrc);
+	rtp_session->send_msg.header.ts = 0;
+	//rtp_session->send_msg.header.seq     = (uint16_t) rand();
+	rtp_session->send_msg.header.m = 0;
+	rtp_session->send_msg.header.pt = (switch_payload_t) htonl(payload);
 	rtp_session->send_msg.header.version = 2;
-	rtp_session->send_msg.header.p       = 0;
-	rtp_session->send_msg.header.x       = 0;
-	rtp_session->send_msg.header.cc      = 0;
-
-	rtp_session->recv_msg.header.ssrc    = htonl(ssrc);
-	rtp_session->recv_msg.header.ts      = 0;
-	rtp_session->recv_msg.header.seq     = 0;
-	rtp_session->recv_msg.header.m       = 0;
-	rtp_session->recv_msg.header.pt      = (switch_payload_t)htonl(payload);
+	rtp_session->send_msg.header.p = 0;
+	rtp_session->send_msg.header.x = 0;
+	rtp_session->send_msg.header.cc = 0;
+
+	rtp_session->recv_msg.header.ssrc = htonl(ssrc);
+	rtp_session->recv_msg.header.ts = 0;
+	rtp_session->recv_msg.header.seq = 0;
+	rtp_session->recv_msg.header.m = 0;
+	rtp_session->recv_msg.header.pt = (switch_payload_t) htonl(payload);
 	rtp_session->recv_msg.header.version = 2;
-	rtp_session->recv_msg.header.p       = 0;
-	rtp_session->recv_msg.header.x       = 0;
-	rtp_session->recv_msg.header.cc      = 0;
+	rtp_session->recv_msg.header.p = 0;
+	rtp_session->recv_msg.header.x = 0;
+	rtp_session->recv_msg.header.cc = 0;
 
-	rtp_session->seq = (uint16_t)rtp_session->send_msg.header.seq;
 	rtp_session->payload = payload;
 	rtp_session->ms_per_packet = ms_per_packet;
-	rtp_session->packet_size = rtp_session->conf_packet_size = packet_size;
-    rtp_session->timer_name = switch_core_strdup(rtp_session->pool, timer_name);
+	rtp_session->samples_per_interval = rtp_session->conf_samples_per_interval = samples_per_interval;
+	rtp_session->timer_name = switch_core_strdup(rtp_session->pool, timer_name);
 
 	if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_SECURE)) {
 		err_status_t stat;
@@ -482,8 +528,10 @@
 	}
 
 	if (!switch_strlen_zero(timer_name)) {
-		if (switch_core_timer_init(&rtp_session->timer, timer_name, ms_per_packet / 1000, packet_size, rtp_session->pool) == SWITCH_STATUS_SUCCESS) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Starting timer [%s] %d bytes per %dms\n", timer_name, packet_size, ms_per_packet);
+		if (switch_core_timer_init(&rtp_session->timer, timer_name, ms_per_packet / 1000, samples_per_interval, rtp_session->pool) ==
+			SWITCH_STATUS_SUCCESS) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Starting timer [%s] %d bytes per %dms\n", timer_name, samples_per_interval,
+							  ms_per_packet);
 		} else {
 			memset(&rtp_session->timer, 0, sizeof(rtp_session->timer));
 			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error starting timer [%s], async RTP disabled\n", timer_name);
@@ -496,22 +544,18 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-SWITCH_DECLARE(switch_rtp_t *)switch_rtp_new(char *rx_host,
-											 switch_port_t rx_port,
-											 char *tx_host,
-											 switch_port_t tx_port,
-											 switch_payload_t payload,
-											 uint32_t packet_size,
-											 uint32_t ms_per_packet,
-											 switch_rtp_flag_t flags,
-											 char *crypto_key,
-											 char *timer_name,
-											 const char **err,
-											 switch_memory_pool_t *pool) 
+SWITCH_DECLARE(switch_rtp_t *) switch_rtp_new(char *rx_host,
+											  switch_port_t rx_port,
+											  char *tx_host,
+											  switch_port_t tx_port,
+											  switch_payload_t payload,
+											  uint32_t samples_per_interval,
+											  uint32_t ms_per_packet,
+											  switch_rtp_flag_t flags, char *crypto_key, char *timer_name, const char **err, switch_memory_pool_t *pool)
 {
 	switch_rtp_t *rtp_session;
 
-	if (switch_rtp_create(&rtp_session, payload, packet_size, ms_per_packet, flags, crypto_key, timer_name, err, pool) != SWITCH_STATUS_SUCCESS) {
+	if (switch_rtp_create(&rtp_session, payload, samples_per_interval, ms_per_packet, flags, crypto_key, timer_name, err, pool) != SWITCH_STATUS_SUCCESS) {
 		return NULL;
 	}
 
@@ -522,9 +566,9 @@
 	if (switch_rtp_set_local_address(rtp_session, rx_host, rx_port, err) != SWITCH_STATUS_SUCCESS) {
 		return NULL;
 	}
-    
+
 	rtp_session->ready = 1;
-	
+
 	return rtp_session;
 }
 
@@ -535,6 +579,13 @@
 	}
 }
 
+SWITCH_DECLARE(void) switch_rtp_set_cng_pt(switch_rtp_t *rtp_session, switch_payload_t pt)
+{
+
+	rtp_session->cng_pt = pt;
+
+}
+
 SWITCH_DECLARE(switch_status_t) switch_rtp_activate_ice(switch_rtp_t *rtp_session, char *login, char *rlogin)
 {
 	char ice_user[80];
@@ -560,7 +611,7 @@
 	switch_mutex_lock(rtp_session->flag_mutex);
 	if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_IO)) {
 		assert(rtp_session->sock != NULL);
-		apr_socket_shutdown(rtp_session->sock, APR_SHUTDOWN_READWRITE);
+		switch_socket_shutdown(rtp_session->sock, SWITCH_SHUTDOWN_READWRITE);
 		switch_clear_flag(rtp_session, SWITCH_RTP_FLAG_IO);
 	}
 	switch_mutex_unlock(rtp_session->flag_mutex);
@@ -580,7 +631,7 @@
 	(*rtp_session)->ready = 0;
 
 	switch_mutex_lock((*rtp_session)->flag_mutex);
-	
+
 	if ((*rtp_session)->dtmf_data.dtmf_buffer) {
 		switch_buffer_destroy(&(*rtp_session)->dtmf_data.dtmf_buffer);
 	}
@@ -608,19 +659,19 @@
 	return;
 }
 
-SWITCH_DECLARE(switch_socket_t *)switch_rtp_get_rtp_socket(switch_rtp_t *rtp_session)
+SWITCH_DECLARE(switch_socket_t *) switch_rtp_get_rtp_socket(switch_rtp_t *rtp_session)
 {
 	return rtp_session->sock;
 }
 
-SWITCH_DECLARE(void) switch_rtp_set_default_packet_size(switch_rtp_t *rtp_session, uint16_t packet_size)
+SWITCH_DECLARE(void) switch_rtp_set_default_samples_per_interval(switch_rtp_t *rtp_session, uint16_t samples_per_interval)
 {
-	rtp_session->packet_size = packet_size;
+	rtp_session->samples_per_interval = samples_per_interval;
 }
 
-SWITCH_DECLARE(uint32_t) switch_rtp_get_default_packet_size(switch_rtp_t *rtp_session)
+SWITCH_DECLARE(uint32_t) switch_rtp_get_default_samples_per_interval(switch_rtp_t *rtp_session)
 {
-	return rtp_session->packet_size;
+	return rtp_session->samples_per_interval;
 }
 
 SWITCH_DECLARE(void) switch_rtp_set_default_payload(switch_rtp_t *rtp_session, switch_payload_t payload)
@@ -638,23 +689,23 @@
 	rtp_session->invalid_handler = on_invalid;
 }
 
-SWITCH_DECLARE(void) switch_rtp_set_flag(switch_rtp_t *rtp_session, switch_rtp_flag_t flags) 
+SWITCH_DECLARE(void) switch_rtp_set_flag(switch_rtp_t *rtp_session, switch_rtp_flag_t flags)
 {
-	
+
 	switch_set_flag_locked(rtp_session, flags);
 
 }
 
-SWITCH_DECLARE(uint8_t) switch_rtp_test_flag(switch_rtp_t *rtp_session, switch_rtp_flag_t flags) 
+SWITCH_DECLARE(uint8_t) switch_rtp_test_flag(switch_rtp_t *rtp_session, switch_rtp_flag_t flags)
 {
-	
+
 	return (uint8_t) switch_test_flag(rtp_session, flags);
-	
+
 }
 
-SWITCH_DECLARE(void) switch_rtp_clear_flag(switch_rtp_t *rtp_session, switch_rtp_flag_t flags) 
+SWITCH_DECLARE(void) switch_rtp_clear_flag(switch_rtp_t *rtp_session, switch_rtp_flag_t flags)
 {
-	
+
 	switch_clear_flag_locked(rtp_session, flags);
 
 }
@@ -663,7 +714,7 @@
 static void do_2833(switch_rtp_t *rtp_session)
 {
 	switch_frame_flag_t flags = 0;
-	uint32_t samples = rtp_session->packet_size;
+	uint32_t samples = rtp_session->samples_per_interval;
 
 	if (rtp_session->dtmf_data.out_digit_dur > 0) {
 		int x, loops = 1, duration;
@@ -678,31 +729,29 @@
 			duration = rtp_session->dtmf_data.out_digit_sofar;
 		}
 
-		//ts = rtp_session->dtmf_data.timestamp_dtmf += samples;
+
 		rtp_session->dtmf_data.out_digit_packet[2] = (unsigned char) (duration >> 8);
 		rtp_session->dtmf_data.out_digit_packet[3] = (unsigned char) duration;
-		
+
 
 		for (x = 0; x < loops; x++) {
 			rtp_session->dtmf_data.out_digit_seq++;
-			switch_rtp_write_manual(rtp_session, 
+			switch_rtp_write_manual(rtp_session,
 									rtp_session->dtmf_data.out_digit_packet,
 									4,
 									0,
 									rtp_session->te,
-									rtp_session->dtmf_data.timestamp_dtmf,
-									rtp_session->dtmf_data.out_digit_seq,
-									rtp_session->dtmf_data.out_digit_ssrc,
+									rtp_session->dtmf_data.timestamp_dtmf, rtp_session->dtmf_data.out_digit_seq, rtp_session->dtmf_data.out_digit_ssrc,
 									&flags);
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Send %s packet for [%c] ts=%d sofar=%u dur=%d seq=%d\n", 
-							  loops == 1 ? "middle" : "end",
-							  rtp_session->dtmf_data.out_digit,
-							  rtp_session->dtmf_data.timestamp_dtmf, 
-							  rtp_session->dtmf_data.out_digit_sofar,
-							  duration,
-							  rtp_session->dtmf_data.out_digit_seq);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Send %s packet for [%c] ts=%d sofar=%u dur=%d seq=%d\n",
+							  loops == 1 ? "middle" : "end", rtp_session->dtmf_data.out_digit, rtp_session->dtmf_data.timestamp_dtmf,
+							  rtp_session->dtmf_data.out_digit_sofar, duration, rtp_session->dtmf_data.out_digit_seq);
 
 		}
+
+		if (loops == 1) {
+			rtp_session->last_write_seq = 0;
+		}
 	}
 
 	if (!rtp_session->dtmf_data.out_digit_dur && rtp_session->dtmf_data.dtmf_queue && switch_queue_size(rtp_session->dtmf_data.dtmf_queue)) {
@@ -716,36 +765,33 @@
 			rtp_session->dtmf_data.out_digit_sofar = 0;
 			rtp_session->dtmf_data.out_digit_dur = rdigit->duration;
 			rtp_session->dtmf_data.out_digit = rdigit->digit;
-			rtp_session->dtmf_data.out_digit_packet[0] = (unsigned char)switch_char_to_rfc2833(rdigit->digit);
+			rtp_session->dtmf_data.out_digit_packet[0] = (unsigned char) switch_char_to_rfc2833(rdigit->digit);
 			rtp_session->dtmf_data.out_digit_packet[1] = 7;
 
-			//ts = rtp_session->dtmf_data.timestamp_dtmf += samples;
-			//rtp_session->dtmf_data.timestamp_dtmf++;
+			if (rtp_session->timer.timer_interface) {
+				rtp_session->dtmf_data.timestamp_dtmf = rtp_session->timer.samplecount;
+			} else {
+				rtp_session->dtmf_data.timestamp_dtmf = rtp_session->last_write_ts;
+			}
 
-			rtp_session->dtmf_data.timestamp_dtmf = rtp_session->last_write_ts;
 			rtp_session->dtmf_data.out_digit_seq = rtp_session->last_write_seq;
 			rtp_session->dtmf_data.out_digit_ssrc = rtp_session->last_write_ssrc;
-			
+
 
 			for (x = 0; x < 3; x++) {
-				rtp_session->dtmf_data.out_digit_seq++;
+				//rtp_session->dtmf_data.out_digit_seq++;
 				switch_rtp_write_manual(rtp_session,
 										rtp_session->dtmf_data.out_digit_packet,
 										4,
- 										switch_test_flag(rtp_session, SWITCH_RTP_FLAG_BUGGY_2833) ? 0 : 1,
+										switch_test_flag(rtp_session, SWITCH_RTP_FLAG_BUGGY_2833) ? 0 : 1,
 										rtp_session->te,
 										rtp_session->dtmf_data.timestamp_dtmf,
-										rtp_session->dtmf_data.out_digit_seq,
-										rtp_session->dtmf_data.out_digit_ssrc,
-										&flags);
+										rtp_session->dtmf_data.out_digit_seq, rtp_session->dtmf_data.out_digit_ssrc, &flags);
 				switch_log_printf(SWITCH_CHANNEL_LOG,
 								  SWITCH_LOG_DEBUG,
 								  "Send start packet for [%c] ts=%d sofar=%u dur=%d seq=%d\n",
 								  rtp_session->dtmf_data.out_digit,
-								  rtp_session->dtmf_data.timestamp_dtmf,
-								  rtp_session->dtmf_data.out_digit_sofar,
-								  0,
-								  rtp_session->dtmf_data.out_digit_seq);
+								  rtp_session->dtmf_data.timestamp_dtmf, rtp_session->dtmf_data.out_digit_sofar, 0, rtp_session->dtmf_data.out_digit_seq);
 			}
 
 			free(rdigit);
@@ -763,160 +809,203 @@
 		rtp_session->last_time = switch_time_now();
 	}
 
-	while(switch_rtp_ready(rtp_session)) {
-		bytes = sizeof(rtp_msg_t);	
-		status = switch_socket_recvfrom(rtp_session->from_addr, rtp_session->sock, 0, (void *)&rtp_session->recv_msg, &bytes);
-
+	while (switch_rtp_ready(rtp_session)) {
+		bytes = sizeof(rtp_msg_t);
+		status = switch_socket_recvfrom(rtp_session->from_addr, rtp_session->sock, 0, (void *) &rtp_session->recv_msg, &bytes);
+		
 		if (!SWITCH_STATUS_IS_BREAK(status) && rtp_session->timer.interval) {
 			switch_core_timer_step(&rtp_session->timer);
 		}
-		
-		if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_BREAK)) {
-			switch_clear_flag_locked(rtp_session, SWITCH_RTP_FLAG_BREAK);
-
-            memset(&rtp_session->recv_msg, 0, SWITCH_RTP_CNG_PAYLOAD);
-            rtp_session->recv_msg.header.pt = SWITCH_RTP_CNG_PAYLOAD;
-            *flags |= SFF_CNG;
-            /* Return a CNG frame */
-            *payload_type = SWITCH_RTP_CNG_PAYLOAD;
-            return SWITCH_RTP_CNG_PAYLOAD + rtp_header_len;
-		}
 
 		if (!switch_test_flag(rtp_session, SWITCH_RTP_FLAG_IO)) {
 			return -1;
 		}
-		
-		if (bytes < 0) {
-			return (int)bytes;
-		} else if (bytes > 0 && switch_test_flag(rtp_session, SWITCH_RTP_FLAG_SECURE)) {
-			int sbytes = (int)bytes;
-			err_status_t stat;
 
-			stat = srtp_unprotect(rtp_session->recv_ctx, &rtp_session->recv_msg.header, &sbytes);
-			if (stat) {
-				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
-								  "error: srtp unprotection failed with code %d%s\n", stat,
-								  stat == err_status_replay_fail ? " (replay check failed)" :
-								  stat == err_status_auth_fail ? " (auth check failed)" : "");
-				return -1;
-			}
-			bytes = sbytes;
-		} 
+		if (!bytes && switch_test_flag(rtp_session, SWITCH_RTP_FLAG_BREAK)) {
+			switch_clear_flag_locked(rtp_session, SWITCH_RTP_FLAG_BREAK);
+
+			memset(&rtp_session->recv_msg.body, 0, 2);
+			rtp_session->recv_msg.body[0] = 127;
+			rtp_session->recv_msg.header.pt = SWITCH_RTP_CNG_PAYLOAD;
+			*flags |= SFF_CNG;
+			/* Return a CNG frame */
+			*payload_type = SWITCH_RTP_CNG_PAYLOAD;
+			return 2 + rtp_header_len;
+		}
+
+		if (bytes < 0) {
+			return (int) bytes;
+		}
 
 		if (rtp_session->timer.interval) {
-			check = (uint8_t)(switch_core_timer_check(&rtp_session->timer) == SWITCH_STATUS_SUCCESS);
+			check = (uint8_t) (switch_core_timer_check(&rtp_session->timer) == SWITCH_STATUS_SUCCESS);
+
+			if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_AUTO_CNG) &&
+				rtp_session->timer.samplecount >= (rtp_session->last_write_samplecount + (rtp_session->samples_per_interval * 50))) {
+				uint8_t data[2] = { 0 };
+				switch_frame_flag_t flags = SFF_NONE;
+				data[0] = 65;
+				rtp_session->cn++;
+				rtp_common_write(rtp_session, (void *) data, sizeof(data), rtp_session->cng_pt, &flags);
+			}
 		}
 
 		if (check) {
 			do_2833(rtp_session);
 
 			if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_USE_TIMER)) {
-				/* We're late! We're Late!*/
+				uint8_t *data = (uint8_t *) rtp_session->recv_msg.body;
+				/* We're late! We're Late! */
 				if (!switch_test_flag(rtp_session, SWITCH_RTP_FLAG_NOBLOCK) && status == SWITCH_STATUS_BREAK) {
 					switch_yield(1000);
 					continue;
 				}
-				memset(&rtp_session->recv_msg, 0, SWITCH_RTP_CNG_PAYLOAD);
-				rtp_session->recv_msg.header.pt = SWITCH_RTP_CNG_PAYLOAD;
+					
+				memset(data, 0, 2);
+				data[0] = 65;
+				
+				rtp_session->recv_msg.header.pt = (uint32_t) rtp_session->cng_pt ? rtp_session->cng_pt : SWITCH_RTP_CNG_PAYLOAD;
 				*flags |= SFF_CNG;
-				/* Return a CNG frame */
-				*payload_type = SWITCH_RTP_CNG_PAYLOAD;
-				return SWITCH_RTP_CNG_PAYLOAD + rtp_header_len;
+				*payload_type = (switch_payload_t)rtp_session->recv_msg.header.pt;
+				return 2 + rtp_header_len;
 			}
-		}		
+		}
+
+		if (bytes && rtp_session->recv_msg.header.version != 2) {
+			uint8_t *data = (uint8_t *) rtp_session->recv_msg.body;
+			if (rtp_session->recv_msg.header.version == 0 && rtp_session->ice_user) {
+				handle_ice(rtp_session, (void *) &rtp_session->recv_msg, bytes);
+			}
+
+			if (rtp_session->invalid_handler) {
+				rtp_session->invalid_handler(rtp_session, rtp_session->sock, (void *) &rtp_session->recv_msg, bytes, rtp_session->from_addr);
+			}
+			
+			memset(data, 0, 2);
+			data[0] = 65;
+
+			rtp_session->recv_msg.header.pt = (uint32_t) rtp_session->cng_pt ? rtp_session->cng_pt : SWITCH_RTP_CNG_PAYLOAD;
+			*flags |= SFF_CNG;
+			*payload_type = (switch_payload_t)rtp_session->recv_msg.header.pt;
+			return 2 + rtp_header_len;
+		}
 		
+
+
+
+		if (bytes && switch_test_flag(rtp_session, SWITCH_RTP_FLAG_SECURE)) {
+			int sbytes = (int) bytes;
+			err_status_t stat;
+
+			stat = srtp_unprotect(rtp_session->recv_ctx, &rtp_session->recv_msg.header, &sbytes);
+			if (stat) {
+				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
+								  "error: srtp unprotection failed with code %d%s\n", stat,
+								  stat == err_status_replay_fail ? " (replay check failed)" : stat == err_status_auth_fail ? " (auth check failed)" : "");
+				return -1;
+			}
+			bytes = sbytes;
+		}
+
 		if (status == SWITCH_STATUS_BREAK || bytes == 0) {
 			if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_DATAWAIT)) {
-				switch_yield((rtp_session->ms_per_packet / 1000) * 750);
+				if (rtp_session->ms_per_packet) {
+					switch_yield((rtp_session->ms_per_packet / 1000) * 750);
+				} else {
+					switch_yield(1000);
+				}
 				continue;
 			}
 			return 0;
 		}
 
-
-		if (rtp_session->recv_msg.header.version) {
-			if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_AUTOADJ) && rtp_session->from_addr->port) {
-                char *tx_host;
-                char *old_host;
-                char bufa[30], bufb[30];
-                tx_host = switch_get_addr(bufa, sizeof(bufa), rtp_session->from_addr);
-                old_host = switch_get_addr(bufb, sizeof(bufb), rtp_session->remote_addr);
-
-				if ((rtp_session->from_addr->port != rtp_session->remote_port) || strcmp(tx_host, old_host)) {
-					const char *err;
-					uint32_t old = rtp_session->remote_port;
-
-					if (!switch_strlen_zero(tx_host) && rtp_session->from_addr->port > 0) {
-						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Auto Changing port from %s:%u to %s:%u\n",
-										  old_host, old, tx_host, rtp_session->from_addr->port);
-						switch_rtp_set_remote_address(rtp_session, tx_host, rtp_session->from_addr->port, &err);
-					}
+		
+		
+		if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_AUTOADJ) && switch_sockaddr_get_port(rtp_session->from_addr)) {
+			
+			char *tx_host;
+			char *old_host;
+			char bufa[30], bufb[30];
+			tx_host = switch_get_addr(bufa, sizeof(bufa), rtp_session->from_addr);
+			old_host = switch_get_addr(bufb, sizeof(bufb), rtp_session->remote_addr);
+
+			if ((switch_sockaddr_get_port(rtp_session->from_addr) != rtp_session->remote_port)
+				|| strcmp(tx_host, old_host)) {
+				const char *err;
+				uint32_t old = rtp_session->remote_port;
+
+				if (!switch_strlen_zero(tx_host) && switch_sockaddr_get_port(rtp_session->from_addr) > 0) {
+					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING,
+									  "Auto Changing port from %s:%u to %s:%u\n", old_host, old, tx_host,
+									  switch_sockaddr_get_port(rtp_session->from_addr));
+					switch_rtp_set_remote_address(rtp_session, tx_host, switch_sockaddr_get_port(rtp_session->from_addr), &err);
 				}
-				switch_clear_flag_locked(rtp_session, SWITCH_RTP_FLAG_AUTOADJ);
 			}
+			switch_clear_flag_locked(rtp_session, SWITCH_RTP_FLAG_AUTOADJ);
 		}
 
-		if (rtp_session->recv_msg.header.version == 2) {
-			if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_GOOGLEHACK) && rtp_session->recv_msg.header.pt == 102) {
-				rtp_session->recv_msg.header.pt = 97;
-			}
-			rtp_session->rseq = ntohs((uint16_t)rtp_session->recv_msg.header.seq);
-			rtp_session->rpayload = (switch_payload_t)rtp_session->recv_msg.header.pt;
-		} else {
-			if (rtp_session->recv_msg.header.version == 0 && rtp_session->ice_user) {
-				handle_ice(rtp_session, (void *) &rtp_session->recv_msg, bytes);
-			}	
+		if (bytes && rtp_session->cng_pt && rtp_session->recv_msg.header.pt == rtp_session->cng_pt) {
+			continue;
+		}
 
-			if (rtp_session->invalid_handler) {
-				rtp_session->invalid_handler(rtp_session, rtp_session->sock, (void *) &rtp_session->recv_msg, bytes, rtp_session->from_addr);
-			}
-			return 0;
+
+		
+		if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_GOOGLEHACK) && rtp_session->recv_msg.header.pt == 102) {
+			rtp_session->recv_msg.header.pt = 97;
 		}
 
-		/* RFC2833 ... TBD try harder to honor the duration etc.*/
-		if (!switch_test_flag(rtp_session, SWITCH_RTP_FLAG_PASS_RFC2833) && rtp_session->recv_msg.header.pt == rtp_session->te) {
+		rtp_session->rseq = ntohs((uint16_t) rtp_session->recv_msg.header.seq);
+		rtp_session->rpayload = (switch_payload_t) rtp_session->recv_msg.header.pt;
+		
+
+		/* RFC2833 ... TBD try harder to honor the duration etc. */
+		if (!switch_test_flag(rtp_session, SWITCH_RTP_FLAG_PASS_RFC2833)
+			&& rtp_session->recv_msg.header.pt == rtp_session->te) {
 			unsigned char *packet = (unsigned char *) rtp_session->recv_msg.body;
-			int end = packet[1]&0x80;
-			int duration = (packet[2]<<8) + packet[3];
+			int end = packet[1] & 0x80;
+			int duration = (packet[2] << 8) + packet[3];
 			char key = switch_rfc2833_to_char(packet[0]);
+			uint16_t in_digit_seq = ntohs((uint16_t) rtp_session->recv_msg.header.seq);
 
-			/* SHEESH.... Curse you RFC2833 inventors!!!!*/
+			/* SHEESH.... Curse you RFC2833 inventors!!!! */
 			if ((time(NULL) - rtp_session->dtmf_data.last_digit_time) > 2) {
 				rtp_session->dtmf_data.last_digit = 0;
 				rtp_session->dtmf_data.dc = 0;
 			}
+			if (in_digit_seq > rtp_session->dtmf_data.in_digit_seq) {
+				rtp_session->dtmf_data.in_digit_seq = in_digit_seq;
 
-			if (duration && end) {
-				if (key != rtp_session->dtmf_data.last_digit) {
-					char digit_str[] = {key, 0};
-					time(&rtp_session->dtmf_data.last_digit_time);
-					switch_rtp_queue_dtmf(rtp_session, digit_str);
-				}
-				if (++rtp_session->dtmf_data.dc >= 3) {
+				if (duration && end) {
+					if (key != rtp_session->dtmf_data.last_digit) {
+						char digit_str[] = { key, 0 };
+						time(&rtp_session->dtmf_data.last_digit_time);
+						switch_rtp_queue_dtmf(rtp_session, digit_str);
+					}
+					if (++rtp_session->dtmf_data.dc >= 3) {
+						rtp_session->dtmf_data.last_digit = 0;
+						rtp_session->dtmf_data.dc = 0;
+					}
+
+					rtp_session->dtmf_data.last_digit = key;
+				} else {
 					rtp_session->dtmf_data.last_digit = 0;
 					rtp_session->dtmf_data.dc = 0;
 				}
-
-				rtp_session->dtmf_data.last_digit = key;
-			} else {
-				rtp_session->dtmf_data.last_digit = 0;
-				rtp_session->dtmf_data.dc = 0;
 			}
-
+			
 			continue;
 		}
 
 		break;
 	}
 
-	rtp_session->last_read = switch_time_now();
-	*payload_type = (switch_payload_t)rtp_session->recv_msg.header.pt;
+	*payload_type = (switch_payload_t) rtp_session->recv_msg.header.pt;
 
 
 	if (*payload_type == SWITCH_RTP_CNG_PAYLOAD) {
 		*flags |= SFF_CNG;
 	}
-	
+
 	if (bytes > 0) {
 		do_2833(rtp_session);
 	}
@@ -928,12 +1017,13 @@
 
 SWITCH_DECLARE(switch_size_t) switch_rtp_has_dtmf(switch_rtp_t *rtp_session)
 {
-	switch_size_t has;
+	switch_size_t has = 0;
 
-	assert(rtp_session != NULL);
-	switch_mutex_lock(rtp_session->dtmf_data.dtmf_mutex);
-	has = switch_buffer_inuse(rtp_session->dtmf_data.dtmf_buffer);
-	switch_mutex_unlock(rtp_session->dtmf_data.dtmf_mutex);
+	if (switch_rtp_ready(rtp_session)) {
+		switch_mutex_lock(rtp_session->dtmf_data.dtmf_mutex);
+		has = switch_buffer_inuse(rtp_session->dtmf_data.dtmf_buffer);
+		switch_mutex_unlock(rtp_session->dtmf_data.dtmf_mutex);
+	}
 
 	return has;
 }
@@ -945,19 +1035,21 @@
 	switch_size_t wr = 0;
 	char *p;
 
-	assert(rtp_session != NULL);
+	if (!switch_rtp_ready(rtp_session)) {
+		return SWITCH_STATUS_FALSE;
+	}
 
 	switch_mutex_lock(rtp_session->dtmf_data.dtmf_mutex);
 
 	inuse = switch_buffer_inuse(rtp_session->dtmf_data.dtmf_buffer);
 	len = strlen(dtmf);
-	
+
 	if (len + inuse > switch_buffer_len(rtp_session->dtmf_data.dtmf_buffer)) {
 		switch_buffer_toss(rtp_session->dtmf_data.dtmf_buffer, strlen(dtmf));
 	}
 
 	p = dtmf;
-	while(wr < len && p) {
+	while (wr < len && p) {
 		if (is_dtmf(*p)) {
 			wr++;
 		} else {
@@ -975,9 +1067,11 @@
 
 SWITCH_DECLARE(switch_size_t) switch_rtp_dequeue_dtmf(switch_rtp_t *rtp_session, char *dtmf, switch_size_t len)
 {
-	switch_size_t bytes;
+	switch_size_t bytes = 0;
 
-	assert(rtp_session != NULL);
+	if (!switch_rtp_ready(rtp_session)) {
+		return bytes;
+	}
 
 	switch_mutex_lock(rtp_session->dtmf_data.dtmf_mutex);
 	if ((bytes = switch_buffer_read(rtp_session->dtmf_data.dtmf_buffer, dtmf, len)) > 0) {
@@ -994,11 +1088,15 @@
 {
 	char *c;
 
+	if (!switch_rtp_ready(rtp_session)) {
+		return SWITCH_STATUS_FALSE;
+	}
+
 	if (!rtp_session->dtmf_data.dtmf_queue) {
 		switch_queue_create(&rtp_session->dtmf_data.dtmf_queue, 100, rtp_session->pool);
 	}
 
-	for(c = digits; *c; c++) {
+	for (c = digits; *c; c++) {
 		struct rfc2833_digit *rdigit;
 
 		if ((rdigit = malloc(sizeof(*rdigit))) != 0) {
@@ -1014,11 +1112,17 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_rtp_read(switch_rtp_t *rtp_session, void *data, uint32_t *datalen, switch_payload_t *payload_type, switch_frame_flag_t *flags)
+SWITCH_DECLARE(switch_status_t) switch_rtp_read(switch_rtp_t *rtp_session, void *data, uint32_t * datalen,
+												switch_payload_t *payload_type, switch_frame_flag_t *flags)
 {
+	int bytes = 0;
+
+	if (!switch_rtp_ready(rtp_session)) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	bytes = rtp_common_read(rtp_session, payload_type, flags);
 
-	int bytes = rtp_common_read(rtp_session, payload_type, flags);
-	
 	if (bytes < 0) {
 		*datalen = 0;
 		return SWITCH_STATUS_GENERR;
@@ -1033,18 +1137,28 @@
 
 	memcpy(data, rtp_session->recv_msg.body, bytes);
 
-	return SWITCH_STATUS_SUCCESS;	
+	return SWITCH_STATUS_SUCCESS;
 }
 
 SWITCH_DECLARE(switch_status_t) switch_rtp_zerocopy_read_frame(switch_rtp_t *rtp_session, switch_frame_t *frame)
 {
-	int bytes = rtp_common_read(rtp_session, &frame->payload, &frame->flags);
+	int bytes = 0;
 
+	if (!switch_rtp_ready(rtp_session)) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	bytes = rtp_common_read(rtp_session, &frame->payload, &frame->flags);
+	
 	frame->data = rtp_session->recv_msg.body;
 	frame->packet = &rtp_session->recv_msg;
 	frame->packetlen = bytes;
 	frame->source = __FILE__;
 	frame->flags |= SFF_RAW_RTP;
+	frame->timestamp = ntohl(rtp_session->recv_msg.header.ts);
+	frame->seq = (uint16_t)ntohs((u_short)rtp_session->recv_msg.header.seq);
+	frame->ssrc = ntohl(rtp_session->recv_msg.header.ssrc);
+	frame->m = rtp_session->recv_msg.header.m ? SWITCH_TRUE : SWITCH_FALSE;
 
 	if (bytes < 0) {
 		frame->datalen = 0;
@@ -1055,20 +1169,26 @@
 	} else {
 		bytes -= rtp_header_len;
 	}
-
+	
 	frame->datalen = bytes;
+		
+
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
 
 SWITCH_DECLARE(switch_status_t) switch_rtp_zerocopy_read(switch_rtp_t *rtp_session,
-														 void **data,
-														 uint32_t *datalen,
-														 switch_payload_t *payload_type,
-														 switch_frame_flag_t *flags)
+														 void **data, uint32_t * datalen, switch_payload_t *payload_type, switch_frame_flag_t *flags)
 {
 
-	int bytes = rtp_common_read(rtp_session, payload_type, flags);
+	int bytes = 0;
+
+	if (!switch_rtp_ready(rtp_session)) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	bytes = rtp_common_read(rtp_session, payload_type, flags);
 	*data = rtp_session->recv_msg.body;
 
 	if (bytes < 0) {
@@ -1082,31 +1202,50 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-static int rtp_common_write(switch_rtp_t *rtp_session, void *data, uint32_t datalen, uint8_t m, switch_payload_t payload, switch_frame_flag_t *flags)
+static int rtp_common_write(switch_rtp_t *rtp_session, void *data, uint32_t datalen, switch_payload_t payload, switch_frame_flag_t *flags)
 {
 	switch_size_t bytes;
-	uint8_t fwd = (uint8_t)(!flags || (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_RAW_WRITE) && (*flags & SFF_RAW_RTP)));
+	uint8_t fwd = 0;
 	rtp_msg_t *send_msg;
 	uint8_t send = 1;
 
+	if (!switch_rtp_ready(rtp_session)) {
+		return SWITCH_STATUS_FALSE;
+	}
+
+	fwd = (uint8_t) (!flags || (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_RAW_WRITE) && (*flags & SFF_RAW_RTP)));
+
 	if (fwd) {
 		bytes = datalen;
 		send_msg = (rtp_msg_t *) data;
 	} else {
+		uint8_t m = 0;
+		if (rtp_session->ts > rtp_session->last_write_ts + rtp_session->samples_per_interval || rtp_session->ts == rtp_session->samples_per_interval) {
+			m++;
+		}
+		if (rtp_session->cn && payload != rtp_session->cng_pt) {
+			rtp_session->cn = 0;
+			m++;
+		}
+
 		send_msg = &rtp_session->send_msg;
 		send_msg->header.pt = payload;
 		send_msg->header.m = m ? 1 : 0;
-        memcpy(send_msg->body, data, datalen);
-		bytes = datalen + rtp_header_len;	
+		rtp_session->seq++;
+		rtp_session->send_msg.header.seq = htons(rtp_session->seq);
+		rtp_session->send_msg.header.ts = htonl(rtp_session->ts);
+
+		memcpy(send_msg->body, data, datalen);
+		bytes = datalen + rtp_header_len;
 	}
 
 	if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_SECURE)) {
-		int sbytes = (int)bytes;
+		int sbytes = (int) bytes;
 		err_status_t stat;
 
 		stat = srtp_protect(rtp_session->send_ctx, &send_msg->header, &sbytes);
 		if (stat) {
-			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "error: srtp unprotection failed with code %d\n", stat);
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "error: srtp protection failed with code %d\n", stat);
 		}
 
 		bytes = sbytes;
@@ -1116,22 +1255,21 @@
 		rtp_session->recv_msg.header.pt = 102;
 	}
 
-	if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_VAD) && 
-		rtp_session->recv_msg.header.pt == rtp_session->vad_data.read_codec->implementation->ianacode &&
-		((datalen == rtp_session->vad_data.read_codec->implementation->encoded_bytes_per_frame) || 
-		 (datalen > SWITCH_RTP_CNG_PAYLOAD && rtp_session->vad_data.read_codec->implementation->encoded_bytes_per_frame == 0))) {
-		int16_t decoded[SWITCH_RECCOMMENDED_BUFFER_SIZE/sizeof(int16_t)];
-		uint32_t rate;
-		uint32_t flags;
+	if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_VAD) &&
+		rtp_session->recv_msg.header.pt == rtp_session->vad_data.read_codec->implementation->ianacode) {
+		
+		int16_t decoded[SWITCH_RECOMMENDED_BUFFER_SIZE / sizeof(int16_t)] = {0};
+		uint32_t rate = 0;
+		uint32_t flags = 0;
 		uint32_t len = sizeof(decoded);
 		time_t now = time(NULL);
 		send = 0;
 
-        
+
 		if (rtp_session->vad_data.scan_freq && rtp_session->vad_data.next_scan <= now) {
 			rtp_session->vad_data.bg_count = rtp_session->vad_data.bg_level = 0;
 			rtp_session->vad_data.next_scan = now + rtp_session->vad_data.scan_freq;
-			//printf("RESCAN\n");
+			/* printf("RESCAN\n"); */
 		}
 
 		if (switch_core_codec_decode(&rtp_session->vad_data.vad_codec,
@@ -1139,10 +1277,8 @@
 									 data,
 									 datalen,
 									 rtp_session->vad_data.read_codec->implementation->samples_per_second,
-									 decoded,
-									 &len,
-									 &rate,
-									 &flags) == SWITCH_STATUS_SUCCESS) {
+									 decoded, &len, &rate, &flags) == SWITCH_STATUS_SUCCESS) {
+			
 
 			uint32_t energy = 0;
 			uint32_t x, y = 0, z = len / sizeof(int16_t);
@@ -1162,8 +1298,9 @@
 						rtp_session->vad_data.bg_level += score;
 						if (++rtp_session->vad_data.bg_count == rtp_session->vad_data.bg_len) {
 							rtp_session->vad_data.bg_level /= rtp_session->vad_data.bg_len;
-							//rtp_session->vad_data.bg_level += (rtp_session->vad_data.bg_level / 3);
-							//printf("AVG %u\n", rtp_session->vad_data.bg_level);
+							/* rtp_session->vad_data.bg_level += (rtp_session->vad_data.bg_level / 3);
+							 * printf("AVG %u\n", rtp_session->vad_data.bg_level);
+							 */
 						}
 						send = 1;
 					} else {
@@ -1186,7 +1323,7 @@
 										switch_event_fire(&event);
 									}
 								}
-							} 
+							}
 						} else {
 							if (rtp_session->vad_data.hangunder_hits) {
 								rtp_session->vad_data.hangunder_hits--;
@@ -1201,40 +1338,38 @@
 											switch_channel_t *channel = switch_core_session_get_channel(rtp_session->vad_data.session);
 											switch_channel_event_set_data(channel, event);
 											switch_event_fire(&event);
-										}					
+										}
 									}
 								}
 							}
 						}
 					}
 				}
-				
+
 				if (switch_test_flag(&rtp_session->vad_data, SWITCH_VAD_FLAG_TALKING)) {
 					send = 1;
-				} else {
-					if (switch_test_flag(&rtp_session->vad_data, SWITCH_VAD_FLAG_CNG) && ++rtp_session->vad_data.cng_count >= rtp_session->vad_data.cng_freq) {
-						rtp_session->send_msg.header.pt = SWITCH_RTP_CNG_PAYLOAD;
-						memset(rtp_session->send_msg.body, 255, SWITCH_RTP_CNG_PAYLOAD);
-						//rtp_session->send_msg.header.ts = htonl(rtp_session->vad_data.ts);
-						//rtp_session->vad_data.ts++;
-						bytes = SWITCH_RTP_CNG_PAYLOAD;
-						send = 1;
-						rtp_session->vad_data.cng_count = 0;
-					}
-				}
-					   
+				} 
 			}
 		} else {
 			return SWITCH_STATUS_GENERR;
 		}
 	}
 
-	rtp_session->last_write_ts = ntohl(send_msg->header.ts);
-	rtp_session->last_write_ssrc = ntohl(send_msg->header.ssrc);
-	rtp_session->last_write_seq = ntohs((u_short)send_msg->header.seq);
+
+	if (rtp_session->last_write_seq >0 && rtp_session->last_write_seq <= rtp_session->dtmf_data.out_digit_seq) {
+		send = 0;
+	}
 
 	if (send) {
-        switch_socket_sendto(rtp_session->sock, rtp_session->remote_addr, 0, (void*)send_msg, &bytes);
+
+		rtp_session->last_write_ts = ntohl(send_msg->header.ts);
+		rtp_session->last_write_ssrc = ntohl(send_msg->header.ssrc);
+		rtp_session->last_write_seq = rtp_session->seq;
+		if (rtp_session->timer.interval) {
+			switch_core_timer_check(&rtp_session->timer);
+			rtp_session->last_write_samplecount = rtp_session->timer.samplecount;
+		}
+		switch_socket_sendto(rtp_session->sock, rtp_session->remote_addr, 0, (void *) send_msg, &bytes);
 	}
 
 	if (rtp_session->ice_user) {
@@ -1243,13 +1378,18 @@
 		}
 	}
 
-	return (int)bytes;
+	return (int) bytes;
 
 }
 
 
 SWITCH_DECLARE(switch_status_t) switch_rtp_disable_vad(switch_rtp_t *rtp_session)
 {
+
+	if (!switch_rtp_ready(rtp_session)) {
+		return SWITCH_STATUS_FALSE;
+	}
+
 	if (!switch_test_flag(rtp_session, SWITCH_RTP_FLAG_VAD)) {
 		return SWITCH_STATUS_GENERR;
 	}
@@ -1258,26 +1398,31 @@
 	return SWITCH_STATUS_SUCCESS;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_rtp_enable_vad(switch_rtp_t *rtp_session, switch_core_session_t *session, switch_codec_t *codec, switch_vad_flag_t flags)
+SWITCH_DECLARE(switch_status_t) switch_rtp_enable_vad(switch_rtp_t *rtp_session, switch_core_session_t *session, switch_codec_t *codec,
+													  switch_vad_flag_t flags)
 {
+
+	if (!switch_rtp_ready(rtp_session)) {
+		return SWITCH_STATUS_FALSE;
+	}
+
 	if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_VAD)) {
 		return SWITCH_STATUS_GENERR;
 	}
 	memset(&rtp_session->vad_data, 0, sizeof(rtp_session->vad_data));
-	
+
 	if (switch_core_codec_init(&rtp_session->vad_data.vad_codec,
 							   codec->implementation->iananame,
 							   NULL,
 							   codec->implementation->samples_per_second,
 							   codec->implementation->microseconds_per_frame / 1000,
 							   codec->implementation->number_of_channels,
-							   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
-							   NULL, 
-							   rtp_session->pool) != SWITCH_STATUS_SUCCESS) {
+							   SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL, rtp_session->pool) != SWITCH_STATUS_SUCCESS) {
 		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't load codec?\n");
 		return SWITCH_STATUS_FALSE;
 	}
-
+	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Activate VAD codec %s %dms\n", codec->implementation->iananame, 
+					  codec->implementation->microseconds_per_frame / 1000);
 	rtp_session->vad_data.diff_level = 400;
 	rtp_session->vad_data.hangunder = 15;
 	rtp_session->vad_data.hangover = 40;
@@ -1300,59 +1445,101 @@
 SWITCH_DECLARE(int) switch_rtp_write(switch_rtp_t *rtp_session, void *data, uint32_t datalen, uint32_t ts, switch_frame_flag_t *flags)
 {
 
+	if (!switch_rtp_ready(rtp_session)) {
+		return -1;
+	}
+
 	if (!switch_test_flag(rtp_session, SWITCH_RTP_FLAG_IO) || !rtp_session->remote_addr) {
 		return -1;
 	}
 
-	rtp_session->ts += ts;
-	rtp_session->seq = ntohs(rtp_session->seq) + 1;
-	rtp_session->seq = htons(rtp_session->seq);
-	rtp_session->send_msg.header.seq = rtp_session->seq;
-	rtp_session->send_msg.header.ts = htonl(rtp_session->ts);
+	if (ts) {
+		rtp_session->ts = ts;
+	} else if (!ts && rtp_session->timer.timer_interface) {
+		uint32_t sc = rtp_session->timer.samplecount;
+		if (rtp_session->last_write_ts == sc) {
+			rtp_session->ts = sc + rtp_session->samples_per_interval;
+		} else {
+			rtp_session->ts = sc;
+		}
+	} else {
+		rtp_session->ts += rtp_session->samples_per_interval;
+	}
 
-	return rtp_common_write(rtp_session, data, datalen, 0, rtp_session->payload, flags);
+	return rtp_common_write(rtp_session, data, datalen, rtp_session->payload, flags);
 
 }
 
 SWITCH_DECLARE(int) switch_rtp_write_frame(switch_rtp_t *rtp_session, switch_frame_t *frame, uint32_t ts)
 {
-	uint8_t fwd = (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_RAW_WRITE) && switch_test_flag(frame, SFF_RAW_RTP)) ? 1 : 0;
-	uint8_t packetize = (rtp_session->packet_size > frame->datalen && (frame->payload == rtp_session->payload)) ? 1 : 0;
+	uint8_t fwd = 0;
 	void *data;
 	uint32_t len;
+	switch_payload_t payload;
+
+
+	if (!switch_rtp_ready(rtp_session)) {
+		return -1;
+	}
+
+	fwd = (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_RAW_WRITE) && switch_test_flag(frame, SFF_RAW_RTP)) ? 1 : 0;
 
 	if (!switch_test_flag(rtp_session, SWITCH_RTP_FLAG_IO) || !rtp_session->remote_addr) {
 		return -1;
 	}
-	
-	if (fwd && !packetize) {
+
+	assert(frame != NULL);
+
+	if (switch_test_flag(frame, SFF_CNG)) {
+		payload = rtp_session->cng_pt;
+	} else {
+		payload = rtp_session->payload;
+	}
+
+	if (switch_test_flag(frame, SFF_RTP_HEADER)) {
+		return switch_rtp_write_manual(rtp_session, frame->data, frame->datalen, frame->m, frame->payload, 
+									   (uint32_t)(frame->timestamp), frame->seq, frame->ssrc, &frame->flags);
+	}
+
+
+	if (fwd) {
 		data = frame->packet;
 		len = frame->packetlen;
 	} else {
 		data = frame->data;
 		len = frame->datalen;
-		rtp_session->ts += ts;
-		rtp_session->seq = ntohs(rtp_session->seq) + 1;
-		rtp_session->seq = htons(rtp_session->seq);
-		rtp_session->send_msg.header.seq = rtp_session->seq;
-		rtp_session->send_msg.header.ts = htonl(rtp_session->ts);
+
+		if (ts) {
+			rtp_session->ts = ts;
+		} else if (frame->timestamp) {
+			rtp_session->ts = (uint32_t) frame->timestamp;
+		} else if (rtp_session->timer.timer_interface) {
+			uint32_t sc = rtp_session->timer.samplecount;
+			if (rtp_session->last_write_ts == sc) {
+				rtp_session->ts = sc + rtp_session->samples_per_interval;
+			} else {
+				rtp_session->ts = sc;
+			}
+		} else {
+			rtp_session->ts += rtp_session->samples_per_interval;
+		}
 	}
 
-	return rtp_common_write(rtp_session, data, len, 0, rtp_session->payload, &frame->flags);
+	return rtp_common_write(rtp_session, data, len, payload, &frame->flags);
 
 }
 
 SWITCH_DECLARE(int) switch_rtp_write_manual(switch_rtp_t *rtp_session,
 											void *data,
-											uint16_t datalen,
-											uint8_t m,
-											switch_payload_t payload,
-											uint32_t ts,
-											uint16_t mseq,
-											uint32_t ssrc,
-											switch_frame_flag_t *flags)
+											uint32_t datalen,
+											uint8_t m, switch_payload_t payload, uint32_t ts, uint16_t mseq, uint32_t ssrc, switch_frame_flag_t *flags)
 {
-	rtp_msg_t send_msg = {{0}};
+	rtp_msg_t send_msg = { {0} };
+	switch_size_t bytes;
+
+	if (!switch_rtp_ready(rtp_session)) {
+		return -1;
+	}
 
 	if (!switch_test_flag(rtp_session, SWITCH_RTP_FLAG_IO) || !rtp_session->remote_addr) {
 		return -1;
@@ -1367,7 +1554,28 @@
 	send_msg.header.m = m ? 1 : 0;
 	memcpy(send_msg.body, data, datalen);
 
-	return rtp_common_write(rtp_session, (void *) &send_msg, rtp_header_len + datalen, m, payload, NULL);
+	bytes = rtp_header_len + datalen;
+
+
+	if (switch_test_flag(rtp_session, SWITCH_RTP_FLAG_SECURE)) {
+		int sbytes = (int) bytes;
+		err_status_t stat;
+
+		stat = srtp_protect(rtp_session->send_ctx, &send_msg.header, &sbytes);
+		if (stat) {
+			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "error: srtp protection failed with code %d\n", stat);
+		}
+
+		bytes = sbytes;
+	}
+
+
+	if (switch_socket_sendto(rtp_session->sock, rtp_session->remote_addr, 0, (void *) &send_msg, &bytes) != SWITCH_STATUS_SUCCESS) {
+		return -1;
+	}
+	return (int) bytes;
+
+	//return rtp_common_write(rtp_session, (void *) &send_msg, rtp_header_len + datalen, m, payload);
 }
 
 SWITCH_DECLARE(uint32_t) switch_rtp_get_ssrc(switch_rtp_t *rtp_session)
@@ -1380,7 +1588,7 @@
 	rtp_session->private_data = private_data;
 }
 
-SWITCH_DECLARE(void *)switch_rtp_get_private(switch_rtp_t *rtp_session)
+SWITCH_DECLARE(void *) switch_rtp_get_private(switch_rtp_t *rtp_session)
 {
 	return rtp_session->private_data;
 }

Modified: freeswitch/branches/cparker/src/switch_stun.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_stun.c	(original)
+++ freeswitch/branches/cparker/src/switch_stun.c	Tue Apr 24 10:14:28 2007
@@ -38,55 +38,58 @@
 };
 
 static const struct value_mapping PACKET_TYPES[] = {
-	{ SWITCH_STUN_BINDING_REQUEST, "BINDING_REQUEST" },
-	{ SWITCH_STUN_BINDING_RESPONSE, "BINDING_RESPONSE" },
-	{ SWITCH_STUN_BINDING_ERROR_RESPONSE, "BINDING_ERROR_RESPONSE" },
-	{ SWITCH_STUN_SHARED_SECRET_REQUEST, "SHARED_SECRET_REQUEST" },
-	{ SWITCH_STUN_SHARED_SECRET_RESPONSE, "SHARED_SECRET_RESPONSE" },
-	{ SWITCH_STUN_SHARED_SECRET_ERROR_RESPONSE, "SHARED_SECRET_ERROR_RESPONSE" },
-	{ SWITCH_STUN_ALLOCATE_REQUEST, "ALLOCATE_REQUEST" },
-	{ SWITCH_STUN_ALLOCATE_RESPONSE, "ALLOCATE_RESPONSE" },
-	{ SWITCH_STUN_ALLOCATE_ERROR_RESPONSE, "ALLOCATE_ERROR_RESPONSE" },
-	{ SWITCH_STUN_SEND_REQUEST, "SEND_REQUEST" },
-	{ SWITCH_STUN_SEND_RESPONSE, "SEND_RESPONSE" },
-	{ SWITCH_STUN_SEND_ERROR_RESPONSE, "SEND_ERROR_RESPONSE" },
-	{ SWITCH_STUN_DATA_INDICATION , "DATA_INDICATION"},
-	{ 0, 0} };
+	{SWITCH_STUN_BINDING_REQUEST, "BINDING_REQUEST"},
+	{SWITCH_STUN_BINDING_RESPONSE, "BINDING_RESPONSE"},
+	{SWITCH_STUN_BINDING_ERROR_RESPONSE, "BINDING_ERROR_RESPONSE"},
+	{SWITCH_STUN_SHARED_SECRET_REQUEST, "SHARED_SECRET_REQUEST"},
+	{SWITCH_STUN_SHARED_SECRET_RESPONSE, "SHARED_SECRET_RESPONSE"},
+	{SWITCH_STUN_SHARED_SECRET_ERROR_RESPONSE, "SHARED_SECRET_ERROR_RESPONSE"},
+	{SWITCH_STUN_ALLOCATE_REQUEST, "ALLOCATE_REQUEST"},
+	{SWITCH_STUN_ALLOCATE_RESPONSE, "ALLOCATE_RESPONSE"},
+	{SWITCH_STUN_ALLOCATE_ERROR_RESPONSE, "ALLOCATE_ERROR_RESPONSE"},
+	{SWITCH_STUN_SEND_REQUEST, "SEND_REQUEST"},
+	{SWITCH_STUN_SEND_RESPONSE, "SEND_RESPONSE"},
+	{SWITCH_STUN_SEND_ERROR_RESPONSE, "SEND_ERROR_RESPONSE"},
+	{SWITCH_STUN_DATA_INDICATION, "DATA_INDICATION"},
+	{0, 0}
+};
 
 static const struct value_mapping ATTR_TYPES[] = {
-	{ SWITCH_STUN_ATTR_MAPPED_ADDRESS, "MAPPED_ADDRESS" },
-	{ SWITCH_STUN_ATTR_RESPONSE_ADDRESS, "RESPONSE_ADDRESS" },
-	{ SWITCH_STUN_ATTR_CHANGE_REQUEST, "CHANGE_REQUEST" },
-	{ SWITCH_STUN_ATTR_SOURCE_ADDRESS, "SOURCE_ADDRESS" },
-	{ SWITCH_STUN_ATTR_CHANGED_ADDRESS, "CHANGED_ADDRESS" },
-	{ SWITCH_STUN_ATTR_USERNAME, "USERNAME" },
-	{ SWITCH_STUN_ATTR_PASSWORD, "PASSWORD" },
-	{ SWITCH_STUN_ATTR_MESSAGE_INTEGRITY, "MESSAGE_INTEGRITY" },
-	{ SWITCH_STUN_ATTR_ERROR_CODE, "ERROR_CODE" },
-	{ SWITCH_STUN_ATTR_UNKNOWN_ATTRIBUTES, "UNKNOWN_ATTRIBUTES" },
-	{ SWITCH_STUN_ATTR_REFLECTED_FROM, "REFLECTED_FROM" },
-	{ SWITCH_STUN_ATTR_TRANSPORT_PREFERENCES, "TRANSPORT_PREFERENCES" },
-	{ SWITCH_STUN_ATTR_LIFETIME, "LIFETIME" },
-	{ SWITCH_STUN_ATTR_ALTERNATE_SERVER, "ALTERNATE_SERVER" },
-	{ SWITCH_STUN_ATTR_MAGIC_COOKIE, "MAGIC_COOKIE" },
-	{ SWITCH_STUN_ATTR_BANDWIDTH, "BANDWIDTH" },
-	{ SWITCH_STUN_ATTR_DESTINATION_ADDRESS, "DESTINATION_ADDRESS" },
-	{ SWITCH_STUN_ATTR_SOURCE_ADDRESS2, "SOURCE_ADDRESS2" },
-	{ SWITCH_STUN_ATTR_DATA, "DATA" },
-	{ SWITCH_STUN_ATTR_OPTIONS, "OPTIONS" },
-	{ 0, 0} };
+	{SWITCH_STUN_ATTR_MAPPED_ADDRESS, "MAPPED_ADDRESS"},
+	{SWITCH_STUN_ATTR_RESPONSE_ADDRESS, "RESPONSE_ADDRESS"},
+	{SWITCH_STUN_ATTR_CHANGE_REQUEST, "CHANGE_REQUEST"},
+	{SWITCH_STUN_ATTR_SOURCE_ADDRESS, "SOURCE_ADDRESS"},
+	{SWITCH_STUN_ATTR_CHANGED_ADDRESS, "CHANGED_ADDRESS"},
+	{SWITCH_STUN_ATTR_USERNAME, "USERNAME"},
+	{SWITCH_STUN_ATTR_PASSWORD, "PASSWORD"},
+	{SWITCH_STUN_ATTR_MESSAGE_INTEGRITY, "MESSAGE_INTEGRITY"},
+	{SWITCH_STUN_ATTR_ERROR_CODE, "ERROR_CODE"},
+	{SWITCH_STUN_ATTR_UNKNOWN_ATTRIBUTES, "UNKNOWN_ATTRIBUTES"},
+	{SWITCH_STUN_ATTR_REFLECTED_FROM, "REFLECTED_FROM"},
+	{SWITCH_STUN_ATTR_TRANSPORT_PREFERENCES, "TRANSPORT_PREFERENCES"},
+	{SWITCH_STUN_ATTR_LIFETIME, "LIFETIME"},
+	{SWITCH_STUN_ATTR_ALTERNATE_SERVER, "ALTERNATE_SERVER"},
+	{SWITCH_STUN_ATTR_MAGIC_COOKIE, "MAGIC_COOKIE"},
+	{SWITCH_STUN_ATTR_BANDWIDTH, "BANDWIDTH"},
+	{SWITCH_STUN_ATTR_DESTINATION_ADDRESS, "DESTINATION_ADDRESS"},
+	{SWITCH_STUN_ATTR_SOURCE_ADDRESS2, "SOURCE_ADDRESS2"},
+	{SWITCH_STUN_ATTR_DATA, "DATA"},
+	{SWITCH_STUN_ATTR_OPTIONS, "OPTIONS"},
+	{0, 0}
+};
 
 static const struct value_mapping ERROR_TYPES[] = {
-	{ SWITCH_STUN_ERROR_BAD_REQUEST, "BAD_REQUEST" },
-	{ SWITCH_STUN_ERROR_UNAUTHORIZED, "UNAUTHORIZED" },
-	{ SWITCH_STUN_ERROR_UNKNOWN_ATTRIBUTE, "UNKNOWN_ATTRIBUTE" },
-	{ SWITCH_STUN_ERROR_STALE_CREDENTIALS, "STALE_CREDENTIALS" },
-	{ SWITCH_STUN_ERROR_INTEGRITY_CHECK_FAILURE, "INTEGRITY_CHECK_FAILURE" },
-	{ SWITCH_STUN_ERROR_MISSING_USERNAME, "MISSING_USERNAME" },
-	{ SWITCH_STUN_ERROR_USE_TLS, "USE_TLS" },
-	{ SWITCH_STUN_ERROR_SERVER_ERROR, "SERVER_ERROR" },
-	{ SWITCH_STUN_ERROR_GLOBAL_FAILURE, "GLOBAL_FAILURE" }, 
-	{ 0, 0 }};
+	{SWITCH_STUN_ERROR_BAD_REQUEST, "BAD_REQUEST"},
+	{SWITCH_STUN_ERROR_UNAUTHORIZED, "UNAUTHORIZED"},
+	{SWITCH_STUN_ERROR_UNKNOWN_ATTRIBUTE, "UNKNOWN_ATTRIBUTE"},
+	{SWITCH_STUN_ERROR_STALE_CREDENTIALS, "STALE_CREDENTIALS"},
+	{SWITCH_STUN_ERROR_INTEGRITY_CHECK_FAILURE, "INTEGRITY_CHECK_FAILURE"},
+	{SWITCH_STUN_ERROR_MISSING_USERNAME, "MISSING_USERNAME"},
+	{SWITCH_STUN_ERROR_USE_TLS, "USE_TLS"},
+	{SWITCH_STUN_ERROR_SERVER_ERROR, "SERVER_ERROR"},
+	{SWITCH_STUN_ERROR_GLOBAL_FAILURE, "GLOBAL_FAILURE"},
+	{0, 0}
+};
 
 SWITCH_DECLARE(void) switch_stun_random_string(char *buf, uint16_t len, char *set)
 {
@@ -98,19 +101,19 @@
 		set = chars;
 	}
 
-	max = (int)strlen(set);
+	max = (int) strlen(set);
 
-	srand((unsigned int)apr_time_now());
+	srand((unsigned int) switch_time_now());
 
-	for(x = 0; x < len; x++) {
-		int j = (int)(max*1.0*rand()/(RAND_MAX+1.0));
+	for (x = 0; x < len; x++) {
+		int j = (int) (max * 1.0 * rand() / (RAND_MAX + 1.0));
 		buf[x] = set[j];
 	}
 }
 
 
 
-SWITCH_DECLARE(switch_stun_packet_t *)switch_stun_packet_parse(uint8_t *buf, uint32_t len)
+SWITCH_DECLARE(switch_stun_packet_t *) switch_stun_packet_parse(uint8_t * buf, uint32_t len)
 {
 	switch_stun_packet_t *packet;
 	switch_stun_packet_attribute_t *attr;
@@ -129,7 +132,7 @@
 		if (!attr->length) {
 			break;
 		}
-		switch(attr->type) {
+		switch (attr->type) {
 		case SWITCH_STUN_ATTR_MAPPED_ADDRESS:
 			if (attr->type) {
 				switch_stun_ip_t *ip;
@@ -143,8 +146,7 @@
 	return packet;
 }
 
-SWITCH_DECLARE(const char *)switch_stun_value_to_name(int32_t type, uint32_t value)
-
+SWITCH_DECLARE(const char *) switch_stun_value_to_name(int32_t type, uint32_t value)
 {
 	uint32_t x = 0;
 	const struct value_mapping *map = NULL;
@@ -164,26 +166,26 @@
 	}
 
 	if (map) {
-		for(x = 0; map[x].value; x++) {
+		for (x = 0; map[x].value; x++) {
 			if (map[x].value == value) {
 				return map[x].name;
 			}
 		}
 	}
-	
+
 	return "INVALID";
 }
 
-SWITCH_DECLARE(uint8_t) switch_stun_packet_attribute_get_mapped_address(switch_stun_packet_attribute_t *attribute, char *ipstr, uint16_t *port)
+SWITCH_DECLARE(uint8_t) switch_stun_packet_attribute_get_mapped_address(switch_stun_packet_attribute_t *attribute, char *ipstr, uint16_t * port)
 {
 	switch_stun_ip_t *ip;
 	uint8_t x, *i;
 	char *p = ipstr;
-	
+
 	ip = (switch_stun_ip_t *) attribute->value;
-	i = (uint8_t *) &ip->address;
+	i = (uint8_t *) & ip->address;
 	*ipstr = 0;
-	for(x =0; x < 4; x++) {
+	for (x = 0; x < 4; x++) {
 		sprintf(p, "%u%s", i[x], x == 3 ? "" : ".");
 		p = ipstr + strlen(ipstr);
 	}
@@ -191,7 +193,7 @@
 	return 1;
 }
 
-SWITCH_DECLARE(char *)switch_stun_packet_attribute_get_username(switch_stun_packet_attribute_t *attribute, char *username, uint16_t len)
+SWITCH_DECLARE(char *) switch_stun_packet_attribute_get_username(switch_stun_packet_attribute_t *attribute, char *username, uint16_t len)
 {
 	uint16_t cpylen;
 
@@ -199,18 +201,15 @@
 	return memcpy(username, attribute->value, cpylen);
 }
 
-SWITCH_DECLARE(switch_stun_packet_t *)switch_stun_packet_build_header(switch_stun_message_t type,
-																	  char *id,
-																	  uint8_t *buf
-																	  )
+SWITCH_DECLARE(switch_stun_packet_t *) switch_stun_packet_build_header(switch_stun_message_t type, char *id, uint8_t * buf)
 {
 	switch_stun_packet_header_t *header;
 
-	
+
 	header = (switch_stun_packet_header_t *) buf;
 	header->type = htons(type);
 	header->length = 0;
-	
+
 	if (id) {
 		memcpy(header->id, id, 16);
 	} else {
@@ -220,24 +219,24 @@
 	return (switch_stun_packet_t *) buf;
 }
 
-SWITCH_DECLARE(uint8_t) switch_stun_packet_attribute_add_binded_address(switch_stun_packet_t *packet, char *ipstr,  uint16_t port)
+SWITCH_DECLARE(uint8_t) switch_stun_packet_attribute_add_binded_address(switch_stun_packet_t *packet, char *ipstr, uint16_t port)
 {
 	switch_stun_packet_attribute_t *attribute;
 	switch_stun_ip_t *ip;
 	uint8_t *i, x;
 	char *p = ipstr;
 
-	attribute = (switch_stun_packet_attribute_t *) ((uint8_t *) &packet->first_attribute + ntohs(packet->header.length));
+	attribute = (switch_stun_packet_attribute_t *) ((uint8_t *) & packet->first_attribute + ntohs(packet->header.length));
 	attribute->type = htons(SWITCH_STUN_ATTR_MAPPED_ADDRESS);
 	attribute->length = htons(8);
 	ip = (switch_stun_ip_t *) attribute->value;
 
 	ip->port = htons(port);
 	ip->family = 1;
-	i = (uint8_t *) &ip->address;
+	i = (uint8_t *) & ip->address;
 
-	for(x = 0; x < 4 ; x++) {
-		i[x] = (uint8_t)atoi(p);
+	for (x = 0; x < 4; x++) {
+		i[x] = (uint8_t) atoi(p);
 		if ((p = strchr(p, '.'))) {
 			p++;
 		} else {
@@ -256,34 +255,29 @@
 	if (ulen % 4 != 0) {
 		return 0;
 	}
-	attribute = (switch_stun_packet_attribute_t *) ((uint8_t *) &packet->first_attribute + ntohs(packet->header.length));
+	attribute = (switch_stun_packet_attribute_t *) ((uint8_t *) & packet->first_attribute + ntohs(packet->header.length));
 	attribute->type = htons(SWITCH_STUN_ATTR_USERNAME);
 	attribute->length = htons(ulen);
 	if (username) {
 		memcpy(attribute->value, username, ulen);
 	} else {
 		switch_stun_random_string(attribute->value, ulen, NULL);
-	} 
+	}
 
 	packet->header.length += htons(sizeof(switch_stun_packet_attribute_t)) + attribute->length;
 	return 1;
 }
 
-SWITCH_DECLARE(switch_status_t) switch_stun_lookup (char **ip, 
-												  switch_port_t *port,
-												  char *stunip,
-												  switch_port_t stunport,
-												  char **err,
-												  switch_memory_pool_t *pool)
-	 
+SWITCH_DECLARE(switch_status_t) switch_stun_lookup(char **ip,
+												   switch_port_t *port, char *stunip, switch_port_t stunport, char **err, switch_memory_pool_t *pool)
 {
 	switch_sockaddr_t *local_addr = NULL, *remote_addr = NULL, *from_addr = NULL;
 	switch_socket_t *sock = NULL;
-	uint8_t buf[256] = {0};
+	uint8_t buf[256] = { 0 };
 	switch_stun_packet_t *packet;
 	switch_stun_packet_attribute_t *attr;
 	switch_size_t bytes = 0;
-	char username[33] = {0};
+	char username[33] = { 0 };
 	char rip[16];
 	uint16_t rport = 0;
 	switch_time_t started = 0;
@@ -307,33 +301,33 @@
 		*err = "Socket Error!";
 		return SWITCH_STATUS_FALSE;
 	}
-	
+
 	if (switch_socket_bind(sock, local_addr) != SWITCH_STATUS_SUCCESS) {
 		*err = "Bind Error!";
 		return SWITCH_STATUS_FALSE;
 	}
-	
-	switch_socket_opt_set(sock, APR_SO_NONBLOCK, TRUE);
+
+	switch_socket_opt_set(sock, SWITCH_SO_NONBLOCK, TRUE);
 	packet = switch_stun_packet_build_header(SWITCH_STUN_BINDING_REQUEST, NULL, buf);
 	switch_stun_random_string(username, 32, NULL);
 	switch_stun_packet_attribute_add_username(packet, username, 32);
 	bytes = switch_stun_packet_length(packet);
-	switch_socket_sendto(sock, remote_addr, 0, (void *)packet, &bytes);
+	switch_socket_sendto(sock, remote_addr, 0, (void *) packet, &bytes);
 	started = switch_time_now();
-	
+
 	*ip = NULL;
 	*port = 0;
 
 
-	for(;;) {
+	for (;;) {
 		bytes = sizeof(buf);
-		if (switch_socket_recvfrom(from_addr, sock, 0, (char *)&buf, &bytes) == SWITCH_STATUS_SUCCESS && bytes > 0) {
+		if (switch_socket_recvfrom(from_addr, sock, 0, (char *) &buf, &bytes) == SWITCH_STATUS_SUCCESS && bytes > 0) {
 			break;
 		}
 
-		if ((elapsed = (unsigned int)((switch_time_now() - started) / 1000)) > 5000) {
+		if ((elapsed = (unsigned int) ((switch_time_now() - started) / 1000)) > 5000) {
 			*err = "Timeout";
-			switch_socket_shutdown(sock, APR_SHUTDOWN_READWRITE);
+			switch_socket_shutdown(sock, SWITCH_SHUTDOWN_READWRITE);
 			switch_socket_close(sock);
 			return SWITCH_STATUS_TIMEOUT;
 		}
@@ -345,14 +339,14 @@
 	switch_stun_packet_first_attribute(packet, attr);
 
 	do {
-		switch(attr->type) {
+		switch (attr->type) {
 		case SWITCH_STUN_ATTR_MAPPED_ADDRESS:
 			if (attr->type) {
 				switch_stun_packet_attribute_get_mapped_address(attr, rip, &rport);
 			}
 			break;
 		case SWITCH_STUN_ATTR_USERNAME:
-			if(attr->type) {
+			if (attr->type) {
 				switch_stun_packet_attribute_get_username(attr, username, 32);
 			}
 			break;
@@ -366,7 +360,7 @@
 	} else {
 		*err = "Invalid Reply";
 	}
-	
+
 
 	return SWITCH_STATUS_FALSE;
 }

Modified: freeswitch/branches/cparker/src/switch_swig.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_swig.c	(original)
+++ freeswitch/branches/cparker/src/switch_swig.c	Tue Apr 24 10:14:28 2007
@@ -64,7 +64,7 @@
 {
 	switch_status_t status;
 
-	status = switch_core_destroy(0);
+	status = switch_core_destroy();
 
 	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
 }
@@ -80,7 +80,7 @@
 	return 1;
 }
 
-int fs_console_loop(void) 
+int fs_console_loop(void)
 {
 	switch_console_loop();
 	return 0;
@@ -88,17 +88,17 @@
 
 void fs_consol_log(char *level_str, char *msg)
 {
-    switch_log_level_t level = SWITCH_LOG_DEBUG;
-    if (level_str) {
-        level = switch_log_str2level(level_str);
+	switch_log_level_t level = SWITCH_LOG_DEBUG;
+	if (level_str) {
+		level = switch_log_str2level(level_str);
 	}
-      
-    switch_log_printf(SWITCH_CHANNEL_LOG, level, msg);
+
+	switch_log_printf(SWITCH_CHANNEL_LOG, level, msg);
 }
-	
+
 void fs_consol_clean(char *msg)
 {
-    switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_DEBUG, msg);
+	switch_log_printf(SWITCH_CHANNEL_LOG_CLEAN, SWITCH_LOG_DEBUG, msg);
 }
 
 switch_core_session_t *fs_core_session_locate(char *uuid)
@@ -157,71 +157,54 @@
   IVR Routines!  You can do IVR in PHP NOW!
 */
 
-int fs_ivr_play_file(switch_core_session_t *session,
-                     switch_file_handle_t *fh,
-					 char *file,
-                     switch_input_args_t *args)
+int fs_ivr_play_file(switch_core_session_t *session, switch_file_handle_t *fh, char *file, switch_input_args_t *args)
 {
 	switch_status_t status;
-	
+
 	status = switch_ivr_play_file(session, fh, file, args);
 	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
 }
 
-int fs_switch_ivr_record_file(switch_core_session_t *session,
-                              switch_file_handle_t *fh,
-                              char *file,
-                              switch_input_args_t *args,
-                              unsigned int limit
-                              )
-{  
+int fs_switch_ivr_record_file(switch_core_session_t *session, switch_file_handle_t *fh, char *file, switch_input_args_t *args, unsigned int limit)
+{
 	switch_status_t status;
-	
-    status = switch_ivr_record_file(session, fh, file, args, limit);
-    return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
+
+	status = switch_ivr_record_file(session, fh, file, args, limit);
+	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
 }
 
-int fs_switch_ivr_sleep(switch_core_session_t *session,
-                        uint32_t ms)
+int fs_switch_ivr_sleep(switch_core_session_t *session, uint32_t ms)
 {
 	switch_status_t status;
 	status = switch_ivr_sleep(session, ms);
 	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
 }
 
-int fs_ivr_play_file2(switch_core_session_t *session,
-					  char *file)
-
+int fs_ivr_play_file2(switch_core_session_t *session, char *file)
 {
 	switch_status_t status;
-	
+
 	status = switch_ivr_play_file(session, NULL, file, NULL);
 	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
 }
 
 
-int fs_switch_ivr_collect_digits_callback (switch_core_session_t *session,
-                                           switch_input_args_t *args,
-										   unsigned int timeout)
+int fs_switch_ivr_collect_digits_callback(switch_core_session_t *session, switch_input_args_t *args, unsigned int timeout)
 {
-    switch_status_t status;
+	switch_status_t status;
 
-    status = switch_ivr_collect_digits_callback(session, args, timeout);
-    return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
+	status = switch_ivr_collect_digits_callback(session, args, timeout);
+	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
 }
 
-int fs_switch_ivr_collect_digits_count  	(switch_core_session_t *session,
-                                             char *buf,
-                                             unsigned int buflen,
-                                             unsigned int maxdigits,
-                                             const char *terminators,
-                                             char *terminator,
-                                             unsigned int timeout)  
+int fs_switch_ivr_collect_digits_count(switch_core_session_t *session,
+									   char *buf, unsigned int buflen, unsigned int maxdigits, const char *terminators, char *terminator,
+									   unsigned int timeout)
 {
-    switch_status_t status;
+	switch_status_t status;
 
-    status = switch_ivr_collect_digits_count(session, buf, buflen, maxdigits, terminators, terminator, timeout);
-    return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
+	status = switch_ivr_collect_digits_count(session, buf, buflen, maxdigits, terminators, terminator, timeout);
+	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
 }
 
 /*int fs_switch_ivr_multi_threaded_bridge   (switch_core_session_t *session,
@@ -237,61 +220,52 @@
   }
 */
 
-int fs_switch_ivr_originate       (switch_core_session_t *session,
-                                   switch_core_session_t **bleg,
-                                   char *  	bridgeto,
-                                   uint32_t  	timelimit_sec)
+int fs_switch_ivr_originate(switch_core_session_t *session, switch_core_session_t **bleg, char *bridgeto, uint32_t timelimit_sec)
 /*const switch_state_handler_table_t *table,
   char *  	cid_name_override,
   char *  	cid_num_override,
   switch_caller_profile_t *caller_profile_override)  */
 {
 
-    switch_channel_t *caller_channel;
-    switch_core_session_t *peer_session;
-    unsigned int timelimit = 60;
-    char *var;
-    switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
+	switch_channel_t *caller_channel;
+	switch_core_session_t *peer_session;
+	unsigned int timelimit = 60;
+	char *var;
+	switch_call_cause_t cause = SWITCH_CAUSE_NORMAL_CLEARING;
+
+	caller_channel = switch_core_session_get_channel(session);
+	assert(caller_channel != NULL);
 
-    caller_channel = switch_core_session_get_channel(session);
-    assert(caller_channel != NULL);
+	if ((var = switch_channel_get_variable(caller_channel, "call_timeout"))) {
+		timelimit = atoi(var);
+	}
 
-    if ((var = switch_channel_get_variable(caller_channel, "call_timeout"))) {
-        timelimit = atoi(var);
-    }
-        
-    if (switch_ivr_originate(session, &peer_session, &cause, bridgeto, timelimit, NULL, NULL, NULL, NULL) != SWITCH_STATUS_SUCCESS) {
-        switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Create Outgoing Channel!\n");
-        switch_channel_hangup(caller_channel, SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL);
-        return;
-    } else {
-        switch_ivr_multi_threaded_bridge(session, peer_session, NULL, NULL, NULL);
-    }
+	if (switch_ivr_originate(session, &peer_session, &cause, bridgeto, timelimit, NULL, NULL, NULL, NULL) != SWITCH_STATUS_SUCCESS) {
+		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Create Outgoing Channel!\n");
+		switch_channel_hangup(caller_channel, SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL);
+		return;
+	} else {
+		switch_ivr_multi_threaded_bridge(session, peer_session, NULL, NULL, NULL);
+        switch_core_session_rwunlock(peer_session);
+	}
 
 
 }
 
-int fs_switch_ivr_session_transfer(switch_core_session_t *session,
-                                   char *extension,
-                                   char *dialplan,
-                                   char *context)  
+int fs_switch_ivr_session_transfer(switch_core_session_t *session, char *extension, char *dialplan, char *context)
 {
-    switch_status_t status;
+	switch_status_t status;
 
-    status = switch_ivr_session_transfer(session,extension,dialplan,context);
-    return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
+	status = switch_ivr_session_transfer(session, extension, dialplan, context);
+	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
 }
 
-int fs_switch_ivr_speak_text      (switch_core_session_t *session,
-                                   char *tts_name,
-                                   char *voice_name,
-                                   uint32_t  	rate,
-                                   char *text)
+int fs_switch_ivr_speak_text(switch_core_session_t *session, char *tts_name, char *voice_name, uint32_t rate, char *text)
 {
-    switch_status_t status;
+	switch_status_t status;
 
-    status = switch_ivr_speak_text(session,tts_name,voice_name,rate,text,NULL);
-    return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
+	status = switch_ivr_speak_text(session, tts_name, voice_name, rate, text, NULL);
+	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
 }
 
 
@@ -301,7 +275,7 @@
 
 */
 
-char* fs_switch_channel_get_variable(switch_channel_t *channel, char *varname)
+char *fs_switch_channel_get_variable(switch_channel_t *channel, char *varname)
 {
 	return switch_channel_get_variable(channel, varname);
 }
@@ -309,11 +283,11 @@
 
 int fs_switch_channel_set_variable(switch_channel_t *channel, char *varname, char *value)
 {
-    switch_status_t status;
+	switch_status_t status;
 
-    status = switch_channel_set_variable(channel, varname, value);
-    return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
-}  
+	status = switch_channel_set_variable(channel, varname, value);
+	return status == SWITCH_STATUS_SUCCESS ? 1 : 0;
+}
 
 /* For Emacs:
  * Local Variables:

Modified: freeswitch/branches/cparker/src/switch_utils.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_utils.c	(original)
+++ freeswitch/branches/cparker/src/switch_utils.c	Tue Apr 24 10:14:28 2007
@@ -30,310 +30,208 @@
  *
  */
 #include <switch.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
 #ifndef WIN32
 #include <arpa/inet.h>
 #endif
 
 SWITCH_DECLARE(switch_status_t) switch_find_local_ip(char *buf, int len, int family)
 {
-    switch_status_t status = SWITCH_STATUS_FALSE;
-    char *base;
+	switch_status_t status = SWITCH_STATUS_FALSE;
+	char *base;
 
 #ifdef WIN32
-    SOCKET tmp_socket;
-    SOCKADDR_STORAGE l_address;
-    int l_address_len;
-    struct addrinfo *address_info;
+	SOCKET tmp_socket;
+	SOCKADDR_STORAGE l_address;
+	int l_address_len;
+	struct addrinfo *address_info;
 #else
 #ifdef __Darwin__
-    int ilen;
+	int ilen;
 #else
-    unsigned int ilen;
+	unsigned int ilen;
 #endif
-    int tmp_socket = -1, on = 1;
-    char abuf[25] = "";
+	int tmp_socket = -1, on = 1;
+	char abuf[25] = "";
 #endif
 
-    switch_copy_string(buf, "127.0.0.1", len);
+	switch_copy_string(buf, "127.0.0.1", len);
 
-    switch(family) {
-    case AF_INET:
-        base = "82.45.148.209";
-        break;
-    case AF_INET6:
-        base = "52.2d.94.d1";
-        break;
+	switch (family) {
+	case AF_INET:
+		base = "82.45.148.209";
+		break;
+	case AF_INET6:
+		base = "52.2d.94.d1";
+		break;
 	default:
 		base = "127.0.0.1";
 		break;
-    }
+	}
 
 
 #ifdef WIN32
-    tmp_socket = socket(family, SOCK_DGRAM, 0);
+	tmp_socket = socket(family, SOCK_DGRAM, 0);
 
-    getaddrinfo(base, NULL, NULL, &address_info);
-  
-    if (WSAIoctl(tmp_socket,
-                 SIO_ROUTING_INTERFACE_QUERY,
-                 address_info->ai_addr,
-                 (DWORD)address_info->ai_addrlen,
-                 &l_address,
-                 sizeof(l_address),
-                 (LPDWORD)&l_address_len,
-                 NULL,
-                 NULL)) {
-        
-        closesocket(tmp_socket);
-        freeaddrinfo(address_info);
-        return status;
-    }
-  
-    closesocket(tmp_socket);
-    freeaddrinfo(address_info);
-  
-    if(!getnameinfo((const struct sockaddr*)&l_address,
-                    l_address_len,
-                    buf,
-                    len,
-                    NULL,
-                    0,
-                    NI_NUMERICHOST)) {
-
-        status = SWITCH_STATUS_SUCCESS;
-        
-    }
+	getaddrinfo(base, NULL, NULL, &address_info);
 
-#else
+	if (WSAIoctl(tmp_socket,
+				 SIO_ROUTING_INTERFACE_QUERY,
+				 address_info->ai_addr, (DWORD) address_info->ai_addrlen, &l_address, sizeof(l_address), (LPDWORD) & l_address_len, NULL, NULL)) {
 
-    switch(family) {
-    case AF_INET:
-        {
-            struct sockaddr_in iface_out;
-            struct sockaddr_in remote;          
-            memset (&remote, 0, sizeof (struct sockaddr_in));
-
-            remote.sin_family = AF_INET;
-            remote.sin_addr.s_addr = inet_addr (base);
-            remote.sin_port = htons (4242);
-
-            memset (&iface_out, 0, sizeof (iface_out));
-            tmp_socket = socket (AF_INET, SOCK_DGRAM, 0);
-            
-            if (setsockopt (tmp_socket, SOL_SOCKET, SO_BROADCAST, &on, sizeof (on)) == -1) {
-                goto doh;
-            }
-
-            if (connect (tmp_socket, (struct sockaddr *) &remote, sizeof (struct sockaddr_in)) == -1) {
-                goto doh;
-            }
-
-            ilen = sizeof (iface_out);
-            if (getsockname (tmp_socket, (struct sockaddr *) &iface_out, &ilen) == -1) {
-                goto doh;
-            }
-
-            if (iface_out.sin_addr.s_addr == 0) {
-                goto doh;
-            }
-            
-            switch_copy_string(buf, get_addr(abuf, sizeof(abuf), &iface_out.sin_addr), len);
-            status = SWITCH_STATUS_SUCCESS;
-        }
-        break;
-        case AF_INET6:
-        {
-            struct sockaddr_in6 iface_out;
-            struct sockaddr_in6 remote;
-            memset (&remote, 0, sizeof (struct sockaddr_in6));
-
-            remote.sin6_family = AF_INET6;
-            inet_pton (AF_INET6, buf, &remote.sin6_addr);
-            remote.sin6_port = htons (4242);
-
-            memset (&iface_out, 0, sizeof (iface_out));
-            tmp_socket = socket (AF_INET6, SOCK_DGRAM, 0);
-
-            if (setsockopt (tmp_socket, SOL_SOCKET, SO_BROADCAST, &on, sizeof (on)) == -1) {
-                goto doh;
-            }
-
-            if (connect (tmp_socket, (struct sockaddr *) &remote, sizeof (struct sockaddr_in)) == -1) {
-                goto doh;
-            }
-
-            ilen = sizeof (iface_out);
-            if (getsockname (tmp_socket, (struct sockaddr *) &iface_out, &ilen) == -1) {
-                goto doh;
-            }
-            
-            if (iface_out.sin6_addr.s6_addr == 0) {
-                goto doh;
-            }
-
-            inet_ntop (AF_INET6, (const void *) &iface_out.sin6_addr, buf, len - 1);
-            status = SWITCH_STATUS_SUCCESS;
-        }
-        break;
-    }
-
-
- doh:
-    if (tmp_socket > 0) {
-        close (tmp_socket);
-        tmp_socket = -1;
-    }
+		closesocket(tmp_socket);
+		freeaddrinfo(address_info);
+		return status;
+	}
 
-#endif
+	closesocket(tmp_socket);
+	freeaddrinfo(address_info);
 
-    return status;
- 
-}
+	if (!getnameinfo((const struct sockaddr *) &l_address, l_address_len, buf, len, NULL, 0, NI_NUMERICHOST)) {
+
+		status = SWITCH_STATUS_SUCCESS;
 
-SWITCH_DECLARE(int) switch_perform_regex(char *field, char *expression, pcre **new_re, int *ovector, uint32_t olen)
-{
-	const char *error = NULL;
-	int erroffset = 0;
-	pcre *re = NULL;
-	int match_count = 0;
-	
-	if (!(field && expression)) {
-		return 0;
 	}
+#else
 
-	re = pcre_compile(expression, /* the pattern */
-					  0,		  /* default options */
-					  &error,	  /* for error message */
-					  &erroffset, /* for error offset */
-					  NULL);	  /* use default character tables */
-	if (error) {
-		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "COMPILE ERROR: %d [%s]\n", erroffset, error);
-		switch_clean_re(re);
-		return 0;
+	switch (family) {
+	case AF_INET:
+		{
+			struct sockaddr_in iface_out;
+			struct sockaddr_in remote;
+			memset(&remote, 0, sizeof(struct sockaddr_in));
+
+			remote.sin_family = AF_INET;
+			remote.sin_addr.s_addr = inet_addr(base);
+			remote.sin_port = htons(4242);
+
+			memset(&iface_out, 0, sizeof(iface_out));
+			tmp_socket = socket(AF_INET, SOCK_DGRAM, 0);
+
+			if (setsockopt(tmp_socket, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) == -1) {
+				goto doh;
+			}
+
+			if (connect(tmp_socket, (struct sockaddr *) &remote, sizeof(struct sockaddr_in)) == -1) {
+				goto doh;
+			}
+
+			ilen = sizeof(iface_out);
+			if (getsockname(tmp_socket, (struct sockaddr *) &iface_out, &ilen) == -1) {
+				goto doh;
+			}
+
+			if (iface_out.sin_addr.s_addr == 0) {
+				goto doh;
+			}
+
+			switch_copy_string(buf, get_addr(abuf, sizeof(abuf), &iface_out.sin_addr), len);
+			status = SWITCH_STATUS_SUCCESS;
+		}
+		break;
+	case AF_INET6:
+		{
+			struct sockaddr_in6 iface_out;
+			struct sockaddr_in6 remote;
+			memset(&remote, 0, sizeof(struct sockaddr_in6));
+
+			remote.sin6_family = AF_INET6;
+			inet_pton(AF_INET6, buf, &remote.sin6_addr);
+			remote.sin6_port = htons(4242);
+
+			memset(&iface_out, 0, sizeof(iface_out));
+			tmp_socket = socket(AF_INET6, SOCK_DGRAM, 0);
+
+			if (setsockopt(tmp_socket, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) == -1) {
+				goto doh;
+			}
+
+			if (connect(tmp_socket, (struct sockaddr *) &remote, sizeof(struct sockaddr_in)) == -1) {
+				goto doh;
+			}
+
+			ilen = sizeof(iface_out);
+			if (getsockname(tmp_socket, (struct sockaddr *) &iface_out, &ilen) == -1) {
+				goto doh;
+			}
+
+			if (iface_out.sin6_addr.s6_addr == 0) {
+				goto doh;
+			}
+
+			inet_ntop(AF_INET6, (const void *) &iface_out.sin6_addr, buf, len - 1);
+			status = SWITCH_STATUS_SUCCESS;
+		}
+		break;
 	}
 
-	match_count = pcre_exec(re,	/* result of pcre_compile() */
-							NULL,	/* we didn't study the pattern */
-							field,	/* the subject string */
-							(int) strlen(field), /* the length of the subject string */
-							0,	/* start at offset 0 in the subject */
-							0,	/* default options */
-							ovector,	/* vector of integers for substring information */
-							olen); /* number of elements (NOT size in bytes) */
 
-	if (match_count <= 0) {
-		switch_clean_re(re);
-		match_count = 0;
+  doh:
+	if (tmp_socket > 0) {
+		close(tmp_socket);
+		tmp_socket = -1;
 	}
+#endif
 
-	*new_re = re;
+	return status;
 
-	return match_count;
 }
 
 
-SWITCH_DECLARE(void) switch_perform_substitution(pcre *re, int match_count, char *data, char *field_data, char *substituted, uint32_t len, int *ovector)
+SWITCH_DECLARE(switch_time_t) switch_str_time(char *in)
 {
-	char index[10] = "";
+	switch_time_exp_t tm = { 0 };
+	int proceed = 0, ovector[30];
+	switch_regex_t *re = NULL;
 	char replace[1024] = "";
-	uint32_t x, y = 0, z = 0, num = 0;
+	switch_time_t ret = 0;
+	char *pattern = "^(\\d+)-(\\d+)-(\\d+)\\s*(\\d*):{0,1}(\\d*):{0,1}(\\d*)";
 
-	for (x = 0; x < (len-1) && x < strlen(data);) {
-		if (data[x] == '$') {
-			x++;
-			
-			if (!(data[x] > 47 && data[x] < 58)) {
-				substituted[y++] = data[x-1];
-				continue;
-			}
-
-			while (data[x] > 47 && data[x] < 58) {
-				index[z++] = data[x];
-				x++;
-			}
-			index[z++] = '\0';
-			z = 0;
-			num = atoi(index);
-			
-			if (pcre_copy_substring(field_data,
-									ovector,
-									match_count,
-									num,
-									replace,
-									sizeof(replace)) > 0) {
-				unsigned int r;
-				for (r = 0; r < strlen(replace); r++) {
-					substituted[y++] = replace[r];
-				}
-			}
-		} else {
-			substituted[y++] = data[x];
-			x++;
+	switch_time_exp_lt(&tm, switch_time_now());
+	tm.tm_year = tm.tm_mon = tm.tm_mday = tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
+
+	if ((proceed = switch_regex_perform(in, pattern, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
+
+		if (proceed > 1) {
+			switch_regex_copy_substring(in, ovector, proceed, 1, replace, sizeof(replace));
+			tm.tm_year = atoi(replace) - 1900;
 		}
-	}
-	substituted[y++] = '\0';
-}
 
+		if (proceed > 2) {
+			switch_regex_copy_substring(in, ovector, proceed, 2, replace, sizeof(replace));
+			tm.tm_mon = atoi(replace) - 1;
+		}
 
+		if (proceed > 3) {
+			switch_regex_copy_substring(in, ovector, proceed, 3, replace, sizeof(replace));
+			tm.tm_mday = atoi(replace);
+		}
 
-SWITCH_DECLARE(switch_time_t) switch_str_time(char *in)
-{
-    switch_time_exp_t tm = {0};
-    int proceed = 0, ovector[30];
-    pcre *re = NULL;
-    char replace[1024] = "";
-    switch_time_t ret = 0;
-    char *pattern = "^(\\d+)-(\\d+)-(\\d+)\\s*(\\d*):{0,1}(\\d*):{0,1}(\\d*)";
-
-    switch_time_exp_lt(&tm, switch_time_now());
-    tm.tm_year = tm.tm_mon = tm.tm_mday = tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
-
-    if ((proceed = switch_perform_regex(in, pattern, &re, ovector, sizeof(ovector) / sizeof(ovector[0])))) {
-
-        if (proceed > 1) {
-            pcre_copy_substring(in, ovector, proceed, 1, replace, sizeof(replace));
-            tm.tm_year = atoi(replace) - 1900;
-        }
-
-        if (proceed > 2) {
-            pcre_copy_substring(in, ovector, proceed, 2, replace, sizeof(replace));
-            tm.tm_mon = atoi(replace) - 1;
-        }
-
-        if (proceed > 3) {
-            pcre_copy_substring(in, ovector, proceed, 3, replace, sizeof(replace));
-            tm.tm_mday = atoi(replace);
-        }
-        
-        if (proceed > 4) {
-            pcre_copy_substring(in, ovector, proceed, 4, replace, sizeof(replace));
-            tm.tm_hour = atoi(replace);
-        }
-
-        if (proceed > 5) {
-            pcre_copy_substring(in, ovector, proceed, 5, replace, sizeof(replace));
-            tm.tm_min = atoi(replace);
-        }
-
-        if (proceed > 6) {
-            pcre_copy_substring(in, ovector, proceed, 6, replace, sizeof(replace));
-            tm.tm_sec = atoi(replace);
-        }
-
-        apr_time_exp_gmt_get(&ret, &tm);
-        return ret;
-    } /* possible else with more patterns later */
-    
-    return ret;
+		if (proceed > 4) {
+			switch_regex_copy_substring(in, ovector, proceed, 4, replace, sizeof(replace));
+			tm.tm_hour = atoi(replace);
+		}
+
+		if (proceed > 5) {
+			switch_regex_copy_substring(in, ovector, proceed, 5, replace, sizeof(replace));
+			tm.tm_min = atoi(replace);
+		}
+
+		if (proceed > 6) {
+			switch_regex_copy_substring(in, ovector, proceed, 6, replace, sizeof(replace));
+			tm.tm_sec = atoi(replace);
+		}
+
+		switch_time_exp_gmt_get(&ret, &tm);
+		return ret;
+	}
+	/* possible else with more patterns later */
+	return ret;
 
 }
 
 SWITCH_DECLARE(char *) switch_priority_name(switch_priority_t priority)
 {
-	switch(priority) { /*lol*/
+	switch (priority) {			/*lol */
 	case SWITCH_PRIORITY_NORMAL:
 		return "NORMAL";
 	case SWITCH_PRIORITY_LOW:
@@ -356,34 +254,13 @@
 	i = (uint8_t *) in;
 
 	memset(buf, 0, len);
-	for(x =0; x < 4; x++) {
+	for (x = 0; x < 4; x++) {
 		sprintf(p, "%u%s", i[x], x == 3 ? "" : ".");
 		p = buf + strlen(buf);
 	}
 	return buf;
 }
 
-SWITCH_DECLARE(char *) switch_get_addr(char *buf, switch_size_t len, switch_sockaddr_t *in)
-{
-    return get_addr(buf, len, &in->sa.sin.sin_addr);
-}
-
-SWITCH_DECLARE(apr_status_t) switch_socket_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock,
-                                                    apr_int32_t flags, char *buf, 
-                                                    apr_size_t *len)
-{
-	apr_status_t r;
-
-	if ((r = apr_socket_recvfrom(from, sock, flags, buf, len)) == APR_SUCCESS) {
-		from->port = ntohs(from->sa.sin.sin_port);
-		//from->ipaddr_ptr = &(from->sa.sin.sin_addr);
-		//from->ipaddr_ptr = inet_ntoa(from->sa.sin.sin_addr);
-	}
-
-	return r;
-
-}
-
 SWITCH_DECLARE(char) switch_rfc2833_to_char(int event)
 {
 	if (event > -1 && event < (int32_t) sizeof(RFC2833_CHARS)) {
@@ -394,55 +271,55 @@
 
 SWITCH_DECLARE(unsigned char) switch_char_to_rfc2833(char key)
 {
-    char *c;
+	char *c;
 	unsigned char counter = 0;
 
-    key = (char)toupper(key);
-    for (c = RFC2833_CHARS; *c ; c++) {
-        if (*c == key) {
-            return counter;
-        }
+	key = (char) toupper(key);
+	for (c = RFC2833_CHARS; *c; c++) {
+		if (*c == key) {
+			return counter;
+		}
 		counter++;
 	}
-    return '\0';
+	return '\0';
 }
 
 SWITCH_DECLARE(char *) switch_escape_char(switch_memory_pool_t *pool, char *in, char *delim, char esc)
 {
-    char *data, *p, *d;
-    int count = 1, i = 0;
+	char *data, *p, *d;
+	int count = 1, i = 0;
 
-    p = in;
-    while(*p) {
-        d = delim;
-        while (*d) {
-            if (*p == *d) {
-                count++;
-            }
-            d++;
-        }
-        p++;
-    }
+	p = in;
+	while (*p) {
+		d = delim;
+		while (*d) {
+			if (*p == *d) {
+				count++;
+			}
+			d++;
+		}
+		p++;
+	}
 
 	if (count == 1) {
 		return in;
 	}
 
 	data = switch_core_alloc(pool, strlen(in) + count);
-	
-    p = in;
-    while(*p) {
-        d = delim;
-        while (*d) {
-            if (*p == *d) {
-                data[i++] = esc;
-            }
-            d++;
-        }
-        data[i++] = *p;
-        p++;
-    }
-    return data;
+
+	p = in;
+	while (*p) {
+		d = delim;
+		while (*d) {
+			if (*p == *d) {
+				data[i++] = esc;
+			}
+			d++;
+		}
+		data[i++] = *p;
+		p++;
+	}
+	return data;
 }
 
 
@@ -484,7 +361,7 @@
 	}
 
 	/* strip quotes */
-	for(x = 0; x < argc; x++) {
+	for (x = 0; x < argc; x++) {
 		if (*(array[x]) == qc) {
 			(array[x])++;
 			if ((e = strchr(array[x], qc))) {
@@ -515,26 +392,6 @@
 	}
 }
 
-SWITCH_DECLARE(switch_status_t) switch_socket_create_pollfd(switch_pollfd_t *poll, switch_socket_t *sock,
-                                                            switch_int16_t flags, switch_memory_pool_t *pool)
-{
-	switch_pollset_t *pollset;
-
-	if (switch_pollset_create(&pollset, 1, pool, flags) != SWITCH_STATUS_SUCCESS) {
-		return SWITCH_STATUS_GENERR;
-	}
-
-	poll->desc_type = SWITCH_POLL_SOCKET;
-	poll->reqevents = flags;
-	poll->desc.s = sock;
-	poll->client_data = sock;
-
-	if (switch_pollset_add(pollset, poll) != SWITCH_STATUS_SUCCESS) {
-		return SWITCH_STATUS_GENERR;
-	}
-
-	return SWITCH_STATUS_SUCCESS;
-}
 
 SWITCH_DECLARE(switch_status_t) switch_string_match(const char *string, size_t string_len, const char *search, size_t search_len)
 {
@@ -544,8 +401,8 @@
 		if (string[i] != search[i]) {
 			return SWITCH_STATUS_FALSE;
 		}
-	}	
-	
+	}
+
 	if (i == search_len) {
 		return SWITCH_STATUS_SUCCESS;
 	}
@@ -561,21 +418,21 @@
 	size_t i, n;
 	size_t dest_len = 0;
 	char *dest;
-  
-	dest = (char *)malloc(sizeof(char));
+
+	dest = (char *) malloc(sizeof(char));
 
 	for (i = 0; i < string_len; i++) {
 		if (switch_string_match(string + i, string_len - i, search, search_len) == SWITCH_STATUS_SUCCESS) {
 			for (n = 0; n < replace_len; n++) {
 				dest[dest_len] = replace[n];
 				dest_len++;
-				dest = (char *)realloc(dest, sizeof(char)*(dest_len+1));
+				dest = (char *) realloc(dest, sizeof(char) * (dest_len + 1));
 			}
-			i += search_len-1;
+			i += search_len - 1;
 		} else {
 			dest[dest_len] = string[i];
 			dest_len++;
-			dest = (char *)realloc(dest, sizeof(char)*(dest_len+1));
+			dest = (char *) realloc(dest, sizeof(char) * (dest_len + 1));
 		}
 	}
 
@@ -583,7 +440,7 @@
 	return dest;
 }
 
-SWITCH_DECLARE(int) switch_socket_waitfor(switch_pollfd_t *poll, int ms)
+SWITCH_DECLARE(int) switch_socket_waitfor(switch_pollfd_t * poll, int ms)
 {
 	int nsds = 0;
 
@@ -595,37 +452,37 @@
 
 SWITCH_DECLARE(size_t) switch_url_encode(char *url, char *buf, size_t len)
 {
-    char *p;
-    size_t x = 0;
-    const char urlunsafe[] = "\r\n \"#%&+:;<=>?@[\\]^`{|}";
-    const char hex[] = "0123456789ABCDEF";
+	char *p;
+	size_t x = 0;
+	const char urlunsafe[] = "\r\n \"#%&+:;<=>?@[\\]^`{|}";
+	const char hex[] = "0123456789ABCDEF";
 
 	if (!buf) {
 		return 0;
 	}
 
-    memset(buf, 0, len);
+	memset(buf, 0, len);
 
 	if (!url) {
 		return 0;
 	}
 
-    for( p = url ; *p ; p++) {
-        if (*p < ' ' || *p > '~' || strchr(urlunsafe, *p)) {
-            if ((x + 3) > len) {
-                break;
-            }
-            buf[x++] = '%';
-            buf[x++] = hex[*p >> 4];
-            buf[x++] = hex[*p & 0x0f];
-        } else {
-            buf[x++] = *p;
-        }
-        if (x == len) {
-            break;
-        }
-    }
-    return x;
+	for (p = url; *p; p++) {
+		if (*p < ' ' || *p > '~' || strchr(urlunsafe, *p)) {
+			if ((x + 3) > len) {
+				break;
+			}
+			buf[x++] = '%';
+			buf[x++] = hex[*p >> 4];
+			buf[x++] = hex[*p & 0x0f];
+		} else {
+			buf[x++] = *p;
+		}
+		if (x == len) {
+			break;
+		}
+	}
+	return x;
 }
 
 SWITCH_DECLARE(char *) switch_url_decode(char *s)
@@ -635,7 +492,7 @@
 
 	for (o = s; *s; s++, o++) {
 		if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
-			*o = (char)tmp;
+			*o = (char) tmp;
 			s += 2;
 		} else {
 			*o = *s;
@@ -646,17 +503,6 @@
 }
 
 
-#ifdef WIN32
-//this forces certain symbols to not be optimized out of the dll
-void include_me(void)
-{
-	apr_socket_shutdown(NULL, 0);
-	apr_socket_recvfrom(NULL, NULL, 0, NULL, NULL);
-	apr_mcast_join(NULL, NULL, NULL, NULL);
-	apr_socket_opt_set(NULL, 0, 0);
-}
-#endif
-
 /* For Emacs:
  * Local Variables:
  * mode:c

Modified: freeswitch/branches/cparker/src/switch_xml.c
==============================================================================
--- freeswitch/branches/cparker/src/switch_xml.c	(original)
+++ freeswitch/branches/cparker/src/switch_xml.c	Tue Apr 24 10:14:28 2007
@@ -28,7 +28,7 @@
  *
  * switch_xml.c -- XML PARSER
  *
- * Derived from switch_xml http://switch_xml.sourceforge.net
+ * Derived from ezxml http://ezxml.sourceforge.net
  * Original Copyright
  *
  * Copyright 2004, 2006 Aaron Voisine <aaron at voisine.org>
@@ -54,38 +54,40 @@
  */
 
 #include <switch.h>
-#include <ctype.h>
-#include <sys/stat.h>
+#ifndef WIN32
+#include <switch_private.h>
+#endif
+
 #ifdef HAVE_MMAP
 #include <sys/mman.h>
 #endif
 
-#define SWITCH_XML_WS   "\t\r\n "  // whitespace
-#define SWITCH_XML_ERRL 128        // maximum error string length
+#define SWITCH_XML_WS   "\t\r\n "	// whitespace
+#define SWITCH_XML_ERRL 128		// maximum error string length
 
 typedef struct switch_xml_root *switch_xml_root_t;
-struct switch_xml_root {       // additional data for the root tag
-    struct switch_xml xml;     // is a super-struct built on top of switch_xml struct
-    switch_xml_t cur;          // current xml tree insertion point
-    char *m;              // original xml string
-    switch_size_t len;    // length of allocated memory for mmap
+struct switch_xml_root {		// additional data for the root tag
+	struct switch_xml xml;		// is a super-struct built on top of switch_xml struct
+	switch_xml_t cur;			// current xml tree insertion point
+	char *m;					// original xml string
+	switch_size_t len;			// length of allocated memory for mmap
 	uint8_t dynamic;
-    char *u;              // UTF-8 conversion of string if original was UTF-16
-    char *s;              // start of work area
-    char *e;              // end of work area
-    char **ent;           // general entities (ampersand sequences)
-    char ***attr;         // default attributes
-    char ***pi;           // processing instructions
-    short standalone;     // non-zero if <?xml standalone="yes"?>
-    char err[SWITCH_XML_ERRL]; // error string
+	char *u;					// UTF-8 conversion of string if original was UTF-16
+	char *s;					// start of work area
+	char *e;					// end of work area
+	char **ent;					// general entities (ampersand sequences)
+	char ***attr;				// default attributes
+	char ***pi;					// processing instructions
+	short standalone;			// non-zero if <?xml standalone="yes"?>
+	char err[SWITCH_XML_ERRL];	// error string
 };
 
-char *SWITCH_XML_NIL[] = { NULL }; // empty, null terminated array of strings
+char *SWITCH_XML_NIL[] = { NULL };	// empty, null terminated array of strings
 
 struct switch_xml_binding {
 	switch_xml_search_function_t function;
 	switch_xml_section_t sections;
-    void *user_data;
+	void *user_data;
 	struct switch_xml_binding *next;
 };
 
@@ -104,25 +106,25 @@
 
 
 static struct xml_section_t SECTIONS[] = {
-	{ "result", SWITCH_XML_SECTION_RESULT},
-	{ "config", SWITCH_XML_SECTION_CONFIG},
-	{ "directory", SWITCH_XML_SECTION_DIRECTORY},
-	{ "dialplan", SWITCH_XML_SECTION_DIALPLAN},
-	{ "phrases", SWITCH_XML_SECTION_PHRASES},
-	{ NULL, 0}
+	{"result", SWITCH_XML_SECTION_RESULT},
+	{"config", SWITCH_XML_SECTION_CONFIG},
+	{"directory", SWITCH_XML_SECTION_DIRECTORY},
+	{"dialplan", SWITCH_XML_SECTION_DIALPLAN},
+	{"phrases", SWITCH_XML_SECTION_PHRASES},
+	{NULL, 0}
 };
 
-SWITCH_DECLARE(switch_xml_section_t) switch_xml_parse_section_string(char *str)
+SWITCH_DECLARE(switch_xml_section_t) switch_xml_parse_section_string(const char *str)
 {
 	size_t x;
 	char buf[1024] = "";
 	switch_xml_section_t sections = SWITCH_XML_SECTION_RESULT;
 
 	if (str) {
-		for(x = 0; x < strlen(str); x++) {
-			buf[x] = (char)tolower((int)str[x]);
+		for (x = 0; x < strlen(str); x++) {
+			buf[x] = (char) tolower((int) str[x]);
 		}
-		for(x = 0;;x++) {
+		for (x = 0;; x++) {
 			if (!SECTIONS[x].name) {
 				break;
 			}
@@ -145,7 +147,7 @@
 
 	binding->function = function;
 	binding->sections = sections;
-    binding->user_data = user_data;
+	binding->user_data = user_data;
 
 	switch_mutex_lock(XML_LOCK);
 	for (ptr = BINDINGS; ptr && ptr->next; ptr = ptr->next);
@@ -156,7 +158,7 @@
 		BINDINGS = binding;
 	}
 	switch_mutex_unlock(XML_LOCK);
-	
+
 	return SWITCH_STATUS_SUCCESS;
 }
 
@@ -182,17 +184,19 @@
 // returns the first child tag with the given name or NULL if not found
 SWITCH_DECLARE(switch_xml_t) switch_xml_child(switch_xml_t xml, const char *name)
 {
-    xml = (xml) ? xml->child : NULL;
-    while (xml && strcmp(name, xml->name)) xml = xml->sibling;
-    return xml;
+	xml = (xml) ? xml->child : NULL;
+	while (xml && strcmp(name, xml->name))
+		xml = xml->sibling;
+	return xml;
 }
 
 // returns the Nth tag with the same name in the same subsection or NULL if not
 // found
 switch_xml_t switch_xml_idx(switch_xml_t xml, int idx)
 {
-    for (; xml && idx; idx--) xml = xml->next;
-    return xml;
+	for (; xml && idx; idx--)
+		xml = xml->next;
+	return xml;
 }
 
 // returns the value of the requested tag attribute or "" if not found
@@ -206,31 +210,37 @@
 // returns the value of the requested tag attribute or NULL if not found
 SWITCH_DECLARE(const char *) switch_xml_attr(switch_xml_t xml, const char *attr)
 {
-    int i = 0, j = 1;
-    switch_xml_root_t root = (switch_xml_root_t)xml;
+	int i = 0, j = 1;
+	switch_xml_root_t root = (switch_xml_root_t) xml;
 
-    if (! xml || ! xml->attr) return NULL;
-    while (xml->attr[i] && strcmp(attr, xml->attr[i])) i += 2;
-    if (xml->attr[i]) return xml->attr[i + 1]; // found attribute
-
-    while (root->xml.parent) root = (switch_xml_root_t)root->xml.parent; // root tag
-    for (i = 0; root->attr[i] && strcmp(xml->name, root->attr[i][0]); i++);
-    if (! root->attr[i]) return NULL; // no matching default attributes
-    while (root->attr[i][j] && strcmp(attr, root->attr[i][j])) j += 3;
-    return (root->attr[i][j]) ? root->attr[i][j + 1] : NULL; // found default
+	if (!xml || !xml->attr)
+		return NULL;
+	while (xml->attr[i] && strcmp(attr, xml->attr[i]))
+		i += 2;
+	if (xml->attr[i])
+		return xml->attr[i + 1];	// found attribute
+
+	while (root->xml.parent)
+		root = (switch_xml_root_t) root->xml.parent;	// root tag
+	for (i = 0; root->attr[i] && strcmp(xml->name, root->attr[i][0]); i++);
+	if (!root->attr[i])
+		return NULL;			// no matching default attributes
+	while (root->attr[i][j] && strcmp(attr, root->attr[i][j]))
+		j += 3;
+	return (root->attr[i][j]) ? root->attr[i][j + 1] : NULL;	// found default
 }
 
 // same as switch_xml_get but takes an already initialized va_list
 static switch_xml_t switch_xml_vget(switch_xml_t xml, va_list ap)
 {
-    char *name = va_arg(ap, char *);
-    int idx = -1;
+	char *name = va_arg(ap, char *);
+	int idx = -1;
 
-    if (name && *name) {
-        idx = va_arg(ap, int);    
-        xml = switch_xml_child(xml, name);
-    }
-    return (idx < 0) ? xml : switch_xml_vget(switch_xml_idx(xml, idx), ap);
+	if (name && *name) {
+		idx = va_arg(ap, int);
+		xml = switch_xml_child(xml, name);
+	}
+	return (idx < 0) ? xml : switch_xml_vget(switch_xml_idx(xml, idx), ap);
 }
 
 // Traverses the xml tree to retrieve a specific subtag. Takes a variable
@@ -239,45 +249,50 @@
 // title = switch_xml_get(library, "shelf", 0, "book", 2, "title", -1);
 // This retrieves the title of the 3rd book on the 1st shelf of library.
 // Returns NULL if not found.
-SWITCH_DECLARE(switch_xml_t) switch_xml_get(switch_xml_t xml, ...)
+SWITCH_DECLARE(switch_xml_t) switch_xml_get(switch_xml_t xml,...)
 {
-    va_list ap;
-    switch_xml_t r;
+	va_list ap;
+	switch_xml_t r;
 
-    va_start(ap, xml);
-    r = switch_xml_vget(xml, ap);
-    va_end(ap);
-    return r;
+	va_start(ap, xml);
+	r = switch_xml_vget(xml, ap);
+	va_end(ap);
+	return r;
 }
 
 // returns a null terminated array of processing instructions for the given
 // target
 SWITCH_DECLARE(const char **) switch_xml_pi(switch_xml_t xml, const char *target)
 {
-    switch_xml_root_t root = (switch_xml_root_t)xml;
-    int i = 0;
+	switch_xml_root_t root = (switch_xml_root_t) xml;
+	int i = 0;
 
-    if (! root) return (const char **)SWITCH_XML_NIL;
-    while (root->xml.parent) root = (switch_xml_root_t)root->xml.parent; // root tag
-    while (root->pi[i] && strcmp(target, root->pi[i][0])) i++; // find target
-    return (const char **)((root->pi[i]) ? root->pi[i] + 1 : SWITCH_XML_NIL);
+	if (!root)
+		return (const char **) SWITCH_XML_NIL;
+	while (root->xml.parent)
+		root = (switch_xml_root_t) root->xml.parent;	// root tag
+	while (root->pi[i] && strcmp(target, root->pi[i][0]))
+		i++;					// find target
+	return (const char **) ((root->pi[i]) ? root->pi[i] + 1 : SWITCH_XML_NIL);
 }
 
 // set an error string and return root
 static switch_xml_t switch_xml_err(switch_xml_root_t root, char *s, const char *err, ...)
 {
-    va_list ap;
-    int line = 1;
-    char *t, fmt[SWITCH_XML_ERRL];
-    
-    for (t = root->s; t && t < s; t++) if (*t == '\n') line++;
-    snprintf(fmt, SWITCH_XML_ERRL, "[error near line %d]: %s", line, err);
-
-    va_start(ap, err);
-    vsnprintf(root->err, SWITCH_XML_ERRL, fmt, ap);
-    va_end(ap);
+	va_list ap;
+	int line = 1;
+	char *t, fmt[SWITCH_XML_ERRL];
+
+	for (t = root->s; t && t < s; t++)
+		if (*t == '\n')
+			line++;
+	snprintf(fmt, SWITCH_XML_ERRL, "[error near line %d]: %s", line, err);
+
+	va_start(ap, err);
+	vsnprintf(root->err, SWITCH_XML_ERRL, fmt, ap);
+	va_end(ap);
 
-    return &root->xml;
+	return &root->xml;
 }
 
 // Recursively decodes entity and character references and normalizes new lines
@@ -288,467 +303,540 @@
 // s, returns a malloced string that must be freed.
 static char *switch_xml_decode(char *s, char **ent, char t)
 {
-    char *e, *r = s, *m = s;
-    long b, c, d, l;
+	char *e, *r = s, *m = s;
+	long b, c, d, l;
+
+	for (; *s; s++) {			// normalize line endings
+		while (*s == '\r') {
+			*(s++) = '\n';
+			if (*s == '\n')
+				memmove(s, (s + 1), strlen(s));
+		}
+	}
+
+	for (s = r;;) {
+		while (*s && *s != '&' && (*s != '%' || t != '%') && !isspace((int) (*s)))
+			s++;
+
+		if (!*s)
+			break;
+		else if (t != 'c' && !strncmp(s, "&#", 2)) {	// character reference
+			if (s[2] == 'x')
+				c = strtol(s + 3, &e, 16);	// base 16
+			else
+				c = strtol(s + 2, &e, 10);	// base 10
+			if (!c || *e != ';') {
+				s++;
+				continue;
+			}					// not a character ref
+
+			if (c < 0x80)
+				*(s++) = (char) c;	// US-ASCII subset
+			else {				// multi-byte UTF-8 sequence
+				for (b = 0, d = c; d; d /= 2)
+					b++;		// number of bits in c
+				b = (b - 2) / 5;	// number of bytes in payload
+				*(s++) = (char) ((0xFF << (7 - b)) | (c >> (6 * b)));	// head
+				while (b)
+					*(s++) = (char) (0x80 | ((c >> (6 * --b)) & 0x3F));	// payload
+			}
 
-    for (; *s; s++) { // normalize line endings
-        while (*s == '\r') {
-            *(s++) = '\n';
-            if (*s == '\n') memmove(s, (s + 1), strlen(s));
-        }
-    }
-    
-    for (s = r; ; ) {
-        while (*s && *s != '&' && (*s != '%' || t != '%') && !isspace((int)(*s))) s++;
-
-        if (! *s) break;
-        else if (t != 'c' && ! strncmp(s, "&#", 2)) { // character reference
-            if (s[2] == 'x') c = strtol(s + 3, &e, 16); // base 16
-            else c = strtol(s + 2, &e, 10); // base 10
-            if (! c || *e != ';') { s++; continue; } // not a character ref
-
-            if (c < 0x80) *(s++) = (char)c; // US-ASCII subset
-            else { // multi-byte UTF-8 sequence
-                for (b = 0, d = c; d; d /= 2) b++; // number of bits in c
-                b = (b - 2) / 5; // number of bytes in payload
-                *(s++) = (char)((0xFF << (7 - b)) | (c >> (6 * b))); // head
-                while (b) *(s++) = (char)(0x80 | ((c >> (6 * --b)) & 0x3F)); // payload
-            }
-
-            memmove(s, strchr(s, ';') + 1, strlen(strchr(s, ';')));
-        }
-        else if ((*s == '&' && (t == '&' || t == ' ' || t == '*')) ||
-                 (*s == '%' && t == '%')) { // entity reference
-            for (b = 0; ent[b] && strncmp(s + 1, ent[b], strlen(ent[b]));
-                 b += 2); // find entity in entity list
-
-            if (ent[b++]) { // found a match
-                if ((c = (long)strlen(ent[b])) - 1 > (e = strchr(s, ';')) - s) {
-                    l = (d = (long)(s - r)) + c + (long)strlen(e); // new length
-                    r = (r == m) ? strcpy(malloc(l), r) : realloc(r, l);
-                    e = strchr((s = r + d), ';'); // fix up pointers
-                }
-
-                memmove(s + c, e + 1, strlen(e)); // shift rest of string
-                strncpy(s, ent[b], c); // copy in replacement text
-            }
-            else s++; // not a known entity
-        }
-        else if ((t == ' ' || t == '*') && isspace((int)(*s))) *(s++) = ' ';
-        else s++; // no decoding needed
-    }
-
-    if (t == '*') { // normalize spaces for non-cdata attributes
-        for (s = r; *s; s++) {
-            if ((l = (long)strspn(s, " "))) memmove(s, s + l, strlen(s + l) + 1);
-            while (*s && *s != ' ') s++;
-        }
-        if (--s >= r && *s == ' ') *s = '\0'; // trim any trailing space
-    }
-    return r;
+			memmove(s, strchr(s, ';') + 1, strlen(strchr(s, ';')));
+		} else if ((*s == '&' && (t == '&' || t == ' ' || t == '*')) || (*s == '%' && t == '%')) {	// entity reference
+			for (b = 0; ent[b] && strncmp(s + 1, ent[b], strlen(ent[b])); b += 2);	// find entity in entity list
+
+			if (ent[b++]) {		// found a match
+				if ((c = (long) strlen(ent[b])) - 1 > (e = strchr(s, ';')) - s) {
+					l = (d = (long) (s - r)) + c + (long) strlen(e);	// new length
+					r = (r == m) ? strcpy(malloc(l), r) : realloc(r, l);
+					e = strchr((s = r + d), ';');	// fix up pointers
+				}
+
+				memmove(s + c, e + 1, strlen(e));	// shift rest of string
+				strncpy(s, ent[b], c);	// copy in replacement text
+			} else
+				s++;			// not a known entity
+		} else if ((t == ' ' || t == '*') && isspace((int) (*s)))
+			*(s++) = ' ';
+		else
+			s++;				// no decoding needed
+	}
+
+	if (t == '*') {				// normalize spaces for non-cdata attributes
+		for (s = r; *s; s++) {
+			if ((l = (long) strspn(s, " ")))
+				memmove(s, s + l, strlen(s + l) + 1);
+			while (*s && *s != ' ')
+				s++;
+		}
+		if (--s >= r && *s == ' ')
+			*s = '\0';			// trim any trailing space
+	}
+	return r;
 }
 
 // called when parser finds start of new tag
 static void switch_xml_open_tag(switch_xml_root_t root, char *name, char **attr)
 {
-    switch_xml_t xml = root->cur;
-    
-    if (xml->name) xml = switch_xml_add_child(xml, name, strlen(xml->txt));
-    else xml->name = name; // first open tag
+	switch_xml_t xml = root->cur;
+
+	if (xml->name)
+		xml = switch_xml_add_child(xml, name, strlen(xml->txt));
+	else
+		xml->name = name;		// first open tag
 
-    xml->attr = attr;
-    root->cur = xml; // update tag insertion point
+	xml->attr = attr;
+	root->cur = xml;			// update tag insertion point
 }
 
 // called when parser finds character content between open and closing tag
 static void switch_xml_char_content(switch_xml_root_t root, char *s, switch_size_t len, char t)
 {
-    switch_xml_t xml = root->cur;
-    char *m = s;
-    switch_size_t l;
-
-    if (! xml || ! xml->name || ! len) return; // sanity check
-
-    s[len] = '\0'; // null terminate text (calling functions anticipate this)
-    len = strlen(s = switch_xml_decode(s, root->ent, t)) + 1;
-
-    if (! *(xml->txt)) xml->txt = s; // initial character content
-    else { // allocate our own memory and make a copy
-        xml->txt = (xml->flags & SWITCH_XML_TXTM) // allocate some space
-                   ? realloc(xml->txt, (l = strlen(xml->txt)) + len)
-                   : strcpy(malloc((l = strlen(xml->txt)) + len), xml->txt);
-        strcpy(xml->txt + l, s); // add new char content
-        if (s != m) free(s); // free s if it was malloced by switch_xml_decode()
-    }
+	switch_xml_t xml = root->cur;
+	char *m = s;
+	switch_size_t l;
+
+	if (!xml || !xml->name || !len)
+		return;					// sanity check
+
+	s[len] = '\0';				// null terminate text (calling functions anticipate this)
+	len = strlen(s = switch_xml_decode(s, root->ent, t)) + 1;
+
+	if (!*(xml->txt))
+		xml->txt = s;			// initial character content
+	else {						// allocate our own memory and make a copy
+		xml->txt = (xml->flags & SWITCH_XML_TXTM)	// allocate some space
+			? realloc(xml->txt, (l = strlen(xml->txt)) + len)
+			: strcpy(malloc((l = strlen(xml->txt)) + len), xml->txt);
+		strcpy(xml->txt + l, s);	// add new char content
+		if (s != m)
+			free(s);			// free s if it was malloced by switch_xml_decode()
+	}
 
-    if (xml->txt != m) switch_xml_set_flag(xml, SWITCH_XML_TXTM);
+	if (xml->txt != m)
+		switch_xml_set_flag(xml, SWITCH_XML_TXTM);
 }
 
 // called when parser finds closing tag
 static switch_xml_t switch_xml_close_tag(switch_xml_root_t root, char *name, char *s)
 {
-    if (! root->cur || ! root->cur->name || strcmp(name, root->cur->name))
-        return switch_xml_err(root, s, "unexpected closing tag </%s>", name);
+	if (!root->cur || !root->cur->name || strcmp(name, root->cur->name))
+		return switch_xml_err(root, s, "unexpected closing tag </%s>", name);
 
-    root->cur = root->cur->parent;
-    return NULL;
+	root->cur = root->cur->parent;
+	return NULL;
 }
 
 // checks for circular entity references, returns non-zero if no circular
 // references are found, zero otherwise
 static int switch_xml_ent_ok(char *name, char *s, char **ent)
 {
-    int i;
+	int i;
 
-    for (; ; s++) {
-        while (*s && *s != '&') s++; // find next entity reference
-        if (! *s) return 1;
-        if (! strncmp(s + 1, name, strlen(name))) return 0; // circular ref.
-        for (i = 0; ent[i] && strncmp(ent[i], s + 1, strlen(ent[i])); i += 2);
-        if (ent[i] && ! switch_xml_ent_ok(name, ent[i + 1], ent)) return 0;
-    }
+	for (;; s++) {
+		while (*s && *s != '&')
+			s++;				// find next entity reference
+		if (!*s)
+			return 1;
+		if (!strncmp(s + 1, name, strlen(name)))
+			return 0;			// circular ref.
+		for (i = 0; ent[i] && strncmp(ent[i], s + 1, strlen(ent[i])); i += 2);
+		if (ent[i] && !switch_xml_ent_ok(name, ent[i + 1], ent))
+			return 0;
+	}
 }
 
 // called when the parser finds a processing instruction
 static void switch_xml_proc_inst(switch_xml_root_t root, char *s, switch_size_t len)
 {
-    int i = 0, j = 1;
-    char *target = s;
+	int i = 0, j = 1;
+	char *target = s;
+
+	s[len] = '\0';				// null terminate instruction
+	if (*(s += strcspn(s, SWITCH_XML_WS))) {
+		*s = '\0';				// null terminate target
+		s += strspn(s + 1, SWITCH_XML_WS) + 1;	// skip whitespace after target
+	}
+
+	if (!strcmp(target, "xml")) {	// <?xml ... ?>
+		if ((s = strstr(s, "standalone")) && !strncmp(s + strspn(s + 10, SWITCH_XML_WS "='\"") + 10, "yes", 3))
+			root->standalone = 1;
+		return;
+	}
 
-    s[len] = '\0'; // null terminate instruction
-    if (*(s += strcspn(s, SWITCH_XML_WS))) {
-        *s = '\0'; // null terminate target
-        s += strspn(s + 1, SWITCH_XML_WS) + 1; // skip whitespace after target
-    }
-
-    if (! strcmp(target, "xml")) { // <?xml ... ?>
-        if ((s = strstr(s, "standalone")) && ! strncmp(s + strspn(s + 10,
-            SWITCH_XML_WS "='\"") + 10, "yes", 3)) root->standalone = 1;
-        return;
-    }
-
-    if (! root->pi[0]) *(root->pi = malloc(sizeof(char **))) = NULL; //first pi
-
-    while (root->pi[i] && strcmp(target, root->pi[i][0])) i++; // find target
-    if (! root->pi[i]) { // new target
-        root->pi = realloc(root->pi, sizeof(char **) * (i + 2));
-        root->pi[i] = malloc(sizeof(char *) * 3);
-        root->pi[i][0] = target;
-        root->pi[i][1] = (char *)(root->pi[i + 1] = NULL); // terminate pi list
-        root->pi[i][2] = strdup(""); // empty document position list
-    }
-
-    while (root->pi[i][j]) j++; // find end of instruction list for this target
-    root->pi[i] = realloc(root->pi[i], sizeof(char *) * (j + 3));
-    root->pi[i][j + 2] = realloc(root->pi[i][j + 1], j + 1);
-    strcpy(root->pi[i][j + 2] + j - 1, (root->xml.name) ? ">" : "<");
-    root->pi[i][j + 1] = NULL; // null terminate pi list for this target
-    root->pi[i][j] = s; // set instruction
+	if (!root->pi[0])
+		*(root->pi = malloc(sizeof(char **))) = NULL;	//first pi
+
+	while (root->pi[i] && strcmp(target, root->pi[i][0]))
+		i++;					// find target
+	if (!root->pi[i]) {			// new target
+		root->pi = realloc(root->pi, sizeof(char **) * (i + 2));
+		root->pi[i] = malloc(sizeof(char *) * 3);
+		root->pi[i][0] = target;
+		root->pi[i][1] = (char *) (root->pi[i + 1] = NULL);	// terminate pi list
+		root->pi[i][2] = strdup("");	// empty document position list
+	}
+
+	while (root->pi[i][j])
+		j++;					// find end of instruction list for this target
+	root->pi[i] = realloc(root->pi[i], sizeof(char *) * (j + 3));
+	root->pi[i][j + 2] = realloc(root->pi[i][j + 1], j + 1);
+	strcpy(root->pi[i][j + 2] + j - 1, (root->xml.name) ? ">" : "<");
+	root->pi[i][j + 1] = NULL;	// null terminate pi list for this target
+	root->pi[i][j] = s;			// set instruction
 }
 
 // called when the parser finds an internal doctype subset
 static short switch_xml_internal_dtd(switch_xml_root_t root, char *s, switch_size_t len)
 {
-    char q, *c, *t, *n = NULL, *v, **ent, **pe;
-    int i, j;
-    
-    pe = memcpy(malloc(sizeof(SWITCH_XML_NIL)), SWITCH_XML_NIL, sizeof(SWITCH_XML_NIL));
-
-    for (s[len] = '\0'; s; ) {
-        while (*s && *s != '<' && *s != '%') s++; // find next declaration
-
-        if (! *s) break;
-        else if (! strncmp(s, "<!ENTITY", 8)) { // parse entity definitions
-            c = s += strspn(s + 8, SWITCH_XML_WS) + 8; // skip white space separator
-            n = s + strspn(s, SWITCH_XML_WS "%"); // find name
-            *(s = n + strcspn(n, SWITCH_XML_WS)) = ';'; // append ; to name
-
-            v = s + strspn(s + 1, SWITCH_XML_WS) + 1; // find value
-            if ((q = *(v++)) != '"' && q != '\'') { // skip externals
-                s = strchr(s, '>');
-                continue;
-            }
-
-            for (i = 0, ent = (*c == '%') ? pe : root->ent; ent[i]; i++);
-            ent = realloc(ent, (i + 3) * sizeof(char *)); // space for next ent
-            if (*c == '%') pe = ent;
-            else root->ent = ent;
-
-            *(++s) = '\0'; // null terminate name
-            if ((s = strchr(v, q))) *(s++) = '\0'; // null terminate value
-            ent[i + 1] = switch_xml_decode(v, pe, '%'); // set value
-            ent[i + 2] = NULL; // null terminate entity list
-            if (! switch_xml_ent_ok(n, ent[i + 1], ent)) { // circular reference
-                if (ent[i + 1] != v) free(ent[i + 1]);
-                switch_xml_err(root, v, "circular entity declaration &%s", n);
-                break;
-            }
-            else ent[i] = n; // set entity name
-        }
-        else if (! strncmp(s, "<!ATTLIST", 9)) { // parse default attributes
-            t = s + strspn(s + 9, SWITCH_XML_WS) + 9; // skip whitespace separator
-            if (! *t) { switch_xml_err(root, t, "unclosed <!ATTLIST"); break; }
-            if (*(s = t + strcspn(t, SWITCH_XML_WS ">")) == '>') continue;
-            else *s = '\0'; // null terminate tag name
-            for (i = 0; root->attr[i] && strcmp(n, root->attr[i][0]); i++);
-
-            while (*(n = ++s + strspn(s, SWITCH_XML_WS)) && *n != '>') {
-                if (*(s = n + strcspn(n, SWITCH_XML_WS))) *s = '\0'; // attr name
-                else { switch_xml_err(root, t, "malformed <!ATTLIST"); break; }
-
-                s += strspn(s + 1, SWITCH_XML_WS) + 1; // find next token
-                c = (strncmp(s, "CDATA", 5)) ? "*" : " "; // is it cdata?
-                if (! strncmp(s, "NOTATION", 8))
-                    s += strspn(s + 8, SWITCH_XML_WS) + 8;
-                s = (*s == '(') ? strchr(s, ')') : s + strcspn(s, SWITCH_XML_WS);
-                if (! s) { switch_xml_err(root, t, "malformed <!ATTLIST"); break; }
-
-                s += strspn(s, SWITCH_XML_WS ")"); // skip white space separator
-                if (! strncmp(s, "#FIXED", 6))
-                    s += strspn(s + 6, SWITCH_XML_WS) + 6;
-                if (*s == '#') { // no default value
-                    s += strcspn(s, SWITCH_XML_WS ">") - 1;
-                    if (*c == ' ') continue; // cdata is default, nothing to do
-                    v = NULL;
-                }
-                else if ((*s == '"' || *s == '\'')  &&  // default value
-                         (s = strchr(v = s + 1, *s))) *s = '\0';
-                else { switch_xml_err(root, t, "malformed <!ATTLIST"); break; }
-
-                if (! root->attr[i]) { // new tag name
-                    root->attr = (! i) ? malloc(2 * sizeof(char **))
-                                       : realloc(root->attr,
-                                                 (i + 2) * sizeof(char **));
-                    root->attr[i] = malloc(2 * sizeof(char *));
-                    root->attr[i][0] = t; // set tag name
-                    root->attr[i][1] = (char *)(root->attr[i + 1] = NULL);
-                }
-
-                for (j = 1; root->attr[i][j]; j += 3); // find end of list
-                root->attr[i] = realloc(root->attr[i],
-                                        (j + 4) * sizeof(char *));
-
-                root->attr[i][j + 3] = NULL; // null terminate list
-                root->attr[i][j + 2] = c; // is it cdata?
-                root->attr[i][j + 1] = (v) ? switch_xml_decode(v, root->ent, *c)
-                                           : NULL;
-                root->attr[i][j] = n; // attribute name 
-            }
-        }
-        else if (! strncmp(s, "<!--", 4)) s = strstr(s + 4, "-->"); // comments
-        else if (! strncmp(s, "<?", 2)) { // processing instructions
-            if ((s = strstr(c = s + 2, "?>")))
-                switch_xml_proc_inst(root, c, s++ - c);
-        }
-        else if (*s == '<') s = strchr(s, '>'); // skip other declarations
-        else if (*(s++) == '%' && ! root->standalone) break;
-    }
+	char q, *c, *t, *n = NULL, *v, **ent, **pe;
+	int i, j;
+
+	pe = memcpy(malloc(sizeof(SWITCH_XML_NIL)), SWITCH_XML_NIL, sizeof(SWITCH_XML_NIL));
+
+	for (s[len] = '\0'; s;) {
+		while (*s && *s != '<' && *s != '%')
+			s++;				// find next declaration
+
+		if (!*s)
+			break;
+		else if (!strncmp(s, "<!ENTITY", 8)) {	// parse entity definitions
+			c = s += strspn(s + 8, SWITCH_XML_WS) + 8;	// skip white space separator
+			n = s + strspn(s, SWITCH_XML_WS "%");	// find name
+			*(s = n + strcspn(n, SWITCH_XML_WS)) = ';';	// append ; to name
+
+			v = s + strspn(s + 1, SWITCH_XML_WS) + 1;	// find value
+			if ((q = *(v++)) != '"' && q != '\'') {	// skip externals
+				s = strchr(s, '>');
+				continue;
+			}
+
+			for (i = 0, ent = (*c == '%') ? pe : root->ent; ent[i]; i++);
+			ent = realloc(ent, (i + 3) * sizeof(char *));	// space for next ent
+			if (*c == '%')
+				pe = ent;
+			else
+				root->ent = ent;
+
+			*(++s) = '\0';		// null terminate name
+			if ((s = strchr(v, q)))
+				*(s++) = '\0';	// null terminate value
+			ent[i + 1] = switch_xml_decode(v, pe, '%');	// set value
+			ent[i + 2] = NULL;	// null terminate entity list
+			if (!switch_xml_ent_ok(n, ent[i + 1], ent)) {	// circular reference
+				if (ent[i + 1] != v)
+					free(ent[i + 1]);
+				switch_xml_err(root, v, "circular entity declaration &%s", n);
+				break;
+			} else
+				ent[i] = n;		// set entity name
+		} else if (!strncmp(s, "<!ATTLIST", 9)) {	// parse default attributes
+			t = s + strspn(s + 9, SWITCH_XML_WS) + 9;	// skip whitespace separator
+			if (!*t) {
+				switch_xml_err(root, t, "unclosed <!ATTLIST");
+				break;
+			}
+			if (*(s = t + strcspn(t, SWITCH_XML_WS ">")) == '>')
+				continue;
+			else
+				*s = '\0';		// null terminate tag name
+			for (i = 0; root->attr[i] && strcmp(n, root->attr[i][0]); i++);
+
+			while (*(n = ++s + strspn(s, SWITCH_XML_WS)) && *n != '>') {
+				if (*(s = n + strcspn(n, SWITCH_XML_WS)))
+					*s = '\0';	// attr name
+				else {
+					switch_xml_err(root, t, "malformed <!ATTLIST");
+					break;
+				}
+
+				s += strspn(s + 1, SWITCH_XML_WS) + 1;	// find next token
+				c = (strncmp(s, "CDATA", 5)) ? "*" : " ";	// is it cdata?
+				if (!strncmp(s, "NOTATION", 8))
+					s += strspn(s + 8, SWITCH_XML_WS) + 8;
+				s = (*s == '(') ? strchr(s, ')') : s + strcspn(s, SWITCH_XML_WS);
+				if (!s) {
+					switch_xml_err(root, t, "malformed <!ATTLIST");
+					break;
+				}
+
+				s += strspn(s, SWITCH_XML_WS ")");	// skip white space separator
+				if (!strncmp(s, "#FIXED", 6))
+					s += strspn(s + 6, SWITCH_XML_WS) + 6;
+				if (*s == '#') {	// no default value
+					s += strcspn(s, SWITCH_XML_WS ">") - 1;
+					if (*c == ' ')
+						continue;	// cdata is default, nothing to do
+					v = NULL;
+				} else if ((*s == '"' || *s == '\'') &&	// default value
+						   (s = strchr(v = s + 1, *s)))
+					*s = '\0';
+				else {
+					switch_xml_err(root, t, "malformed <!ATTLIST");
+					break;
+				}
+
+				if (!root->attr[i]) {	// new tag name
+					root->attr = (!i) ? malloc(2 * sizeof(char **))
+						: realloc(root->attr, (i + 2) * sizeof(char **));
+					root->attr[i] = malloc(2 * sizeof(char *));
+					root->attr[i][0] = t;	// set tag name
+					root->attr[i][1] = (char *) (root->attr[i + 1] = NULL);
+				}
+
+				for (j = 1; root->attr[i][j]; j += 3);	// find end of list
+				root->attr[i] = realloc(root->attr[i], (j + 4) * sizeof(char *));
+
+				root->attr[i][j + 3] = NULL;	// null terminate list
+				root->attr[i][j + 2] = c;	// is it cdata?
+				root->attr[i][j + 1] = (v) ? switch_xml_decode(v, root->ent, *c)
+					: NULL;
+				root->attr[i][j] = n;	// attribute name 
+			}
+		} else if (!strncmp(s, "<!--", 4))
+			s = strstr(s + 4, "-->");	// comments
+		else if (!strncmp(s, "<?", 2)) {	// processing instructions
+			if ((s = strstr(c = s + 2, "?>")))
+				switch_xml_proc_inst(root, c, s++ - c);
+		} else if (*s == '<')
+			s = strchr(s, '>');	// skip other declarations
+		else if (*(s++) == '%' && !root->standalone)
+			break;
+	}
 
-    free(pe);
-    return ! *root->err;
+	free(pe);
+	return !*root->err;
 }
 
 // Converts a UTF-16 string to UTF-8. Returns a new string that must be freed
 // or NULL if no conversion was needed.
 static char *switch_xml_str2utf8(char **s, switch_size_t *len)
 {
-    char *u;
-    switch_size_t l = 0, sl, max = *len;
-    long c, d;
-    int b, be = (**s == '\xFE') ? 1 : (**s == '\xFF') ? 0 : -1;
-
-    if (be == -1) return NULL; // not UTF-16
-
-    u = malloc(max);
-    for (sl = 2; sl < *len - 1; sl += 2) {
-        c = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)  //UTF-16BE
-                 : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF); //UTF-16LE
-        if (c >= 0xD800 && c <= 0xDFFF && (sl += 2) < *len - 1) { // high-half
-            d = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)
-                     : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF);
-            c = (((c & 0x3FF) << 10) | (d & 0x3FF)) + 0x10000;
-        }
-
-        while (l + 6 > max) u = realloc(u, max += SWITCH_XML_BUFSIZE);
-        if (c < 0x80) u[l++] = (char)c; // US-ASCII subset
-        else { // multi-byte UTF-8 sequence
-            for (b = 0, d = c; d; d /= 2) b++; // bits in c
-            b = (b - 2) / 5; // bytes in payload
-            u[l++] = (char)((0xFF << (7 - b)) | (c >> (6 * b))); // head
-            while (b) u[l++] = (char)(0x80 | ((c >> (6 * --b)) & 0x3F)); // payload
-        }
-    }
-    return *s = realloc(u, *len = l);
+	char *u;
+	switch_size_t l = 0, sl, max = *len;
+	long c, d;
+	int b, be = (**s == '\xFE') ? 1 : (**s == '\xFF') ? 0 : -1;
+
+	if (be == -1)
+		return NULL;			// not UTF-16
+
+	u = malloc(max);
+	for (sl = 2; sl < *len - 1; sl += 2) {
+		c = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)	//UTF-16BE
+			: (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF);	//UTF-16LE
+		if (c >= 0xD800 && c <= 0xDFFF && (sl += 2) < *len - 1) {	// high-half
+			d = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)
+				: (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF);
+			c = (((c & 0x3FF) << 10) | (d & 0x3FF)) + 0x10000;
+		}
+
+		while (l + 6 > max)
+			u = realloc(u, max += SWITCH_XML_BUFSIZE);
+		if (c < 0x80)
+			u[l++] = (char) c;	// US-ASCII subset
+		else {					// multi-byte UTF-8 sequence
+			for (b = 0, d = c; d; d /= 2)
+				b++;			// bits in c
+			b = (b - 2) / 5;	// bytes in payload
+			u[l++] = (char) ((0xFF << (7 - b)) | (c >> (6 * b)));	// head
+			while (b)
+				u[l++] = (char) (0x80 | ((c >> (6 * --b)) & 0x3F));	// payload
+		}
+	}
+	return *s = realloc(u, *len = l);
 }
 
 // frees a tag attribute list
-static void switch_xml_free_attr(char **attr) {
-    int i = 0;
-    char *m;
-    
-    if (! attr || attr == SWITCH_XML_NIL) return; // nothing to free
-    while (attr[i]) i += 2; // find end of attribute list
-    m = attr[i + 1]; // list of which names and values are malloced
-    for (i = 0; m[i]; i++) {
-        if (m[i] & SWITCH_XML_NAMEM) free(attr[i * 2]);
-        if (m[i] & SWITCH_XML_TXTM) free(attr[(i * 2) + 1]);
-    }
-    free(m);
-    free(attr);
+static void switch_xml_free_attr(char **attr)
+{
+	int i = 0;
+	char *m;
+
+	if (!attr || attr == SWITCH_XML_NIL)
+		return;					// nothing to free
+	while (attr[i])
+		i += 2;					// find end of attribute list
+	m = attr[i + 1];			// list of which names and values are malloced
+	for (i = 0; m[i]; i++) {
+		if (m[i] & SWITCH_XML_NAMEM)
+			free(attr[i * 2]);
+		if (m[i] & SWITCH_XML_TXTM)
+			free(attr[(i * 2) + 1]);
+	}
+	free(m);
+	free(attr);
 }
 
 // parse the given xml string and return an switch_xml structure
 SWITCH_DECLARE(switch_xml_t) switch_xml_parse_str(char *s, switch_size_t len)
 {
-    switch_xml_root_t root = (switch_xml_root_t)switch_xml_new(NULL);
-    char q, e, *d, **attr, **a = NULL; // initialize a to avoid compile warning
-    int l, i, j;
-
-    root->m = s;
-    if (! len) return switch_xml_err(root, s, "root tag missing");
-    root->u = switch_xml_str2utf8(&s, &len); // convert utf-16 to utf-8
-    root->e = (root->s = s) + len; // record start and end of work area
-    
-    e = s[len - 1]; // save end char
-    s[len - 1] = '\0'; // turn end char into null terminator
-
-    while (*s && *s != '<') s++; // find first tag
-    if (! *s) return switch_xml_err(root, s, "root tag missing");
-
-    for (; ; ) {
-        attr = (char **)SWITCH_XML_NIL;
-        d = ++s;
-        
-        if (isalpha((int)(*s)) || *s == '_' || *s == ':' || (int8_t) *s < '\0') { // new tag
-            if (! root->cur)
-                return switch_xml_err(root, d, "markup outside of root element");
-
-            s += strcspn(s, SWITCH_XML_WS "/>");
-            while (isspace((int)(*s))) *(s++) = '\0'; // null terminate tag name
-  
-            if (*s && *s != '/' && *s != '>') // find tag in default attr list
-                for (i = 0; (a = root->attr[i]) && strcmp(a[0], d); i++);
-
-            for (l = 0; *s && *s != '/' && *s != '>'; l += 2) { // new attrib
-                attr = (l) ? realloc(attr, (l + 4) * sizeof(char *))
-                           : malloc(4 * sizeof(char *)); // allocate space
-                attr[l + 3] = (l) ? realloc(attr[l + 1], (l / 2) + 2)
-                                  : malloc(2); // mem for list of maloced vals
-                strcpy(attr[l + 3] + (l / 2), " "); // value is not malloced
-                attr[l + 2] = NULL; // null terminate list
-                attr[l + 1] = ""; // temporary attribute value
-                attr[l] = s; // set attribute name
-
-                s += strcspn(s, SWITCH_XML_WS "=/>");
-                if (*s == '=' || isspace((int)(*s))) { 
-                    *(s++) = '\0'; // null terminate tag attribute name
-                    q = *(s += strspn(s, SWITCH_XML_WS "="));
-                    if (q == '"' || q == '\'') { // attribute value
-                        attr[l + 1] = ++s;
-                        while (*s && *s != q) s++;
-                        if (*s) *(s++) = '\0'; // null terminate attribute val
-                        else {
-                            switch_xml_free_attr(attr);
-                            return switch_xml_err(root, d, "missing %c", q);
-                        }
-
-                        for (j = 1; a && a[j] && strcmp(a[j], attr[l]); j +=3);
-                        attr[l + 1] = switch_xml_decode(attr[l + 1], root->ent, (a
-                                                   && a[j]) ? *a[j + 2] : ' ');
-                        if (attr[l + 1] < d || attr[l + 1] > s)
-                            attr[l + 3][l / 2] = SWITCH_XML_TXTM; // value malloced
-                    }
-                }
-                while (isspace((int)(*s))) s++;
-            }
-
-            if (*s == '/') { // self closing tag
-                *(s++) = '\0';
-                if ((*s && *s != '>') || (! *s && e != '>')) {
-                    if (l) switch_xml_free_attr(attr);
-                    return switch_xml_err(root, d, "missing >");
-                }
-                switch_xml_open_tag(root, d, attr);
-                switch_xml_close_tag(root, d, s);
-            }
-            else if ((q = *s) == '>' || (! *s && e == '>')) { // open tag
-                *s = '\0'; // temporarily null terminate tag name
-                switch_xml_open_tag(root, d, attr);
-                *s = q;
-            }
-            else {
-                if (l) switch_xml_free_attr(attr);
-                return switch_xml_err(root, d, "missing >"); 
-            }
-        }
-        else if (*s == '/') { // close tag
-            s += strcspn(d = s + 1, SWITCH_XML_WS ">") + 1;
-            if (! (q = *s) && e != '>') return switch_xml_err(root, d, "missing >");
-            *s = '\0'; // temporarily null terminate tag name
-            if (switch_xml_close_tag(root, d, s)) return &root->xml;
-            if (isspace((int)(*s = q))) s += strspn(s, SWITCH_XML_WS);
-        }
-        else if (! strncmp(s, "!--", 3)) { // xml comment
-            if (! (s = strstr(s + 3, "--")) || (*(s += 2) != '>' && *s) ||
-                (! *s && e != '>')) return switch_xml_err(root, d, "unclosed <!--");
-        }
-        else if (! strncmp(s, "![CDATA[", 8)) { // cdata
-            if ((s = strstr(s, "]]>")))
-                switch_xml_char_content(root, d + 8, (s += 2) - d - 10, 'c');
-            else return switch_xml_err(root, d, "unclosed <![CDATA[");
-        }
-        else if (! strncmp(s, "!DOCTYPE", 8)) { // dtd
-            for (l = 0; *s && ((! l && *s != '>') || (l && (*s != ']' || 
-                 *(s + strspn(s + 1, SWITCH_XML_WS) + 1) != '>')));
-                 l = (*s == '[') ? 1 : l) s += strcspn(s + 1, "[]>") + 1;
-            if (! *s && e != '>')
-                return switch_xml_err(root, d, "unclosed <!DOCTYPE");
-            d = (l) ? strchr(d, '[') + 1 : d;
-            if (l && ! switch_xml_internal_dtd(root, d, s++ - d)) return &root->xml;
-        }
-        else if (*s == '?') { // <?...?> processing instructions
-            do { s = strchr(s, '?'); } while (s && *(++s) && *s != '>');
-            if (! s || (! *s && e != '>')) 
-                return switch_xml_err(root, d, "unclosed <?");
-            else switch_xml_proc_inst(root, d + 1, s - d - 2);
-        }
-        else return switch_xml_err(root, d, "unexpected <");
-        
-        if (! s || ! *s) break;
-        *s = '\0';
-        d = ++s;
-        if (*s && *s != '<') { // tag character content
-            while (*s && *s != '<') s++;
-            if (*s) switch_xml_char_content(root, d, s - d, '&');
-            else break;
-        }
-        else if (! *s) break;
-    }
-
-    if (! root->cur) return &root->xml;
-    else if (! root->cur->name) return switch_xml_err(root, d, "root tag missing");
-    else return switch_xml_err(root, d, "unclosed tag <%s>", root->cur->name);
+	switch_xml_root_t root = (switch_xml_root_t) switch_xml_new(NULL);
+	char q, e, *d, **attr, **a = NULL;	// initialize a to avoid compile warning
+	int l, i, j;
+
+	root->m = s;
+	if (!len)
+		return switch_xml_err(root, s, "root tag missing");
+	root->u = switch_xml_str2utf8(&s, &len);	// convert utf-16 to utf-8
+	root->e = (root->s = s) + len;	// record start and end of work area
+
+	e = s[len - 1];				// save end char
+	s[len - 1] = '\0';			// turn end char into null terminator
+
+	while (*s && *s != '<')
+		s++;					// find first tag
+	if (!*s)
+		return switch_xml_err(root, s, "root tag missing");
+
+	for (;;) {
+		attr = (char **) SWITCH_XML_NIL;
+		d = ++s;
+
+		if (isalpha((int) (*s)) || *s == '_' || *s == ':' || (int8_t) *s < '\0') {	// new tag
+			if (!root->cur)
+				return switch_xml_err(root, d, "markup outside of root element");
+
+			s += strcspn(s, SWITCH_XML_WS "/>");
+			while (isspace((int) (*s)))
+				*(s++) = '\0';	// null terminate tag name
+
+			if (*s && *s != '/' && *s != '>')	// find tag in default attr list
+				for (i = 0; (a = root->attr[i]) && strcmp(a[0], d); i++);
+
+			for (l = 0; *s && *s != '/' && *s != '>'; l += 2) {	// new attrib
+				attr = (l) ? realloc(attr, (l + 4) * sizeof(char *))
+					: malloc(4 * sizeof(char *));	// allocate space
+				attr[l + 3] = (l) ? realloc(attr[l + 1], (l / 2) + 2)
+					: malloc(2);	// mem for list of maloced vals
+				strcpy(attr[l + 3] + (l / 2), " ");	// value is not malloced
+				attr[l + 2] = NULL;	// null terminate list
+				attr[l + 1] = "";	// temporary attribute value
+				attr[l] = s;	// set attribute name
+
+				s += strcspn(s, SWITCH_XML_WS "=/>");
+				if (*s == '=' || isspace((int) (*s))) {
+					*(s++) = '\0';	// null terminate tag attribute name
+					q = *(s += strspn(s, SWITCH_XML_WS "="));
+					if (q == '"' || q == '\'') {	// attribute value
+						attr[l + 1] = ++s;
+						while (*s && *s != q)
+							s++;
+						if (*s)
+							*(s++) = '\0';	// null terminate attribute val
+						else {
+							switch_xml_free_attr(attr);
+							return switch_xml_err(root, d, "missing %c", q);
+						}
+
+						for (j = 1; a && a[j] && strcmp(a[j], attr[l]); j += 3);
+						attr[l + 1] = switch_xml_decode(attr[l + 1], root->ent, (a && a[j]) ? *a[j + 2] : ' ');
+						if (attr[l + 1] < d || attr[l + 1] > s)
+							attr[l + 3][l / 2] = SWITCH_XML_TXTM;	// value malloced
+					}
+				}
+				while (isspace((int) (*s)))
+					s++;
+			}
+
+			if (*s == '/') {	// self closing tag
+				*(s++) = '\0';
+				if ((*s && *s != '>') || (!*s && e != '>')) {
+					if (l)
+						switch_xml_free_attr(attr);
+					return switch_xml_err(root, d, "missing >");
+				}
+				switch_xml_open_tag(root, d, attr);
+				switch_xml_close_tag(root, d, s);
+			} else if ((q = *s) == '>' || (!*s && e == '>')) {	// open tag
+				*s = '\0';		// temporarily null terminate tag name
+				switch_xml_open_tag(root, d, attr);
+				*s = q;
+			} else {
+				if (l)
+					switch_xml_free_attr(attr);
+				return switch_xml_err(root, d, "missing >");
+			}
+		} else if (*s == '/') {	// close tag
+			s += strcspn(d = s + 1, SWITCH_XML_WS ">") + 1;
+			if (!(q = *s) && e != '>')
+				return switch_xml_err(root, d, "missing >");
+			*s = '\0';			// temporarily null terminate tag name
+			if (switch_xml_close_tag(root, d, s))
+				return &root->xml;
+			if (isspace((int) (*s = q)))
+				s += strspn(s, SWITCH_XML_WS);
+		} else if (!strncmp(s, "!--", 3)) {	// xml comment
+			if (!(s = strstr(s + 3, "--")) || (*(s += 2) != '>' && *s) || (!*s && e != '>'))
+				return switch_xml_err(root, d, "unclosed <!--");
+		} else if (!strncmp(s, "![CDATA[", 8)) {	// cdata
+			if ((s = strstr(s, "]]>")))
+				switch_xml_char_content(root, d + 8, (s += 2) - d - 10, 'c');
+			else
+				return switch_xml_err(root, d, "unclosed <![CDATA[");
+		} else if (!strncmp(s, "!DOCTYPE", 8)) {	// dtd
+			for (l = 0; *s && ((!l && *s != '>') || (l && (*s != ']' || *(s + strspn(s + 1, SWITCH_XML_WS) + 1) != '>'))); l = (*s == '[') ? 1 : l)
+				s += strcspn(s + 1, "[]>") + 1;
+			if (!*s && e != '>')
+				return switch_xml_err(root, d, "unclosed <!DOCTYPE");
+			d = (l) ? strchr(d, '[') + 1 : d;
+			if (l && !switch_xml_internal_dtd(root, d, s++ - d))
+				return &root->xml;
+		} else if (*s == '?') {	// <?...?> processing instructions
+			do {
+				s = strchr(s, '?');
+			} while (s && *(++s) && *s != '>');
+			if (!s || (!*s && e != '>'))
+				return switch_xml_err(root, d, "unclosed <?");
+			else
+				switch_xml_proc_inst(root, d + 1, s - d - 2);
+		} else
+			return switch_xml_err(root, d, "unexpected <");
+
+		if (!s || !*s)
+			break;
+		*s = '\0';
+		d = ++s;
+		if (*s && *s != '<') {	// tag character content
+			while (*s && *s != '<')
+				s++;
+			if (*s)
+				switch_xml_char_content(root, d, s - d, '&');
+			else
+				break;
+		} else if (!*s)
+			break;
+	}
+
+	if (!root->cur)
+		return &root->xml;
+	else if (!root->cur->name)
+		return switch_xml_err(root, d, "root tag missing");
+	else
+		return switch_xml_err(root, d, "unclosed tag <%s>", root->cur->name);
 }
 
 // Wrapper for switch_xml_parse_str() that accepts a file stream. Reads the entire
 // stream into memory and then parses it. For xml files, use switch_xml_parse_file()
 // or switch_xml_parse_fd()
-SWITCH_DECLARE(switch_xml_t) switch_xml_parse_fp(FILE *fp)
+SWITCH_DECLARE(switch_xml_t) switch_xml_parse_fp(FILE * fp)
 {
-    switch_xml_root_t root;
-    switch_size_t l, len = 0;
-    char *s;
-
-    if (! (s = malloc(SWITCH_XML_BUFSIZE))) return NULL;
-    do {
-        len += (l = fread((s + len), 1, SWITCH_XML_BUFSIZE, fp));
-        if (l == SWITCH_XML_BUFSIZE) s = realloc(s, len + SWITCH_XML_BUFSIZE);
-    } while (s && l == SWITCH_XML_BUFSIZE);
-
-    if (! s) return NULL;
-    root = (switch_xml_root_t)switch_xml_parse_str(s, len);
-    root->dynamic = 1; // so we know to free s in switch_xml_free()
-    return &root->xml;
+	switch_xml_root_t root;
+	switch_size_t l, len = 0;
+	char *s;
+
+	if (!(s = malloc(SWITCH_XML_BUFSIZE)))
+		return NULL;
+	do {
+		len += (l = fread((s + len), 1, SWITCH_XML_BUFSIZE, fp));
+		if (l == SWITCH_XML_BUFSIZE)
+			s = realloc(s, len + SWITCH_XML_BUFSIZE);
+	} while (s && l == SWITCH_XML_BUFSIZE);
+
+	if (!s)
+		return NULL;
+	root = (switch_xml_root_t) switch_xml_parse_str(s, len);
+	root->dynamic = 1;			// so we know to free s in switch_xml_free()
+	return &root->xml;
 }
 
 // A wrapper for switch_xml_parse_str() that accepts a file descriptor. First
@@ -756,248 +844,264 @@
 // Returns NULL on failure.
 SWITCH_DECLARE(switch_xml_t) switch_xml_parse_fd(int fd)
 {
-    switch_xml_root_t root;
-    struct stat st;
-    switch_size_t l;
-    void *m;
-
-    if (fd < 0) return NULL;
-    fstat(fd, &st);
+	switch_xml_root_t root;
+	struct stat st;
+	switch_size_t l;
+	void *m;
+
+	if (fd < 0)
+		return NULL;
+	fstat(fd, &st);
 
 #ifdef HAVE_MMAP
-    l = (st.st_size + sysconf(_SC_PAGESIZE) - 1) & ~(sysconf(_SC_PAGESIZE) -1);
-    if ((m = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)) !=
-        MAP_FAILED) {
-        madvise(m, l, MADV_SEQUENTIAL); // optimize for sequential access
-        root = (switch_xml_root_t)switch_xml_parse_str(m, st.st_size);
-        madvise(m, root->len = l, MADV_NORMAL); // put it back to normal
-    }
-    else { // mmap failed, read file into memory
+	l = (st.st_size + sysconf(_SC_PAGESIZE) - 1) & ~(sysconf(_SC_PAGESIZE) - 1);
+	if ((m = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)) != MAP_FAILED) {
+		madvise(m, l, MADV_SEQUENTIAL);	// optimize for sequential access
+		root = (switch_xml_root_t) switch_xml_parse_str(m, st.st_size);
+		madvise(m, root->len = l, MADV_NORMAL);	// put it back to normal
+	} else {					// mmap failed, read file into memory
 #endif // HAVE_MMAP
-        l = read(fd, m = malloc(st.st_size), st.st_size);
-        root = (switch_xml_root_t)switch_xml_parse_str(m, l);
-        root->dynamic = 1; // so we know to free s in switch_xml_free()
+		l = read(fd, m = malloc(st.st_size), st.st_size);
+		root = (switch_xml_root_t) switch_xml_parse_str(m, l);
+		root->dynamic = 1;		// so we know to free s in switch_xml_free()
 #ifdef HAVE_MMAP
-    }
+	}
 #endif // HAVE_MMAP
-    return &root->xml;
+	return &root->xml;
 }
 
-static switch_size_t read_line(int fd, char *buf, switch_size_t len) {
-    char c, *p;
-    int cur;
-    switch_size_t total = 0;
-    
-    p = buf;
-    while (total + sizeof(c) < len && (cur = read(fd, &c, sizeof(c))) > 0) {
-        total += cur;
-        *p++ = c;
-        if (c == '\n') {
-            break;
-        }
-    }
+static switch_size_t read_line(int fd, char *buf, switch_size_t len)
+{
+	char c, *p;
+	int cur;
+	switch_size_t total = 0;
+
+	p = buf;
+	while (total + sizeof(c) < len && (cur = read(fd, &c, sizeof(c))) > 0) {
+		total += cur;
+		*p++ = c;
+		if (c == '\n') {
+			break;
+		}
+	}
 
-    *p++ = '\0';
-    return total;
+	*p++ = '\0';
+	return total;
 }
 
 static char *expand_vars(char *buf, char *ebuf, switch_size_t elen, switch_size_t *newlen)
 {
-    char *var, *val;
-    char *rp = buf;
-    char *wp = ebuf;
-    char *ep = ebuf + elen - 1;
-
-    if (!(var = strstr(rp, "$${"))) {
-        *newlen = strlen(buf);
-        return buf;
-    }
-
-    while(*rp && wp < ep) {
-
-        if (*rp == '$' && *(rp+1) == '$' && *(rp+2) == '{') {
-            char *e = strchr(rp, '}');
-
-            if (e) {
-                rp += 3;
-                var = rp;
-                *e++ = '\0';
-                rp = e;
-                if ((val = switch_core_get_variable(var))) {
-                    char *p;
-                    for(p = val; p && *p && wp <= ep; p++) {
-                        *wp++ = *p;
-                    }
-                }
-            }
-
-        }
-
-        *wp++ = *rp++;
-    }
-    *wp++ = '\0';
-    *newlen = strlen(ebuf);
+	char *var, *val;
+	char *rp = buf;
+	char *wp = ebuf;
+	char *ep = ebuf + elen - 1;
+
+	if (!(var = strstr(rp, "$${"))) {
+		*newlen = strlen(buf);
+		return buf;
+	}
+
+	while (*rp && wp < ep) {
+
+		if (*rp == '$' && *(rp + 1) == '$' && *(rp + 2) == '{') {
+			char *e = strchr(rp, '}');
+
+			if (e) {
+				rp += 3;
+				var = rp;
+				*e++ = '\0';
+				rp = e;
+				if ((val = switch_core_get_variable(var))) {
+					char *p;
+					for (p = val; p && *p && wp <= ep; p++) {
+						*wp++ = *p;
+					}
+				}
+			}
+
+		}
+
+		*wp++ = *rp++;
+	}
+	*wp++ = '\0';
+	*newlen = strlen(ebuf);
+
+	return ebuf;
 
-    return ebuf;
-    
 }
 
 static int preprocess(const char *file, int write_fd, int rlevel)
 {
-    int read_fd = -1;
-    switch_size_t cur = 0, ml = 0;
-    char *q, *cmd, buf[2048], ebuf[8192];
-
-    if ((read_fd = open(file, O_RDONLY, 0)) < 0) {
-        return read_fd;
-    }
-
-    if (rlevel > 100) {
-        return -1;
-    }
-
-    while((cur = read_line(read_fd, buf, sizeof(buf))) > 0) {
-        char *arg, *e;
-        char *bp = expand_vars(buf, ebuf, sizeof(ebuf), &cur);
-
-        /* we ignore <include> or </include> for the sake of validators */
-        if (strstr(buf, "<include>") || strstr(buf, "</include>")) {
-            continue;
-        }
-
-        if (ml) {
-            if ((e = strstr(buf, "-->"))) {
-                ml = 0;
-                bp = e + 3;
-                cur = strlen(bp);
-            } else {
-                continue;
-            }
-        }
-
-        if ((cmd = strstr(bp, "<!--#"))) {
-            write(write_fd, bp, (unsigned)(cmd - bp));
-            if ((e = strstr(cmd, "-->"))) {
-                *e = '\0';
-                e += 3;
-                write(write_fd, e, (unsigned)strlen(e));
-            } else {
-                ml++;
-            }
-            
-            cmd += 5;
-            if ((e = strchr(cmd, '\r')) || (e = strchr(cmd, '\n'))) {
-                *e = '\0';
-            }
-
-            if ((arg = strchr(cmd, ' '))) {
-                *arg++ = '\0';
-                if ((q = strchr(arg, '"'))) {
-                    char *qq = q+1;
-
-                    if ((qq = strchr(qq, '"'))) {
-                        *qq = '\0';
-                        arg = q+1;
-                    }
-                }
-
-                if (!strcasecmp(cmd, "set")) {
-                    char *name = arg;
-                    char *val = strchr(name, '=');
-
-                    if (val) {
-                        char *ve = val++;
-                        while(*val && *val == ' ') {
-                            val++;
-                        }
-                        *ve-- = '\0';
-                        while(*ve && *ve == ' ') {
-                            *ve-- = '\0';
-                        }
-                    }
-                
-                    if (name && val) {
-                        switch_core_set_variable(name, val);
-                    }
-                
-                } else if (!strcasecmp(cmd, "include")) {
-                    char *fme = NULL, *ifile = arg;
-                
-                    if (!switch_is_file_path(ifile)) {
-                        fme = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, arg);
-                        ifile = fme;
-                    }
-                    if (preprocess(ifile, write_fd, rlevel + 1) < 0) {
-                        fprintf(stderr, "Error including %s (%s)\n", ifile, strerror(errno));
-                    }
-                    switch_safe_free(fme);
-                } /* else NO OP */
-            }
-
-            continue;
-        }
+	int read_fd = -1;
+	switch_size_t cur = 0, ml = 0;
+	char *q, *cmd, buf[2048], ebuf[8192];
+
+	if ((read_fd = open(file, O_RDONLY, 0)) < 0) {
+		return read_fd;
+	}
+
+	if (rlevel > 100) {
+		return -1;
+	}
+
+	while ((cur = read_line(read_fd, buf, sizeof(buf))) > 0) {
+		char *arg, *e;
+		char *bp = expand_vars(buf, ebuf, sizeof(ebuf), &cur);
+
+		/* we ignore <include> or </include> for the sake of validators */
+		if (strstr(buf, "<include>") || strstr(buf, "</include>")) {
+			continue;
+		}
+
+		if (ml) {
+			if ((e = strstr(buf, "-->"))) {
+				ml = 0;
+				bp = e + 3;
+				cur = strlen(bp);
+			} else {
+				continue;
+			}
+		}
+
+		if ((cmd = strstr(bp, "<!--#"))) {
+			write(write_fd, bp, (unsigned) (cmd - bp));
+			if ((e = strstr(cmd, "-->"))) {
+				*e = '\0';
+				e += 3;
+				write(write_fd, e, (unsigned) strlen(e));
+			} else {
+				ml++;
+			}
+
+			cmd += 5;
+			if ((e = strchr(cmd, '\r')) || (e = strchr(cmd, '\n'))) {
+				*e = '\0';
+			}
+
+			if ((arg = strchr(cmd, ' '))) {
+				*arg++ = '\0';
+				if ((q = strchr(arg, '"'))) {
+					char *qq = q + 1;
+
+					if ((qq = strchr(qq, '"'))) {
+						*qq = '\0';
+						arg = q + 1;
+					}
+				}
+
+				if (!strcasecmp(cmd, "set")) {
+					char *name = arg;
+					char *val = strchr(name, '=');
+
+					if (val) {
+						char *ve = val++;
+						while (*val && *val == ' ') {
+							val++;
+						}
+						*ve-- = '\0';
+						while (*ve && *ve == ' ') {
+							*ve-- = '\0';
+						}
+					}
+
+					if (name && val) {
+						switch_core_set_variable(name, val);
+					}
+
+				} else if (!strcasecmp(cmd, "include")) {
+					char *fme = NULL, *ifile = arg;
+
+					if (!switch_is_file_path(ifile)) {
+						fme = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, arg);
+						ifile = fme;
+					}
+					if (preprocess(ifile, write_fd, rlevel + 1) < 0) {
+						fprintf(stderr, "Error including %s (%s)\n", ifile, strerror(errno));
+					}
+					switch_safe_free(fme);
+				}				/* else NO OP */
+			}
+
+			continue;
+		}
 
-        write(write_fd, bp, (unsigned)cur);
-    }
+		write(write_fd, bp, (unsigned) cur);
+	}
 
-    close(read_fd);
-    return write_fd;
+	close(read_fd);
+	return write_fd;
+}
+
+SWITCH_DECLARE(switch_xml_t) switch_xml_parse_file_simple(const char *file)
+{
+	int fd = -1;
+	struct stat st;
+	switch_size_t l;
+	void *m;
+	switch_xml_root_t root;
+
+	if ((fd = open(file, O_RDONLY, 0)) > -1) {
+		fstat(fd, &st);
+		l = read(fd, m = malloc(st.st_size), st.st_size);
+		root = (switch_xml_root_t) switch_xml_parse_str(m, l);
+		root->dynamic = 1;
+		close(fd);
+		return &root->xml;
+	}
+	
+	return NULL;
 }
 
-// a wrapper for switch_xml_parse_fd that accepts a file name
 SWITCH_DECLARE(switch_xml_t) switch_xml_parse_file(const char *file)
 {
-    int fd = -1, write_fd = -1;
-    switch_xml_t xml = NULL;
-    char *new_file = NULL;
-    char *abs;
-
-    if ((abs = strrchr(file, '/')) || (abs = strrchr(file, '\\'))) {
-        abs++;
-    } else {
-        abs = (char *)file;
-    }
-    
-    if (!(new_file = switch_mprintf("%s%s%s.fsxml", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, abs))) {
-        return NULL;
-    }
-
-    if ((write_fd = open(new_file, O_WRONLY | O_CREAT | O_TRUNC,  S_IRUSR | S_IWUSR)) < 0) {
-        goto done;
-    }
-
-    if (preprocess(file, write_fd, 0) > -1) {
-        close(write_fd);
-        write_fd = -1;
-        if ((fd = open(new_file, O_RDONLY, 0)) > -1) {
-            if ((xml = switch_xml_parse_fd(fd))) {
-                xml->free_path = new_file;
-                new_file = NULL;
-            }
-            close(fd);
-            fd = -1;
-        }
-    }
-
- done:
-    if (write_fd > -1) {
-        close(write_fd);
-    }
-    if (fd > -1) {
-        close(fd);
-    }
-    switch_safe_free(new_file);
-    return xml;
+	int fd = -1, write_fd = -1;
+	switch_xml_t xml = NULL;
+	char *new_file = NULL;
+	const char *abs;
+
+	if ((abs = strrchr(file, '/')) || (abs = strrchr(file, '\\'))) {
+		abs++;
+	} else {
+		abs = file;
+	}
+	
+	if (!(new_file = switch_mprintf("%s%s%s.fsxml", SWITCH_GLOBAL_dirs.log_dir, SWITCH_PATH_SEPARATOR, abs))) {
+		return NULL;
+	}
+
+	if ((write_fd = open(new_file, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) < 0) {
+		goto done;
+	}
+
+	if (preprocess(file, write_fd, 0) > -1) {
+		close(write_fd);
+		write_fd = -1;
+		if ((fd = open(new_file, O_RDONLY, 0)) > -1) {
+			if ((xml = switch_xml_parse_fd(fd))) {
+				xml->free_path = new_file;
+				new_file = NULL;
+			}
+			close(fd);
+			fd = -1;
+		}
+	}
+
+  done:
+	if (write_fd > -1) {
+		close(write_fd);
+	}
+	if (fd > -1) {
+		close(fd);
+	}
+	switch_safe_free(new_file);
+	return xml;
 }
 
 
-SWITCH_DECLARE(switch_status_t) switch_xml_locate(char *section,
-												  char *tag_name,
-												  char *key_name,
-												  char *key_value,
-												  switch_xml_t *root,
-												  switch_xml_t *node,
-												  char *params)
+SWITCH_DECLARE(switch_status_t) switch_xml_locate(const char *section,
+												  const char *tag_name,
+												  const char *key_name, const char *key_value, switch_xml_t * root, switch_xml_t * node,
+												  const char *params)
 {
 	switch_xml_t conf = NULL;
 	switch_xml_t tag = NULL;
@@ -1007,7 +1111,7 @@
 
 	switch_mutex_lock(XML_LOCK);
 
-	for(binding = BINDINGS; binding; binding = binding->next) {
+	for (binding = BINDINGS; binding; binding = binding->next) {
 		switch_xml_section_t sections = switch_xml_parse_section_string(section);
 
 		if (binding->sections && !(sections & binding->sections)) {
@@ -1016,7 +1120,7 @@
 
 		if ((xml = binding->function(section, tag_name, key_name, key_value, params, binding->user_data))) {
 			const char *err = NULL;
-			
+
 			err = switch_xml_error(xml);
 			if (switch_strlen_zero(err)) {
 				if ((conf = switch_xml_find_child(xml, "section", "name", "result"))) {
@@ -1042,7 +1146,7 @@
 	}
 	switch_mutex_unlock(XML_LOCK);
 
-	for(;;) {
+	for (;;) {
 		if (!xml) {
 			if (!(xml = switch_xml_root())) {
 				*node = NULL;
@@ -1051,8 +1155,7 @@
 			}
 		}
 
-		if ((conf = switch_xml_find_child(xml, "section", "name", section)) && 
-			(tag = switch_xml_find_child(conf, tag_name, key_name, key_value))) {
+		if ((conf = switch_xml_find_child(xml, "section", "name", section)) && (tag = switch_xml_find_child(conf, tag_name, key_name, key_value))) {
 			*node = tag;
 			*root = xml;
 			return SWITCH_STATUS_SUCCESS;
@@ -1070,6 +1173,46 @@
 	return SWITCH_STATUS_FALSE;
 }
 
+SWITCH_DECLARE(switch_status_t) switch_xml_locate_domain(char *domain_name, char *params, switch_xml_t *root, switch_xml_t *domain)
+{
+	*domain = NULL;
+	return switch_xml_locate("directory", "domain", "name", domain_name, root, domain, params);
+}
+
+
+SWITCH_DECLARE(switch_status_t) switch_xml_locate_user(char *user_name, char *domain_name, 
+													   char *ip, 
+													   switch_xml_t *root,
+													   switch_xml_t *domain,
+													   switch_xml_t *user)
+{
+	char params[1024] = "";
+	switch_status_t status;
+	*root = NULL;
+	*user = NULL;
+	*domain = NULL;
+	
+	snprintf(params, sizeof(params), "user=%s&domain=%s&ip=%s", switch_str_nil(user_name), switch_str_nil(domain_name), switch_str_nil(ip));
+	if ((status = switch_xml_locate_domain(domain_name, params, root, domain)) != SWITCH_STATUS_SUCCESS) {
+		return status;
+	}
+	
+	if (ip) {
+		if ((*user = switch_xml_find_child(*domain, "user", "ip", ip))) {
+			return SWITCH_STATUS_SUCCESS;
+		}
+	} 
+
+	if (user_name) {
+		if (!(*user = switch_xml_find_child(*domain, "user", "id", user_name))) {
+			return SWITCH_STATUS_FALSE;
+		}
+		return SWITCH_STATUS_SUCCESS;
+	}
+
+	return SWITCH_STATUS_FALSE;
+}
+
 
 SWITCH_DECLARE(switch_xml_t) switch_xml_root(void)
 {
@@ -1081,37 +1224,40 @@
 SWITCH_DECLARE(switch_xml_t) switch_xml_open_root(uint8_t reload, const char **err)
 {
 	char path_buf[1024];
-	uint8_t hasmain = 0;
-	
+	uint8_t hasmain = 0, errcnt = 0;
+	switch_xml_t new_main;
+
 	switch_mutex_lock(XML_LOCK);
 
 	if (MAIN_XML_ROOT) {
-		switch_xml_t xml;
 		hasmain++;
 
 		if (!reload) {
 			switch_mutex_unlock(XML_LOCK);
 			return switch_xml_root();
 		}
-		xml = MAIN_XML_ROOT;
-		MAIN_XML_ROOT = NULL;
 		switch_thread_rwlock_wrlock(RWLOCK);
-		switch_xml_free(xml);
 	}
 
 	snprintf(path_buf, sizeof(path_buf), "%s%s%s", SWITCH_GLOBAL_dirs.conf_dir, SWITCH_PATH_SEPARATOR, "freeswitch.xml");
-	if ((MAIN_XML_ROOT = switch_xml_parse_file(path_buf))) {
-		*err = switch_xml_error(MAIN_XML_ROOT);
+	if ((new_main = switch_xml_parse_file(path_buf))) {
+		*err = switch_xml_error(new_main);
 
 		if (!switch_strlen_zero(*err)) {
-			switch_xml_free(MAIN_XML_ROOT);
-			MAIN_XML_ROOT = NULL;
+			switch_xml_free(new_main);
+			new_main = NULL;
+			errcnt++;
 		} else {
+			switch_xml_t old_root;
 			*err = "Success";
+			old_root = MAIN_XML_ROOT;
+			MAIN_XML_ROOT = new_main;
 			switch_set_flag(MAIN_XML_ROOT, SWITCH_XML_ROOT);
+			switch_xml_free(old_root);
 		}
 	} else {
 		*err = "Cannot Open log directory or XML Root!";
+		errcnt++;
 	}
 
 	if (hasmain) {
@@ -1119,7 +1265,7 @@
 	}
 	switch_mutex_unlock(XML_LOCK);
 
-	return switch_xml_root();
+	return errcnt == 0 ? switch_xml_root() : NULL;
 }
 
 
@@ -1134,7 +1280,7 @@
 
 	assert(pool != NULL);
 
-	if((xml=switch_xml_open_root(FALSE, err))) {
+	if ((xml = switch_xml_open_root(FALSE, err))) {
 		switch_xml_free(xml);
 		return SWITCH_STATUS_SUCCESS;
 	} else {
@@ -1154,7 +1300,7 @@
 	return SWITCH_STATUS_FALSE;
 }
 
-SWITCH_DECLARE(switch_xml_t) switch_xml_open_cfg(char *file_path, switch_xml_t *node, char *params)
+SWITCH_DECLARE(switch_xml_t) switch_xml_open_cfg(const char *file_path, switch_xml_t * node, const char *params)
 {
 	switch_xml_t xml = NULL, cfg = NULL;
 
@@ -1166,8 +1312,8 @@
 		*node = cfg;
 	}
 
-	return xml;	
-	
+	return xml;
+
 }
 
 
@@ -1175,78 +1321,95 @@
 // if length excedes max. a is non-zero for attribute encoding. Returns *dst
 static char *switch_xml_ampencode(const char *s, switch_size_t len, char **dst, switch_size_t *dlen, switch_size_t *max, short a)
 {
-    const char *e = NULL;
+	const char *e = NULL;
 
 	if (len) {
 		e = s + len;
 	}
-    
-    while (s != e) {
-        while (*dlen + 10 > *max) *dst = realloc(*dst, *max += SWITCH_XML_BUFSIZE);
-
-        switch (*s) {
-        case '\0': return *dst;
-        case '&': *dlen += sprintf(*dst + *dlen, "&amp;"); break;
-        case '<': *dlen += sprintf(*dst + *dlen, "&lt;"); break;
-        case '>': *dlen += sprintf(*dst + *dlen, "&gt;"); break;
-        case '"': *dlen += sprintf(*dst + *dlen, (a) ? "&quot;" : "\""); break;
-        case '\n': *dlen += sprintf(*dst + *dlen, (a) ? "&#xA;" : "\n"); break;
-        case '\t': *dlen += sprintf(*dst + *dlen, (a) ? "&#x9;" : "\t"); break;
-        case '\r': *dlen += sprintf(*dst + *dlen, "&#xD;"); break;
-        default: (*dst)[(*dlen)++] = *s;
-        }
+
+	while (s != e) {
+		while (*dlen + 10 > *max)
+			*dst = realloc(*dst, *max += SWITCH_XML_BUFSIZE);
+
+		switch (*s) {
+		case '\0':
+			return *dst;
+		case '&':
+			*dlen += sprintf(*dst + *dlen, "&amp;");
+			break;
+		case '<':
+			*dlen += sprintf(*dst + *dlen, "&lt;");
+			break;
+		case '>':
+			*dlen += sprintf(*dst + *dlen, "&gt;");
+			break;
+		case '"':
+			*dlen += sprintf(*dst + *dlen, (a) ? "&quot;" : "\"");
+			break;
+		case '\n':
+			*dlen += sprintf(*dst + *dlen, (a) ? "&#xA;" : "\n");
+			break;
+		case '\t':
+			*dlen += sprintf(*dst + *dlen, (a) ? "&#x9;" : "\t");
+			break;
+		case '\r':
+			*dlen += sprintf(*dst + *dlen, "&#xD;");
+			break;
+		default:
+			(*dst)[(*dlen)++] = *s;
+		}
 		s++;
-    }
-    return *dst;
+	}
+	return *dst;
 }
 
 #define XML_INDENT "  "
 // Recursively converts each tag to xml appending it to *s. Reallocates *s if
 // its length excedes max. start is the location of the previous tag in the
 // parent tag's character content. Returns *s.
-static char *switch_xml_toxml_r(switch_xml_t xml, char **s, switch_size_t *len, switch_size_t *max,
-                    switch_size_t start, char ***attr, uint32_t *count)
+static char *switch_xml_toxml_r(switch_xml_t xml, char **s, switch_size_t *len, switch_size_t *max, switch_size_t start, char ***attr, uint32_t * count)
 {
-    int i, j;
-    char *txt = (xml->parent) ? xml->parent->txt : "";
-    switch_size_t off = 0;
+	int i, j;
+	char *txt = (xml->parent) ? xml->parent->txt : "";
+	switch_size_t off = 0;
 	uint32_t lcount = 0;
-	
-    // parent character content up to this tag
-    *s = switch_xml_ampencode(txt + start, xml->off - start, s, len, max, 0);
 
-    while (*len + strlen(xml->name) + 5 + (strlen(XML_INDENT) * (*count)) + 1 > *max) // reallocate s
-        *s = realloc(*s, *max += SWITCH_XML_BUFSIZE);
+	// parent character content up to this tag
+	*s = switch_xml_ampencode(txt + start, xml->off - start, s, len, max, 0);
+
+	while (*len + strlen(xml->name) + 5 + (strlen(XML_INDENT) * (*count)) + 1 > *max)	// reallocate s
+		*s = realloc(*s, *max += SWITCH_XML_BUFSIZE);
 
-	if (*(*s+(*len)-1) == '>') {
-		*len += sprintf(*s + *len, "\n"); // indent
+	if (*(*s + (*len) - 1) == '>') {
+		*len += sprintf(*s + *len, "\n");	// indent
 	}
 	for (lcount = 0; lcount < *count; lcount++) {
-		*len += sprintf(*s + *len, "%s", XML_INDENT); // indent
+		*len += sprintf(*s + *len, "%s", XML_INDENT);	// indent
+	}
+
+	*len += sprintf(*s + *len, "<%s", xml->name);	// open tag
+	for (i = 0; xml->attr[i]; i += 2) {	// tag attributes
+		if (switch_xml_attr(xml, xml->attr[i]) != xml->attr[i + 1])
+			continue;
+		while (*len + strlen(xml->attr[i]) + 7 + (strlen(XML_INDENT) * (*count)) > *max)	// reallocate s
+			*s = realloc(*s, *max += SWITCH_XML_BUFSIZE);
+
+		*len += sprintf(*s + *len, " %s=\"", xml->attr[i]);
+		switch_xml_ampencode(xml->attr[i + 1], 0, s, len, max, 1);
+		*len += sprintf(*s + *len, "\"");
+	}
+
+	for (i = 0; attr[i] && strcmp(attr[i][0], xml->name); i++);
+	for (j = 1; attr[i] && attr[i][j]; j += 3) {	// default attributes
+		if (!attr[i][j + 1] || switch_xml_attr(xml, attr[i][j]) != attr[i][j + 1])
+			continue;			// skip duplicates and non-values
+		while (*len + strlen(attr[i][j]) + 8 + (strlen(XML_INDENT) * (*count)) > *max)	// reallocate s
+			*s = realloc(*s, *max += SWITCH_XML_BUFSIZE);
+
+		*len += sprintf(*s + *len, " %s=\"", attr[i][j]);
+		switch_xml_ampencode(attr[i][j + 1], 0, s, len, max, 1);
+		*len += sprintf(*s + *len, "\"");
 	}
-	
-    *len += sprintf(*s + *len, "<%s", xml->name); // open tag
-    for (i = 0; xml->attr[i]; i += 2) { // tag attributes
-        if (switch_xml_attr(xml, xml->attr[i]) != xml->attr[i + 1]) continue;
-        while (*len + strlen(xml->attr[i]) + 7 + (strlen(XML_INDENT) * (*count)) > *max) // reallocate s
-            *s = realloc(*s, *max += SWITCH_XML_BUFSIZE);
-
-        *len += sprintf(*s + *len, " %s=\"", xml->attr[i]);
-        switch_xml_ampencode(xml->attr[i + 1], 0, s, len, max, 1);
-        *len += sprintf(*s + *len, "\"");
-    }
-
-    for (i = 0; attr[i] && strcmp(attr[i][0], xml->name); i++);
-    for (j = 1; attr[i] && attr[i][j]; j += 3) { // default attributes
-        if (! attr[i][j + 1] || switch_xml_attr(xml, attr[i][j]) != attr[i][j + 1])
-            continue; // skip duplicates and non-values
-        while (*len + strlen(attr[i][j]) + 8 + (strlen(XML_INDENT) * (*count)) > *max) // reallocate s
-            *s = realloc(*s, *max += SWITCH_XML_BUFSIZE);
-
-        *len += sprintf(*s + *len, " %s=\"", attr[i][j]);
-        switch_xml_ampencode(attr[i][j + 1], 0, s, len, max, 1);
-        *len += sprintf(*s + *len, "\"");
-    }
 
 	*len += sprintf(*s + *len, (xml->child || xml->txt) ? ">" : "/>\n");
 
@@ -1255,23 +1418,24 @@
 		*s = switch_xml_toxml_r(xml->child, s, len, max, 0, attr, count);
 
 	} else {
-		*s = switch_xml_ampencode(xml->txt, 0, s, len, max, 0);  //data
+		*s = switch_xml_ampencode(xml->txt, 0, s, len, max, 0);	//data
 	}
-	
-    while (*len + strlen(xml->name) + 5 + (strlen(XML_INDENT) * (*count)) > *max) // reallocate s
-        *s = realloc(*s, *max += SWITCH_XML_BUFSIZE);
+
+	while (*len + strlen(xml->name) + 5 + (strlen(XML_INDENT) * (*count)) > *max)	// reallocate s
+		*s = realloc(*s, *max += SWITCH_XML_BUFSIZE);
 
 
 	if (xml->child || xml->txt) {
-		if (*(*s+(*len)-1) == '\n') {
+		if (*(*s + (*len) - 1) == '\n') {
 			for (lcount = 0; lcount < *count; lcount++) {
-				*len += sprintf(*s + *len, "%s", XML_INDENT); // indent
+				*len += sprintf(*s + *len, "%s", XML_INDENT);	// indent
 			}
 		}
-		*len += sprintf(*s + (*len), "</%s>\n", xml->name); // close tag
+		*len += sprintf(*s + (*len), "</%s>\n", xml->name);	// close tag
 	}
 
-    while (txt[off] && off < xml->off) off++; // make sure off is within bounds
+	while (txt[off] && off < xml->off)
+		off++;					// make sure off is within bounds
 
 	if (xml->ordered) {
 		return switch_xml_toxml_r(xml->ordered, s, len, max, off, attr, count);
@@ -1287,52 +1451,57 @@
 // must be freed
 SWITCH_DECLARE(char *) switch_xml_toxml(switch_xml_t xml)
 {
-    switch_xml_t p = (xml) ? xml->parent : NULL, o = (xml) ? xml->ordered : NULL;
-    switch_xml_root_t root = (switch_xml_root_t)xml;
-    switch_size_t len = 0, max = SWITCH_XML_BUFSIZE;
-    char *s = strcpy(malloc(max), ""), *t, *n;
-    int i, j, k;
+	switch_xml_t p = (xml) ? xml->parent : NULL, o = (xml) ? xml->ordered : NULL;
+	switch_xml_root_t root = (switch_xml_root_t) xml;
+	switch_size_t len = 0, max = SWITCH_XML_BUFSIZE;
+	char *s = strcpy(malloc(max), ""), *t, *n;
+	int i, j, k;
 	uint32_t count = 0;
 
-    if (! xml || ! xml->name) return realloc(s, len + 1);
-    while (root->xml.parent) root = (switch_xml_root_t)root->xml.parent; // root tag
+	if (!xml || !xml->name)
+		return realloc(s, len + 1);
+	while (root->xml.parent)
+		root = (switch_xml_root_t) root->xml.parent;	// root tag
+
+	for (i = 0; !p && root->pi[i]; i++) {	// pre-root processing instructions
+		for (k = 2; root->pi[i][k - 1]; k++);
+		for (j = 1; (n = root->pi[i][j]); j++) {
+			if (root->pi[i][k][j - 1] == '>')
+				continue;		// not pre-root
+			while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
+				s = realloc(s, max += SWITCH_XML_BUFSIZE);
+			len += sprintf(s + len, "<?%s%s%s?>", t, *n ? " " : "", n);
+		}
+	}
 
-    for (i = 0; ! p && root->pi[i]; i++) { // pre-root processing instructions
-        for (k = 2; root->pi[i][k - 1]; k++);
-        for (j = 1; (n = root->pi[i][j]); j++) {
-            if (root->pi[i][k][j - 1] == '>') continue; // not pre-root
-            while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
-                s = realloc(s, max += SWITCH_XML_BUFSIZE);
-            len += sprintf(s + len, "<?%s%s%s?>", t, *n ? " " : "", n);
-        }
-    }
-
-    xml->parent = xml->ordered = NULL;
-    s = switch_xml_toxml_r(xml, &s, &len, &max, 0, root->attr, &count);
-    xml->parent = p;
-    xml->ordered = o;
-
-    for (i = 0; ! p && root->pi[i]; i++) { // post-root processing instructions
-        for (k = 2; root->pi[i][k - 1]; k++);
-        for (j = 1; (n = root->pi[i][j]); j++) {
-            if (root->pi[i][k][j - 1] == '<') continue; // not post-root
-            while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
-                s = realloc(s, max += SWITCH_XML_BUFSIZE);
-            len += sprintf(s + len, "\n<?%s%s%s?>", t, *n ? " " : "", n);
-        }
-    }
-    return realloc(s, len + 1);
+	xml->parent = xml->ordered = NULL;
+	s = switch_xml_toxml_r(xml, &s, &len, &max, 0, root->attr, &count);
+	xml->parent = p;
+	xml->ordered = o;
+
+	for (i = 0; !p && root->pi[i]; i++) {	// post-root processing instructions
+		for (k = 2; root->pi[i][k - 1]; k++);
+		for (j = 1; (n = root->pi[i][j]); j++) {
+			if (root->pi[i][k][j - 1] == '<')
+				continue;		// not post-root
+			while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
+				s = realloc(s, max += SWITCH_XML_BUFSIZE);
+			len += sprintf(s + len, "\n<?%s%s%s?>", t, *n ? " " : "", n);
+		}
+	}
+	return realloc(s, len + 1);
 }
 
 // free the memory allocated for the switch_xml structure
 SWITCH_DECLARE(void) switch_xml_free(switch_xml_t xml)
 {
-    switch_xml_root_t root = (switch_xml_root_t)xml;
-    int i, j;
-    char **a, *s;
+	switch_xml_root_t root = (switch_xml_root_t) xml;
+	int i, j;
+	char **a, *s;
 
 
-    if (! xml ) return;
+	if (!xml)
+		return;
 
 	if (switch_test_flag(xml, SWITCH_XML_ROOT)) {
 		if (lock_count > 0) {
@@ -1343,179 +1512,197 @@
 
 	if (xml == MAIN_XML_ROOT) {
 		return;
-	} 
+	}
+
+	if (xml->free_path) {
+		unlink(xml->free_path);
+		switch_safe_free(xml->free_path);
+	}
 
-    if (xml->free_path) {
-        unlink(xml->free_path);
-        switch_safe_free(xml->free_path);
-    }
-
-    switch_xml_free(xml->child);
-    switch_xml_free(xml->ordered);
-
-    if (! xml->parent) { // free root tag allocations
-        for (i = 10; root->ent[i]; i += 2) // 0 - 9 are default entites (<>&"')
-            if ((s = root->ent[i + 1]) < root->s || s > root->e) free(s);
-        free(root->ent); // free list of general entities
-
-        for (i = 0; (a = root->attr[i]); i++) {
-            for (j = 1; a[j++]; j += 2) // free malloced attribute values
-                if (a[j] && (a[j] < root->s || a[j] > root->e)) free(a[j]);
-            free(a);
-        }
-        if (root->attr[0]) free(root->attr); // free default attribute list
-
-        for (i = 0; root->pi[i]; i++) {
-            for (j = 1; root->pi[i][j]; j++);
-            free(root->pi[i][j + 1]);
-            free(root->pi[i]);
-        }            
-        if (root->pi[0]) free(root->pi); // free processing instructions
+	switch_xml_free(xml->child);
+	switch_xml_free(xml->ordered);
 
-        if (root->dynamic == 1) free(root->m); // malloced xml data
+	if (!xml->parent) {			// free root tag allocations
+		for (i = 10; root->ent[i]; i += 2)	// 0 - 9 are default entites (<>&"')
+			if ((s = root->ent[i + 1]) < root->s || s > root->e)
+				free(s);
+		free(root->ent);		// free list of general entities
+
+		for (i = 0; (a = root->attr[i]); i++) {
+			for (j = 1; a[j++]; j += 2)	// free malloced attribute values
+				if (a[j] && (a[j] < root->s || a[j] > root->e))
+					free(a[j]);
+			free(a);
+		}
+		if (root->attr[0])
+			free(root->attr);	// free default attribute list
+
+		for (i = 0; root->pi[i]; i++) {
+			for (j = 1; root->pi[i][j]; j++);
+			free(root->pi[i][j + 1]);
+			free(root->pi[i]);
+		}
+		if (root->pi[0])
+			free(root->pi);		// free processing instructions
+
+		if (root->dynamic == 1)
+			free(root->m);		// malloced xml data
 #ifdef HAVE_MMAP
-        else if (root->len) munmap(root->m, root->len); // mem mapped xml data
+		else if (root->len)
+			munmap(root->m, root->len);	// mem mapped xml data
 #endif // HAVE_MMAP
-        if (root->u) free(root->u); // utf8 conversion
-    }
+		if (root->u)
+			free(root->u);		// utf8 conversion
+	}
 
-    switch_xml_free_attr(xml->attr); // tag attributes
-    if ((xml->flags & SWITCH_XML_TXTM)) free(xml->txt); // character content
-    if ((xml->flags & SWITCH_XML_NAMEM)) free(xml->name); // tag name
-    free(xml);
+	switch_xml_free_attr(xml->attr);	// tag attributes
+	if ((xml->flags & SWITCH_XML_TXTM))
+		free(xml->txt);			// character content
+	if ((xml->flags & SWITCH_XML_NAMEM))
+		free(xml->name);		// tag name
+	free(xml);
 }
 
 // return parser error message or empty string if none
 SWITCH_DECLARE(const char *) switch_xml_error(switch_xml_t xml)
 {
-    while (xml && xml->parent) xml = xml->parent; // find root tag
-    return (xml) ? ((switch_xml_root_t)xml)->err : "";
+	while (xml && xml->parent)
+		xml = xml->parent;		// find root tag
+	return (xml) ? ((switch_xml_root_t) xml)->err : "";
 }
 
 // returns a new empty switch_xml structure with the given root tag name
 SWITCH_DECLARE(switch_xml_t) switch_xml_new(const char *name)
 {
-    static char *ent[] = { "lt;", "&#60;", "gt;", "&#62;", "quot;", "&#34;",
-                           "apos;", "&#39;", "amp;", "&#38;", NULL };
-    switch_xml_root_t root = (switch_xml_root_t)memset(malloc(sizeof(struct switch_xml_root)), 
-                                             '\0', sizeof(struct switch_xml_root));
-    root->xml.name = (char *)name;
-    root->cur = &root->xml;
-    strcpy(root->err, root->xml.txt = "");
-    root->ent = memcpy(malloc(sizeof(ent)), ent, sizeof(ent));
-    root->attr = root->pi = (char ***)(root->xml.attr = SWITCH_XML_NIL);
-    return &root->xml;
+	static char *ent[] = { "lt;", "&#60;", "gt;", "&#62;", "quot;", "&#34;",
+		"apos;", "&#39;", "amp;", "&#38;", NULL
+	};
+	switch_xml_root_t root = (switch_xml_root_t) memset(malloc(sizeof(struct switch_xml_root)),
+														'\0', sizeof(struct switch_xml_root));
+	root->xml.name = (char *) name;
+	root->cur = &root->xml;
+	strcpy(root->err, root->xml.txt = "");
+	root->ent = memcpy(malloc(sizeof(ent)), ent, sizeof(ent));
+	root->attr = root->pi = (char ***) (root->xml.attr = SWITCH_XML_NIL);
+	return &root->xml;
 }
 
 // inserts an existing tag into an switch_xml structure
 SWITCH_DECLARE(switch_xml_t) switch_xml_insert(switch_xml_t xml, switch_xml_t dest, switch_size_t off)
 {
-    switch_xml_t cur, prev, head;
+	switch_xml_t cur, prev, head;
 
-    xml->next = xml->sibling = xml->ordered = NULL;
-    xml->off = off;
-    xml->parent = dest;
-
-    if ((head = dest->child)) { // already have sub tags
-        if (head->off <= off) { // not first subtag
-            for (cur = head; cur->ordered && cur->ordered->off <= off;
-                 cur = cur->ordered);
-            xml->ordered = cur->ordered;
-            cur->ordered = xml;
-        }
-        else { // first subtag
-            xml->ordered = head;
-            dest->child = xml;
-        }
-
-        for (cur = head, prev = NULL; cur && strcmp(cur->name, xml->name);
-             prev = cur, cur = cur->sibling); // find tag type
-        if (cur && cur->off <= off) { // not first of type
-            while (cur->next && cur->next->off <= off) cur = cur->next;
-            xml->next = cur->next;
-            cur->next = xml;
-        }
-        else { // first tag of this type
-            if (prev && cur) prev->sibling = cur->sibling; // remove old first
-            xml->next = cur; // old first tag is now next
-            for (cur = head, prev = NULL; cur && cur->off <= off;
-                 prev = cur, cur = cur->sibling); // new sibling insert point
-            xml->sibling = cur;
-            if (prev) prev->sibling = xml;
-        }
-    }
-    else dest->child = xml; // only sub tag
+	xml->next = xml->sibling = xml->ordered = NULL;
+	xml->off = off;
+	xml->parent = dest;
+
+	if ((head = dest->child)) {	// already have sub tags
+		if (head->off <= off) {	// not first subtag
+			for (cur = head; cur->ordered && cur->ordered->off <= off; cur = cur->ordered);
+			xml->ordered = cur->ordered;
+			cur->ordered = xml;
+		} else {				// first subtag
+			xml->ordered = head;
+			dest->child = xml;
+		}
 
-    return xml;
+		for (cur = head, prev = NULL; cur && strcmp(cur->name, xml->name); prev = cur, cur = cur->sibling);	// find tag type
+		if (cur && cur->off <= off) {	// not first of type
+			while (cur->next && cur->next->off <= off)
+				cur = cur->next;
+			xml->next = cur->next;
+			cur->next = xml;
+		} else {				// first tag of this type
+			if (prev && cur)
+				prev->sibling = cur->sibling;	// remove old first
+			xml->next = cur;	// old first tag is now next
+			for (cur = head, prev = NULL; cur && cur->off <= off; prev = cur, cur = cur->sibling);	// new sibling insert point
+			xml->sibling = cur;
+			if (prev)
+				prev->sibling = xml;
+		}
+	} else
+		dest->child = xml;		// only sub tag
+
+	return xml;
 }
 
 // Adds a child tag. off is the offset of the child tag relative to the start
 // of the parent tag's character content. Returns the child tag
-switch_xml_t switch_xml_add_child(switch_xml_t xml, const char *name, switch_size_t off)
+SWITCH_DECLARE(switch_xml_t) switch_xml_add_child(switch_xml_t xml, const char *name, switch_size_t off)
 {
-    switch_xml_t child;
+	switch_xml_t child;
 
-    if (! xml) return NULL;
-    child = (switch_xml_t)memset(malloc(sizeof(struct switch_xml)), '\0',
-                            sizeof(struct switch_xml));
-    child->name = (char *)name;
-    child->attr = SWITCH_XML_NIL;
-    child->off = off;
-    child->parent = xml;
-    child->txt = "";
+	if (!xml)
+		return NULL;
+	child = (switch_xml_t) memset(malloc(sizeof(struct switch_xml)), '\0', sizeof(struct switch_xml));
+	child->name = (char *) name;
+	child->attr = SWITCH_XML_NIL;
+	child->off = off;
+	child->parent = xml;
+	child->txt = "";
 
-    return switch_xml_insert(child, xml, off);
+	return switch_xml_insert(child, xml, off);
 }
 
 // sets the character content for the given tag and returns the tag
-switch_xml_t switch_xml_set_txt(switch_xml_t xml, const char *txt)
+SWITCH_DECLARE(switch_xml_t) switch_xml_set_txt(switch_xml_t xml, const char *txt)
 {
-    if (! xml) return NULL;
-    if (xml->flags & SWITCH_XML_TXTM) free(xml->txt); // existing txt was malloced
-    xml->flags &= ~SWITCH_XML_TXTM;
-    xml->txt = (char *)txt;
-    return xml;
+	if (!xml)
+		return NULL;
+	if (xml->flags & SWITCH_XML_TXTM)
+		free(xml->txt);			// existing txt was malloced
+	xml->flags &= ~SWITCH_XML_TXTM;
+	xml->txt = (char *) txt;
+	return xml;
 }
 
 // Sets the given tag attribute or adds a new attribute if not found. A value
 // of NULL will remove the specified attribute.  Returns the tag given
 SWITCH_DECLARE(switch_xml_t) switch_xml_set_attr(switch_xml_t xml, const char *name, const char *value)
 {
-    int l = 0, c;
+	int l = 0, c;
 
-    if (! xml) return NULL;
-    while (xml->attr[l] && strcmp(xml->attr[l], name)) l += 2;
-    if (! xml->attr[l]) { // not found, add as new attribute
-        if (! value) return xml; // nothing to do
-        if (xml->attr == SWITCH_XML_NIL) { // first attribute
-            xml->attr = malloc(4 * sizeof(char *));
-            xml->attr[1] = strdup(""); // empty list of malloced names/vals
-        }
-        else xml->attr = realloc(xml->attr, (l + 4) * sizeof(char *));
-
-        xml->attr[l] = (char *)name; // set attribute name
-        xml->attr[l + 2] = NULL; // null terminate attribute list
-        xml->attr[l + 3] = realloc(xml->attr[l + 1],
-                                   (c = (int)strlen(xml->attr[l + 1])) + 2);
-        strcpy(xml->attr[l + 3] + c, " "); // set name/value as not malloced
-        if (xml->flags & SWITCH_XML_DUP) xml->attr[l + 3][c] = SWITCH_XML_NAMEM;
-    }
-    else if (xml->flags & SWITCH_XML_DUP) free((char *)name); // name was strduped
-
-    for (c = l; xml->attr[c]; c += 2); // find end of attribute list
-    if (xml->attr[c + 1][l / 2] & SWITCH_XML_TXTM) free(xml->attr[l + 1]); //old val
-    if (xml->flags & SWITCH_XML_DUP) xml->attr[c + 1][l / 2] |= SWITCH_XML_TXTM;
-    else xml->attr[c + 1][l / 2] &= ~SWITCH_XML_TXTM;
-
-    if (value) xml->attr[l + 1] = (char *)value; // set attribute value
-    else { // remove attribute
-        if (xml->attr[c + 1][l / 2] & SWITCH_XML_NAMEM) free(xml->attr[l]);
-        memmove(xml->attr + l, xml->attr + l + 2, (c - l + 2) * sizeof(char*));
-        xml->attr = realloc(xml->attr, (c + 2) * sizeof(char *));
-        memmove(xml->attr[c + 1] + (l / 2), xml->attr[c + 1] + (l / 2) + 1,
-                (c / 2) - (l / 2)); // fix list of which name/vals are malloced
-    }
-    xml->flags &= ~SWITCH_XML_DUP; // clear strdup() flag
+	if (!xml)
+		return NULL;
+	while (xml->attr[l] && strcmp(xml->attr[l], name))
+		l += 2;
+	if (!xml->attr[l]) {		// not found, add as new attribute
+		if (!value)
+			return xml;			// nothing to do
+		if (xml->attr == SWITCH_XML_NIL) {	// first attribute
+			xml->attr = malloc(4 * sizeof(char *));
+			xml->attr[1] = strdup("");	// empty list of malloced names/vals
+		} else
+			xml->attr = realloc(xml->attr, (l + 4) * sizeof(char *));
+
+		xml->attr[l] = (char *) name;	// set attribute name
+		xml->attr[l + 2] = NULL;	// null terminate attribute list
+		xml->attr[l + 3] = realloc(xml->attr[l + 1], (c = (int) strlen(xml->attr[l + 1])) + 2);
+		strcpy(xml->attr[l + 3] + c, " ");	// set name/value as not malloced
+		if (xml->flags & SWITCH_XML_DUP)
+			xml->attr[l + 3][c] = SWITCH_XML_NAMEM;
+	} else if (xml->flags & SWITCH_XML_DUP)
+		free((char *) name);	// name was strduped
+
+	for (c = l; xml->attr[c]; c += 2);	// find end of attribute list
+	if (xml->attr[c + 1][l / 2] & SWITCH_XML_TXTM)
+		free(xml->attr[l + 1]);	//old val
+	if (xml->flags & SWITCH_XML_DUP)
+		xml->attr[c + 1][l / 2] |= SWITCH_XML_TXTM;
+	else
+		xml->attr[c + 1][l / 2] &= ~SWITCH_XML_TXTM;
+
+	if (value)
+		xml->attr[l + 1] = (char *) value;	// set attribute value
+	else {						// remove attribute
+		if (xml->attr[c + 1][l / 2] & SWITCH_XML_NAMEM)
+			free(xml->attr[l]);
+		memmove(xml->attr + l, xml->attr + l + 2, (c - l + 2) * sizeof(char *));
+		xml->attr = realloc(xml->attr, (c + 2) * sizeof(char *));
+		memmove(xml->attr[c + 1] + (l / 2), xml->attr[c + 1] + (l / 2) + 1, (c / 2) - (l / 2));	// fix list of which name/vals are malloced
+	}
+	xml->flags &= ~SWITCH_XML_DUP;	// clear strdup() flag
 
 	return xml;
 }
@@ -1523,42 +1710,48 @@
 // sets a flag for the given tag and returns the tag
 SWITCH_DECLARE(switch_xml_t) switch_xml_set_flag(switch_xml_t xml, switch_xml_flag_t flag)
 {
-    if (xml) xml->flags |= flag;
-    return xml;
+	if (xml)
+		xml->flags |= flag;
+	return xml;
 }
 
 // removes a tag along with its subtags without freeing its memory
 SWITCH_DECLARE(switch_xml_t) switch_xml_cut(switch_xml_t xml)
 {
-    switch_xml_t cur;
+	switch_xml_t cur;
 
-    if (! xml) return NULL; // nothing to do
-    if (xml->next) xml->next->sibling = xml->sibling; // patch sibling list
+	if (!xml)
+		return NULL;			// nothing to do
+	if (xml->next)
+		xml->next->sibling = xml->sibling;	// patch sibling list
+
+	if (xml->parent) {			// not root tag
+		cur = xml->parent->child;	// find head of subtag list
+		if (cur == xml)
+			xml->parent->child = xml->ordered;	// first subtag
+		else {					// not first subtag
+			while (cur->ordered != xml)
+				cur = cur->ordered;
+			cur->ordered = cur->ordered->ordered;	// patch ordered list
+
+			cur = xml->parent->child;	// go back to head of subtag list
+			if (strcmp(cur->name, xml->name)) {	// not in first sibling list
+				while (strcmp(cur->sibling->name, xml->name))
+					cur = cur->sibling;
+				if (cur->sibling == xml) {	// first of a sibling list
+					cur->sibling = (xml->next) ? xml->next : cur->sibling->sibling;
+				} else
+					cur = cur->sibling;	// not first of a sibling list
+			}
 
-    if (xml->parent) { // not root tag
-        cur = xml->parent->child; // find head of subtag list
-        if (cur == xml) xml->parent->child = xml->ordered; // first subtag
-        else { // not first subtag
-            while (cur->ordered != xml) cur = cur->ordered;
-            cur->ordered = cur->ordered->ordered; // patch ordered list
-
-            cur = xml->parent->child; // go back to head of subtag list
-            if (strcmp(cur->name, xml->name)) { // not in first sibling list
-                while (strcmp(cur->sibling->name, xml->name))
-                    cur = cur->sibling;
-                if (cur->sibling == xml) { // first of a sibling list
-                    cur->sibling = (xml->next) ? xml->next
-                                               : cur->sibling->sibling;
-                }
-                else cur = cur->sibling; // not first of a sibling list
-            }
-
-            while (cur->next && cur->next != xml) cur = cur->next;
-            if (cur->next) cur->next = cur->next->next; // patch next list
-        }        
-    }
-	xml->ordered = xml->sibling = xml->next =  NULL; // prevent switch_xml_free() from clobbering ordered list
-    return xml;
+			while (cur->next && cur->next != xml)
+				cur = cur->next;
+			if (cur->next)
+				cur->next = cur->next->next;	// patch next list
+		}
+	}
+	xml->ordered = xml->sibling = xml->next = NULL;	// prevent switch_xml_free() from clobbering ordered list
+	return xml;
 }
 
 /* For Emacs:

Modified: freeswitch/branches/cparker/w32/Library/FreeSwitchCore.vcproj
==============================================================================
--- freeswitch/branches/cparker/w32/Library/FreeSwitchCore.vcproj	(original)
+++ freeswitch/branches/cparker/w32/Library/FreeSwitchCore.vcproj	Tue Apr 24 10:14:28 2007
@@ -43,8 +43,8 @@
 			<Tool
 				Name="VCCLCompilerTool"
 				Optimization="0"
-				AdditionalIncludeDirectories="..\..\src\include;..\..\libs\include;..\..\libs\srtp\include;..\..\libs\srtp\crypto\include;..\..\libs\libresample\include;..\..\libs\libteletone\src"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;FREESWITCHCORE_EXPORTS"
+				AdditionalIncludeDirectories="..\..\src\include;..\..\libs\include;..\..\libs\srtp\include;..\..\libs\srtp\crypto\include;..\..\libs\libresample\include;..\..\libs\libteletone\src;..\..\libs\win32\sqlite;..\..\libs\pcre"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;FREESWITCHCORE_EXPORTS;PCRE_STATIC"
 				MinimalRebuild="true"
 				BasicRuntimeChecks="3"
 				RuntimeLibrary="3"
@@ -136,8 +136,8 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="..\..\src\include;..\..\libs\include;..\..\libs\srtp\include;..\..\libs\srtp\crypto\include;..\..\libs\libresample\include;..\..\libs\libteletone\src"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;FREESWITCHCORE_EXPORTS;CRASH_PROT"
+				AdditionalIncludeDirectories="..\..\src\include;..\..\libs\include;..\..\libs\srtp\include;..\..\libs\srtp\crypto\include;..\..\libs\libresample\include;..\..\libs\libteletone\src;..\..\libs\win32\sqlite;..\..\libs\pcre"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;FREESWITCHCORE_EXPORTS;CRASH_PROT;PCRE_STATIC"
 				RuntimeLibrary="2"
 				UsePrecompiledHeader="2"
 				PrecompiledHeaderThrough="switch.h"
@@ -208,6 +208,10 @@
 			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
 			>
 			<File
+				RelativePath="..\..\src\switch_apr.c"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\switch_buffer.c"
 				>
 				<FileConfiguration
@@ -236,15 +240,79 @@
 				>
 			</File>
 			<File
-				RelativePath="..\..\src\switch_config.c"
+				RelativePath="..\..\src\switch_console.c"
 				>
 			</File>
 			<File
-				RelativePath="..\..\src\switch_console.c"
+				RelativePath="..\..\src\switch_core.c"
 				>
 			</File>
 			<File
-				RelativePath="..\..\src\switch_core.c"
+				RelativePath="..\..\src\switch_core_asr.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_codec.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_db.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_directory.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_event_hook.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_file.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_hash.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_io.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_media_bug.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_memory.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_port_allocator.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_rwlock.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_session.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_speech.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_sqldb.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_state_machine.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_core_timer.c"
 				>
 			</File>
 			<File
@@ -256,6 +324,26 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\switch_ivr_async.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_ivr_bridge.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_ivr_menu.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_ivr_originate.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_ivr_play_say.c"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\switch_loadable_module.c"
 				>
 			</File>
@@ -264,6 +352,14 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\switch_odbc.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\switch_regex.c"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\switch_resample.c"
 				>
 			</File>
@@ -272,6 +368,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\switch_scheduler.c"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\switch_stun.c"
 				>
 			</File>
@@ -298,6 +398,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\include\switch_bitpack.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\include\switch_buffer.h"
 				>
 			</File>
@@ -318,10 +422,22 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\include\private\switch_core.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\include\switch_core.h"
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\include\switch_core_db.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\include\switch_core_event_hook.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\include\switch_event.h"
 				>
 			</File>
@@ -346,10 +462,18 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\include\switch_odbc.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\include\switch_platform.h"
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\include\switch_regex.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\include\switch_resample.h"
 				>
 			</File>
@@ -358,6 +482,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\include\switch_scheduler.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\include\switch_sqlite.h"
 				>
 			</File>
@@ -374,6 +502,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\include\switch_version.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\include\switch_xml.h"
 				>
 			</File>
@@ -388,6 +520,26 @@
 			Name="Generated Header Files"
 			>
 			<File
+				RelativePath="..\..\src\include\switch_am_config.h.in"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					ExcludedFromBuild="true"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					ExcludedFromBuild="true"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
 				RelativePath="..\..\src\include\switch_version.h.in"
 				>
 				<FileConfiguration



More information about the Freeswitch-svn mailing list