diff --git a/daemon/README b/daemon/README
index e5a95a585739968d4b06e0a70635029b188db50c..53dbb8625d8b7060b054265ee8c0f3caea6b5b0b 100644
--- a/daemon/README
+++ b/daemon/README
@@ -51,8 +51,6 @@ Short description of content of source tree
 -------------------------------------------
 
 - ringtones/ contains the different ringtones.
-- stund/ is an implementation of the protocol STUN used when there is a NAT.
-- utilspp/ allows to implement a singleton.
 - src/ is the core of SFLphone. It contains the main.cpp, managerimpl.cpp
   files, audio and gui directories, and files about signalisation SIP. Later,
   it should be better, when IAX will be implemented, that a directory groups
diff --git a/daemon/README.gentoo b/daemon/README.gentoo
deleted file mode 100644
index c17db2a1f46bb519e1d3a5fc7888c3e775050838..0000000000000000000000000000000000000000
--- a/daemon/README.gentoo
+++ /dev/null
@@ -1,23 +0,0 @@
-emerge commoncpp2
-# editer /usr/lib/pkgconfig/libccext2.pc pour le includedir -> /usr/include/
-ACCEPT_KEYWORDS=~x86 emerge ccrtp
-emerge libosip
-ACCEPT_KEYWORDS=~x86 emerge libeXosip
-emerge libsamplerate
-emerge cvs
-emerge =qt-3.3.6-r1
-
-cvs ...
-
-cd tools/
-portaudio.sh
-cd portaudio
-make install
-cd ../../
-./tools/autotoolize.sh
-./configure --with-qtdir=/usr/qt/3 PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
-make
-make install
-
-sflphone
-
diff --git a/daemon/configure.ac b/daemon/configure.ac
index c5d6dd71a47930d1edbcc088ee730a5781be5bd7..e1d7c8aae127a8a9fc184442c0a4781669452f66 100644
--- a/daemon/configure.ac
+++ b/daemon/configure.ac
@@ -6,10 +6,6 @@ AC_INIT([sflphone],[1.0.2],[sflphoneteam@savoirfairelinux.com],[sflphone])
 AC_COPYRIGHT([[Copyright (c) Savoir-Faire Linux 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012]])
 AC_REVISION([$Revision$])
 
-AC_CANONICAL_BUILD
-AC_CANONICAL_HOST
-AC_CANONICAL_TARGET
-
 AM_INIT_AUTOMAKE
 AC_CONFIG_HEADERS([config.h])
 
@@ -50,7 +46,8 @@ AC_FUNC_ALLOCA
 AC_HEADER_STDC
 AC_CHECK_HEADERS([arpa/inet.h fcntl.h libintl.h limits.h malloc.h memory.h \
                   netdb.h netinet/in.h stdlib.h string.h strings.h \
-                  sys/ioctl.h sys/socket.h sys/time.h unistd.h utime.h ostream])
+                  sys/ioctl.h sys/socket.h sys/time.h unistd.h utime.h \
+                  ostream getopt.h])
 
 dnl Check for typedefs, structures, and compiler characteristics
 AC_HEADER_STAT
@@ -89,9 +86,6 @@ AC_DEFINE_UNQUOTED([RETSIGTYPE],[$ac_cv_type_signal],[Define as the return type
 AC_FUNC_STAT
 AC_FUNC_UTIME_NULL
 AC_FUNC_VPRINTF
-AC_CHECK_FUNCS([bzero floor gethostbyname gethrtime gettimeofday \
-                inet_ntoa memset mkdir pathconf pow regcomp select setlocale \
-                socket strchr strdup strerror strrchr strstr strtol utime])
 
 dnl Check for GNU ccRTP
 PKG_PROG_PKG_CONFIG
@@ -147,13 +141,15 @@ AS_IF([test "x$enable_video" != "xno"], [
 AM_CONDITIONAL(SFL_VIDEO, test "x$enable_video" != "xno")
 
 LIBCCGNU2_MIN_VERSION=1.3.1
-PKG_CHECK_MODULES(CCGNU2, libccgnu2 >= ${LIBCCGNU2_MIN_VERSION},, AC_MSG_ERROR([Missing common cpp development package: libcommoncpp2-dev]))
-
-LIBCCEXT2_MIN_VERSION=1.3.1
-PKG_CHECK_MODULES(CCEXT2, libccext2 >= ${LIBCCEXT2_MIN_VERSION})
+PKG_CHECK_MODULES([CCGNU2], [commoncpp] >= ${LIBCCGNU2_MIN_VERSION}, AC_DEFINE_UNQUOTED([COMMONCPP_PREFIX], [1], [Use commoncpp include prefix]), [
+        PKG_CHECK_MODULES([CCGNU2], [libccgnu2] >= ${LIBCCGNU2_MIN_VERSION}, AC_DEFINE_UNQUOTED([CCPP_PREFIX], [1], [Use cc++ include prefix]),
+            AC_MSG_ERROR([Missing common cpp development package: libcommoncpp2-dev]))
+        ])
 
-LIBCCRT_MIN_VERSION=1.3.0
-PKG_CHECK_MODULES(CCRTP, libccrtp1 >= ${LIBCCRT_MIN_VERSION},, AC_MSG_ERROR([Missing ccrtp development package: libccrtp-dev]))
+LIBCCRTP_MIN_VERSION=1.3.0
+PKG_CHECK_MODULES([CCRTP], [libccrtp] >= ${LIBCCRTP_MIN_VERSION},, [
+        PKG_CHECK_MODULES([CCRTP], [libccrtp1] >= ${LIBCCRTP_MIN_VERSION},, AC_MSG_ERROR([Missing ccrtp development package: libccrtp-dev]))
+        ])
 
 dnl Check for OpenSSL to link against pjsip and provide SIPS TLS support
 PKG_CHECK_MODULES([libssl], libssl,, AC_MSG_ERROR([Missing ssl development package: libssl-dev]))
@@ -218,37 +214,6 @@ AC_SEARCH_LIBS([speex_preprocess_run], [speexdsp], [], [
        AC_MSG_ERROR([Unable to find speexdsp development files])
 ])
 
-# check for libcelt
-AC_ARG_WITH([celt], [AS_HELP_STRING([--without-celt],
-            [disable support for celt codec])], [], [with_celt=yes])
-
-AS_IF([test "x$with_celt" != xno],
-    [PKG_CHECK_MODULES(CELT, celt >= 0.9.1,
-        [
-            with_celt_91=yes; AC_MSG_NOTICE([Using celt 0.9.1])
-        ],
-        [
-            PKG_CHECK_MODULES(CELT, celt >= 0.7.1,
-            [
-                with_celt_71=yes; AC_MSG_NOTICE([Using celt 0.7.1])
-            ],
-            [
-dnl celt071 is how certain distros package celt
-        PKG_CHECK_MODULES(CELT, celt071 >= 0.7.1,
-        [
-            with_celt_071=yes; AC_MSG_NOTICE([Using celt071])
-        ],
-        [
-                     AC_MSG_FAILURE([libcelt link test failed. You may use --without-celt to compile without celt codec support.])
-        ])
-        ])
-    ])]
-)
-
-AM_CONDITIONAL(BUILD_CELT_91, test "x$with_celt_91" = "xyes" )
-AM_CONDITIONAL(BUILD_CELT_71, test "x$with_celt_71" = "xyes" )
-AM_CONDITIONAL(BUILD_CELT_071, test "x$with_celt_071" = "xyes" )
-
 dnl Check for IAX
 AC_ARG_WITH([iax2], [AS_HELP_STRING([--without-iax2],
             [disable support for the iax2 protocol])], [], [with_iax2=yes])
@@ -285,8 +250,6 @@ CXXFLAGS="${CXXFLAGS} -g -Wno-return-type -Wall -Wextra -Wnon-virtual-dtor -Weff
 dnl What to generate
 AC_CONFIG_FILES([Makefile])
 AC_CONFIG_FILES([libs/Makefile \
-                 libs/utilspp/Makefile \
-                 libs/utilspp/singleton/Makefile \
                  libs/iax2/Makefile])
 
 AC_CONFIG_FILES([src/Makefile \
diff --git a/daemon/globals.mak b/daemon/globals.mak
index f9c1582cac2f4d2fb18b05c7bae156a7a3cb8a4b..9bbe2ef629bab6dd79d0029e0ebf20779f91cf72 100644
--- a/daemon/globals.mak
+++ b/daemon/globals.mak
@@ -9,20 +9,8 @@ ASTYLERC="$(top_srcdir)/../astylerc"
 indent="/usr/bin/astyle"
 
 # for pjsip
-PJSIP_LIBS= \
-			-L$(src)/libs/pjproject/pjnath/lib/ \
-			-L$(src)/libs/pjproject/pjsip/lib/ \
-			-L$(src)/libs/pjproject/pjlib/lib/ \
-			-L$(src)/libs/pjproject/pjlib-util/lib/ \
-			-L$(src)/libs/pjproject/pjmedia/lib/ \
-			-lpjnath-$(target) \
-			-lpjsua-$(target) \
-			-lpjsip-$(target) \
-			-lpjmedia-$(target) \
-			-lpjsip-simple-$(target) \
-			-lpjsip-ua-$(target) \
-			-lpjlib-util-$(target) \
-			-lpj-$(target)
+include $(src)/libs/pjproject/build.mak
+PJSIP_LIBS=$(APP_LDFLAGS) $(APP_LDLIBS)
 
 SIP_CFLAGS=-I$(src)/libs/pjproject/pjsip/include \
 		   -I$(src)/libs/pjproject/pjlib/include \
diff --git a/daemon/libs/Makefile.am b/daemon/libs/Makefile.am
index da08ea625d6194b4d887ad36554994d3917bad7d..105bcd0231a42a82de43d0f493962f5c01bef334 100644
--- a/daemon/libs/Makefile.am
+++ b/daemon/libs/Makefile.am
@@ -1,3 +1,3 @@
-SUBDIRS = utilspp iax2
+SUBDIRS = iax2
 
 EXTRA_DIST=pjproject
diff --git a/daemon/libs/pjproject/config.guess b/daemon/libs/pjproject/config.guess
index dff9e481b70f9505b49ce999629a168a19976f4f..d622a44e551f209d5e8c5462b3fe53a162f7b330 100755
--- a/daemon/libs/pjproject/config.guess
+++ b/daemon/libs/pjproject/config.guess
@@ -1,9 +1,10 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
-#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
-#   Free Software Foundation, Inc.
+#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+#   2011, 2012 Free Software Foundation, Inc.
 
-timestamp='2001-09-04'
+timestamp='2012-02-10'
 
 # 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
@@ -16,23 +17,24 @@ timestamp='2001-09-04'
 # 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.
+# along with this program; if not, see <http://www.gnu.org/licenses/>.
 #
 # 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.
 
-# Written by Per Bothner <bothner@cygnus.com>.
-# Please send patches to <config-patches@gnu.org>.
+
+# Originally written by Per Bothner.  Please send patches (context
+# diff format) to <config-patches@gnu.org> and include a ChangeLog
+# entry.
 #
 # This script attempts to guess a canonical system name similar to
 # config.sub.  If it succeeds, it prints the system name on stdout, and
 # exits with 0.  Otherwise, it exits with 1.
 #
-# The plan is that this can be called by configure scripts if you
-# don't specify an explicit build system type.
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
 
 me=`echo "$0" | sed -e 's,.*/,,'`
 
@@ -52,7 +54,8 @@ version="\
 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, 2006, 2007, 2008, 2009, 2010, 2011, 2012
 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
@@ -65,11 +68,11 @@ Try \`$me --help' for more information."
 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.
@@ -87,30 +90,42 @@ if test $# != 0; then
   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 ;
-	for c in cc gcc c89 ; do
-	  ($c $dummy.c -c -o $dummy.o) >/dev/null 2>&1 ;
-	  if test $? = 0 ; then
+# 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 "$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
+	  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@noc.rutgers.edu 1994-08-24)
@@ -127,32 +142,34 @@ UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
 
 case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
     *:NetBSD:*:*)
-	# Netbsd (nbsd) targets should (where applicable) match one or
-	# more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
+	# NetBSD (nbsd) targets should (where applicable) match one or
+	# more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*,
 	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
 	# switched to ELF, *-*-netbsd* would select the old
 	# object file format.  This provides both forward
 	# compatibility and a consistent mechanism for selecting the
 	# object file format.
-	# Determine the machine/vendor (is the vendor relevant).
-	case "${UNAME_MACHINE}" in
-	    amiga) machine=m68k-unknown ;;
-	    arm32) machine=arm-unknown ;;
-	    atari*) machine=m68k-atari ;;
-	    sun3*) machine=m68k-sun ;;
-	    mac68k) machine=m68k-apple ;;
-	    macppc) machine=powerpc-apple ;;
-	    hp3[0-9][05]) machine=m68k-hp ;;
-	    ibmrt|romp-ibm) machine=romp-ibm ;;
-	    *) machine=${UNAME_MACHINE}-unknown ;;
+	#
+	# Note: NetBSD doesn't particularly care about the vendor
+	# portion of the name.  We always set it to "unknown".
+	sysctl="sysctl -n hw.machine_arch"
+	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
+	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+	case "${UNAME_MACHINE_ARCH}" in
+	    armeb) machine=armeb-unknown ;;
+	    arm*) machine=arm-unknown ;;
+	    sh3el) machine=shl-unknown ;;
+	    sh3eb) machine=sh-unknown ;;
+	    sh5el) machine=sh5le-unknown ;;
+	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
 	esac
 	# The Operating System including object format, if it has switched
 	# to ELF recently, or will in the future.
-	case "${UNAME_MACHINE}" in
-	    i386|sparc|amiga|arm*|hp300|mvme68k|vax|atari|luna68k|mac68k|news68k|next68k|pc532|sun3*|x68k)
+	case "${UNAME_MACHINE_ARCH}" in
+	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
 		eval $set_cc_for_build
 		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
-			| grep __ELF__ >/dev/null
+			| grep -q __ELF__
 		then
 		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
 		    # Return netbsd for either.  FIX?
@@ -162,124 +179,135 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 		fi
 		;;
 	    *)
-	        os=netbsd
+		os=netbsd
 		;;
 	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 ;;
+	exit ;;
+    *:OpenBSD:*:*)
+	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 ;;
+    *:SolidBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
+	exit ;;
+    macppc:MirBSD:*:*)
+	echo powerpc-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'`
+	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.
+	exitcode=$?
+	trap '' 0
+	exit $exitcode ;;
     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;;
-    amiga:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
     *:[Aa]miga[Oo][Ss]:*:*)
 	echo ${UNAME_MACHINE}-unknown-amigaos
-	exit 0 ;;
-    arc64:OpenBSD:*:*)
-	echo mips64el-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    arc:OpenBSD:*:*)
-	echo mipsel-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    hkmips:OpenBSD:*:*)
-	echo mips-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    pmax:OpenBSD:*:*)
-	echo mipsel-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    sgi:OpenBSD:*:*)
-	echo mips-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    wgrisc:OpenBSD:*:*)
-	echo mipsel-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
+	exit ;;
+    *:[Mm]orph[Oo][Ss]:*:*)
+	echo ${UNAME_MACHINE}-unknown-morphos
+	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@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
 	if test "`(/bin/universe) 2>/dev/null`" = att ; then
@@ -287,25 +315,51 @@ EOF
 	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 ;;
+    s390x:SunOS:*:*)
+	echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
     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 ;;
-    i86pc:SunOS:5.*:*)
-	echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit 0 ;;
+	exit ;;
+    i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
+	echo i386-pc-auroraux${UNAME_RELEASE}
+	exit ;;
+    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+	eval $set_cc_for_build
+	SUN_ARCH="i386"
+	# If there is a compiler, see if it is configured for 64-bit objects.
+	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+	# This test works for both compilers.
+	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
+		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		grep IS_64BIT_ARCH >/dev/null
+	    then
+		SUN_ARCH="x86_64"
+	    fi
+	fi
+	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	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*)
@@ -314,12 +368,12 @@ EOF
 	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=`(head -1 /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
 	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
 	case "`/bin/arch`" in
 	    sun3)
@@ -329,16 +383,10 @@ EOF
 		echo sparc-sun-sunos${UNAME_RELEASE}
 		;;
 	esac
-	exit 0 ;;
+	exit ;;
     aushp:SunOS:*:*)
 	echo sparc-auspex-sunos${UNAME_RELEASE}
-	exit 0 ;;
-    sparc*:NetBSD:*)
-	echo `uname -p`-unknown-netbsd${UNAME_RELEASE}
-	exit 0 ;;
-    atari*:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${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
@@ -348,50 +396,41 @@ EOF
     # MiNT.  But MiNT is downward compatible to TOS, so this should
     # be no problem.
     atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
-        echo m68k-atari-mint${UNAME_RELEASE}
-	exit 0 ;;
+	echo m68k-atari-mint${UNAME_RELEASE}
+	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 ;;
+	echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
     milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
-        echo m68k-milan-mint${UNAME_RELEASE}
-        exit 0 ;;
+	echo m68k-milan-mint${UNAME_RELEASE}
+	exit ;;
     hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
-        echo m68k-hades-mint${UNAME_RELEASE}
-        exit 0 ;;
+	echo m68k-hades-mint${UNAME_RELEASE}
+	exit ;;
     *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
-        echo m68k-unknown-mint${UNAME_RELEASE}
-        exit 0 ;;
-    sun3*:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
-    mac68k:OpenBSD:*:*)
-	echo m68k-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 ;;
+	echo m68k-unknown-mint${UNAME_RELEASE}
+	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
@@ -415,30 +454,36 @@ EOF
 	  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`
+	# DG/UX returns AViiON for all architectures
+	UNAME_PROCESSOR=`/usr/bin/uname -p`
 	if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
 	then
 	    if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
@@ -451,29 +496,29 @@ EOF
 	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`
@@ -481,7 +526,7 @@ EOF
 		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
@@ -496,17 +541,20 @@ EOF
 			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 ;;
-    *:AIX:*:[45])
-	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | head -1 | awk '{ print $1 }'`
+	exit ;;
+    *:AIX:*:[4567])
+	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
 		IBM_ARCH=rs6000
 	else
@@ -518,96 +566,114 @@ EOF
 		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
 	    9000/31? )            HP_ARCH=m68000 ;;
 	    9000/[34]?? )         HP_ARCH=m68k ;;
 	    9000/[678][0-9][0-9])
-              case "${HPUX_REV}" in
-                11.[0-9][0-9])
-                  if [ -x /usr/bin/getconf ]; then
-                    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
-                    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
-                    case "${sc_cpu_version}" in
-                      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
-                      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
-                      532)                      # CPU_PA_RISC2_0
-                        case "${sc_kernel_bits}" in
-                          32) HP_ARCH="hppa2.0n" ;;
-                          64) HP_ARCH="hppa2.0w" ;;
-                        esac ;;
-                    esac
-                  fi ;;
-              esac
-              if [ "${HP_ARCH}" = "" ]; then
-	      eval $set_cc_for_build
-              sed 's/^              //' << EOF >$dummy.c
+		if [ -x /usr/bin/getconf ]; then
+		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+		    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+		    case "${sc_cpu_version}" in
+		      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+		      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+		      532)                      # CPU_PA_RISC2_0
+			case "${sc_kernel_bits}" in
+			  32) HP_ARCH="hppa2.0n" ;;
+			  64) HP_ARCH="hppa2.0w" ;;
+			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+			esac ;;
+		    esac
+		fi
+		if [ "${HP_ARCH}" = "" ]; then
+		    eval $set_cc_for_build
+		    sed 's/^		//' << EOF >$dummy.c
 
-              #define _HPUX_SOURCE
-              #include <stdlib.h>
-              #include <unistd.h>
+		#define _HPUX_SOURCE
+		#include <stdlib.h>
+		#include <unistd.h>
 
-              int main ()
-              {
-              #if defined(_SC_KERNEL_BITS)
-                  long bits = sysconf(_SC_KERNEL_BITS);
-              #endif
-                  long cpu  = sysconf (_SC_CPU_VERSION);
+		int main ()
+		{
+		#if defined(_SC_KERNEL_BITS)
+		    long bits = sysconf(_SC_KERNEL_BITS);
+		#endif
+		    long cpu  = sysconf (_SC_CPU_VERSION);
 
-                  switch (cpu)
-              	{
-              	case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
-              	case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
-              	case CPU_PA_RISC2_0:
-              #if defined(_SC_KERNEL_BITS)
-              	    switch (bits)
-              		{
-              		case 64: puts ("hppa2.0w"); break;
-              		case 32: puts ("hppa2.0n"); break;
-              		default: puts ("hppa2.0"); break;
-              		} break;
-              #else  /* !defined(_SC_KERNEL_BITS) */
-              	    puts ("hppa2.0"); break;
-              #endif
-              	default: puts ("hppa1.0"); break;
-              	}
-                  exit (0);
-              }
+		    switch (cpu)
+			{
+			case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+			case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+			case CPU_PA_RISC2_0:
+		#if defined(_SC_KERNEL_BITS)
+			    switch (bits)
+				{
+				case 64: puts ("hppa2.0w"); break;
+				case 32: puts ("hppa2.0n"); break;
+				default: puts ("hppa2.0"); break;
+				} break;
+		#else  /* !defined(_SC_KERNEL_BITS) */
+			    puts ("hppa2.0"); break;
+		#endif
+			default: puts ("hppa1.0"); break;
+			}
+		    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
-	fi ;;
+		    (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 -q __LP64__
+	    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
@@ -635,158 +701,173 @@ EOF
 	  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 ;;
-    hppa*:OpenBSD:*:*)
-	echo hppa-unknown-openbsd
-	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 ;;
-    CRAY*X-MP:*:*:*)
-	echo xmp-cray-unicos
-        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 ;;
-    CRAY-2:*:*:*)
-	echo cray2-cray-unicos
-        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 ;;
-    hp300:OpenBSD:*:*)
-	echo m68k-unknown-openbsd${UNAME_RELEASE}
-	exit 0 ;;
+	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+	FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+	echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+	exit ;;
+    5000:UNIX_System_V:4.*:*)
+	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+	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 ;;
-    *:OpenBSD:*:*)
-	echo ${UNAME_MACHINE}-unknown-openbsd`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
-	exit 0 ;;
+	UNAME_PROCESSOR=`/usr/bin/uname -p`
+	case ${UNAME_PROCESSOR} in
+	    amd64)
+		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    *)
+		echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	esac
+	exit ;;
     i*:CYGWIN*:*)
 	echo ${UNAME_MACHINE}-pc-cygwin
-	exit 0 ;;
-    i*:MINGW*:*)
+	exit ;;
+    *:MINGW*:*)
 	echo ${UNAME_MACHINE}-pc-mingw32
-	exit 0 ;;
+	exit ;;
+    i*:MSYS*:*)
+	echo ${UNAME_MACHINE}-pc-msys
+	exit ;;
+    i*:windows32*:*)
+	# uname -m includes "-pc" on this system.
+	echo ${UNAME_MACHINE}-mingw32
+	exit ;;
     i*:PW*:*)
 	echo ${UNAME_MACHINE}-pc-pw32
-	exit 0 ;;
+	exit ;;
+    *:Interix*:*)
+	case ${UNAME_MACHINE} in
+	    x86)
+		echo i586-pc-interix${UNAME_RELEASE}
+		exit ;;
+	    authenticamd | genuineintel | EM64T)
+		echo x86_64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	    IA64)
+		echo ia64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	esac ;;
+    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+	echo i${UNAME_MACHINE}-pc-mks
+	exit ;;
+    8664:Windows_NT:*)
+	echo x86_64-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 ;;
-    arm*:Linux:*:*)
+	exit ;;
+    aarch64:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
-    ia64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux
-	exit 0 ;;
-    m68*:Linux:*:*)
+	exit ;;
+    aarch64_be:Linux:*:*)
+	UNAME_MACHINE=aarch64_be
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
-	exit 0 ;;
-    mips:Linux:*:*)
-	case `sed -n '/^byte/s/^.*: \(.*\) endian/\1/p' < /proc/cpuinfo` in
-	  big)    echo mips-unknown-linux-gnu && exit 0 ;;
-	  little) echo mipsel-unknown-linux-gnu && exit 0 ;;
-	esac
-	;;
-    ppc:Linux:*:*)
-	echo powerpc-unknown-linux-gnu
-	exit 0 ;;
-    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 ;;
@@ -796,11 +877,90 @@ EOF
 	  EV6)   UNAME_MACHINE=alphaev6 ;;
 	  EV67)  UNAME_MACHINE=alphaev67 ;;
 	  EV68*) UNAME_MACHINE=alphaev68 ;;
-        esac
-	objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
+	esac
+	objdump --private-headers /bin/sh | grep -q ld.so.1
 	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
 	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
-	exit 0 ;;
+	exit ;;
+    arm*:Linux:*:*)
+	eval $set_cc_for_build
+	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+	    | grep -q __ARM_EABI__
+	then
+	    echo ${UNAME_MACHINE}-unknown-linux-gnu
+	else
+	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
+		| grep -q __ARM_PCS_VFP
+	    then
+		echo ${UNAME_MACHINE}-unknown-linux-gnueabi
+	    else
+		echo ${UNAME_MACHINE}-unknown-linux-gnueabihf
+	    fi
+	fi
+	exit ;;
+    avr32*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    cris:Linux:*:*)
+	echo ${UNAME_MACHINE}-axis-linux-gnu
+	exit ;;
+    crisv32:Linux:*:*)
+	echo ${UNAME_MACHINE}-axis-linux-gnu
+	exit ;;
+    frv:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    hexagon:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    i*86:Linux:*:*)
+	LIBC=gnu
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#ifdef __dietlibc__
+	LIBC=dietlibc
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
+	echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+	exit ;;
+    ia64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    m32r*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    m68*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    mips:Linux:*:* | mips64:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef ${UNAME_MACHINE}
+	#undef ${UNAME_MACHINE}el
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=${UNAME_MACHINE}el
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=${UNAME_MACHINE}
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	;;
+    or32:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    padre:Linux:*:*)
+	echo sparc-unknown-linux-gnu
+	exit ;;
+    parisc64:Linux:*:* | hppa64:Linux:*:*)
+	echo hppa64-unknown-linux-gnu
+	exit ;;
     parisc:Linux:*:* | hppa:Linux:*:*)
 	# Look for CPU level
 	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
@@ -808,92 +968,71 @@ EOF
 	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
 	  *)    echo hppa-unknown-linux-gnu ;;
 	esac
-	exit 0 ;;
-    parisc64:Linux:*:* | hppa64:Linux:*:*)
-	echo hppa64-unknown-linux-gnu
-	exit 0 ;;
+	exit ;;
+    ppc64:Linux:*:*)
+	echo powerpc64-unknown-linux-gnu
+	exit ;;
+    ppc:Linux:*:*)
+	echo powerpc-unknown-linux-gnu
+	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 ;;
+    tile*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    vax:Linux:*:*)
+	echo ${UNAME_MACHINE}-dec-linux-gnu
+	exit ;;
     x86_64:Linux:*:*)
-	echo x86_64-unknown-linux-gnu
-	exit 0 ;;
-    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
-	# problems with other programs or directories called `ld' in the path.
-	ld_supported_targets=`cd /; ld --help 2>&1 \
-			 | sed -ne '/supported targets:/!d
-				    s/[ 	][ 	]*/ /g
-				    s/.*supported targets: *//
-				    s/ .*//
-				    p'`
-        case "$ld_supported_targets" in
-	  elf32-i386)
-		TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu"
-		;;
-	  a.out-i386-linux)
-		echo "${UNAME_MACHINE}-pc-linux-gnuaout"
-		exit 0 ;;		
-	  coff-i386)
-		echo "${UNAME_MACHINE}-pc-linux-gnucoff"
-		exit 0 ;;
-	  "")
-		# 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 ;;
-	esac
-	# Determine whether the default compiler is a.out or elf
-	eval $set_cc_for_build
-	cat >$dummy.c <<EOF
-#include <features.h>
-#ifdef __cplusplus
-#include <stdio.h>  /* for printf() prototype */
-	int main (int argc, char *argv[]) {
-#else
-	int main (argc, argv) int argc; char *argv[]; {
-#endif
-#ifdef __ELF__
-# ifdef __GLIBC__
-#  if __GLIBC__ >= 2
-    printf ("%s-pc-linux-gnu\n", argv[1]);
-#  else
-    printf ("%s-pc-linux-gnulibc1\n", argv[1]);
-#  endif
-# else
-   printf ("%s-pc-linux-gnulibc1\n", argv[1]);
-# endif
-#else
-  printf ("%s-pc-linux-gnuaout\n", argv[1]);
-#endif
-  return 0;
-}
-EOF
-	$CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy "${UNAME_MACHINE}" && rm -f $dummy.c $dummy && exit 0
-	rm -f $dummy.c $dummy
-	test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0
-	;;
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    xtensa*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	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...
-        # I am not positive that other SVR4 systems won't match this,
+	# Unixware is an offshoot of SVR4, but it has its own version
+	# number series starting with 2...
+	# I am not positive that other SVR4 systems won't match this,
 	# I just have to hope.  -- rms.
-        # Use sysv4.2uw... so that sysv4* matches it.
+	# 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.[02]*:*)
+	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
@@ -901,99 +1040,113 @@ EOF
 	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 ;;
+	# uname -m prints for DJGPP always 'pc', but it prints nothing about
+	# the processor, so we play safe by assuming i586.
+	# Note: whatever this is, it MUST be the same as what config.sub
+	# prints for the "djgpp" host, or else GDB configury will decide that
+	# this is a cross-build.
+	echo i586-pc-msdosdjgpp
+	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 | 4850:*: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 ;;
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	  && { echo i486-ncr-sysv4; exit; } ;;
+    NCR*:*:4.2:* | MPRAS*:*:4.2:*)
+	OS_REL='.3'
+	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; }
+	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
+	    && { echo i586-ncr-sysv4.3${OS_REL}; 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 ;;
-    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
+	exit ;;
+    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
 	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`
@@ -1001,82 +1154,123 @@ EOF
 	else
 		echo ns32k-sni-sysv
 	fi
-	exit 0 ;;
-    PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
-                      # says <Richard.M.Bartel@ccMail.Census.GOV>
-        echo i586-unisys-sysv4
-        exit 0 ;;
+	exit ;;
+    PENTIUM:*:4.0*:*)	# Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+			# says <Richard.M.Bartel@ccMail.Census.GOV>
+	echo i586-unisys-sysv4
+	exit ;;
     *:UNIX_System_V:4*:FTX*)
 	# From Gerald Hewes <hewes@openmarket.com>.
 	# How about differentiating between stratus architectures? -djm
 	echo hppa1.1-stratus-sysv4
-	exit 0 ;;
+	exit ;;
     *:*:*:FTX*)
 	# From seanf@swdc.stratus.com.
 	echo i860-stratus-sysv4
-	exit 0 ;;
+	exit ;;
+    i*86:VOS:*:*)
+	# From Paul.Green@stratus.com.
+	echo ${UNAME_MACHINE}-stratus-vos
+	exit ;;
     *:VOS:*:*)
 	# From Paul.Green@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}
+		echo mips-nec-sysv${UNAME_RELEASE}
 	else
-	        echo mips-unknown-sysv${UNAME_RELEASE}
+		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 ;;
+    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
+	echo i586-pc-haiku
+	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 ;;
+    SX-7:SUPER-UX:*:*)
+	echo sx7-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8:SUPER-UX:*:*)
+	echo sx8-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8R:SUPER-UX:*:*)
+	echo sx8r-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
+	    i386)
+		eval $set_cc_for_build
+		if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+		  if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+		      (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		      grep IS_64BIT_ARCH >/dev/null
+		  then
+		      UNAME_PROCESSOR="x86_64"
+		  fi
+		fi ;;
+	    unknown) UNAME_PROCESSOR=powerpc ;;
+	esac
+	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+	exit ;;
     *:procnto*:*:* | *:QNX:[0123456789]*:*)
-	if test "${UNAME_MACHINE}" = "x86pc"; then
+	UNAME_PROCESSOR=`uname -p`
+	if test "$UNAME_PROCESSOR" = "x86"; then
+		UNAME_PROCESSOR=i386
 		UNAME_MACHINE=pc
 	fi
-	echo `uname -p`-${UNAME_MACHINE}-nto-qnx
-	exit 0 ;;
+	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+	exit ;;
     *:QNX:*:4*)
 	echo i386-pc-qnx
-	exit 0 ;;
-    NSR-[KW]:NONSTOP_KERNEL:*:*)
+	exit ;;
+    NEO-?:NONSTOP_KERNEL:*:*)
+	echo neo-tandem-nsk${UNAME_RELEASE}
+	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
@@ -1087,36 +1281,53 @@ EOF
 	    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 ;;
+    i*86:AROS:*:*)
+	echo ${UNAME_MACHINE}-pc-aros
+	exit ;;
+    x86_64:VMkernel:*:*)
+	echo ${UNAME_MACHINE}-unknown-esx
+	exit ;;
 esac
 
 #echo '(No uname command or uname output not recognized.)' 1>&2
@@ -1139,16 +1350,16 @@ main ()
 #include <sys/param.h>
   printf ("m68k-sony-newsos%s\n",
 #ifdef NEWSOS4
-          "4"
+	"4"
 #else
-	  ""
+	""
 #endif
-         ); exit (0);
+	); exit (0);
 #endif
 #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)
@@ -1237,12 +1448,12 @@ main ()
 }
 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)
 
@@ -1251,22 +1462,22 @@ then
     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
 
@@ -1277,7 +1488,9 @@ This script, last modified $timestamp, has failed to recognize
 the operating system you are using. It is advised that you
 download the most up to date version of the config scripts from
 
-    ftp://ftp.gnu.org/pub/gnu/config/
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+and
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
 
 If the version you run ($0) is already up to date, please
 send the following data and any information you think might be
diff --git a/daemon/libs/pjproject/config.sub b/daemon/libs/pjproject/config.sub
index 746ee208a175a4f263cc9a186f5dc8f420524274..c894da45500c4af1bf5688e713a8895622d18182 100755
--- a/daemon/libs/pjproject/config.sub
+++ b/daemon/libs/pjproject/config.sub
@@ -1,9 +1,10 @@
 #! /bin/sh
 # Configuration validation subroutine script.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+#   2011, 2012 Free Software Foundation, Inc.
 
-timestamp='2005-04-22'
+timestamp='2012-02-10'
 
 # This file is (in principle) common to ALL GNU software.
 # The presence of a machine in this file suggests that SOME GNU software
@@ -20,23 +21,25 @@ timestamp='2005-04-22'
 # 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.
-
+# along with this program; if not, see <http://www.gnu.org/licenses/>.
+#
 # 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.
 
+
 # Please send patches to <config-patches@gnu.org>.  Submit a context
-# diff and a properly formatted ChangeLog entry.
+# diff and a properly formatted GNU ChangeLog entry.
 #
 # Configuration subroutine to validate and canonicalize a configuration type.
 # Supply the specified configuration type as an argument.
 # If it is invalid, we print an error message on stderr and exit with code 1.
 # Otherwise, we print the canonical config type on stdout and succeed.
 
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
 # This file is supposed to be the same for all GNU packages
 # and recognize all the CPU types, system types and aliases
 # that are meaningful with *any* GNU software.
@@ -70,7 +73,8 @@ Report bugs and patches to <config-patches@gnu.org>."
 version="\
 GNU config.sub ($timestamp)
 
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
+2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
@@ -83,11 +87,11 @@ Try \`$me --help' for more information."
 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.
@@ -99,7 +103,7 @@ while test $# -gt 0 ; do
     *local*)
        # First pass through any local machine types.
        echo $1
-       exit 0;;
+       exit ;;
 
     * )
        break ;;
@@ -118,11 +122,18 @@ esac
 # 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* | linux-dietlibc | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | \
-  kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | storm-chaos* | os2-emx* | rtmk-nova*)
+  nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
+  linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
+  knetbsd*-gnu* | netbsd*-gnu* | \
+  kopensolaris*-gnu* | \
+  storm-chaos* | os2-emx* | rtmk-nova*)
     os=-$maybe_os
     basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
     ;;
+  android-linux)
+    os=-linux-android
+    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
+    ;;
   *)
     basic_machine=`echo $1 | sed 's/-[^-]*$//'`
     if [ $basic_machine != $1 ]
@@ -145,10 +156,13 @@ case $os in
 	-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 | -knuth | -cray)
+	-apple | -axis | -knuth | -cray | -microblaze)
 		os=
 		basic_machine=$1
 		;;
+	-bluegene*)
+		os=-cnk
+		;;
 	-sim | -cisco | -oki | -wec | -winbond)
 		os=
 		basic_machine=$1
@@ -163,13 +177,17 @@ case $os in
 		os=-chorusos
 		basic_machine=$1
 		;;
- 	-chorusrdb)
- 		os=-chorusrdb
+	-chorusrdb)
+		os=-chorusrdb
 		basic_machine=$1
- 		;;
+		;;
 	-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/'`
@@ -186,6 +204,10 @@ case $os in
 		# 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/'`
@@ -227,26 +249,36 @@ case $basic_machine in
 	# Some are omitted here because they have special meanings below.
 	1750a | 580 \
 	| a29k \
+	| aarch64 | aarch64_be \
 	| 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 \
+	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \
+        | be32 | be64 \
 	| bfin \
 	| c4x | clipper \
 	| d10v | d30v | dlx | dsp16xx \
-	| fr30 | frv \
+	| epiphany \
+	| fido | fr30 | frv \
 	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+	| hexagon \
 	| i370 | i860 | i960 | ia64 \
 	| ip2k | iq2000 \
-	| m32r | m32rle | m68000 | m68k | m88k | maxq | mcore \
+	| le32 | le64 \
+	| lm32 \
+	| m32c | m32r | m32rle | m68000 | m68k | m88k \
+	| maxq | mb | microblaze | mcore | mep | metag \
 	| mips | mipsbe | mipseb | mipsel | mipsle \
 	| mips16 \
 	| mips64 | mips64el \
-	| mips64vr | mips64vrel \
+	| mips64octeon | mips64octeonel \
 	| mips64orion | mips64orionel \
+	| mips64r5900 | mips64r5900el \
+	| mips64vr | mips64vrel \
 	| mips64vr4100 | mips64vr4100el \
 	| mips64vr4300 | mips64vr4300el \
 	| mips64vr5000 | mips64vr5000el \
+	| mips64vr5900 | mips64vr5900el \
 	| mipsisa32 | mipsisa32el \
 	| mipsisa32r2 | mipsisa32r2el \
 	| mipsisa64 | mipsisa64el \
@@ -255,31 +287,65 @@ case $basic_machine in
 	| mipsisa64sr71k | mipsisa64sr71kel \
 	| mipstx39 | mipstx39el \
 	| mn10200 | mn10300 \
+	| moxie \
+	| mt \
 	| msp430 \
+	| nds32 | nds32le | nds32be \
+	| nios | nios2 \
 	| ns16k | ns32k \
-	| openrisc | or32 \
+	| open8 \
+	| or32 \
 	| pdp10 | pdp11 | pj | pjl \
-	| powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
+	| powerpc | powerpc64 | powerpc64le | powerpcle \
 	| pyramid \
-	| sh | sh[1234] | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \
+	| rl78 | rx \
+	| score \
+	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
 	| sh64 | sh64le \
-	| sparc | sparc64 | sparc64b | sparc86x | sparclet | sparclite \
-	| sparcv8 | sparcv9 | sparcv9b \
-	| strongarm \
-	| tahoe | thumb | tic4x | tic80 | tron \
-	| v850 | v850e \
+	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+	| spu \
+	| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
+	| ubicom32 \
+	| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
 	| we32k \
-	| x86 | xscale | xscalee[bl] | xstormy16 | xtensa \
-	| z8k)
+	| x86 | xc16x | xstormy16 | xtensa \
+	| z8k | z80)
 		basic_machine=$basic_machine-unknown
 		;;
-	m6811 | m68hc11 | m6812 | m68hc12)
-		# Motorola 68HC11/12.
+	c54x)
+		basic_machine=tic54x-unknown
+		;;
+	c55x)
+		basic_machine=tic55x-unknown
+		;;
+	c6x)
+		basic_machine=tic6x-unknown
+		;;
+	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip)
 		basic_machine=$basic_machine-unknown
 		os=-none
 		;;
 	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
 		;;
+	ms1)
+		basic_machine=mt-unknown
+		;;
+
+	strongarm | thumb | xscale)
+		basic_machine=arm-unknown
+		;;
+	xgate)
+		basic_machine=$basic_machine-unknown
+		os=-none
+		;;
+	xscaleeb)
+		basic_machine=armeb-unknown
+		;;
+
+	xscaleel)
+		basic_machine=armel-unknown
+		;;
 
 	# We use `pc' rather than `unknown'
 	# because (1) that's what they normally are, and
@@ -295,32 +361,40 @@ case $basic_machine in
 	# Recognize the basic CPU types with company name.
 	580-* \
 	| a29k-* \
+	| aarch64-* | aarch64_be-* \
 	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
 	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
 	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
 	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
-	| avr-* \
+	| avr-* | avr32-* \
+	| be32-* | be64-* \
 	| bfin-* | bs2000-* \
-	| c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
+	| c[123]* | c30-* | [cjt]90-* | c4x-* \
 	| clipper-* | craynv-* | cydra-* \
 	| d10v-* | d30v-* | dlx-* \
 	| elxsi-* \
-	| f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
+	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
 	| h8300-* | h8500-* \
 	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+	| hexagon-* \
 	| i*86-* | i860-* | i960-* | ia64-* \
 	| ip2k-* | iq2000-* \
-	| m32r-* | m32rle-* \
+	| le32-* | le64-* \
+	| lm32-* \
+	| m32c-* | m32r-* | m32rle-* \
 	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
-	| m88110-* | m88k-* | maxq-* | mcore-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \
 	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
 	| mips16-* \
 	| mips64-* | mips64el-* \
-	| mips64vr-* | mips64vrel-* \
+	| mips64octeon-* | mips64octeonel-* \
 	| mips64orion-* | mips64orionel-* \
+	| mips64r5900-* | mips64r5900el-* \
+	| mips64vr-* | mips64vrel-* \
 	| mips64vr4100-* | mips64vr4100el-* \
 	| mips64vr4300-* | mips64vr4300el-* \
 	| mips64vr5000-* | mips64vr5000el-* \
+	| mips64vr5900-* | mips64vr5900el-* \
 	| mipsisa32-* | mipsisa32el-* \
 	| mipsisa32r2-* | mipsisa32r2el-* \
 	| mipsisa64-* | mipsisa64el-* \
@@ -329,27 +403,38 @@ case $basic_machine in
 	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
 	| mipstx39-* | mipstx39el-* \
 	| mmix-* \
+	| mt-* \
 	| msp430-* \
+	| nds32-* | nds32le-* | nds32be-* \
+	| nios-* | nios2-* \
 	| none-* | np1-* | ns16k-* | ns32k-* \
+	| open8-* \
 	| orion-* \
 	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
-	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
+	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
 	| pyramid-* \
-	| romp-* | rs6000-* \
-	| sh-* | sh[1234]-* | sh[23]e-* | sh[34]eb-* | shbe-* \
+	| rl78-* | romp-* | rs6000-* | rx-* \
+	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
 	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
-	| sparc-* | sparc64-* | sparc64b-* | sparc86x-* | sparclet-* \
+	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
 	| sparclite-* \
-	| sparcv8-* | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \
-	| tahoe-* | thumb-* \
+	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
+	| tahoe-* \
 	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+	| tile*-* \
 	| tron-* \
-	| v850-* | v850e-* | vax-* \
+	| ubicom32-* \
+	| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
+	| vax-* \
 	| we32k-* \
-	| x86-* | x86_64-* | xps100-* | xscale-* | xscalee[bl]-* \
-	| xstormy16-* | xtensa-* \
+	| x86-* | x86_64-* | xc16x-* | xps100-* \
+	| xstormy16-* | xtensa*-* \
 	| ymp-* \
-	| z8k-*)
+	| z8k-* | z80-*)
+		;;
+	# Recognize the basic CPU types without company name, with glob match.
+	xtensa*)
+		basic_machine=$basic_machine-unknown
 		;;
 	# Recognize the various machine names and aliases which stand
 	# for a CPU type and a company and sometimes even an OS.
@@ -367,7 +452,7 @@ case $basic_machine in
 		basic_machine=a29k-amd
 		os=-udi
 		;;
-    	abacus)
+	abacus)
 		basic_machine=abacus-unknown
 		;;
 	adobe68k)
@@ -413,6 +498,10 @@ case $basic_machine in
 		basic_machine=m68k-apollo
 		os=-bsd
 		;;
+	aros)
+		basic_machine=i386-pc
+		os=-aros
+		;;
 	aux)
 		basic_machine=m68k-apple
 		os=-aux
@@ -421,10 +510,35 @@ case $basic_machine in
 		basic_machine=ns32k-sequent
 		os=-dynix
 		;;
+	blackfin)
+		basic_machine=bfin-unknown
+		os=-linux
+		;;
+	blackfin-*)
+		basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	bluegene*)
+		basic_machine=powerpc-ibm
+		os=-cnk
+		;;
+	c54x-*)
+		basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c55x-*)
+		basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c6x-*)
+		basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
 	c90)
 		basic_machine=c90-cray
 		os=-unicos
 		;;
+	cegcc)
+		basic_machine=arm-unknown
+		os=-cegcc
+		;;
 	convex-c1)
 		basic_machine=c1-convex
 		os=-bsd
@@ -453,8 +567,8 @@ case $basic_machine in
 		basic_machine=craynv-cray
 		os=-unicosmp
 		;;
-	cr16c)
-		basic_machine=cr16c-unknown
+	cr16 | cr16-*)
+		basic_machine=cr16-unknown
 		os=-elf
 		;;
 	crds | unos)
@@ -492,6 +606,10 @@ case $basic_machine in
 		basic_machine=m88k-motorola
 		os=-sysv3
 		;;
+	dicos)
+		basic_machine=i686-pc
+		os=-dicos
+		;;
 	djgpp)
 		basic_machine=i586-pc
 		os=-msdosdjgpp
@@ -607,7 +725,6 @@ case $basic_machine in
 	i370-ibm* | ibm*)
 		basic_machine=i370-ibm
 		;;
-# I'm not sure what "Sysv32" means.  Should this be sysv3.2?
 	i*86v32)
 		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
 		os=-sysv32
@@ -646,6 +763,14 @@ case $basic_machine in
 		basic_machine=m68k-isi
 		os=-sysv
 		;;
+	m68knommu)
+		basic_machine=m68k-unknown
+		os=-linux
+		;;
+	m68knommu-*)
+		basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
 	m88k-omron*)
 		basic_machine=m88k-omron
 		;;
@@ -657,10 +782,17 @@ case $basic_machine in
 		basic_machine=ns32k-utek
 		os=-sysv
 		;;
+	microblaze)
+		basic_machine=microblaze-xilinx
+		;;
 	mingw32)
 		basic_machine=i386-pc
 		os=-mingw32
 		;;
+	mingw32ce)
+		basic_machine=arm-unknown
+		os=-mingw32ce
+		;;
 	miniframe)
 		basic_machine=m68000-convergent
 		;;
@@ -686,10 +818,21 @@ case $basic_machine in
 		basic_machine=i386-pc
 		os=-msdos
 		;;
+	ms1-*)
+		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+		;;
+	msys)
+		basic_machine=i386-pc
+		os=-msys
+		;;
 	mvs)
 		basic_machine=i370-ibm
 		os=-mvs
 		;;
+	nacl)
+		basic_machine=le32-unknown
+		os=-nacl
+		;;
 	ncr3000)
 		basic_machine=i486-ncr
 		os=-sysv4
@@ -754,6 +897,12 @@ case $basic_machine in
 	np1)
 		basic_machine=np1-gould
 		;;
+	neo-tandem)
+		basic_machine=neo-tandem
+		;;
+	nse-tandem)
+		basic_machine=nse-tandem
+		;;
 	nsr-tandem)
 		basic_machine=nsr-tandem
 		;;
@@ -761,9 +910,8 @@ case $basic_machine in
 		basic_machine=hppa1.1-oki
 		os=-proelf
 		;;
-	or32 | or32-*)
+	openrisc | openrisc-*)
 		basic_machine=or32-unknown
-		os=-coff
 		;;
 	os400)
 		basic_machine=powerpc-ibm
@@ -785,6 +933,14 @@ case $basic_machine in
 		basic_machine=i860-intel
 		os=-osf
 		;;
+	parisc)
+		basic_machine=hppa-unknown
+		os=-linux
+		;;
+	parisc-*)
+		basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
 	pbd)
 		basic_machine=sparc-tti
 		;;
@@ -794,6 +950,12 @@ case $basic_machine in
 	pc532 | pc532-*)
 		basic_machine=ns32k-pc532
 		;;
+	pc98)
+		basic_machine=i386-pc
+		;;
+	pc98-*)
+		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
 	pentium | p5 | k5 | k6 | nexgen | viac3)
 		basic_machine=i586-pc
 		;;
@@ -823,9 +985,10 @@ case $basic_machine in
 		;;
 	power)	basic_machine=power-ibm
 		;;
-	ppc)	basic_machine=powerpc-unknown
+	ppc | ppcbe)	basic_machine=powerpc-unknown
 		;;
-	ppc-*)	basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+	ppc-* | ppcbe-*)
+		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
 	ppcle | powerpclittle | ppc-le | powerpc-little)
 		basic_machine=powerpcle-unknown
@@ -850,6 +1013,10 @@ case $basic_machine in
 		basic_machine=i586-unknown
 		os=-pw32
 		;;
+	rdos)
+		basic_machine=i386-pc
+		os=-rdos
+		;;
 	rom68k)
 		basic_machine=m68k-rom68k
 		os=-coff
@@ -876,6 +1043,10 @@ case $basic_machine in
 	sb1el)
 		basic_machine=mipsisa64sb1el-unknown
 		;;
+	sde)
+		basic_machine=mipsisa32-sde
+		os=-elf
+		;;
 	sei)
 		basic_machine=mips-sei
 		os=-seiux
@@ -887,6 +1058,9 @@ case $basic_machine in
 		basic_machine=sh-hitachi
 		os=-hms
 		;;
+	sh5el)
+		basic_machine=sh5le-unknown
+		;;
 	sh64)
 		basic_machine=sh64-unknown
 		;;
@@ -908,6 +1082,9 @@ case $basic_machine in
 		basic_machine=i860-stratus
 		os=-sysv4
 		;;
+	strongarm-* | thumb-*)
+		basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
 	sun2)
 		basic_machine=m68000-sun
 		;;
@@ -964,17 +1141,9 @@ case $basic_machine in
 		basic_machine=t90-cray
 		os=-unicos
 		;;
-	tic54x | c54x*)
-		basic_machine=tic54x-unknown
-		os=-coff
-		;;
-	tic55x | c55x*)
-		basic_machine=tic55x-unknown
-		os=-coff
-		;;
-	tic6x | c6x*)
-		basic_machine=tic6x-unknown
-		os=-coff
+	tile*)
+		basic_machine=$basic_machine-unknown
+		os=-linux-gnu
 		;;
 	tx39)
 		basic_machine=mipstx39-unknown
@@ -1043,6 +1212,9 @@ case $basic_machine in
 	xps | xps100)
 		basic_machine=xps100-honeywell
 		;;
+	xscale-* | xscalee[bl]-*)
+		basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
+		;;
 	ymp)
 		basic_machine=ymp-cray
 		os=-unicos
@@ -1051,6 +1223,10 @@ case $basic_machine in
 		basic_machine=z8k-unknown
 		os=-sim
 		;;
+	z80-*-coff)
+		basic_machine=z80-unknown
+		os=-sim
+		;;
 	none)
 		basic_machine=none-none
 		os=-none
@@ -1089,13 +1265,10 @@ case $basic_machine in
 	we32k)
 		basic_machine=we32k-att
 		;;
-	sh3 | sh4 | sh[34]eb | sh[1234]le | sh[23]ele)
+	sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
 		basic_machine=sh-unknown
 		;;
-	sh64)
-		basic_machine=sh64-unknown
-		;;
-	sparc | sparcv8 | sparcv9 | sparcv9b)
+	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
 		basic_machine=sparc-sun
 		;;
 	cydra)
@@ -1113,9 +1286,6 @@ case $basic_machine in
 	pmac | pmac-mpw)
 		basic_machine=powerpc-apple
 		;;
-	nios2*)
-		basic_machine=nios2-altera
-		;;
 	*-unknown)
 		# Make sure to match an already-canonicalized machine name.
 		;;
@@ -1142,9 +1312,12 @@ esac
 if [ x"$os" != x"" ]
 then
 case $os in
-        # First match some system type aliases
-        # that might get confused with valid system types.
+	# First match some system type aliases
+	# that might get confused with valid system types.
 	# -solaris* is a basic system type, with this one exception.
+	-auroraux)
+		os=-auroraux
+		;;
 	-solaris1 | -solaris1.*)
 		os=`echo $os | sed -e 's|solaris1|sunos4|'`
 		;;
@@ -1165,26 +1338,31 @@ case $os in
 	# Each alternative MUST END IN A *, to match a version number.
 	# -sysv* is not here because it comes later, after sysvr4.
 	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
-	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
-	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
+	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
+	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
+	      | -sym* | -kopensolaris* \
 	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
-	      | -aos* \
+	      | -aos* | -aros* \
 	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
 	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
-	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* | -openbsd* \
+	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+	      | -openbsd* | -solidbsd* \
 	      | -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* | -linux-uclibc* | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -chorusos* | -chorusrdb* | -cegcc* \
+	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+	      | -mingw32* | -linux-gnu* | -linux-android* \
+	      | -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* | -windiss* \
-	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly*)
+	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
 	# Remember, each alternative MUST END IN *, to match a version number.
 		;;
 	-qnx*)
@@ -1202,7 +1380,7 @@ case $os in
 		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*)
@@ -1223,7 +1401,7 @@ case $os in
 	-opened*)
 		os=-openedition
 		;;
-        -os400*)
+	-os400*)
 		os=-os400
 		;;
 	-wince*)
@@ -1272,7 +1450,7 @@ case $os in
 	-sinix*)
 		os=-sysv4
 		;;
-        -tpf*)
+	-tpf*)
 		os=-tpf
 		;;
 	-triton*)
@@ -1314,6 +1492,11 @@ case $os in
 	-zvmoe)
 		os=-zvmoe
 		;;
+	-dicos*)
+		os=-dicos
+		;;
+	-nacl*)
+		;;
 	-none)
 		;;
 	*)
@@ -1336,6 +1519,12 @@ else
 # system, and we'll never get to this point.
 
 case $basic_machine in
+	score-*)
+		os=-elf
+		;;
+	spu-*)
+		os=-elf
+		;;
 	*-acorn)
 		os=-riscix1.2
 		;;
@@ -1345,9 +1534,18 @@ case $basic_machine in
 	arm*-semi)
 		os=-aout
 		;;
-    c4x-* | tic4x-*)
-        os=-coff
-        ;;
+	c4x-* | tic4x-*)
+		os=-coff
+		;;
+	tic54x-*)
+		os=-coff
+		;;
+	tic55x-*)
+		os=-coff
+		;;
+	tic6x-*)
+		os=-coff
+		;;
 	# This must come before the *-dec entry.
 	pdp10-*)
 		os=-tops20
@@ -1366,13 +1564,13 @@ case $basic_machine in
 		;;
 	m68000-sun)
 		os=-sunos3
-		# This also exists in the configure program, but was not the
-		# default.
-		# os=-sunos4
 		;;
 	m68*-cisco)
 		os=-aout
 		;;
+	mep-*)
+		os=-elf
+		;;
 	mips*-cisco)
 		os=-elf
 		;;
@@ -1391,10 +1589,13 @@ case $basic_machine in
 	*-be)
 		os=-beos
 		;;
+	*-haiku)
+		os=-haiku
+		;;
 	*-ibm)
 		os=-aix
 		;;
-    	*-knuth)
+	*-knuth)
 		os=-mmixware
 		;;
 	*-wec)
@@ -1499,7 +1700,7 @@ case $basic_machine in
 			-sunos*)
 				vendor=sun
 				;;
-			-aix*)
+			-cnk*|-aix*)
 				vendor=ibm
 				;;
 			-beos*)
@@ -1562,7 +1763,7 @@ case $basic_machine in
 esac
 
 echo $basic_machine$os
-exit 0
+exit
 
 # Local variables:
 # eval: (add-hook 'write-file-hooks 'time-stamp)
diff --git a/daemon/libs/utilspp/Makefile.am b/daemon/libs/utilspp/Makefile.am
deleted file mode 100644
index 403b7fc158899e61b14337c92505efb4f8e6b2ba..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/Makefile.am
+++ /dev/null
@@ -1,10 +0,0 @@
-SUBDIRS = singleton
-
-noinst_LTLIBRARIES = libutilspp.la
-
-libutilspp_la_SOURCES = \
-	null_type.hpp \
-	singleton.hpp \
-	threading_single.hpp threading_single.inl
-
-libutilspp_la_LIBADD = ./singleton/libsingleton.la
diff --git a/daemon/libs/utilspp/null_type.hpp b/daemon/libs/utilspp/null_type.hpp
deleted file mode 100644
index 0ba1208ad44028f147ecbbd0840d299771d7e88a..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/null_type.hpp
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- *    Copyright (c) <2002-2004> <Jean-Philippe Barrette-LaPierre>
- *
- *    Permission is hereby granted, free of charge, to any person obtaining
- *    a copy of this software and associated documentation files
- *    (cURLpp), to deal in the Software without restriction,
- *    including without limitation the rights to use, copy, modify, merge,
- *    publish, distribute, sublicense, and/or sell copies of the Software,
- *    and to permit persons to whom the Software is furnished to do so,
- *    subject to the following conditions:
- *
- *    The above copyright notice and this permission notice shall be included
- *    in all copies or substantial portions of the Software.
- *
- *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef UTILSPP_NULLTYPE_HPP
-#define UTILSPP_NULLTYPE_HPP
-
-namespace utilspp
-{
-	struct NullType;
-}
-
-#endif
diff --git a/daemon/libs/utilspp/singleton.hpp b/daemon/libs/utilspp/singleton.hpp
deleted file mode 100644
index 649394f938addcb72c6cb317953dd20b4cf6c3a8..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/singleton.hpp
+++ /dev/null
@@ -1,2 +0,0 @@
-#include "threading_single.hpp"
-#include "singleton/singleton_holder.hpp"
diff --git a/daemon/libs/utilspp/singleton/Makefile.am b/daemon/libs/utilspp/singleton/Makefile.am
deleted file mode 100644
index d494c4c5e8f963fd9a25b28abd8e576bbb0e78d9..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/singleton/Makefile.am
+++ /dev/null
@@ -1,6 +0,0 @@
-noinst_LTLIBRARIES = libsingleton.la
-
-libsingleton_la_SOURCES = \
-	creation_using_new.hpp creation_using_new.inl \
-	lifetime_default.hpp lifetime_default.inl \
-	singleton_holder.hpp singleton_holder.inl
diff --git a/daemon/libs/utilspp/singleton/creation_using_new.hpp b/daemon/libs/utilspp/singleton/creation_using_new.hpp
deleted file mode 100644
index fe94f128528572979518adbf753436e8338a2b83..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/singleton/creation_using_new.hpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *    Copyright (c) <2002-2004> <Jean-Philippe Barrette-LaPierre>
- *
- *    Permission is hereby granted, free of charge, to any person obtaining
- *    a copy of this software and associated documentation files
- *    (cURLpp), to deal in the Software without restriction,
- *    including without limitation the rights to use, copy, modify, merge,
- *    publish, distribute, sublicense, and/or sell copies of the Software,
- *    and to permit persons to whom the Software is furnished to do so,
- *    subject to the following conditions:
- *
- *    The above copyright notice and this permission notice shall be included
- *    in all copies or substantial portions of the Software.
- *
- *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef __CREATION_USING_NEW_HPP__
-#define __CREATION_USING_NEW_HPP__
-
-/**
- * This class is a creation policy for the utilspp::singleton_holder. The
- * policy is creating the singleton by a "new" call.
- */
-namespace utilspp
-{
-   template< typename T >
-   struct CreationUsingNew
-   {
-         static T *create();
-         static void destroy( T *obj );
-   };
-}
-
-#include "creation_using_new.inl"
-#endif // __CREATION_USING_NEW_HPP__
diff --git a/daemon/libs/utilspp/singleton/creation_using_new.inl b/daemon/libs/utilspp/singleton/creation_using_new.inl
deleted file mode 100644
index 5c9ae88eb8d07084494879f7849ef0d994015f78..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/singleton/creation_using_new.inl
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *    Copyright (c) <2002-2004> <Jean-Philippe Barrette-LaPierre>
- *
- *    Permission is hereby granted, free of charge, to any person obtaining
- *    a copy of this software and associated documentation files
- *    (cURLpp), to deal in the Software without restriction,
- *    including without limitation the rights to use, copy, modify, merge,
- *    publish, distribute, sublicense, and/or sell copies of the Software,
- *    and to permit persons to whom the Software is furnished to do so,
- *    subject to the following conditions:
- *
- *    The above copyright notice and this permission notice shall be included
- *    in all copies or substantial portions of the Software.
- *
- *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef CREATION_USING_NEW_INL
-#define CREATION_USING_NEW_INL
-
-template< typename T >
-T *
-utilspp::CreationUsingNew< T >::create()
-{
-   return new T;
-}
-
-template< typename T >
-void
-utilspp::CreationUsingNew< T >::destroy( T *obj )
-{
-   delete obj;
-}
-
-
-#endif
diff --git a/daemon/libs/utilspp/singleton/lifetime_default.hpp b/daemon/libs/utilspp/singleton/lifetime_default.hpp
deleted file mode 100644
index ba0208c0a2fbf4e5a7fcb0c5ce10fe7873140078..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/singleton/lifetime_default.hpp
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- *    Copyright (c) <2002-2004> <Jean-Philippe Barrette-LaPierre>
- *
- *    Permission is hereby granted, free of charge, to any person obtaining
- *    a copy of this software and associated documentation files
- *    (cURLpp), to deal in the Software without restriction,
- *    including without limitation the rights to use, copy, modify, merge,
- *    publish, distribute, sublicense, and/or sell copies of the Software,
- *    and to permit persons to whom the Software is furnished to do so,
- *    subject to the following conditions:
- *
- *    The above copyright notice and this permission notice shall be included
- *    in all copies or substantial portions of the Software.
- *
- *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef LIFETIME_DEFAULT_HPP
-#define LIFETIME_DEFAULT_HPP
-
-namespace utilspp
-{
-   template< typename T >
-   class LifetimeDefault
-   {
-      public:
-         static void scheduleDestruction( T *obj, void (*func)() );
-         static void onDeadReference();
-   };
-}
-
-#include "lifetime_default.inl"
-
-#endif
diff --git a/daemon/libs/utilspp/singleton/lifetime_default.inl b/daemon/libs/utilspp/singleton/lifetime_default.inl
deleted file mode 100644
index 6760ececcd6d07376fc9b33df7556d1b4d092063..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/singleton/lifetime_default.inl
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *    Copyright (c) <2002-2004> <Jean-Philippe Barrette-LaPierre>
- *
- *    Permission is hereby granted, free of charge, to any person obtaining
- *    a copy of this software and associated documentation files
- *    (cURLpp), to deal in the Software without restriction,
- *    including without limitation the rights to use, copy, modify, merge,
- *    publish, distribute, sublicense, and/or sell copies of the Software,
- *    and to permit persons to whom the Software is furnished to do so,
- *    subject to the following conditions:
- *
- *    The above copyright notice and this permission notice shall be included
- *    in all copies or substantial portions of the Software.
- *
- *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef __LIFETIME_DEFAULT_INL__
-#define __LIFETIME_DEFAULT_INL__
-
-#include <cstdlib>
-#include <stdexcept>
-
-template< typename T >
-void
-utilspp::LifetimeDefault< T >::scheduleDestruction( T *, void (*func)() )
-{
-   std::atexit(func);
-}
-
-template< typename T >
-void
-utilspp::LifetimeDefault< T >::onDeadReference()
-{
-   throw std::logic_error("Dead reference detected");
-}
-
-#endif // __LIFETIME_DEFAULT_INL__
diff --git a/daemon/libs/utilspp/singleton/singleton_holder.hpp b/daemon/libs/utilspp/singleton/singleton_holder.hpp
deleted file mode 100644
index 6b0fcf47b1503620c1f12c59fc256ff065e2c83d..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/singleton/singleton_holder.hpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- *    Copyright (c) <2002-2004> <Jean-Philippe Barrette-LaPierre>
- *
- *    Permission is hereby granted, free of charge, to any person obtaining
- *    a copy of this software and associated documentation files
- *    (cURLpp), to deal in the Software without restriction,
- *    including without limitation the rights to use, copy, modify, merge,
- *    publish, distribute, sublicense, and/or sell copies of the Software,
- *    and to permit persons to whom the Software is furnished to do so,
- *    subject to the following conditions:
- *
- *    The above copyright notice and this permission notice shall be included
- *    in all copies or substantial portions of the Software.
- *
- *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef __SINGLETON_HOLDER_HPP__
-#define __SINGLETON_HOLDER_HPP__
-
-#include "creation_using_new.hpp"
-#include "lifetime_default.hpp"
-#include "../threading_single.hpp"
-
-namespace utilspp
-{
-  template
-  < class T,
-    template < class > class CreationPolicy = utilspp::CreationUsingNew,
-    template < class > class LifetimePolicy = utilspp::LifetimeDefault,
-    template < class > class ThreadingModel = utilspp::ThreadingSingle >
-  class SingletonHolder
-  {
-  public:
-    //the accessor method.
-    static T& instance();
-    static void makeInstance();
-    static void terminate();
-
-  protected:
-    //protected to be sure that nobody may create one by himself.
-    SingletonHolder();
-
-  private:
-    static void destroySingleton();
-
-  private:
-    typedef typename ThreadingModel< T * >::VolatileType InstanceType;
-    static InstanceType mInstance;
-    static bool mDestroyed;
-  };
-
-}
-
-#include "singleton_holder.inl"
-
-#endif
diff --git a/daemon/libs/utilspp/singleton/singleton_holder.inl b/daemon/libs/utilspp/singleton/singleton_holder.inl
deleted file mode 100644
index 5fb9fab7f480e13a2243d95f572e77a9d93fa0c0..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/singleton/singleton_holder.inl
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- *    Copyright (c) <2002-2004> <Jean-Philippe Barrette-LaPierre>
- *
- *    Permission is hereby granted, free of charge, to any person obtaining
- *    a copy of this software and associated documentation files
- *    (cURLpp), to deal in the Software without restriction,
- *    including without limitation the rights to use, copy, modify, merge,
- *    publish, distribute, sublicense, and/or sell copies of the Software,
- *    and to permit persons to whom the Software is furnished to do so,
- *    subject to the following conditions:
- *
- *    The above copyright notice and this permission notice shall be included
- *    in all copies or substantial portions of the Software.
- *
- *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef __SINGLETON_HOLDER_INL__
-#define __SINGLETON_HOLDER_INL__
-
-#include <cassert>
-template
-<
-class T,
-template < class > class CreationPolicy,
-template < class > class LifetimePolicy,
-template < class > class ThreadingModel
->
-T&
-utilspp::SingletonHolder
-<
-T,
-CreationPolicy,
-LifetimePolicy,
-ThreadingModel
->
-::instance()
-{
-    if ( mInstance == NULL )
-    {
-        makeInstance();
-    }
-
-    return ( *mInstance );
-}
-
-template
-<
-class T,
-template < class > class CreationPolicy,
-template < class > class LifetimePolicy,
-template < class > class ThreadingModel
->
-void
-utilspp::SingletonHolder
-<
-T,
-CreationPolicy,
-LifetimePolicy,
-ThreadingModel
->::makeInstance()
-{
-    if ( mInstance == NULL )
-    {
-	typename ThreadingModel< T >::lock guard;
-        (void)guard;
-
-	if ( mInstance == NULL ) {
-            if ( mDestroyed )
-            {
-                LifetimePolicy< T >::onDeadReference();
-                mDestroyed = false;
-            }
-
-            mInstance = CreationPolicy< T >::create();
-            LifetimePolicy< T >::scheduleDestruction( mInstance, &destroySingleton );
-        }
-    }
-}
-
-template
-<
-class T,
-template < class > class CreationPolicy,
-template < class > class LifetimePolicy,
-template < class > class ThreadingModel
->
-void
-utilspp::SingletonHolder
-<
-T,
-CreationPolicy,
-LifetimePolicy,
-ThreadingModel
->
-::destroySingleton()
-{
-    assert( !mDestroyed );
-    CreationPolicy< T >::destroy( mInstance );
-    mInstance = NULL;
-    mDestroyed = true;
-}
-
-template < class T,
-template < class > class C,
-template < class > class L,
-template < class > class M
->
-typename utilspp::SingletonHolder< T, C, L, M>::InstanceType
-utilspp::SingletonHolder< T, C, L, M >::mInstance;
-
-template
-<
-class T,
-template < class > class C,
-template < class > class L,
-template < class > class M
->
-bool utilspp::SingletonHolder< T, C, L, M >::mDestroyed;
-
-#endif // __SINGLETON_HOLDER_INL__
diff --git a/daemon/libs/utilspp/threading_single.hpp b/daemon/libs/utilspp/threading_single.hpp
deleted file mode 100644
index 81c023402c5dd18dc9e107b48653ee33df80dbcd..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/threading_single.hpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- *    Copyright (c) <2002-2004> <Jean-Philippe Barrette-LaPierre>
- *
- *    Permission is hereby granted, free of charge, to any person obtaining
- *    a copy of this software and associated documentation files
- *    (cURLpp), to deal in the Software without restriction,
- *    including without limitation the rights to use, copy, modify, merge,
- *    publish, distribute, sublicense, and/or sell copies of the Software,
- *    and to permit persons to whom the Software is furnished to do so,
- *    subject to the following conditions:
- *
- *    The above copyright notice and this permission notice shall be included
- *    in all copies or substantial portions of the Software.
- *
- *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef __THREADING_SINGLE_HPP__
-#define __THREADING_SINGLE_HPP__
-
-#include "null_type.hpp"
-
-namespace utilspp
-{
-   template < typename T = utilspp::NullType >
-      struct ThreadingSingle
-      {
-         struct mutex
-         {
-            void lock();
-            void unlock();
-         };
-
-         struct lock
-         {
-            lock();
-            lock( mutex &m );
-         };
-
-         typedef T VolatileType;
-      };
-}
-
-#include "threading_single.inl"
-
-#endif // __THREADING_SINGLE_HPP__
diff --git a/daemon/libs/utilspp/threading_single.inl b/daemon/libs/utilspp/threading_single.inl
deleted file mode 100644
index 4d26c4ff1dab7593a37761e024d7537d3857e99a..0000000000000000000000000000000000000000
--- a/daemon/libs/utilspp/threading_single.inl
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *    Copyright (c) <2002-2004> <Jean-Philippe Barrette-LaPierre>
- *
- *    Permission is hereby granted, free of charge, to any person obtaining
- *    a copy of this software and associated documentation files
- *    (cURLpp), to deal in the Software without restriction,
- *    including without limitation the rights to use, copy, modify, merge,
- *    publish, distribute, sublicense, and/or sell copies of the Software,
- *    and to permit persons to whom the Software is furnished to do so,
- *    subject to the following conditions:
- *
- *    The above copyright notice and this permission notice shall be included
- *    in all copies or substantial portions of the Software.
- *
- *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#ifndef __THREADING_SINGLE_INL__
-#define __THREADING_SINGLE_INL__
-
-template< typename T >
-inline
-utilspp::ThreadingSingle< T >::lock::lock()
-{}
-
-template< typename T >
-inline
-utilspp::ThreadingSingle< T >::lock::lock(
-      utilspp::ThreadingSingle< T >::mutex & )
-{}
-
-template< typename T >
-inline
-void
-utilspp::ThreadingSingle< T >::mutex::lock()
-{}
-
-template< typename T >
-inline
-void
-utilspp::ThreadingSingle< T >::mutex::unlock()
-{}
-
-#endif // __THREADING_SINGLE_INL__
diff --git a/daemon/src/Makefile.am b/daemon/src/Makefile.am
index 94ca5f6941585d562da79281fcddccc5c478c215..2f83fe6bf6525bde85331934ee8627770df4743b 100644
--- a/daemon/src/Makefile.am
+++ b/daemon/src/Makefile.am
@@ -50,14 +50,17 @@ noinst_HEADERS = \
 		logger.h \
 		numbercleaner.h \
 		fileutils.h \
-		noncopyable.h
+		noncopyable.h \
+		cc_thread.h \
+		cc_config.h \
+		sfl_types.h \
+		array_size.h
 
 if SFL_VIDEO
 SFL_VIDEO_LIB=./video/libvideo.la
 endif
 
 libsflphone_la_LIBADD = \
-	$(top_builddir)/libs/utilspp/libutilspp.la \
 	$(top_builddir)/libs/iax2/libiax2.la \
 	$(IAX_LIB) \
 	./im/libim.la \
@@ -97,6 +100,7 @@ libsflphone_la_SOURCES = conference.cpp \
 		voiplink.cpp \
 		preferences.cpp \
 		managerimpl.cpp \
+		manager.cpp \
 		managerimpl_registration.cpp \
 		eventthread.cpp \
 		call.cpp \
diff --git a/daemon/src/account.h b/daemon/src/account.h
index afdcdf10e87bc0bd8696d4c2cba449760b2caa82..708a3a31065d83cd9e4e5dc57d6201de11610d16 100644
--- a/daemon/src/account.h
+++ b/daemon/src/account.h
@@ -63,7 +63,7 @@ enum RegistrationState {
     ErrorNetwork ,
     ErrorHost,
     ErrorExistStun,
-    ErrorConfStun,
+    ErrorNotAcceptable,
     NumberOfStates
 };
 
@@ -133,23 +133,23 @@ static const char *const CONFIG_REGISTRATION_STATE_CODE             = "Registrat
 static const char *const CONFIG_REGISTRATION_STATE_DESCRIPTION      = "Registration.description";
 
 // General configuration keys for accounts
-static const char * const aliasKey = "alias";
-static const char * const typeKey = "type";
-static const char * const idKey = "id";
-static const char * const usernameKey = "username";
-static const char * const authenticationUsernameKey = "authenticationUsername";
-static const char * const passwordKey = "password";
-static const char * const hostnameKey = "hostname";
-static const char * const accountEnableKey = "enable";
-static const char * const mailboxKey = "mailbox";
-
-static const char * const codecsKey = "codecs";  // 0/9/110/111/112/
+static const char * const ALIAS_KEY = "alias";
+static const char * const TYPE_KEY = "type";
+static const char * const ID_KEY = "id";
+static const char * const USERNAME_KEY = "username";
+static const char * const AUTHENTICATION_USERNAME_KEY = "authenticationUsername";
+static const char * const PASSWORD_KEY = "password";
+static const char * const HOSTNAME_KEY = "hostname";
+static const char * const ACCOUNT_ENABLE_KEY = "enable";
+static const char * const MAILBOX_KEY = "mailbox";
+
+static const char * const CODECS_KEY = "codecs";  // 0/9/110/111/112/
 #ifdef SFL_VIDEO
-static const char * const videocodecsKey = "videocodecs";
+static const char * const VIDEO_CODECS_KEY = "videoCodecs";
 #endif
-static const char * const ringtonePathKey = "ringtonePath";
-static const char * const ringtoneEnabledKey = "ringtoneEnabled";
-static const char * const displayNameKey = "displayName";
+static const char * const RINGTONE_PATH_KEY = "ringtonePath";
+static const char * const RINGTONE_ENABLED_KEY = "ringtoneEnabled";
+static const char * const DISPLAY_NAME_KEY = "displayName";
 
 class Account : public Serializable {
 
@@ -235,13 +235,6 @@ class Account : public Serializable {
             alias_ = alias;
         }
 
-        std::string getType() const {
-            return type_;
-        }
-        void setType(const std::string &type) {
-            type_ = type;
-        }
-
 #ifdef SFL_VIDEO
         /**
          * Accessor to data structures
@@ -252,8 +245,7 @@ class Account : public Serializable {
         }
 #endif
 
-        /**
-         * Accessor to data structures
+         /* Accessor to data structures
          * @return CodecOrder& The list that reflects the user's choice
          */
         std::vector<int> getActiveCodecs() const {
diff --git a/daemon/src/array_size.h b/daemon/src/array_size.h
new file mode 100644
index 0000000000000000000000000000000000000000..9bca08aadb5aa4b6d88f3ad49c71816e063eb7f5
--- /dev/null
+++ b/daemon/src/array_size.h
@@ -0,0 +1,39 @@
+/*
+ *  Copyright (C) 2004-2012 Savoir-Faire Linux Inc.
+ *  Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ *  Additional permission under GNU GPL version 3 section 7:
+ *
+ *  If you modify this program, or any covered work, by linking or
+ *  combining it with the OpenSSL project's OpenSSL library (or a
+ *  modified version of that library), containing parts covered by the
+ *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
+ *  grants you additional permission to convey the resulting work.
+ *  Corresponding Source for a non-source form of such a combination
+ *  shall include the source code for the parts of OpenSSL used as well
+ *  as that of the covered work.
+ */
+
+#ifndef ARRAY_SIZE_H_
+#define ARRAY_SIZE_H_
+
+// Returns the number of elements in a, calculated at compile-time
+#define ARRAYSIZE(a) \
+      ((sizeof(a) / sizeof(*(a))) / \
+         static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
+
+#endif // ARRAY_SIZE_H_
diff --git a/daemon/src/audio/Makefile.am b/daemon/src/audio/Makefile.am
index f816e45a5b45953a026a8c78b1b9d83ec0d65881..de8950ed4a11f11d71ea43ce4baf17acae4b5bf3 100644
--- a/daemon/src/audio/Makefile.am
+++ b/daemon/src/audio/Makefile.am
@@ -22,7 +22,6 @@ libaudio_la_SOURCES = \
 
 noinst_HEADERS = \
 		audioloop.h \
-		common.h \
 		ringbuffer.h \
 		mainbuffer.h \
 		audiorecord.h \
diff --git a/daemon/src/audio/alsa/alsalayer.cpp b/daemon/src/audio/alsa/alsalayer.cpp
index 2d0054aab03a439c0f966877deb290de59a26f16..00ecd4aa9e2d64786d482e2ac7f6a2fc0fcd048f 100644
--- a/daemon/src/audio/alsa/alsalayer.cpp
+++ b/daemon/src/audio/alsa/alsalayer.cpp
@@ -33,17 +33,17 @@
 #include "audio/dcblocker.h"
 #include "eventthread.h"
 #include "audio/samplerateconverter.h"
-#include "managerimpl.h"
+#include "logger.h"
+#include "manager.h"
 #include "noncopyable.h"
 #include "dbus/configurationmanager.h"
+#include <ctime>
 
 class AlsaThread : public ost::Thread {
     public:
         AlsaThread(AlsaLayer *alsa);
 
-        ~AlsaThread() {
-            terminate();
-        }
+        ~AlsaThread() { terminate(); }
 
         virtual void run();
 
@@ -53,17 +53,15 @@ class AlsaThread : public ost::Thread {
 };
 
 AlsaThread::AlsaThread(AlsaLayer *alsa)
-    : Thread(), alsa_(alsa)
-{
-    setCancel(cancelDeferred);
-}
+    : ost::Thread(), alsa_(alsa)
+{}
 
 /**
  * Reimplementation of run()
  */
 void AlsaThread::run()
 {
-    while (!testCancel()) {
+    while (alsa_->isStarted_) {
         alsa_->audioCallback();
         Thread::sleep(20);
     }
@@ -94,6 +92,7 @@ AlsaLayer::AlsaLayer()
 // Destructor
 AlsaLayer::~AlsaLayer()
 {
+    isStarted_ = false;
     delete audioThread_;
 
     /* Then close the audio devices */
@@ -109,7 +108,8 @@ bool AlsaLayer::openDevice(snd_pcm_t **pcm, const std::string &dev, snd_pcm_stre
 
     // Retry if busy, since dmix plugin may not have released the device yet
     for (int tries = 0; tries < MAX_RETRIES and err == -EBUSY; ++tries) {
-        usleep(10000);
+        const struct timespec req = {0, 10000000};
+        nanosleep(&req, 0);
         err = snd_pcm_open(pcm, dev.c_str(), stream, 0);
     }
 
@@ -556,31 +556,29 @@ void AlsaLayer::capture()
     if (toGetSamples > framesPerBufferAlsa)
         toGetSamples = framesPerBufferAlsa;
 
-    int toGetBytes = toGetSamples * sizeof(SFLDataFormat);
-    SFLDataFormat* in = (SFLDataFormat*) malloc(toGetBytes);
+    std::vector<SFLDataFormat> in(toGetSamples);
 
-    if (read(in, toGetBytes) != toGetBytes) {
+    const int toGetBytes = in.size() * sizeof(in[0]);
+    if (read(&(*in.begin()), toGetBytes) != toGetBytes) {
         ERROR("ALSA MIC : Couldn't read!");
-        goto end;
+        return;
     }
 
-    AudioLayer::applyGain(in, toGetSamples, getCaptureGain());
+    AudioLayer::applyGain(&(*in.begin()), toGetSamples, getCaptureGain());
 
     if (resample) {
         int outSamples = toGetSamples * ((double) audioSampleRate_ / mainBufferSampleRate);
-        int outBytes = outSamples * sizeof(SFLDataFormat);
-        SFLDataFormat* rsmpl_out = (SFLDataFormat*) malloc(outBytes);
-        converter_->resample((SFLDataFormat*) in, rsmpl_out, mainBufferSampleRate, audioSampleRate_, toGetSamples);
-        dcblocker_.process(rsmpl_out, rsmpl_out, outSamples);
-        Manager::instance().getMainBuffer()->putData(rsmpl_out, outBytes);
-        free(rsmpl_out);
+        std::vector<SFLDataFormat> rsmpl_out(outSamples);
+        converter_->resample(&(*in.begin()), &(*rsmpl_out.begin()),
+                mainBufferSampleRate, audioSampleRate_, toGetSamples);
+        dcblocker_.process(&(*rsmpl_out.begin()), &(*rsmpl_out.begin()), outSamples);
+        Manager::instance().getMainBuffer()->putData(&(*rsmpl_out.begin()),
+                rsmpl_out.size() * sizeof(rsmpl_out[0]), MainBuffer::DEFAULT_ID);
     } else {
-        dcblocker_.process(in, in, toGetSamples);
-        Manager::instance().getMainBuffer()->putData(in, toGetBytes);
+        dcblocker_.process(&(*in.begin()), &(*in.begin()), toGetSamples);
+        Manager::instance().getMainBuffer()->putData(&(*in.begin()),
+                toGetBytes, MainBuffer::DEFAULT_ID);
     }
-
-end:
-    free(in);
 }
 
 void AlsaLayer::playback(int maxSamples)
@@ -589,7 +587,7 @@ void AlsaLayer::playback(int maxSamples)
     unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate();
     bool resample = audioSampleRate_ != mainBufferSampleRate;
 
-    int toGet = Manager::instance().getMainBuffer()->availForGet();
+    int toGet = Manager::instance().getMainBuffer()->availForGet(MainBuffer::DEFAULT_ID);
     int toPut = maxSamples * sizeof(SFLDataFormat);
 
     if (toGet <= 0) {    	// no audio available, play tone or silence
@@ -627,7 +625,7 @@ void AlsaLayer::playback(int maxSamples)
         toGet = maxNbBytesToGet;
 
     SFLDataFormat *out = (SFLDataFormat*) malloc(toGet);
-    Manager::instance().getMainBuffer()->getData(out, toGet);
+    Manager::instance().getMainBuffer()->getData(out, toGet, MainBuffer::DEFAULT_ID);
     AudioLayer::applyGain(out, toGet / sizeof(SFLDataFormat), getPlaybackGain());
 
     if (resample) {
@@ -649,14 +647,14 @@ void AlsaLayer::audioCallback()
     if (!playbackHandle_ or !captureHandle_)
         return;
 
-    notifyincomingCall();
+    notifyIncomingCall();
 
     snd_pcm_wait(playbackHandle_, 20);
 
     int playbackAvailSmpl = snd_pcm_avail_update(playbackHandle_);
     int playbackAvailBytes = playbackAvailSmpl * sizeof(SFLDataFormat);
 
-    int toGet = urgentRingBuffer_.AvailForGet();
+    int toGet = urgentRingBuffer_.AvailForGet(MainBuffer::DEFAULT_ID);
 
     if (toGet > 0) {
         // Urgent data (dtmf, incoming call signal) come first.
@@ -664,13 +662,13 @@ void AlsaLayer::audioCallback()
             toGet = playbackAvailBytes;
 
         SFLDataFormat *out = (SFLDataFormat*) malloc(toGet);
-        urgentRingBuffer_.Get(out, toGet);
+        urgentRingBuffer_.Get(out, toGet, MainBuffer::DEFAULT_ID);
         AudioLayer::applyGain(out, toGet / sizeof(SFLDataFormat), getPlaybackGain());
 
         write(out, toGet, playbackHandle_);
         free(out);
         // Consume the regular one as well (same amount of bytes)
-        Manager::instance().getMainBuffer()->discard(toGet);
+        Manager::instance().getMainBuffer()->discard(toGet, MainBuffer::DEFAULT_ID);
     } else {
         // regular audio data
         playback(playbackAvailSmpl);
@@ -679,19 +677,17 @@ void AlsaLayer::audioCallback()
     if (ringtoneHandle_) {
         AudioLoop *file_tone = Manager::instance().getTelephoneFile();
         int ringtoneAvailSmpl = snd_pcm_avail_update(ringtoneHandle_);
-        int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof(SFLDataFormat);
+        int ringtoneAvailBytes = ringtoneAvailSmpl * sizeof(SFLDataFormat);
 
-        SFLDataFormat *out = (SFLDataFormat *) malloc(ringtoneAvailBytes);
+        std::vector<SFLDataFormat> out(ringtoneAvailSmpl, 0);
 
         if (file_tone) {
             DEBUG("playback gain %d", getPlaybackGain());
-            file_tone->getNext(out, ringtoneAvailSmpl, getPlaybackGain());
+            file_tone->getNext(&(*out.begin()), ringtoneAvailSmpl,
+                               getPlaybackGain());
         }
-        else
-            memset(out, 0, ringtoneAvailBytes);
 
-        write(out, ringtoneAvailBytes, ringtoneHandle_);
-        free(out);
+        write(&(*out.begin()), ringtoneAvailBytes, ringtoneHandle_);
     }
 
     // Additionally handle the mic's audio stream
diff --git a/daemon/src/audio/alsa/alsalayer.h b/daemon/src/audio/alsa/alsalayer.h
index f15d0d333a5a3d9592ff6397df5f1ee5d30f22bf..fbc4cec171846e28cdb4a16f07d0982c11d10cef 100644
--- a/daemon/src/audio/alsa/alsalayer.h
+++ b/daemon/src/audio/alsa/alsalayer.h
@@ -149,7 +149,7 @@ class AlsaLayer : public AudioLayer {
         }
 
     private:
-
+        friend class AlsaThread;
 
         /**
          * Calls snd_pcm_open and retries if device is busy, since dmix plugin
@@ -241,7 +241,7 @@ class AlsaLayer : public AudioLayer {
         bool is_playback_open_;
         bool is_capture_open_;
 
-        AlsaThread* audioThread_;
+        AlsaThread *audioThread_;
 };
 
 #endif // _ALSA_LAYER_H_
diff --git a/daemon/src/audio/audiolayer.cpp b/daemon/src/audio/audiolayer.cpp
index 8e3363611ed6a915e36e386e6165e87237d1c54a..1c772030703a4316976a2edddd6337bdad1b49a9 100644
--- a/daemon/src/audio/audiolayer.cpp
+++ b/daemon/src/audio/audiolayer.cpp
@@ -39,7 +39,7 @@ unsigned int AudioLayer::playbackGain_ = 100;
 
 AudioLayer::AudioLayer()
     : isStarted_(false)
-    , urgentRingBuffer_(SIZEBUF, Call::DEFAULT_ID)
+    , urgentRingBuffer_(SIZEBUF, MainBuffer::DEFAULT_ID)
     , audioSampleRate_(Manager::instance().getMainBuffer()->getInternalSamplingRate())
     , mutex_()
     , dcblocker_()
@@ -47,7 +47,7 @@ AudioLayer::AudioLayer()
     , converter_(new SamplerateConverter(audioSampleRate_))
     , lastNotificationTime_(0)
 {
-    urgentRingBuffer_.createReadPointer();
+    urgentRingBuffer_.createReadPointer(MainBuffer::DEFAULT_ID);
 }
 
 
@@ -86,7 +86,7 @@ void AudioLayer::applyGain(SFLDataFormat *src , int samples, int gain)
 }
 
 // Notify (with a beep) an incoming call when there is already a call in progress
-void AudioLayer::notifyincomingCall()
+void AudioLayer::notifyIncomingCall()
 {
     if (!Manager::instance().incomingCallWaiting())
         return;
diff --git a/daemon/src/audio/audiolayer.h b/daemon/src/audio/audiolayer.h
index db5ec9bd065e16c2ca0ba943f9e6091878f8e9f0..d7729f8bb3f1f445110ac64f4ac18a1235bfd5f8 100644
--- a/daemon/src/audio/audiolayer.h
+++ b/daemon/src/audio/audiolayer.h
@@ -31,13 +31,12 @@
  *  as that of the covered work.
  */
 
-#ifndef __AUDIO_LAYER_H__
-#define __AUDIO_LAYER_H__
+#ifndef AUDIO_LAYER_H_
+#define AUDIO_LAYER_H_
 
-#include <cc++/thread.h> // for ost::Mutex
+#include "cc_thread.h" // for ost::Mutex
 #include <sys/time.h>
-
-#include "manager.h"
+#include <vector>
 #include "ringbuffer.h"
 #include "dcblocker.h"
 #include "samplerateconverter.h"
@@ -49,6 +48,7 @@
  */
 
 class MainBuffer;
+class AudioPreference;
 
 namespace ost {
 class Time;
@@ -171,7 +171,7 @@ class AudioLayer {
 	/**
          * Emit an audio notification on incoming calls
          */
-        void notifyincomingCall();
+        void notifyIncomingCall();
 
         /**
          * Gain applied to mic signal
diff --git a/daemon/src/audio/audioloop.cpp b/daemon/src/audio/audioloop.cpp
index 8c34366b7feddd47bd0a2ae74a7a66f10d749ef0..354f7c56f12685997d7a033d0cd43a225cc82959 100644
--- a/daemon/src/audio/audioloop.cpp
+++ b/daemon/src/audio/audioloop.cpp
@@ -37,6 +37,7 @@
 #include <numeric>
 #include <cstring>
 #include <cassert>
+#include "logger.h"
 
 AudioLoop::AudioLoop() : buffer_(0),  size_(0), pos_(0), sampleRate_(0)
 {}
diff --git a/daemon/src/audio/audioloop.h b/daemon/src/audio/audioloop.h
index cc6cc653fbe85e4df52c35e415667f70f497c20f..b7d54a7e0e2a499f22a79170b9654c7c7d1c3eb5 100644
--- a/daemon/src/audio/audioloop.h
+++ b/daemon/src/audio/audioloop.h
@@ -33,7 +33,8 @@
 #ifndef __AUDIOLOOP_H__
 #define __AUDIOLOOP_H__
 
-#include "global.h" // for SFLDataFormat
+#include "sfl_types.h"
+#include <cstring>
 #include "noncopyable.h"
 
 /**
diff --git a/daemon/src/audio/audiorecord.cpp b/daemon/src/audio/audiorecord.cpp
index a8215080c434cb25b9a1f14f55285f6094eea677..8acdfa853fce8a11d8c025cd4619992e19284643 100644
--- a/daemon/src/audio/audiorecord.cpp
+++ b/daemon/src/audio/audiorecord.cpp
@@ -31,6 +31,9 @@
 #include "audiorecord.h"
 #include <unistd.h>
 #include <sstream> // for stringstream
+#include <cstdio>
+#include "logger.h"
+#include "fileutils.h"
 
 // structure for the wave header
 
@@ -74,10 +77,22 @@ void AudioRecord::setSndSamplingRate(int smplRate)
 
 void AudioRecord::setRecordingOption(FILE_TYPE type, int sndSmplRate, const std::string &path)
 {
+    std::stringstream s;
+    std::string filePath;
+
+    // use HOME directory if path is empty, or if path does not exist
+    if (path.empty() || !fileutils::check_dir(path.c_str())) {
+        s << getenv("HOME");
+        filePath = s.str();
+    }
+    else {
+        filePath = path;
+    }
+
     fileType_ = type;
     channels_ = 1;
     sndSmplRate_ = sndSmplRate;
-    savePath_ = path + "/";
+    savePath_ = (*filePath.rbegin() == '/') ? filePath : filePath + "/";
 }
 
 void AudioRecord::initFilename(const std::string &peerNumber)
@@ -109,8 +124,6 @@ bool AudioRecord::openFile()
 {
     bool result = false;
 
-    DEBUG("AudioRecord: Open file()");
-
     if (not fileExists()) {
         DEBUG("AudioRecord: Filename does not exist, creating one");
         byteCounter_ = 0;
@@ -155,24 +168,14 @@ bool AudioRecord::isRecording() const
     return recordingEnabled_;
 }
 
-bool AudioRecord::setRecording()
+void AudioRecord::setRecording()
 {
     if (isOpenFile()) {
-        if (!recordingEnabled_) {
-            DEBUG("AudioRecording: Start recording");
-            recordingEnabled_ = true;
-        } else {
-            DEBUG("AudioRecording: Stop recording");
-            recordingEnabled_ = false;
-        }
+        recordingEnabled_ = !recordingEnabled_;
     } else {
         openFile();
         recordingEnabled_ = true; // once opend file, start recording
     }
-
-    // WARNING: Unused return value
-    return true;
-
 }
 
 void AudioRecord::stopRecording()
@@ -183,12 +186,8 @@ void AudioRecord::stopRecording()
 
 void AudioRecord::createFilename()
 {
-    time_t rawtime;
-
-    struct tm * timeinfo;
-
-    rawtime = time(NULL);
-    timeinfo = localtime(&rawtime);
+    time_t rawtime = time(NULL);
+    struct tm * timeinfo = localtime(&rawtime);
 
     std::stringstream out;
 
@@ -228,7 +227,7 @@ void AudioRecord::createFilename()
     out << timeinfo->tm_sec;
     filename_ = out.str();
 
-    DEBUG("AudioRecord: create filename for this call %s ", filename_.c_str());
+    DEBUG("AudioRecord: Generate filename for this call %s ", filename_.c_str());
 }
 
 bool AudioRecord::setRawFile()
@@ -393,28 +392,7 @@ void AudioRecord::closeWavFile()
         WARN("AudioRecord: Error: can't close file");
 }
 
-void AudioRecord::recSpkrData(SFLDataFormat* buffer, int nSamples)
-{
-    if (recordingEnabled_) {
-        nbSamplesMic_ = nSamples;
-
-        for (int i = 0; i < nbSamplesMic_; i++)
-            micBuffer_[i] = buffer[i];
-    }
-}
-
-void AudioRecord::recMicData(SFLDataFormat* buffer, int nSamples)
-{
-    if (recordingEnabled_) {
-        nbSamplesSpk_ = nSamples;
-
-        for (int i = 0; i < nbSamplesSpk_; i++)
-            spkBuffer_[i] = buffer[i];
-
-    }
-}
-
-void AudioRecord::recData(SFLDataFormat* buffer, int nSamples)
+void AudioRecord::recData(SFLDataFormat* buffer, size_t nSamples)
 {
     if (recordingEnabled_) {
         if (fileHandle_ == 0) {
@@ -422,34 +400,11 @@ void AudioRecord::recData(SFLDataFormat* buffer, int nSamples)
             return;
         }
 
-        if (fwrite(buffer, sizeof(SFLDataFormat), nSamples, fileHandle_) != (unsigned int) nSamples)
+        if (fwrite(buffer, sizeof(SFLDataFormat), nSamples, fileHandle_) != nSamples)
             WARN("AudioRecord: Could not record data! ");
         else {
             fflush(fileHandle_);
-            byteCounter_ += (unsigned long)(nSamples*sizeof(SFLDataFormat));
+            byteCounter_ += nSamples * sizeof(SFLDataFormat);
         }
     }
 }
-
-void AudioRecord::recData(SFLDataFormat* buffer_1, SFLDataFormat* buffer_2,
-                          int nSamples_1, int /*nSamples_2*/)
-{
-    if (recordingEnabled_) {
-        if (fileHandle_ == 0) {
-            DEBUG("AudioRecord: Can't record data, a file has not yet been opened!");
-            return;
-        }
-
-        for (int k = 0; k < nSamples_1; k++) {
-            mixBuffer_[k] = (buffer_1[k]+buffer_2[k]);
-
-            if (fwrite(&mixBuffer_[k], 2, 1, fileHandle_) != 1)
-                WARN("AudioRecord: Could not record data!");
-            else
-                fflush(fileHandle_);
-        }
-
-        byteCounter_ += (unsigned long)(nSamples_1 * sizeof(SFLDataFormat));
-    }
-}
-
diff --git a/daemon/src/audio/audiorecord.h b/daemon/src/audio/audiorecord.h
index 95571c198bf25eb9241581a4e5f065d7e3e7e8e1..47bfa28ac303771cc0d47eb73a8d2458e65d1c2e 100644
--- a/daemon/src/audio/audiorecord.h
+++ b/daemon/src/audio/audiorecord.h
@@ -35,7 +35,7 @@
 #include <cstdlib>
 #include <memory>
 
-#include "global.h"
+#include "sfl_types.h"
 #include "noncopyable.h"
 
 class AudioRecord {
@@ -90,44 +90,19 @@ class AudioRecord {
         /**
          * Set recording flag
          */
-        bool setRecording();
+        void setRecording();
 
         /**
          * Stop recording flag
          */
         void stopRecording();
 
-
-        /**
-         * Record a chunk of data in an internal buffer
-         * @param buffer  The data chunk to be recorded
-         * @param nSamples Number of samples (number of bytes) to be recorded
-         */
-        void recSpkrData(SFLDataFormat* buffer, int nSamples);
-
-        /**
-         * Record a chunk of data in an internal buffer
-         * @param buffer  The data chunk to be recorded
-         * @param nSamples Number of samples (number of bytes) to be recorded
-         */
-        void recMicData(SFLDataFormat* buffer, int nSamples);
-
         /**
          * Record a chunk of data in an openend file
          * @param buffer  The data chunk to be recorded
          * @param nSamples Number of samples (number of bytes) to be recorded
          */
-        void recData(SFLDataFormat* buffer, int nSamples);
-
-        /**
-         * Record a chunk of data in an openend file, Mix two differnet buffer
-         * @param buffer_1  The first data chunk to be recorded
-         * @param buffer_2  The second data chunk to be recorded
-         * @param nSamples_1 Number of samples (number of bytes) of buffer_1
-         * @param nSamples_2 Number of samples (number of bytes) of buffer_2
-         */
-        void recData(SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int nSamples_1, int nSamples_2);
-
+        void recData(SFLDataFormat* buffer, size_t nSamples);
 
     protected:
 
diff --git a/daemon/src/audio/audiorecorder.cpp b/daemon/src/audio/audiorecorder.cpp
index 462c32165b74342434d0ebff8e44d25e469476c7..63cac9e7e56e64a704f8a893b721703b995b665b 100644
--- a/daemon/src/audio/audiorecorder.cpp
+++ b/daemon/src/audio/audiorecorder.cpp
@@ -30,15 +30,15 @@
 
 #include "audiorecorder.h"
 #include "mainbuffer.h"
+#include <sstream>
 #include <cassert>
 
 int AudioRecorder::count_ = 0;
 
-AudioRecorder::AudioRecorder(AudioRecord  *arec, MainBuffer *mb) : Thread(),
+AudioRecorder::AudioRecorder(AudioRecord  *arec, MainBuffer *mb) : ost::Thread(),
     recorderId_(), mbuffer_(mb), arecord_(arec)
 {
     assert(mb);
-    setCancel(cancelDeferred);
 
     ++count_;
 
@@ -46,7 +46,7 @@ AudioRecorder::AudioRecorder(AudioRecord  *arec, MainBuffer *mb) : Thread(),
 
     // convert count into string
     std::string s;
-    std::stringstream out;
+    std::ostringstream out;
     out << count_;
     s = out.str();
 
@@ -58,14 +58,13 @@ AudioRecorder::AudioRecorder(AudioRecord  *arec, MainBuffer *mb) : Thread(),
  */
 void AudioRecorder::run()
 {
-    int bufferLength = 10000;
-    SFLDataFormat buffer[bufferLength];
+    const size_t BUFFER_LENGTH = 10000;
+    SFLDataFormat buffer[BUFFER_LENGTH];
 
-    while (true) {
-        int availBytes = mbuffer_->availForGet(recorderId_);
-        int toGet = (availBytes < bufferLength) ? availBytes : bufferLength;
+    while (isRunning()) {
+        size_t availBytes = mbuffer_->availForGet(recorderId_);
 
-        mbuffer_->getData(buffer, toGet, recorderId_);
+        mbuffer_->getData(buffer, std::min(availBytes, BUFFER_LENGTH), recorderId_);
 
         if (availBytes > 0)
             arecord_->recData(buffer, availBytes / sizeof(SFLDataFormat));
diff --git a/daemon/src/audio/audiorecorder.h b/daemon/src/audio/audiorecorder.h
index eb7ccf1fe146b4d763befce1afdabe8eff9e8856..82be9a4795f4555073944080294a0c56dc14c8b5 100644
--- a/daemon/src/audio/audiorecorder.h
+++ b/daemon/src/audio/audiorecorder.h
@@ -28,11 +28,11 @@
  *  as that of the covered work.
  */
 
-#ifndef __AUDIORECORDER_H_
-#define __AUDIORECORDER_H_
+#ifndef AUDIORECORDER_H_
+#define AUDIORECORDER_H_
 
 #include <string>
-#include <cc++/thread.h>
+#include "cc_thread.h"
 #include "audiorecord.h"
 #include "noncopyable.h"
 
diff --git a/daemon/src/audio/audiortp/audio_rtp_factory.h b/daemon/src/audio/audiortp/audio_rtp_factory.h
index fd15beb51ef068db1a74da0fa9b5aeb4c5ba96d6..0aa88f0f31279b16e0653991be5192685020ff9f 100644
--- a/daemon/src/audio/audiortp/audio_rtp_factory.h
+++ b/daemon/src/audio/audiortp/audio_rtp_factory.h
@@ -32,8 +32,8 @@
 #define __AUDIO_RTP_FACTORY_H__
 
 #include <stdexcept>
-#include <cc++/thread.h>
 #include <ccrtp/CryptoContext.h>
+#include "cc_thread.h"
 #include "audio_rtp_session.h"
 #include "noncopyable.h"
 
diff --git a/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp b/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp
index 99c5064d94a00d36bcfba5c137f3a9ff1848e312..071a978ce5363bd1fbc4851a6c90bfded60ee170 100644
--- a/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp
+++ b/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp
@@ -30,6 +30,7 @@
 #include "audio_rtp_record_handler.h"
 #include <fstream>
 
+#include "logger.h"
 #include "sip/sipcall.h"
 #include "audio/audiolayer.h"
 #include "manager.h"
@@ -113,10 +114,6 @@ void AudioRtpRecordHandler::putDtmfEvent(int digit)
     audioRtpRecord_.dtmfQueue_.push_back(digit);
 }
 
-#ifdef DUMP_PROCESS_DATA_ENCODE
-std::ofstream teststream("test_process_data_encode.raw");
-#endif
-
 int AudioRtpRecordHandler::processDataEncode()
 {
     SFLDataFormat *micData 			= audioRtpRecord_.decData_;
@@ -149,15 +146,12 @@ int AudioRtpRecordHandler::processDataEncode()
     if (Manager::instance().getEchoCancelState())
         echoCanceller.getData(micData);
 
-#ifdef DUMP_PROCESS_DATA_ENCODE
-    teststream.write(reinterpret_cast<char *>(micData), bytesToGet);
-#endif
-
     SFLDataFormat *out = micData;
 
     if (codecSampleRate != mainBufferSampleRate) {
         out = micDataConverted;
-        audioRtpRecord_.converter_->resample(micData, micDataConverted, codecSampleRate, mainBufferSampleRate, samplesToGet);
+        audioRtpRecord_.converter_->resample(micData, micDataConverted,
+                codecSampleRate, mainBufferSampleRate, samplesToGet);
     }
 
     if (Manager::instance().audioPreference.getNoiseReduce()) {
@@ -165,16 +159,13 @@ int AudioRtpRecordHandler::processDataEncode()
         audioRtpRecord_.noiseSuppress_->process(micData, getCodecFrameSize());
     }
 
-    int compSize;
     {
         ost::MutexLock lock(audioRtpRecord_.audioCodecMutex_);
-        compSize = audioRtpRecord_.audioCodec_->encode(micDataEncoded, out, getCodecFrameSize());
+        return audioRtpRecord_.audioCodec_->encode(micDataEncoded, out, getCodecFrameSize());
     }
-
-    return compSize;
 }
 
-void AudioRtpRecordHandler::processDataDecode(unsigned char *spkrData, unsigned int size, int payloadType)
+void AudioRtpRecordHandler::processDataDecode(unsigned char *spkrData, size_t size, int payloadType)
 {
     if (getCodecPayloadType() != payloadType)
         return;
@@ -215,13 +206,13 @@ void AudioRtpRecordHandler::processDataDecode(unsigned char *spkrData, unsigned
     Manager::instance().getMainBuffer()->putData(out, outSamples * sizeof(SFLDataFormat), id_);
 }
 
-void AudioRtpRecordHandler::fadeIn(SFLDataFormat *audio, int size, SFLDataFormat *factor)
+void AudioRtpRecordHandler::fadeIn(SFLDataFormat *audio, size_t size, SFLDataFormat *factor)
 {
-    // if factor reach 0, this function should have no effect
-    if (*factor <= 0)
+    // if factor reaches 0, this function should have no effect
+    if (!audio or !factor or *factor <= 0)
         return;
 
-    while (size)
+    while (size > 0)
         audio[--size] /= *factor;
 
     *factor /= FADEIN_STEP_SIZE;
diff --git a/daemon/src/audio/audiortp/audio_rtp_record_handler.h b/daemon/src/audio/audiortp/audio_rtp_record_handler.h
index ac630e2872aac936f7aa05f8c73897c80e6b1296..b1bdad528f6dee98cffff0f0e16e3e554bfd5cbf 100644
--- a/daemon/src/audio/audiortp/audio_rtp_record_handler.h
+++ b/daemon/src/audio/audiortp/audio_rtp_record_handler.h
@@ -132,7 +132,7 @@ class AudioRtpRecordHandler {
         }
 
         int DtmfPending() const {
-            return audioRtpRecord_.dtmfQueue_.size() > 0;
+            return not audioRtpRecord_.dtmfQueue_.empty();
         }
 
         const unsigned char *getMicDataEncoded() const {
@@ -151,12 +151,12 @@ class AudioRtpRecordHandler {
         /**
          * Decode audio data received from peer
          */
-        void processDataDecode(unsigned char * spkrData, unsigned int size, int payloadType);
+        void processDataDecode(unsigned char * spkrData, size_t size, int payloadType);
 
         /**
         * Ramp In audio data to avoid audio click from peer
         */
-        void fadeIn(SFLDataFormat *audio, int size, SFLDataFormat *factor);
+        void fadeIn(SFLDataFormat *audio, size_t size, SFLDataFormat *factor);
 
         void setDtmfPayloadType(unsigned int payloadType) {
             audioRtpRecord_.dtmfPayloadType_ = payloadType;
@@ -169,7 +169,7 @@ class AudioRtpRecordHandler {
         void putDtmfEvent(int digit);
 
     protected:
-        AudioRtpRecord	audioRtpRecord_;
+        AudioRtpRecord audioRtpRecord_;
 
     private:
 
diff --git a/daemon/src/audio/audiortp/audio_rtp_session.cpp b/daemon/src/audio/audiortp/audio_rtp_session.cpp
index 70efc7860d0c2c61825bc62830b2572cab79f027..b0464cae86f4ef6f1572ee902a68300459a62cdb 100644
--- a/daemon/src/audio/audiortp/audio_rtp_session.cpp
+++ b/daemon/src/audio/audiortp/audio_rtp_session.cpp
@@ -34,7 +34,7 @@
 
 #include "audio_rtp_session.h"
 #include "audio_symmetric_rtp_session.h"
-
+#include "logger.h"
 #include "sip/sdp.h"
 #include "sip/sipcall.h"
 #include "audio/audiolayer.h"
@@ -243,7 +243,8 @@ int AudioRtpSession::startRtpThread(AudioCodec &audiocodec)
     initNoiseSuppress();
 
     queue_.enableStack();
-    return thread_.start();
+    thread_.start();
+    return 0;
 }
 
 
diff --git a/daemon/src/audio/audiortp/audio_srtp_session.cpp b/daemon/src/audio/audiortp/audio_srtp_session.cpp
index fb14463dbb0983fa9e669a9fb03f4fa2ed6021b8..38567d1b629cdbe7dbc29971401039429b9b3cc3 100644
--- a/daemon/src/audio/audiortp/audio_srtp_session.cpp
+++ b/daemon/src/audio/audiortp/audio_srtp_session.cpp
@@ -28,6 +28,8 @@
  *  as that of the covered work.
  */
 #include "audio_srtp_session.h"
+#include "logger.h"
+#include "array_size.h"
 
 #include <openssl/sha.h>
 #include <openssl/hmac.h>
@@ -102,12 +104,9 @@ namespace {
         std::vector<unsigned char> random_key(length);
 
         // Generate ryptographically strong pseudo-random bytes
-        int err;
-
-        if ((err = RAND_bytes(&(*random_key.begin()), length)) != 1)
+        if (RAND_bytes(&(*random_key.begin()), length) != 1)
             DEBUG("Error occured while generating cryptographically strong pseudo-random key");
 
-        assert((sizeof dest / sizeof dest[0]) <= length);
         memcpy(dest, &(*random_key.begin()), length);
     }
 }
@@ -210,6 +209,7 @@ void AudioSrtpSession::initializeLocalMasterKey()
     DEBUG("AudioSrtp: Init local master key");
     // @TODO key may have different length depending on cipher suite
     localMasterKeyLength_ = sfl::CryptoSuites[localCryptoSuite_].masterKeyLength / 8;
+    assert(ARRAYSIZE(localMasterKey_) >= localMasterKeyLength_);
     DEBUG("AudioSrtp: Local master key length %d", localMasterKeyLength_);
     buffer_fill(localMasterKey_, localMasterKeyLength_);
 }
@@ -218,6 +218,7 @@ void AudioSrtpSession::initializeLocalMasterSalt()
 {
     // @TODO key may have different length depending on cipher suite
     localMasterSaltLength_ = sfl::CryptoSuites[localCryptoSuite_].masterSaltLength / 8;
+    assert(ARRAYSIZE(localMasterSalt_) >= localMasterSaltLength_);
     DEBUG("AudioSrtp: Local master salt length %d", localMasterSaltLength_);
     buffer_fill(localMasterSalt_, localMasterSaltLength_);
 }
diff --git a/daemon/src/audio/audiortp/audio_srtp_session.h b/daemon/src/audio/audiortp/audio_srtp_session.h
index 97b9b2ce675dbd848ea6c76c235a2f50e2e33dc3..a84cfccc847b3ae4e1fc1827383e422289bcf9ee 100644
--- a/daemon/src/audio/audiortp/audio_srtp_session.h
+++ b/daemon/src/audio/audiortp/audio_srtp_session.h
@@ -153,22 +153,22 @@ class AudioSrtpSession : public AudioSymmetricRtpSession {
         uint8 localMasterKey_[16];
 
         /** local master key length in byte */
-        int localMasterKeyLength_;
+        size_t localMasterKeyLength_;
 
         uint8 localMasterSalt_[14];
 
         /** local master salt length in byte */
-        int localMasterSaltLength_;
+        size_t localMasterSaltLength_;
 
         uint8 remoteMasterKey_[16];
 
         /** remote master key length in byte */
-        int remoteMasterKeyLength_;
+        size_t remoteMasterKeyLength_;
 
         uint8 remoteMasterSalt_[14];
 
         /** remote master salt length in byte */
-        int remoteMasterSaltLength_;
+        size_t remoteMasterSaltLength_;
 
         /** Used to make sure remote crypto context not initialized wice. */
         bool remoteOfferIsSet_;
diff --git a/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp
index 3324f22ff4358f7713cf8e024decb2eff9f4abc1..ee5e3a53b3614c04633847a31848f00b87bdb188 100644
--- a/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp
+++ b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp
@@ -35,6 +35,7 @@
 #include "audio_rtp_session.h"
 #include "audio_symmetric_rtp_session.h"
 #include "audio_rtp_record_handler.h"
+#include "logger.h"
 #include "sip/sdp.h"
 #include "sip/sipcall.h"
 #include "audio/audiolayer.h"
diff --git a/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h
index b0fda2be3d926de11341e7c546ce5f69327c03f6..c89d39143b9f0412533b4bc6c2f5b1a81ac5bbb7 100644
--- a/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h
+++ b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h
@@ -66,7 +66,8 @@ class AudioSymmetricRtpSession : public ost::TimerPort, public ost::SymmetricRTP
         }
 
         int startSymmetricRtpThread() {
-            return rtpThread_.start();
+            rtpThread_.start();
+            return 0;
         }
 
     private:
diff --git a/daemon/src/audio/audiortp/audio_zrtp_session.cpp b/daemon/src/audio/audiortp/audio_zrtp_session.cpp
index 222adb89c1f3c84440fe6363002043d5e0e800ed..ca4449e3188e8e3b42bee9ef3961dbd0ae6214b5 100644
--- a/daemon/src/audio/audiortp/audio_zrtp_session.cpp
+++ b/daemon/src/audio/audiortp/audio_zrtp_session.cpp
@@ -28,13 +28,17 @@
  *  as that of the covered work.
  */
 
+#ifdef HAVE_CONFIG_H
 #include "config.h"
+#endif
+
 #include "audio_zrtp_session.h"
 #include "zrtp_session_callback.h"
-
+#include "fileutils.h"
 #include "sip/sipcall.h"
 #include "sip/sdp.h"
 #include "audio/audiolayer.h"
+#include "logger.h"
 #include "manager.h"
 
 #include <libzrtpcpp/zrtpccrtp.h>
@@ -60,9 +64,6 @@ AudioZrtpSession::AudioZrtpSession(SIPCall &call, const std::string& zidFilename
 {
     DEBUG("AudioZrtpSession initialized");
     initializeZid();
-
-    setCancel(cancelDefault);
-
     DEBUG("AudioZrtpSession: Setting new RTP session with destination %s:%d",
           call_.getLocalIp().c_str(), call_.getLocalAudioPort());
 }
@@ -73,14 +74,6 @@ AudioZrtpSession::~AudioZrtpSession()
     Manager::instance().getMainBuffer()->unBindAll(call_.getCallId());
 }
 
-void AudioZrtpSession::final()
-{
-// tmatth:Oct 25 2011:FIXME:
-// This was crashing...seems like it's not necessary. Double check
-// with valgrind/helgrind
-// delete this;
-}
-
 void AudioZrtpSession::initializeZid()
 {
     if (zidFilename_.empty())
@@ -154,10 +147,8 @@ void AudioZrtpSession::run()
         else
             sendMicData();
 
-        setCancel(cancelDeferred);
         controlReceptionService();
         controlTransmissionService();
-        setCancel(cancelImmediate);
         uint32 maxWait = timeval2microtimeout(getRTCPCheckInterval());
         // make sure the scheduling timeout is
         // <= the check interval for RTCP
@@ -165,18 +156,13 @@ void AudioZrtpSession::run()
         timeout = (timeout > maxWait) ? maxWait : timeout;
 
         if (timeout < 1000) {   // !(timeout/1000)
-            setCancel(cancelDeferred);
             // dispatchDataPacket();
-            setCancel(cancelImmediate);
             timerTick();
         } else {
             if (isPendingData(timeout / 1000)) {
-                setCancel(cancelDeferred);
 
                 if (isActive())
                     takeInDataPacket();
-
-                setCancel(cancelImmediate);
             }
             timeout = 0;
         }
diff --git a/daemon/src/audio/audiortp/audio_zrtp_session.h b/daemon/src/audio/audiortp/audio_zrtp_session.h
index 9e7c196e3dcf91646c91ac61ce8957cfe176995d..65a86fa352e3fe24d559c4b10bc51364b694afea 100644
--- a/daemon/src/audio/audiortp/audio_zrtp_session.h
+++ b/daemon/src/audio/audiortp/audio_zrtp_session.h
@@ -40,7 +40,7 @@ using std::ptrdiff_t;
 #include <libzrtpcpp/ZrtpUserCallback.h>
 
 #include "audio_rtp_session.h"
-#include <cc++/numbers.h> // OST::Time
+// #include <commoncpp/numbers.h> // OST::Time
 
 class SIPCall;
 class AudioCodec;
@@ -60,8 +60,6 @@ class AudioZrtpSession :
         AudioZrtpSession(SIPCall &call, const std::string& zidFilename);
         ~AudioZrtpSession();
 
-        virtual void final();
-
         // Thread associated method
         virtual void run();
 
diff --git a/daemon/src/audio/audiortp/zrtp_session_callback.cpp b/daemon/src/audio/audiortp/zrtp_session_callback.cpp
index 061cf1c64c22b66f270e80302085e149d5328de8..4383d09d1553d3f62439e31f9c0f2f5720255f3a 100644
--- a/daemon/src/audio/audiortp/zrtp_session_callback.cpp
+++ b/daemon/src/audio/audiortp/zrtp_session_callback.cpp
@@ -28,7 +28,7 @@
  *  as that of the covered work.
  */
 #include "zrtp_session_callback.h"
-#include "global.h"
+#include "logger.h"
 #include "sip/sipcall.h"
 #include "dbus/dbusmanager.h"
 #include "dbus/callmanager.h"
diff --git a/daemon/src/audio/codecs/Makefile.am b/daemon/src/audio/codecs/Makefile.am
index 21a1389a9d20514da8db5d0d042fb2dcc5aebbf9..f696c728bd3be79c737982a01a5d21662f6b6871 100644
--- a/daemon/src/audio/codecs/Makefile.am
+++ b/daemon/src/audio/codecs/Makefile.am
@@ -41,34 +41,7 @@ libcodec_speex_ub_so_LDADD = libcodecdescriptor.la
 INSTALL_SPEEX_UB_RULE = install-libcodec_speex_ub_so
 endif
 
-if BUILD_CELT_91
-CELT_LIB = libcodec_celt.so
-libcodec_celt_so_SOURCES = celtcodec.cpp
-libcodec_celt_so_CXXFLAGS = -fPIC -g -Wall -DBUILD_CELT_91
-libcodec_celt_so_LDFLAGS = --shared -lc ${CELT_LIBS}
-libcodec_celt_so_LDADD = libcodecdescriptor.la
-INSTALL_CELT_RULE = install-libcodec_celt_so
-endif
-
-if BUILD_CELT_71
-CELT_LIB = libcodec_celt.so
-libcodec_celt_so_SOURCES = celtcodec.cpp
-libcodec_celt_so_CXXFLAGS = -fPIC -g -Wall -DBUILD_CELT_71
-libcodec_celt_so_LDFLAGS = --shared -lc ${CELT_LIBS}
-libcodec_celt_so_LDADD = libcodecdescriptor.la
-INSTALL_CELT_RULE = install-libcodec_celt_so
-endif
-
-if BUILD_CELT_071
-CELT_LIB = libcodec_celt.so
-libcodec_celt_so_SOURCES = celtcodec.cpp
-libcodec_celt_so_CXXFLAGS = -fPIC -g -Wall -DBUILD_CELT_071 -I${top_srcdir}/src
-libcodec_celt_so_LDFLAGS = --shared -lc ${CELT_LIBS}
-libcodec_celt_so_LDADD = libcodecdescriptor.la
-INSTALL_CELT_RULE = install-libcodec_celt_so
-endif
-
-noinst_PROGRAMS = libcodec_ulaw.so libcodec_alaw.so libcodec_g722.so $(GSM_LIB) $(SPEEX_NB_LIB) $(SPEEX_WB_LIB) $(SPEEX_UB_LIB) $(CELT_LIB)
+noinst_PROGRAMS = libcodec_ulaw.so libcodec_alaw.so libcodec_g722.so $(GSM_LIB) $(SPEEX_NB_LIB) $(SPEEX_WB_LIB) $(SPEEX_UB_LIB)
 
 noinst_HEADERS = audiocodec.h audiocodecfactory.h speexcodec.h g722.h
 
@@ -87,8 +60,8 @@ libcodec_g722_so_CXXFLAGS = -fPIC -g -Wall
 libcodec_g722_so_LDADD = libcodecdescriptor.la
 libcodec_g722_so_LDFLAGS = --shared -lc
 
-install-exec-local:  install-libcodec_ulaw_so install-libcodec_alaw_so install-libcodec_g722_so $(INSTALL_GSM_RULE) $(INSTALL_SPEEX_NB_RULE) $(INSTALL_SPEEX_WB_RULE) $(INSTALL_SPEEX_UB_RULE) $(INSTALL_CELT_RULE) $(INSTALL_ILBC_RULE)
-uninstall-local:  uninstall-libcodec_ulaw_so uninstall-libcodec_alaw_so uninstall-libcodec_g722_so uninstall-libcodec_gsm_so uninstall-libcodec_speex_nb_so uninstall-libcodec_speex_wb_so uninstall-libcodec_speex_ub_so uninstall-libcodec_celt_so
+install-exec-local:  install-libcodec_ulaw_so install-libcodec_alaw_so install-libcodec_g722_so $(INSTALL_GSM_RULE) $(INSTALL_SPEEX_NB_RULE) $(INSTALL_SPEEX_WB_RULE) $(INSTALL_SPEEX_UB_RULE) $(INSTALL_ILBC_RULE)
+uninstall-local:  uninstall-libcodec_ulaw_so uninstall-libcodec_alaw_so uninstall-libcodec_g722_so uninstall-libcodec_gsm_so uninstall-libcodec_speex_nb_so uninstall-libcodec_speex_wb_so uninstall-libcodec_speex_ub_so
 
 
 install-libcodec_ulaw_so: libcodec_ulaw.so
@@ -112,9 +85,6 @@ install-libcodec_speex_wb_so: libcodec_speex_wb.so
 install-libcodec_speex_ub_so: libcodec_speex_ub.so
 	mkdir -p $(sflcodecdir)
 	$(INSTALL_PROGRAM)  libcodec_speex_ub.so $(sflcodecdir)
-install-libcodec_celt_so: libcodec_celt.so
-	mkdir -p $(sflcodecdir)
-	$(INSTALL_PROGRAM)  libcodec_celt.so $(sflcodecdir)
 
 uninstall-libcodec_ulaw_so:
 	rm -f $(sflcodecdir)/libcodec_ulaw.so
@@ -130,7 +100,4 @@ uninstall-libcodec_speex_wb_so:
 	rm -f $(sflcodecdir)/libcodec_speex_wb.so
 uninstall-libcodec_speex_ub_so:
 	rm -f $(sflcodecdir)/libcodec_speex_ub.so
-uninstall-libcodec_celt_so:
-	rm -f $(sflcodecdir)/libcodec_celt.so
-	rm -rf $(sflcodecdir)
 
diff --git a/daemon/src/audio/codecs/alaw.cpp b/daemon/src/audio/codecs/alaw.cpp
index 9c20b4c8696492f4312a0047d4d6a4aeac2b71e4..9adc558fdb61badaa7f4f62af42f648cf5ce45e0 100644
--- a/daemon/src/audio/codecs/alaw.cpp
+++ b/daemon/src/audio/codecs/alaw.cpp
@@ -29,8 +29,7 @@
  *  as that of the covered work.
  */
 
-#include "global.h"
-#include "../common.h"
+#include "sfl_types.h"
 #include "audiocodec.h"
 #include <cassert>
 
diff --git a/daemon/src/audio/codecs/audiocodecfactory.cpp b/daemon/src/audio/codecs/audiocodecfactory.cpp
index 4c4a0b6f979cc43c8222797d67fa4f48bba3d7ca..51422014a7c410387a92a5b6ed8dc8054ba9ed12 100644
--- a/daemon/src/audio/codecs/audiocodecfactory.cpp
+++ b/daemon/src/audio/codecs/audiocodecfactory.cpp
@@ -31,11 +31,15 @@
  *  as that of the covered work.
  */
 
+#ifdef HAVE_CONFIG_H
 #include "config.h"
+#endif
+
 #include "audiocodecfactory.h"
 #include <cstdlib>
 #include <algorithm> // for std::find
 #include "fileutils.h"
+#include "logger.h"
 
 AudioCodecFactory::AudioCodecFactory() :
     codecsMap_(), defaultCodecList_(), libCache_(), codecInMemory_()
diff --git a/daemon/src/audio/codecs/celtcodec.cpp b/daemon/src/audio/codecs/celtcodec.cpp
deleted file mode 100644
index 647c1277c587bc34eb9eb1bfc924c1277eebd117..0000000000000000000000000000000000000000
--- a/daemon/src/audio/codecs/celtcodec.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- *  Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc.
- *  Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
- *
- *  This program is free software; you can redistribute it and/or modify
- *  it under the terms of the GNU General Public License as published by
- *  the Free Software Foundation; either version 3 of the License, or
- *  (at your option) any later version.
- *
- *  This program is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU General Public License for more details.
- *
- *  You should have received a copy of the GNU General Public License
- *  along with this program; if not, write to the Free Software
- *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- *
- *  Additional permission under GNU GPL version 3 section 7:
- *
- *  If you modify this program, or any covered work, by linking or
- *  combining it with the OpenSSL project's OpenSSL library (or a
- *  modified version of that library), containing parts covered by the
- *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
- *  grants you additional permission to convey the resulting work.
- *  Corresponding Source for a non-source form of such a combination
- *  shall include the source code for the parts of OpenSSL used as well
- *  as that of the covered work.
- */
-
-#include "audiocodec.h"
-#include <cstdio>
-#ifdef BUILD_CELT_071
-// FIXME: Hack to workaround celt's insufficient pkg-config file
-#include <celt071/celt.h>
-#else
-#include <celt/celt.h>
-#endif
-#include <stdexcept>
-#include "noncopyable.h"
-
-class Celt : public sfl::AudioCodec {
-
-    public:
-        Celt(int payload = 115)	: sfl::AudioCodec(payload, "celt"), mode_(0), enc_(0), dec_(0) {
-            clockRate_ = 32000;
-            frameSize_ = 320;  // fixed frameSize, TODO: support variable size from 64 to 512
-            channel_ = 1;
-            bitrate_ = 0;
-            hasDynamicPayload_ = true;
-            int error = 0;
-
-            mode_ = celt_mode_create(clockRate_, frameSize_, &error);
-
-            if (error != CELT_OK) {
-                switch (error) {
-                    case CELT_BAD_ARG:
-                        throw std::runtime_error("Celt: An (or more) invalid argument (e.g. out of range)\n");
-                        break;
-                    case CELT_INVALID_MODE:
-                        throw std::runtime_error("Celt: The mode struct passed is invalid\n");
-                        break;
-                    case CELT_INTERNAL_ERROR:
-                        throw std::runtime_error("Celt: An internal error was detected\n");
-                        break;
-                    case CELT_CORRUPTED_DATA:
-                        throw std::runtime_error("Celt: The data passed (e.g. compressed data to decoder) is corrupted\n");
-                        break;
-                    case CELT_UNIMPLEMENTED:
-                        throw std::runtime_error("Celt: Invalid/unsupported request numbe\n");
-                        break;
-                    case CELT_INVALID_STATE:
-                        throw std::runtime_error("Celt: An encoder or decoder structure is invalid or already freed\n");
-                        break;
-                    case CELT_ALLOC_FAIL:
-                        throw std::runtime_error("Celt: Memory allocation has failed\n");
-                        break;
-                    default:
-                        throw std::runtime_error("Celt: Unknown error");
-                }
-
-            }
-
-            if (mode_ == NULL)
-                throw std::runtime_error("Celt: Failed to create Celt mode");
-
-            enc_ = celt_encoder_create(mode_, channel_, &error);
-            dec_ = celt_decoder_create(mode_, channel_, &error);
-
-            celt_encoder_ctl(enc_, CELT_SET_COMPLEXITY(2));
-            celt_decoder_ctl(dec_, CELT_SET_COMPLEXITY(2));
-
-            celt_encoder_ctl(enc_, CELT_SET_PREDICTION(2));
-            celt_decoder_ctl(dec_, CELT_SET_PREDICTION(2));
-        }
-
-        NON_COPYABLE(Celt);
-
-        ~Celt() {
-            celt_encoder_destroy(enc_);
-            celt_decoder_destroy(dec_);
-            celt_mode_destroy(mode_);
-        }
-
-        virtual int decode(short *dst, unsigned char *src, size_t buf_size) {
-#ifdef BUILD_CELT_91 // == 91
-            celt_decode(dec_, src, buf_size, (celt_int16*) dst, frameSize_);
-#endif
-#ifdef BUILD_CELT_71
-            celt_decode(dec_, src, buf_size, (celt_int16*) dst);
-#endif
-            return frameSize_;
-        }
-
-        virtual int encode(unsigned char *dst, short *src, size_t buf_size) {
-            int len = 0;
-#ifdef BUILD_CELT_91// == 91
-            len = celt_encode(enc_, (celt_int16*) src, frameSize_, dst, buf_size);
-#endif
-#ifdef BUILD_CELT_71
-            len = celt_encode(enc_, (celt_int16*) src, (celt_int16 *) src, dst, buf_size);
-#endif
-            return len;
-        }
-
-    private:
-        CELTMode *mode_;
-
-        CELTEncoder *enc_;
-        CELTDecoder *dec_;
-};
-
-// the class factories
-// cppcheck-suppress unusedFunction
-extern "C" sfl::Codec* CODEC_ENTRY()
-{
-    return new Celt(115);
-}
-
-// cppcheck-suppress unusedFunction
-extern "C" void destroy(sfl::Codec* a)
-{
-    delete a;
-}
diff --git a/daemon/src/audio/codecs/g722.cpp b/daemon/src/audio/codecs/g722.cpp
index 33b1716a653c34b3861b9f23cfee015e62536214..21755430a794d126521c13186b711488c1657d23 100644
--- a/daemon/src/audio/codecs/g722.cpp
+++ b/daemon/src/audio/codecs/g722.cpp
@@ -30,11 +30,8 @@
  *  as that of the covered work.
  */
 
-
-
-#include "global.h"
-#include "../common.h"
 #include "audiocodec.h"
+#include "sfl_types.h"
 #include "g722.h"
 #include "noncopyable.h"
 
diff --git a/daemon/src/audio/codecs/ulaw.cpp b/daemon/src/audio/codecs/ulaw.cpp
index f7a087057af94b751512596d5be9ce2e8adefb48..9efe77c80ace537f2ff1f66739ceb3b41fdad012 100644
--- a/daemon/src/audio/codecs/ulaw.cpp
+++ b/daemon/src/audio/codecs/ulaw.cpp
@@ -29,10 +29,8 @@
  *  as that of the covered work.
  */
 
-
-#include "global.h"
-#include "../common.h"
 #include "audiocodec.h"
+#include "sfl_types.h"
 #include <cassert>
 
 class Ulaw : public sfl::AudioCodec {
diff --git a/daemon/src/audio/common.h b/daemon/src/audio/common.h
deleted file mode 100644
index e8a2b460fb8e6b436c5b25348dfcc2a155bbbfe9..0000000000000000000000000000000000000000
--- a/daemon/src/audio/common.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- *  Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc.
- *  Author:
- *
- *  This program is free software; you can redistribute it and/or modify
- *  it under the terms of the GNU General Public License as published by
- *  the Free Software Foundation; either version 3 of the License, or
- *  (at your option) any later version.
- *
- *  This program is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU General Public License for more details.
- *
- *  You should have received a copy of the GNU General Public License
- *  along with this program; if not, write to the Free Software
- *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- *
- *  Additional permission under GNU GPL version 3 section 7:
- *
- *  If you modify this program, or any covered work, by linking or
- *  combining it with the OpenSSL project's OpenSSL library (or a
- *  modified version of that library), containing parts covered by the
- *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
- *  grants you additional permission to convey the resulting work.
- *  Corresponding Source for a non-source form of such a combination
- *  shall include the source code for the parts of OpenSSL used as well
- *  as that of the covered work.
- */
-
-/*
-	Type definitions and helper macros which aren't part of Standard C++
-	This will need to be edited on systems where 'char', 'short' and 'int'
-   	have sizes different from 8, 16 and 32 bits.
-*/
-
-#ifndef __COMMON_H__
-#define __COMMON_H__
-
-
-// #define DEBUG	/**< Defined when compiling code for debugging */
-
-/*
-Basic integer types.
-Note 'int' is assumed to be in 2s complement format and at least 32 bits in size
-*/
-typedef unsigned char  uint8;	/**< An 8 bit unsigned integer */
-typedef unsigned short uint16;	/**< An 16 bit unsigned integer */
-typedef unsigned int   uint32;	/**< An 32 bit unsigned integer */
-typedef signed char    int8;	/**< An 8 bit signed integer (2s complement) */
-typedef signed short   int16;	/**< An 16 bit signed integer (2s complement) */
-typedef signed int     int32;	/**< An 32 bit signed integer (2s complement) */
-typedef unsigned int   uint;	/**< An unsigned integer or at least 32 bits */
-
-#ifndef NULL
-#define NULL 0		/**< Used to represent a null pointer type */
-#endif
-
-#ifdef _MSC_VER		// Compiling for Microsoft Visual C++
-
-#define DEBUGGER	{ _asm int 3 }			/**< Invoke debugger */
-#define IMPORT		__declspec(dllexport)	/**< Mark a function which is to be imported from a DLL */
-#define EXPORT		__declspec(dllexport)	/**< Mark a function to be exported from a DLL */
-#define ASSERT(c)	{ if(!(c)) DEBUGGER; }	/**< Assert that expression 'c' is true */
-
-#else				// Not compiling for Microsoft Visual C++ ...
-
-#define DEBUGGER							/**< Invoke debugger */
-#define IMPORT								/**< Mark a function which is to be imported from a DLL */
-#define EXPORT								/**< Mark a function to be exported from a DLL */
-
-#endif
-
-#ifdef DEBUG
-#define ASSERT_DEBUG(c) ASSERT(c)	/**< Assert that expression 'c' is true (when compiled for debugging)*/
-#else
-#define ASSERT_DEBUG(c)
-#endif
-
-#endif
diff --git a/daemon/src/audio/dcblocker.cpp b/daemon/src/audio/dcblocker.cpp
index 3aa1169a36fa0ffbf0fe7f48df336a8ee6408643..923dffcd21d70b9a556920be3184637e25bf1292 100644
--- a/daemon/src/audio/dcblocker.cpp
+++ b/daemon/src/audio/dcblocker.cpp
@@ -30,6 +30,9 @@
 
 #include "dcblocker.h"
 
+DcBlocker::DcBlocker() : y_(0), x_(0), xm1_(0), ym1_(0)
+{}
+
 void DcBlocker::reset()
 {
     y_ = 0;
diff --git a/daemon/src/audio/dcblocker.h b/daemon/src/audio/dcblocker.h
index 6dbb073ea50330eef90b3308d20a99b1e2c4f524..caedcbae430b5d3a062dc677d9e21429f09fefde 100644
--- a/daemon/src/audio/dcblocker.h
+++ b/daemon/src/audio/dcblocker.h
@@ -31,10 +31,11 @@
 #ifndef DCBLOCKER_H
 #define DCBLOCKER_H
 
-#include "global.h"
+#include "sfl_types.h"
 
 class DcBlocker {
     public:
+        DcBlocker();
         void reset();
         void process(SFLDataFormat *out, SFLDataFormat *in, int samples);
 
diff --git a/daemon/src/audio/delaydetection.h b/daemon/src/audio/delaydetection.h
index 286baab13c628402b9ebfb615b5bd2fbb80ff99c..f83dba536e7e87463100e0b95dca9c2ef3b734c0 100644
--- a/daemon/src/audio/delaydetection.h
+++ b/daemon/src/audio/delaydetection.h
@@ -32,7 +32,7 @@
 #ifndef DELAYDETECTION_H
 #define DELAYDETECTION_H
 
-#include "global.h"
+#include "sfl_types.h"
 #include <vector>
 
 // Template size in samples for correlation
diff --git a/daemon/src/audio/echosuppress.cpp b/daemon/src/audio/echosuppress.cpp
index 4f384c0bf8a747ab752d52cf6ee6ccff86f17be8..b509155f8641cd83a17caad595d8d9ddb72769d2 100644
--- a/daemon/src/audio/echosuppress.cpp
+++ b/daemon/src/audio/echosuppress.cpp
@@ -7,8 +7,9 @@
 
 #include <cassert>
 #include <stdexcept>
-
+#include "logger.h"
 #include "echosuppress.h"
+#include "pjmedia/echo.h"
 #include "pj/pool.h"
 #include "pj/os.h"
 
diff --git a/daemon/src/audio/echosuppress.h b/daemon/src/audio/echosuppress.h
index 15b7eed93231622d00ed5d6c56ebcc014fd61e68..9b7d08fbecb83674d30c9e0a4fc81cf7190c1c89 100644
--- a/daemon/src/audio/echosuppress.h
+++ b/daemon/src/audio/echosuppress.h
@@ -8,10 +8,12 @@
 #ifndef ECHOSUPPRESS_H_
 #define ECHOSUPPRESS_H_
 
-#include "pjmedia/echo.h"
-#include "global.h"
+#include "sfl_types.h"
 #include "noncopyable.h"
 
+class pjmedia_echo_state;
+class pj_pool_t;
+
 class EchoSuppress {
     public:
         EchoSuppress(pj_pool_t *pool);
diff --git a/daemon/src/audio/gaincontrol.cpp b/daemon/src/audio/gaincontrol.cpp
index 336d99870cd5ebb93b69b451ac7c85c380da0982..5e0f282fd5734292aadb3a00c8b5e7c7a6de676b 100644
--- a/daemon/src/audio/gaincontrol.cpp
+++ b/daemon/src/audio/gaincontrol.cpp
@@ -2,7 +2,8 @@
 #include <climits>
 #include <fstream>
 
-#include "global.h"
+#include "sfl_types.h"
+#include "logger.h"
 #include "gaincontrol.h"
 
 #define SFL_GAIN_ATTACK_TIME 10
@@ -81,7 +82,7 @@ double GainControl::DetectionAverage::getAverage(double in)
 GainControl::Limiter::Limiter(double r, double thresh) : ratio_(r), threshold_(thresh)
 {}
 
-double GainControl::Limiter::limit(double in)
+double GainControl::Limiter::limit(double in) const
 {
     double out = (in > threshold_ ? (ratio_ * (in - threshold_)) + threshold_ :
            in < -threshold_ ? (ratio_ * (in + threshold_)) - threshold_ : in);
diff --git a/daemon/src/audio/gaincontrol.h b/daemon/src/audio/gaincontrol.h
index e8f0ecd685103c14d4232805d7f17b2cf79ebec7..eeed3745c0abab8ce40dcaf6091d38e127323657 100644
--- a/daemon/src/audio/gaincontrol.h
+++ b/daemon/src/audio/gaincontrol.h
@@ -80,7 +80,7 @@ class GainControl {
                 /**
                  * Perform compression on input signal
                  */
-                double limit(double);
+                double limit(double) const;
 
             private:
                 double ratio_;
diff --git a/daemon/src/audio/mainbuffer.cpp b/daemon/src/audio/mainbuffer.cpp
index 5982da64b0305e1ee54d3848f4079880ee71ef28..6b19f0b1004be43a3b301c7f5b36cf8384d2ec45 100644
--- a/daemon/src/audio/mainbuffer.cpp
+++ b/daemon/src/audio/mainbuffer.cpp
@@ -30,8 +30,12 @@
  */
 
 #include "mainbuffer.h"
+#include "ringbuffer.h"
+#include "sfl_types.h" // for SIZEBUF
 #include <utility> // for std::pair
-#include "manager.h"
+#include "logger.h"
+
+const char * const MainBuffer::DEFAULT_ID = "audiolayer_id";
 
 MainBuffer::MainBuffer() : ringBufferMap_(), callIDMap_(), mutex_(), internalSamplingRate_(8000)
 {}
@@ -132,19 +136,16 @@ void MainBuffer::bindCallID(const std::string & call_id1, const std::string & ca
 {
     ost::MutexLock guard(mutex_);
 
-    RingBuffer* ring_buffer;
-    CallIDSet* callid_set;
-
-    if ((ring_buffer = getRingBuffer(call_id1)) == NULL)
+    if (getRingBuffer(call_id1) == NULL)
         createRingBuffer(call_id1);
 
-    if ((callid_set = getCallIDSet(call_id1)) == NULL)
+    if (getCallIDSet(call_id1) == NULL)
         createCallIDSet(call_id1);
 
-    if ((ring_buffer = getRingBuffer(call_id2)) == NULL)
+    if (getRingBuffer(call_id2) == NULL)
         createRingBuffer(call_id2);
 
-    if ((callid_set = getCallIDSet(call_id2)) == NULL)
+    if (getCallIDSet(call_id2) == NULL)
         createCallIDSet(call_id2);
 
     getRingBuffer(call_id1)->createReadPointer(call_id2);
@@ -310,7 +311,7 @@ int MainBuffer::availForGet(const std::string & call_id)
     if (callid_set->size() == 1) {
         CallIDSet::iterator iter_id = callid_set->begin();
 
-        if ((call_id != Call::DEFAULT_ID) && (*iter_id == call_id))
+        if ((call_id != DEFAULT_ID) && (*iter_id == call_id))
             DEBUG("This problem should not occur since we have %i element", (int) callid_set->size());
 
         return availForGetByID(*iter_id, call_id);
@@ -337,7 +338,7 @@ int MainBuffer::availForGet(const std::string & call_id)
 int MainBuffer::availForGetByID(const std::string &call_id,
                                 const std::string &reader_id)
 {
-    if ((call_id != Call::DEFAULT_ID) and (reader_id == call_id))
+    if ((call_id != DEFAULT_ID) and (reader_id == call_id))
         ERROR("MainBuffer: Error: RingBuffer has a readpointer on itself");
 
     RingBuffer* ringbuffer = getRingBuffer(call_id);
diff --git a/daemon/src/audio/mainbuffer.h b/daemon/src/audio/mainbuffer.h
index b2fddc4c0a03fb73dcdd316ae156345ef7faf3be..13b374b510653eaed15ac9709135a2a4490c9666 100644
--- a/daemon/src/audio/mainbuffer.h
+++ b/daemon/src/audio/mainbuffer.h
@@ -29,17 +29,16 @@
  *  as that of the covered work.
  */
 
-#ifndef __MAIN_BUFFER__
-#define __MAIN_BUFFER__
+#ifndef MAIN_BUFFER_H_
+#define MAIN_BUFFER_H_
 
 #include <map>
 #include <set>
-#include <cc++/thread.h> // for ost::Mutex
 #include <string>
 
-#include "global.h"
-#include "call.h"
-#include "ringbuffer.h"
+#include "cc_thread.h" // for ost::Mutex
+
+class RingBuffer;
 
 typedef std::map<std::string, RingBuffer*> RingBufferMap;
 
@@ -50,6 +49,7 @@ typedef std::map<std::string, CallIDSet*> CallIDMap;
 class MainBuffer {
 
     public:
+        static const char * const DEFAULT_ID;
 
         MainBuffer();
 
@@ -57,7 +57,7 @@ class MainBuffer {
 
         void setInternalSamplingRate(int sr);
 
-        int getInternalSamplingRate() {
+        int getInternalSamplingRate() const {
             return internalSamplingRate_;
         }
 
@@ -65,74 +65,74 @@ class MainBuffer {
          * Bind together two audio streams so taht a client will be able
          * to put and get data specifying its callid only.
          */
-        void bindCallID(const std::string & call_id1, const std::string & call_id2 = Call::DEFAULT_ID);
+        void bindCallID(const std::string &call_id1, const std::string &call_id2);
 
         /**
          * Add a new call_id to unidirectional outgoing stream
          * \param call_id New call id to be added for this stream
          * \param process_id Process that require this stream
          */
-        void bindHalfDuplexOut(const std::string & process_id, const std::string & call_id = Call::DEFAULT_ID);
+        void bindHalfDuplexOut(const std::string &process_id, const std::string &call_id);
 
         /**
          * Unbind two calls
          */
-        void unBindCallID(const std::string & call_id1, const std::string & call_id2 = Call::DEFAULT_ID);
+        void unBindCallID(const std::string &call_id1, const std::string &call_id2);
 
         /**
          * Unbind a unidirectional stream
          */
-        void unBindHalfDuplexOut(const std::string & process_id, const std::string & call_id = Call::DEFAULT_ID);
+        void unBindHalfDuplexOut(const std::string &process_id, const std::string &call_id);
 
-        void unBindAll(const std::string & call_id);
+        void unBindAll(const std::string &call_id);
 
-        void putData(void *buffer, int toCopy, const std::string & call_id = Call::DEFAULT_ID);
+        void putData(void *buffer, int toCopy, const std::string &call_id);
 
-        int getData(void *buffer, int toCopy, const std::string & call_id = Call::DEFAULT_ID);
+        int getData(void *buffer, int toCopy, const std::string &call_id);
 
-        int availForGet(const std::string & call_id = Call::DEFAULT_ID);
+        int availForGet(const std::string &call_id);
 
-        int discard(int toDiscard, const std::string & call_id = Call::DEFAULT_ID);
+        int discard(int toDiscard, const std::string &call_id);
 
-        void flush(const std::string & call_id = Call::DEFAULT_ID);
+        void flush(const std::string &call_id);
 
         void flushAllBuffers();
 
-        void syncBuffers(const std::string & call_id);
+        void syncBuffers(const std::string &call_id);
 
         void stateInfo();
 
     private:
 
-        CallIDSet* getCallIDSet(const std::string & call_id);
+        CallIDSet* getCallIDSet(const std::string &call_id);
 
-        void createCallIDSet(const std::string & set_id);
+        void createCallIDSet(const std::string &set_id);
 
-        bool removeCallIDSet(const std::string & set_id);
+        bool removeCallIDSet(const std::string &set_id);
 
         /**
          * Add a new call id to this set
          */
-        void addCallIDtoSet(const std::string & set_id, const std::string & call_id);
+        void addCallIDtoSet(const std::string &set_id, const std::string &call_id);
 
-        void removeCallIDfromSet(const std::string & set_id, const std::string & call_id);
+        void removeCallIDfromSet(const std::string &set_id, const std::string &call_id);
 
         /**
          * Create a new ringbuffer with default readpointer
          */
-        RingBuffer* createRingBuffer(const std::string & call_id);
+        RingBuffer* createRingBuffer(const std::string &call_id);
 
-        bool removeRingBuffer(const std::string & call_id);
+        bool removeRingBuffer(const std::string &call_id);
 
-        RingBuffer* getRingBuffer(const std::string & call_id);
+        RingBuffer* getRingBuffer(const std::string &call_id);
 
-        int getDataByID(void *buffer, int toCopy, const std::string & call_id, const std::string & reader_id);
+        int getDataByID(void *buffer, int toCopy, const std::string &call_id, const std::string &reader_id);
 
-        int availForGetByID(const std::string & call_id, const std::string & reader_id);
+        int availForGetByID(const std::string &call_id, const std::string &reader_id);
 
-        void discardByID(int toDiscard, const std::string & call_id, const std::string & reader_id);
+        void discardByID(int toDiscard, const std::string &call_id, const std::string &reader_id);
 
-        void flushByID(const std::string & call_id, const std::string & reader_id);
+        void flushByID(const std::string &call_id, const std::string &reader_id);
 
         RingBufferMap ringBufferMap_;
 
@@ -142,9 +142,7 @@ class MainBuffer {
 
         int internalSamplingRate_;
 
-    public:
-
         friend class MainBufferTest;
 };
 
-#endif
+#endif  // MainBuffer
diff --git a/daemon/src/audio/noisesuppress.h b/daemon/src/audio/noisesuppress.h
index 0e58f20ac7ffaee5ec641305c71648d4c495e5ac..30197386db6266afa660657c9758fc49cac3eb81 100644
--- a/daemon/src/audio/noisesuppress.h
+++ b/daemon/src/audio/noisesuppress.h
@@ -32,7 +32,7 @@
 #define NOISESUPPRESS_H
 
 #include <speex/speex_preprocess.h>
-#include "global.h" // for SFLDataFormat
+#include "sfl_types.h"
 #include "noncopyable.h"
 
 class NoiseSuppress {
diff --git a/daemon/src/audio/pulseaudio/audiostream.cpp b/daemon/src/audio/pulseaudio/audiostream.cpp
index 2eb1308e5098c1e1c54fe6635b38737edcaa1b21..8ac348f7823a47697a57614aa7f6ff2edda5b820 100644
--- a/daemon/src/audio/pulseaudio/audiostream.cpp
+++ b/daemon/src/audio/pulseaudio/audiostream.cpp
@@ -28,8 +28,10 @@
  *  as that of the covered work.
  */
 
-#include <audiostream.h>
+#include "audiostream.h"
 #include "pulselayer.h"
+#include "logger.h"
+#include <stdexcept>
 
 AudioStream::AudioStream(pa_context *c, pa_threaded_mainloop *m, const char *desc, int type, int smplrate, std::string& deviceName)
     : audiostream_(0), mainloop_(m)
@@ -94,7 +96,7 @@ AudioStream::~AudioStream()
 }
 
 void
-AudioStream::stream_state_callback(pa_stream* s, void* user_data UNUSED)
+AudioStream::stream_state_callback(pa_stream* s, void* /*user_data*/)
 {
     char str[PA_SAMPLE_SPEC_SNPRINT_MAX];
 
diff --git a/daemon/src/audio/pulseaudio/pulselayer.cpp b/daemon/src/audio/pulseaudio/pulselayer.cpp
index a77ae98d4cd3dcc6deb00164ecd4c530c96ba6c2..575e8a1e8b5fb766bb9ec7390e6e76be7a683de6 100644
--- a/daemon/src/audio/pulseaudio/pulselayer.cpp
+++ b/daemon/src/audio/pulseaudio/pulselayer.cpp
@@ -30,32 +30,28 @@
  */
 
 #include <algorithm> // for std::find
+#include <stdexcept>
 #include "audiostream.h"
 #include "pulselayer.h"
 #include "audio/samplerateconverter.h"
 #include "audio/dcblocker.h"
-#include "managerimpl.h"
+#include "logger.h"
+#include "manager.h"
 
 namespace {
 
-void playback_callback(pa_stream* s, size_t bytes, void* userdata)
+void playback_callback(pa_stream * /*s*/, size_t /*bytes*/, void* userdata)
 {
-    assert(s && bytes);
-    assert(bytes > 0);
     static_cast<PulseLayer*>(userdata)->writeToSpeaker();
 }
 
-void capture_callback(pa_stream* s, size_t bytes, void* userdata)
+void capture_callback(pa_stream * /*s*/, size_t /*bytes*/, void* userdata)
 {
-    assert(s && bytes);
-    assert(bytes > 0);
     static_cast<PulseLayer*>(userdata)->readFromMic();
 }
 
-void ringtone_callback(pa_stream* s, size_t bytes, void* userdata)
+void ringtone_callback(pa_stream * /*s*/, size_t /*bytes*/, void* userdata)
 {
-    assert(s && bytes);
-    assert(bytes > 0);
     static_cast<PulseLayer*>(userdata)->ringtoneToSpeaker();
 }
 
@@ -123,16 +119,17 @@ PulseLayer::~PulseLayer()
     if (mainloop_)
         pa_threaded_mainloop_free(mainloop_);
 
-    delete[] mic_buffer_;
+    delete [] mic_buffer_;
 }
 
 void PulseLayer::context_state_callback(pa_context* c, void *user_data)
 {
     PulseLayer *pulse = static_cast<PulseLayer*>(user_data);
-    assert(c && pulse->mainloop_);
+    assert(c and pulse and pulse->mainloop_);
+    const pa_subscription_mask_t mask = (pa_subscription_mask_t)
+        (PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SOURCE);
 
     switch (pa_context_get_state(c)) {
-
         case PA_CONTEXT_CONNECTING:
         case PA_CONTEXT_AUTHORIZING:
         case PA_CONTEXT_SETTING_NAME:
@@ -142,8 +139,7 @@ void PulseLayer::context_state_callback(pa_context* c, void *user_data)
         case PA_CONTEXT_READY:
             DEBUG("Audio: Connection to PulseAudio server established");
             pa_threaded_mainloop_signal(pulse->mainloop_, 0);
-            pa_context_subscribe(c, (pa_subscription_mask_t)(PA_SUBSCRIPTION_MASK_SINK|
-                                 PA_SUBSCRIPTION_MASK_SOURCE), NULL, pulse);
+            pa_context_subscribe(c, mask, NULL, pulse);
             pa_context_set_subscribe_callback(c, context_changed_callback, pulse);
             pulse->updateSinkList();
             pulse->updateSourceList();
@@ -165,7 +161,7 @@ void PulseLayer::context_state_callback(pa_context* c, void *user_data)
 void PulseLayer::updateSinkList()
 {
     sinkList_.clear();
-    pa_context_get_sink_info_list(context_, sink_input_info_callback,  this);
+    pa_context_get_sink_info_list(context_, sink_input_info_callback, this);
 }
 
 void PulseLayer::updateSourceList()
@@ -187,12 +183,10 @@ bool PulseLayer::inSourceList(const std::string &deviceName) const
 
 std::vector<std::string> PulseLayer::getAudioDeviceList(AudioStreamDirection dir) const
 {
-    if(AUDIO_STREAM_CAPTURE == dir) {
+    if (AUDIO_STREAM_CAPTURE == dir)
         return sinkList_;
-    }
-    if(AUDIO_STREAM_PLAYBACK) {
+    else if (AUDIO_STREAM_PLAYBACK)
         return sourceList_;
-    }
 }
 
 void PulseLayer::createStreams(pa_context* c)
@@ -305,33 +299,32 @@ void PulseLayer::writeToSpeaker()
 
     pa_stream *s = playback_->pulseStream();
 
-
     // available bytes to be written in pulseaudio internal buffer
     int writable = pa_stream_writable_size(s);
 
-    if (writable < 0)
+    if (writable < 0) {
         ERROR("Pulse: playback error : %s", pa_strerror(writable));
-
-    if (writable <= 0)
+        return;
+    } else if (writable == 0)
         return;
 
     size_t bytes = writable;
-    void *data;
 
-    notifyincomingCall();
+    notifyIncomingCall();
 
-    size_t urgentBytes = urgentRingBuffer_.AvailForGet();
+    size_t urgentBytes = urgentRingBuffer_.AvailForGet(MainBuffer::DEFAULT_ID);
 
     if (urgentBytes > bytes)
         urgentBytes = bytes;
 
+    void *data;
     if (urgentBytes) {
         pa_stream_begin_write(s, &data, &urgentBytes);
-        urgentRingBuffer_.Get(data, urgentBytes);
+        urgentRingBuffer_.Get(data, urgentBytes, MainBuffer::DEFAULT_ID);
         applyGain(static_cast<SFLDataFormat *>(data), urgentBytes / sizeof(SFLDataFormat), getPlaybackGain());
         pa_stream_write(s, data, urgentBytes, NULL, 0, PA_SEEK_RELATIVE);
         // Consume the regular one as well (same amount of bytes)
-        Manager::instance().getMainBuffer()->discard(urgentBytes);
+        Manager::instance().getMainBuffer()->discard(urgentBytes, MainBuffer::DEFAULT_ID);
         return;
     }
 
@@ -350,7 +343,7 @@ void PulseLayer::writeToSpeaker()
 
     flushUrgent(); // flush remaining samples in _urgentRingBuffer
 
-    size_t availSamples = Manager::instance().getMainBuffer()->availForGet() / sizeof(SFLDataFormat);
+    size_t availSamples = Manager::instance().getMainBuffer()->availForGet(MainBuffer::DEFAULT_ID) / sizeof(SFLDataFormat);
 
     if (availSamples == 0) {
         pa_stream_begin_write(s, &data, &bytes);
@@ -382,7 +375,7 @@ void PulseLayer::writeToSpeaker()
 
     size_t inBytes = inSamples * sizeof(SFLDataFormat);
     pa_stream_begin_write(s, &data, &inBytes);
-    Manager::instance().getMainBuffer()->getData(data, inBytes);
+    Manager::instance().getMainBuffer()->getData(data, inBytes, MainBuffer::DEFAULT_ID);
 
     if (resample) {
         SFLDataFormat* rsmpl_out = (SFLDataFormat*) pa_xmalloc(outBytes);
@@ -421,7 +414,7 @@ void PulseLayer::readFromMic()
 
     if (bytes > mic_buf_size_) {
         mic_buf_size_ = bytes;
-        delete[] mic_buffer_;
+        delete [] mic_buffer_;
         mic_buffer_ = new SFLDataFormat[samples];
     }
 
@@ -430,7 +423,7 @@ void PulseLayer::readFromMic()
 
     dcblocker_.process(mic_buffer_, resample ? mic_buffer_ : (SFLDataFormat*)data, samples);
     applyGain(mic_buffer_, bytes / sizeof(SFLDataFormat), getCaptureGain());
-    Manager::instance().getMainBuffer()->putData(mic_buffer_, bytes);
+    Manager::instance().getMainBuffer()->putData(mic_buffer_, bytes, MainBuffer::DEFAULT_ID);
 
     if (pa_stream_drop(record_->pulseStream()) < 0)
         ERROR("Audio: Error: capture stream drop failed: %s" , pa_strerror(pa_context_errno(context_)));
diff --git a/daemon/src/audio/recordable.cpp b/daemon/src/audio/recordable.cpp
index 72649412d5c723b2c096bfc10a2ddfa34e7475cf..7eda5bd661f1d8e24c8c092f8e0425ac8b0b5b37 100644
--- a/daemon/src/audio/recordable.cpp
+++ b/daemon/src/audio/recordable.cpp
@@ -29,9 +29,11 @@
 
 #include "recordable.h"
 #include "manager.h"
+#include "logger.h"
 
 Recordable::Recordable() : recAudio_(), recorder_(&recAudio_, Manager::instance().getMainBuffer())
 {
+    DEBUG("=================== Set recornding options: %s", Manager::instance().audioPreference.getRecordpath().c_str());
     recAudio_.setRecordingOption(AudioRecord::FILE_WAV, 8000, Manager::instance().audioPreference.getRecordpath());
 }
 
diff --git a/daemon/src/audio/ringbuffer.cpp b/daemon/src/audio/ringbuffer.cpp
index 9119838ffea0acfdebc05288b9204bfb8963c269..fe8547d06fc89c791a99f0a9801840fd76d4fef6 100644
--- a/daemon/src/audio/ringbuffer.cpp
+++ b/daemon/src/audio/ringbuffer.cpp
@@ -36,11 +36,11 @@
 #include <cstring>
 #include <utility> // for std::pair
 
+#include "logger.h"
 #include "ringbuffer.h"
-#include "global.h"
 
 // corespond to 106 ms (about 5 rtp packets)
-#define MIN_BUFFER_SIZE	1280
+#define MIN_BUFFER_SIZE 1280
 
 int RingBuffer::count_rb = 0;
 
diff --git a/daemon/src/audio/ringbuffer.h b/daemon/src/audio/ringbuffer.h
index f22b1f7f10965248f59ffdadb4bc51576840bc0c..6fde62b4d1d807fd57435d49a92dfd2f8c258550 100644
--- a/daemon/src/audio/ringbuffer.h
+++ b/daemon/src/audio/ringbuffer.h
@@ -23,7 +23,7 @@
 #define __RING_BUFFER__
 
 #include <fstream>
-#include "../call.h"
+#include <map>
 #include "noncopyable.h"
 
 typedef std::map<std::string, int> ReadPointer;
@@ -34,28 +34,28 @@ class RingBuffer {
          * Constructor
          * @param size  Size of the buffer to create
          */
-        RingBuffer(int size, const std::string &call_id = Call::DEFAULT_ID);
+        RingBuffer(int size, const std::string &call_id);
 
         /**
          * Destructor
          */
         ~RingBuffer();
 
-        std::string getBufferId() {
+        std::string getBufferId() const {
             return buffer_id_;
         }
 
         /**
          * Reset the counters to 0 for this read pointer
          */
-        void flush(const std::string &call_id = Call::DEFAULT_ID);
+        void flush(const std::string &call_id);
 
         void flushAll();
 
         /**
          * Get read pointer coresponding to this call
          */
-        int getReadPointer(const std::string &call_id = Call::DEFAULT_ID);
+        int getReadPointer(const std::string &call_id);
 
         /**
          * Get the whole readpointer list for this ringbuffer
@@ -72,17 +72,17 @@ class RingBuffer {
         /**
          * Move readpointer forward by pointer_value
          */
-        void storeReadPointer(int pointer_value, const std::string &call_id = Call::DEFAULT_ID);
+        void storeReadPointer(int pointer_value, const std::string &call_id);
 
         /**
          * Add a new readpointer for this ringbuffer
          */
-        void createReadPointer(const std::string &call_id = Call::DEFAULT_ID);
+        void createReadPointer(const std::string &call_id);
 
         /**
          * Remove a readpointer for this ringbuffer
          */
-        void removeReadPointer(const std::string &call_id = Call::DEFAULT_ID);
+        void removeReadPointer(const std::string &call_id);
 
         /**
          * Test if readpointer coresponding to this call is still active
@@ -102,7 +102,7 @@ class RingBuffer {
          * To get how much space is available in the buffer to read in
          * @return int The available size
          */
-        int AvailForGet(const std::string &call_id = Call::DEFAULT_ID);
+        int AvailForGet(const std::string &call_id);
 
         /**
          * Get data in the ring buffer
@@ -110,14 +110,14 @@ class RingBuffer {
          * @param toCopy Number of bytes to copy
          * @return int Number of bytes copied
          */
-        int Get(void* buffer, int toCopy, const std::string &call_id = Call::DEFAULT_ID);
+        int Get(void* buffer, int toCopy, const std::string &call_id);
 
         /**
          * Discard data from the buffer
          * @param toDiscard Number of bytes to discard
          * @return int Number of bytes discarded
          */
-        int Discard(int toDiscard, const std::string &call_id = Call::DEFAULT_ID);
+        int Discard(int toDiscard, const std::string &call_id);
 
         /**
          * Total length of the ring buffer
@@ -125,7 +125,7 @@ class RingBuffer {
          */
         int putLen();
 
-        int getLen(const std::string &call_id = Call::DEFAULT_ID);
+        int getLen(const std::string &call_id);
 
         /**
          * Debug function print mEnd, mStart, mBufferSize
@@ -142,13 +142,13 @@ class RingBuffer {
         /** Data */
         unsigned char *buffer_;
 
-        ReadPointer   readpointer_;
+        ReadPointer readpointer_;
         std::string buffer_id_;
 
-    public:
-
         friend class MainBufferTest;
 
+    public:
+
         std::fstream *buffer_input_rec;
         std::fstream *buffer_output_rec;
 
diff --git a/daemon/src/audio/samplerateconverter.h b/daemon/src/audio/samplerateconverter.h
index f367161eba2e0d3e6afb7a2ef52123ff522a1fd1..31518d203aabf3d4f78cca5854edf44dac9730af 100644
--- a/daemon/src/audio/samplerateconverter.h
+++ b/daemon/src/audio/samplerateconverter.h
@@ -33,8 +33,9 @@
 
 #include <samplerate.h>
 #include <cmath>
+#include <cstring>
 
-#include "global.h"
+#include "sfl_types.h"
 #include "noncopyable.h"
 
 class SamplerateConverter {
diff --git a/daemon/src/audio/sound/audiofile.cpp b/daemon/src/audio/sound/audiofile.cpp
index c9f88e6975914d8929e970aed8a9925217b3f17b..be11a5b2d576de2fbaeaa8c50ca7c367c6848542 100644
--- a/daemon/src/audio/sound/audiofile.cpp
+++ b/daemon/src/audio/sound/audiofile.cpp
@@ -31,18 +31,16 @@
  *  as that of the covered work.
  */
 #include <fstream>
-#include <math.h>
+#include <cmath>
 #include <samplerate.h>
 #include <cstring>
 #include <vector>
 #include <climits>
 
 #include "audiofile.h"
-#include "audio/codecs/audiocodecfactory.h"
 #include "audio/codecs/audiocodec.h"
 #include "audio/samplerateconverter.h"
-
-#include "manager.h"
+#include "logger.h"
 
 RawFile::RawFile(const std::string& name, sfl::AudioCodec *codec, unsigned int sampleRate)
     : AudioFile(name), audioCodec_(codec)
@@ -122,16 +120,16 @@ WaveFile::WaveFile(const std::string &fileName, int newRate) : AudioFile(fileNam
     fileStream.open(fileName.c_str(), std::ios::in | std::ios::binary);
 
     char riff[4] = { 0, 0, 0, 0 };
-    fileStream.read(riff, sizeof riff / sizeof riff[0]);
+    fileStream.read(riff, sizeof riff / sizeof *riff);
 
-    if (strncmp("RIFF", riff, sizeof riff / sizeof riff[0]) != 0)
+    if (strncmp("RIFF", riff, sizeof riff / sizeof *riff) != 0)
         throw AudioFileException("File is not of RIFF format");
 
     char fmt[4] = { 0, 0, 0, 0 };
     int maxIteration = 10;
 
-    while (maxIteration-- and strncmp("fmt ", fmt, sizeof fmt / sizeof fmt[0]))
-        fileStream.read(fmt, sizeof fmt / sizeof fmt[0]);
+    while (maxIteration-- and strncmp("fmt ", fmt, sizeof fmt / sizeof *fmt))
+        fileStream.read(fmt, sizeof fmt / sizeof *fmt);
 
     if (maxIteration == 0)
         throw AudioFileException("Could not find \"fmt \" chunk");
@@ -172,8 +170,8 @@ WaveFile::WaveFile(const std::string &fileName, int newRate) : AudioFile(fileNam
     char data[4] = { 0, 0, 0, 0 };
     maxIteration = 10;
 
-    while (maxIteration-- && strncmp("data", data, sizeof data / sizeof data[0]))
-        fileStream.read(data, sizeof data / sizeof data[0]);
+    while (maxIteration-- && strncmp("data", data, sizeof data / sizeof *data))
+        fileStream.read(data, sizeof data / sizeof *data);
 
     // Samplerate converter initialized with 88200 sample long
     SamplerateConverter converter(std::max(fileRate, newRate));
diff --git a/daemon/src/audio/sound/tone.cpp b/daemon/src/audio/sound/tone.cpp
index 5f0086373155048ccc3a1d9825eaee781592cd1e..8a3eee76bf0eee2245c7ba899d721209abc15146 100644
--- a/daemon/src/audio/sound/tone.cpp
+++ b/daemon/src/audio/sound/tone.cpp
@@ -35,10 +35,13 @@
  * YM: 2006-11-15: changes unsigned int to std::string::size_type, thanks to Pierre Pomes (AMD64 compilation)
  */
 #include "tone.h"
+#include "logger.h"
+#include "sfl_types.h"
 #include <cmath>
 #include <cassert>
 #include <cstdlib>
 #include <cstring>
+#include <vector>
 
 Tone::Tone(const std::string& definition, unsigned int sampleRate) :
     sampleRate_(sampleRate), xhigher_(0.0), xlower_(0.0)
@@ -55,8 +58,8 @@ Tone::genBuffer(const std::string& definition)
 
     size_ = 0;
 
-    SFLDataFormat* buffer = new SFLDataFormat[SIZEBUF]; //1kb
-    SFLDataFormat* bufferPos = buffer;
+    std::vector<SFLDataFormat> buffer(SIZEBUF); // 1kb
+    SFLDataFormat* bufferPos = &(*buffer.begin());
 
     // Number of format sections
     std::string::size_type posStart = 0; // position of precedent comma
@@ -123,9 +126,7 @@ Tone::genBuffer(const std::string& definition)
     assert(!buffer_);
     buffer_ = new SFLDataFormat[size_];
 
-    memcpy(buffer_, buffer, size_ * sizeof(SFLDataFormat)); // copy char, not SFLDataFormat.
-
-    delete [] buffer;
+    memcpy(buffer_, &(*buffer.begin()), size_ * sizeof(SFLDataFormat)); // copy char, not SFLDataFormat.
 }
 
 void
@@ -139,7 +140,7 @@ Tone::fillWavetable()
 }
 
 double
-Tone::interpolate(double x)
+Tone::interpolate(double x) const
 {
     int xi_0 = x;
     int xi_1 = xi_0 + 1;
diff --git a/daemon/src/audio/sound/tone.h b/daemon/src/audio/sound/tone.h
index bf6eeee85302759d711150a94007853eacefe3b9..55422bd0f508a76d26f209a639f5a785abf54614 100644
--- a/daemon/src/audio/sound/tone.h
+++ b/daemon/src/audio/sound/tone.h
@@ -73,8 +73,7 @@ class Tone : public AudioLoop {
          */
         void fillWavetable();
 
-        double interpolate(double x);
-
+        double interpolate(double x) const;
 
     private:
 
diff --git a/daemon/src/audio/speexechocancel.cpp b/daemon/src/audio/speexechocancel.cpp
index 9c61182692ece610c9e4a3952eff24510e3265d7..f51989ed5d47853a8cf5d7fd5620c6adf4beef81 100644
--- a/daemon/src/audio/speexechocancel.cpp
+++ b/daemon/src/audio/speexechocancel.cpp
@@ -21,6 +21,7 @@
 #include <climits>
 
 #include "speexechocancel.h"
+#include "logger.h"
 #include <speex/speex_echo.h>
 #include <speex/speex_preprocess.h>
 #include "manager.h"
@@ -40,19 +41,23 @@ SpeexEchoCancel::SpeexEchoCancel() :
     echoTailLength_(Manager::instance().getEchoCancelTailLength() * SPEEX_SAMPLE_RATE / 1000),
     echoState_(speex_echo_state_init(EC_FRAME_SIZE, echoTailLength_)),
     preState_(speex_preprocess_state_init(EC_FRAME_SIZE, SPEEX_SAMPLE_RATE)),
-    micData_(RINGBUFFER_SIZE),
-    spkrData_(RINGBUFFER_SIZE),
-    spkrStopped_(true)
+    micData_(RINGBUFFER_SIZE, MainBuffer::DEFAULT_ID),
+    spkrData_(RINGBUFFER_SIZE, MainBuffer::DEFAULT_ID),
+    spkrStopped_(true),
+    tmpSpkr_(),
+    tmpMic_(),
+    tmpOut_()
 {
-    DEBUG("EchoCancel: Initializing echo canceller with delay: %d, filter length: %d, frame size: %d and samplerate %d",
-          echoDelay_, echoTailLength_, EC_FRAME_SIZE, SPEEX_SAMPLE_RATE);
+    DEBUG("EchoCancel: Initializing echo canceller with delay: %d, filter "
+          "length: %d, frame size: %d and samplerate %d", echoDelay_,
+          echoTailLength_, EC_FRAME_SIZE, SPEEX_SAMPLE_RATE);
 
     int rate = SPEEX_SAMPLE_RATE;
     speex_echo_ctl(echoState_, SPEEX_ECHO_SET_SAMPLING_RATE, &rate);
     speex_preprocess_ctl(preState_, SPEEX_PREPROCESS_SET_ECHO_STATE, echoState_);
 
-    micData_.createReadPointer();
-    spkrData_.createReadPointer();
+    micData_.createReadPointer(MainBuffer::DEFAULT_ID);
+    spkrData_.createReadPointer(MainBuffer::DEFAULT_ID);
 }
 
 SpeexEchoCancel::~SpeexEchoCancel()
@@ -88,16 +93,16 @@ int SpeexEchoCancel::process(SFLDataFormat *inputData, SFLDataFormat *outputData
     micData_.Put(inputData, samples * sizeof(SFLDataFormat));
 
     // Store data for synchronization
-    int spkrAvail = spkrData_.AvailForGet();
-    int micAvail = micData_.AvailForGet();
+    int spkrAvail = spkrData_.AvailForGet(MainBuffer::DEFAULT_ID);
+    int micAvail = micData_.AvailForGet(MainBuffer::DEFAULT_ID);
 
-    if (spkrAvail < (echoDelay_+byteSize) || micAvail < byteSize) {
-        micData_.Discard(byteSize);
+    if ((spkrAvail < (echoDelay_ + byteSize)) or micAvail < byteSize) {
+        micData_.Discard(byteSize, MainBuffer::DEFAULT_ID);
         return 0;
     }
 
-    spkrData_.Get(tmpSpkr_, byteSize);
-    micData_.Get(tmpMic_, byteSize);
+    spkrData_.Get(tmpSpkr_, byteSize, MainBuffer::DEFAULT_ID);
+    micData_.Get(tmpMic_, byteSize, MainBuffer::DEFAULT_ID);
 
     for (int i = 0; i < EC_FRAME_SIZE; i++) {
         int32_t tmp = tmpSpkr_[i] * 3;
@@ -118,8 +123,8 @@ int SpeexEchoCancel::process(SFLDataFormat *inputData, SFLDataFormat *outputData
 
     memcpy(outputData, tmpOut_, byteSize);
 
-    spkrAvail = spkrData_.AvailForGet();
-    micAvail = micData_.AvailForGet();
+    spkrAvail = spkrData_.AvailForGet(MainBuffer::DEFAULT_ID);
+    micAvail = micData_.AvailForGet(MainBuffer::DEFAULT_ID);
 
     return EC_FRAME_SIZE;
 }
diff --git a/daemon/src/audio/speexechocancel.h b/daemon/src/audio/speexechocancel.h
index 3f0fbb35ec8d4ce1007f7876bcdaec9e11fcf7e4..51b1cc583c5a31a93ff7080758f8d07e3c09337a 100644
--- a/daemon/src/audio/speexechocancel.h
+++ b/daemon/src/audio/speexechocancel.h
@@ -20,7 +20,7 @@
 #ifndef SPEEXECHOCANCEL_H
 #define SPEEXECHOCANCEL_H
 
-#include "global.h"
+#include "sfl_types.h"
 #include "noncopyable.h"
 #include "ringbuffer.h"
 
diff --git a/daemon/src/call.cpp b/daemon/src/call.cpp
index 819113c4b3e541e840fdbc0183ab78158fd81ccf..19b95803092df067ec2bed49801ab253812e621d 100644
--- a/daemon/src/call.cpp
+++ b/daemon/src/call.cpp
@@ -33,8 +33,6 @@
 #include "audio/mainbuffer.h"
 #include "history/historyitem.h"
 
-const char * const Call::DEFAULT_ID = "audiolayer_id";
-
 Call::Call(const std::string& id, Call::CallType type)
     : callMutex_()
     , localIPAddress_("")
@@ -155,12 +153,12 @@ Call::setRecording()
 
     if (!recordStatus) {
         mbuffer->bindHalfDuplexOut(process_id, id_);
-        mbuffer->bindHalfDuplexOut(process_id);
+        mbuffer->bindHalfDuplexOut(process_id, MainBuffer::DEFAULT_ID);
 
         Recordable::recorder_.start();
     } else {
         mbuffer->unBindHalfDuplexOut(process_id, id_);
-        mbuffer->unBindHalfDuplexOut(process_id);
+        mbuffer->unBindHalfDuplexOut(process_id, MainBuffer::DEFAULT_ID);
     }
 
     Manager::instance().getMainBuffer()->stateInfo();
diff --git a/daemon/src/call.h b/daemon/src/call.h
index c88118493b239cd2a3b02cdc9896f5474e7df9a6..0ea8dd9d66855cee054addabc0c49da76e9bd728 100644
--- a/daemon/src/call.h
+++ b/daemon/src/call.h
@@ -32,9 +32,9 @@
 #ifndef __CALL_H__
 #define __CALL_H__
 
-#include <cc++/thread.h> // for mutex
 #include <sstream>
-
+#include <map>
+#include "cc_thread.h"
 #include "audio/recordable.h"
 
 /*
diff --git a/daemon/test/ringtonetest.cpp b/daemon/src/cc_config.h
similarity index 73%
rename from daemon/test/ringtonetest.cpp
rename to daemon/src/cc_config.h
index 0b82edd1d1698bac9cc54521647423fa0fca5257..5f391d0b809c104b0423c7d1dbacd2429670ab0e 100644
--- a/daemon/test/ringtonetest.cpp
+++ b/daemon/src/cc_config.h
@@ -1,6 +1,6 @@
 /*
- *  Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc.
- *  Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
+ *  Copyright (C) 2012 Savoir-Faire Linux Inc.
+ *  Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
@@ -28,16 +28,19 @@
  *  as that of the covered work.
  */
 
-#include "ringtonetest.h"
+#ifndef CC_CONFIG_H_
+#define CC_CONFIG_H_
 
-void RingtoneTest::testLoadWavefile()
-{
-    WavFile wav;
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
 
-    // Test initial values
-    CPPUNIT_ASSERT(not wav.isStarted());
-    CPPUNIT_ASSERT(wav.getSize() == 0);
+#ifdef CCPP_PREFIX
+#include <cc++/config.h>
+#elif defined COMMONCPP_PREFIX
+#include <commoncpp/config.h>
+#else
+#error No CCGNU2 include directory found.
+#endif
 
-    // Test protection against wrong file name
-    CPPUNIT_ASSERT(not wav.loadFile(std::string("wrongfilename.wav"), NULL, 44100));
-}
+#endif // CC_CONFIG_H_
diff --git a/daemon/src/cc_thread.h b/daemon/src/cc_thread.h
new file mode 100644
index 0000000000000000000000000000000000000000..fbbaf277e5c08b203ddfdc15374097b37e420a9b
--- /dev/null
+++ b/daemon/src/cc_thread.h
@@ -0,0 +1,46 @@
+/*
+ *  Copyright (C) 2012 Savoir-Faire Linux Inc.
+ *  Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ *  Additional permission under GNU GPL version 3 section 7:
+ *
+ *  If you modify this program, or any covered work, by linking or
+ *  combining it with the OpenSSL project's OpenSSL library (or a
+ *  modified version of that library), containing parts covered by the
+ *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
+ *  grants you additional permission to convey the resulting work.
+ *  Corresponding Source for a non-source form of such a combination
+ *  shall include the source code for the parts of OpenSSL used as well
+ *  as that of the covered work.
+ */
+
+#ifndef CC_THREAD_H_
+#define CC_THREAD_H_
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#ifdef CCPP_PREFIX
+#include <cc++/thread.h> // for mutex
+#elif defined COMMONCPP_PREFIX
+#include <commoncpp/thread.h> // for mutex
+#else
+#error No CCGNU2 include directory found.
+#endif
+
+#endif	// CC_THREAD_H_
diff --git a/daemon/src/codec.h b/daemon/src/codec.h
index c2048c059f9c568cf7a1166b32ed242c0f2149e4..713ac9a1d9ba5a29636f456e78a5859918276408 100644
--- a/daemon/src/codec.h
+++ b/daemon/src/codec.h
@@ -27,10 +27,10 @@
  *  as that of the covered work.
  */
 
-#ifndef __SFL_CODEC_H__
-#define __SFL_CODEC_H__
+#ifndef CODEC_H_
+#define CODEC_H_
 
-#include <cc++/config.h> // for types
+#include "cc_config.h" // for types
 
 /**
  * Interface for both audio codecs as well as video codecs.
@@ -65,4 +65,4 @@ typedef sfl::Codec* create_t();
 
 typedef void destroy_t (sfl::Codec*);
 
-#endif
+#endif // CODEC_H_
diff --git a/daemon/src/conference.cpp b/daemon/src/conference.cpp
index a44d8d91e9961f9324bbf4b4a1d8dab88dc9de46..f2850f99bba4fb0cb3e0e878d54cac595f180961 100644
--- a/daemon/src/conference.cpp
+++ b/daemon/src/conference.cpp
@@ -71,7 +71,7 @@ void Conference::bindParticipant(const std::string &participant_id)
         if (participant_id != *iter)
             Manager::instance().getMainBuffer()->bindCallID(participant_id, *iter);
 
-    Manager::instance().getMainBuffer()->bindCallID(participant_id);
+    Manager::instance().getMainBuffer()->bindCallID(participant_id, MainBuffer::DEFAULT_ID);
 }
 
 std::string Conference::getStateStr() const
@@ -113,14 +113,14 @@ bool Conference::setRecording()
         for (ParticipantSet::const_iterator iter = participants_.begin(); iter != participants_.end(); ++iter)
             mbuffer->bindHalfDuplexOut(process_id, *iter);
 
-        mbuffer->bindHalfDuplexOut(process_id);
+        mbuffer->bindHalfDuplexOut(process_id, MainBuffer::DEFAULT_ID);
 
         Recordable::recorder_.start();
     } else {
         for (ParticipantSet::const_iterator iter = participants_.begin(); iter != participants_.end(); ++iter)
             mbuffer->unBindHalfDuplexOut(process_id, *iter);
 
-        mbuffer->unBindHalfDuplexOut(process_id);
+        mbuffer->unBindHalfDuplexOut(process_id, MainBuffer::DEFAULT_ID);
     }
 
     return recordStatus;
diff --git a/daemon/src/config/serializable.h b/daemon/src/config/serializable.h
index 0299f8e5e09cd47865b735062efab6352182a235..24d008b25275a3cd1781edd37bd0b5000fa78263 100644
--- a/daemon/src/config/serializable.h
+++ b/daemon/src/config/serializable.h
@@ -28,8 +28,8 @@
  *  as that of the covered work.
  */
 
-#ifndef __SERIALIZABLE_H__
-#define __SERIALIZABLE_H__
+#ifndef SERIALIZABLE_H__
+#define SERIALIZABLE_H__
 
 namespace Conf {
     class YamlEmitter;
@@ -40,8 +40,8 @@ class Serializable {
 
     public:
         virtual ~Serializable() {};
-        virtual void serialize(Conf::YamlEmitter *emitter) = 0;
-        virtual void unserialize(const Conf::MappingNode *map) = 0;
+        virtual void serialize(Conf::YamlEmitter &emitter) = 0;
+        virtual void unserialize(const Conf::MappingNode &map) = 0;
 };
 
 #endif
diff --git a/daemon/src/config/sfl_config.cpp b/daemon/src/config/sfl_config.cpp
index 42da7a12cc3fa230a9f57bdc1f2736b0fa5c4797..5b4841b0bdf57a8a511d69c391f6a2fbee06da10 100644
--- a/daemon/src/config/sfl_config.cpp
+++ b/daemon/src/config/sfl_config.cpp
@@ -30,7 +30,7 @@
  */
 
 #include "sfl_config.h"
-#include "../global.h"
+#include "logger.h"
 #include <fstream>
 #include <cstdlib>
 #include <sys/types.h>
diff --git a/daemon/src/config/yamlemitter.cpp b/daemon/src/config/yamlemitter.cpp
index 902c1a4ab4431d7b452b25d60f5a00cbf9195459..6ab19a941624d21669e946cd8d71e0186f95970d 100644
--- a/daemon/src/config/yamlemitter.cpp
+++ b/daemon/src/config/yamlemitter.cpp
@@ -29,8 +29,9 @@
  */
 
 #include "yamlemitter.h"
-#include <stdio.h>
-#include "../global.h"
+#include "yamlnode.h"
+#include <cstdio>
+#include "logger.h"
 
 namespace Conf {
 
@@ -73,11 +74,13 @@ void YamlEmitter::close()
 {
     yaml_emitter_delete(&emitter_);
 
+    // Refererence:
+    // http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.9
     if (!fd_)
-        throw YamlEmitterException("File descriptor not valid");
+        ERROR("File descriptor not valid");
 
     if (fclose(fd_))
-        throw YamlEmitterException("Error closing file descriptor");
+        ERROR("Error closing file descriptor");
 }
 
 void YamlEmitter::serializeData()
@@ -89,8 +92,6 @@ void YamlEmitter::serializeData()
 
 void YamlEmitter::serializeAccount(MappingNode *map)
 {
-    int accountmapping;
-
     if (map->getType() != MAPPING)
         throw YamlEmitterException("Node type is not a mapping while writing account");
 
@@ -111,184 +112,44 @@ void YamlEmitter::serializeAccount(MappingNode *map)
         isFirstAccount_ = false;
     }
 
-    if ((accountmapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
+    int accountMapping;
+    if ((accountMapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
         throw YamlEmitterException("Could not add account mapping to document");
 
-    if (yaml_document_append_sequence_item(&document_, accountSequence_, accountmapping) == 0)
+    if (yaml_document_append_sequence_item(&document_, accountSequence_, accountMapping) == 0)
         throw YamlEmitterException("Could not append account mapping to sequence");
 
-    Mapping *internalmap = map->getMapping();
-    for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter)
-        addMappingItem(accountmapping, iter->first, iter->second);
-}
-
-void YamlEmitter::serializePreference(MappingNode *map)
-{
-    if (map->getType() != MAPPING)
-        throw YamlEmitterException("Node type is not a mapping while writing preferences");
-
-    static const char * const PREFERENCE_STR = "preferences";
-    int preferenceid;
-
-    if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0)
-        throw YamlEmitterException("Could not add scalar to document");
-
-    int preferencemapping;
-    if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
-        throw YamlEmitterException("Could not add mapping to document");
-
-    if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0)
-        throw YamlEmitterException("Could not add mapping pair to top leve mapping");
-
-    Mapping *internalmap = map->getMapping();
-    for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter)
-        addMappingItem(preferencemapping, iter->first, iter->second);
-}
-
-void YamlEmitter::serializeVoipPreference(MappingNode *map)
-{
-    if (map->getType() != MAPPING)
-        throw YamlEmitterException("Node type is not a mapping while writing preferences");
-
-
-    static const char *const PREFERENCE_STR = "voipPreferences";
-    int preferenceid;
-    if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0)
-        throw YamlEmitterException("Could not add scalar to document");
-
-    int preferencemapping;
-    if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
-        throw YamlEmitterException("Could not add mapping to document");
-
-    if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0)
-        throw YamlEmitterException("Could not add mapping pair to top leve mapping");
-
-    Mapping *internalmap = map->getMapping();
-    Mapping::iterator iter = internalmap->begin();
-
-    while (iter != internalmap->end()) {
-        addMappingItem(preferencemapping, iter->first, iter->second);
-        iter++;
-    }
-}
-
-void YamlEmitter::serializeAddressbookPreference(MappingNode *map)
-{
-    if (map->getType() != MAPPING)
-        throw YamlEmitterException("Node type is not a mapping while writing preferences");
-
-    static const char * const PREFERENCE_STR = "addressbook";
-    int preferenceid;
-    if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0)
-        throw YamlEmitterException("Could not add scalar to document");
-    int preferencemapping;
-    if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
-        throw YamlEmitterException("Could not add mapping to document");
-
-    if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0)
-        throw YamlEmitterException("Could not add mapping pair to top leve mapping");
-
-    Mapping *internalmap = map->getMapping();
-    for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter)
-        addMappingItem(preferencemapping, iter->first, iter->second);
-}
-
-void YamlEmitter::serializeHooksPreference(MappingNode *map)
-{
-    if (map->getType() != MAPPING)
-        throw YamlEmitterException("Node type is not a mapping while writing preferences");
-
-    static const char * const PREFERENCE_STR = "hooks";
-    int preferenceid;
-    if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0)
-        throw YamlEmitterException("Could not add scalar to document");
-
-    int preferencemapping;
-    if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
-        throw YamlEmitterException("Could not add mapping to document");
-
-    if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0)
-        throw YamlEmitterException("Could not add mapping pair to top leve mapping");
-
-    Mapping *internalmap = map->getMapping();
-    for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter)
-        addMappingItem(preferencemapping, iter->first, iter->second);
-}
-
-
-void YamlEmitter::serializeAudioPreference(MappingNode *map)
-{
-    static const char *const PREFERENCE_STR = "audio";
-
-    int preferenceid, preferencemapping;
-
-    if (map->getType() != MAPPING)
-        throw YamlEmitterException("Node type is not a mapping while writing preferences");
-
-    if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0)
-        throw YamlEmitterException("Could not add scalar to document");
-
-    if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
-        throw YamlEmitterException("Could not add mapping to document");
-
-    if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0)
-        throw YamlEmitterException("Could not add mapping pair to top leve mapping");
-
-    Mapping *internalmap = map->getMapping();
-    for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter)
-        addMappingItem(preferencemapping, iter->first, iter->second);
+    addMappingItems(accountMapping, map->getMapping());
 }
 
-#ifdef SFL_VIDEO
-void YamlEmitter::serializeVideoPreference(MappingNode *map)
+void YamlEmitter::serializePreference(MappingNode *map, const char *preference_str)
 {
     if (map->getType() != MAPPING)
         throw YamlEmitterException("Node type is not a mapping while writing preferences");
 
-
-    static const char * const PREFERENCE_STR = "video";
     int preferenceid;
-    if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0)
+    if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) preference_str, -1, YAML_PLAIN_SCALAR_STYLE)) == 0)
         throw YamlEmitterException("Could not add scalar to document");
 
-    int preferencemapping;
-    if ((preferencemapping = yaml_document_add_mapping (&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
+    int preferenceMapping;
+    if ((preferenceMapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
         throw YamlEmitterException("Could not add mapping to document");
 
-    if (yaml_document_append_mapping_pair (&document_, topLevelMapping_, preferenceid, preferencemapping) == 0)
+    if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferenceMapping) == 0)
         throw YamlEmitterException("Could not add mapping pair to top leve mapping");
 
-    Mapping *internalmap = map->getMapping();
-    for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter)
-        addMappingItem(preferencemapping, iter->first, iter->second);
+    addMappingItems(preferenceMapping, map->getMapping());
 }
-#endif
 
+typedef std::map<std::string, YamlNode*> Mapping;
 
-void YamlEmitter::serializeShortcutPreference(MappingNode *map)
+void YamlEmitter::addMappingItems(int mappingID, Mapping *iMap)
 {
-    if (map->getType() != MAPPING)
-        throw YamlEmitterException("Node type is not a mapping while writing preferences");
-
-    static const char *const PREFERENCE_STR = "shortcuts";
-    int preferenceid;
-    if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0)
-        throw YamlEmitterException("Could not add scalar to document");
-
-    int preferencemapping;
-    if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0)
-        throw YamlEmitterException("Could not add mapping to document");
-
-    if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0)
-        throw YamlEmitterException("Could not add mapping pair to top leve mapping");
-
-    Mapping *internalmap = map->getMapping();
-    for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter)
-        addMappingItem(preferencemapping, iter->first, iter->second);
+    for (Mapping::const_iterator i = iMap->begin(); i != iMap->end(); ++i)
+        addMappingItem(mappingID, i->first, i->second);
 }
 
-
-void YamlEmitter::addMappingItem(int mappingid, std::string key, YamlNode *node)
+void YamlEmitter::addMappingItem(int mappingid, const std::string &key, YamlNode *node)
 {
     if (node->getType() == SCALAR) {
         ScalarNode *sclr = static_cast<ScalarNode *>(node);
@@ -318,9 +179,7 @@ void YamlEmitter::addMappingItem(int mappingid, std::string key, YamlNode *node)
         if (yaml_document_append_mapping_pair(&document_, mappingid, temp1, temp2) == 0)
             throw YamlEmitterException("Could not add mapping pair to mapping");
 
-        Mapping *internalmap = map->getMapping();
-        for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter)
-            addMappingItem(temp2, iter->first, iter->second);
+        addMappingItems(temp2, map->getMapping());
 
     } else if (node->getType() == SEQUENCE) {
         SequenceNode *seqnode = static_cast<SequenceNode *>(node);
@@ -347,11 +206,7 @@ void YamlEmitter::addMappingItem(int mappingid, std::string key, YamlNode *node)
                 throw YamlEmitterException("Could not append account mapping to sequence");
 
             MappingNode *mapnode = static_cast<MappingNode*>(yamlNode);
-            Mapping *map = mapnode->getMapping();
-            Mapping::iterator mapit;
-
-            for (mapit = map->begin(); mapit != map->end() ; ++mapit)
-                addMappingItem(id, mapit->first, mapit->second);
+            addMappingItems(id, mapnode->getMapping());
         }
     } else
         throw YamlEmitterException("Unknown node type while adding mapping node");
diff --git a/daemon/src/config/yamlemitter.h b/daemon/src/config/yamlemitter.h
index e26e0a2efbfd4bf11e6422e6ba0abee61b844768..599c476aa22789bd1b4886c8115bf375e1c82a2e 100644
--- a/daemon/src/config/yamlemitter.h
+++ b/daemon/src/config/yamlemitter.h
@@ -38,18 +38,20 @@
 #include <yaml.h>
 #include <stdexcept>
 #include <string>
+#include <map>
 #include "noncopyable.h"
-#include "yamlnode.h"
 
 namespace Conf {
 
 #define EMITTER_BUFFERSIZE 65536
 #define EMITTER_MAXEVENT 1024
 
+class MappingNode;
+class YamlNode;
+
 class YamlEmitterException : public std::runtime_error {
     public:
-        YamlEmitterException(const std::string& str="") :
-            std::runtime_error("YamlEmitterException occured: " + str) {}
+        YamlEmitterException(const char *err) : std::runtime_error(err) {}
 };
 
 class YamlEmitter {
@@ -65,20 +67,7 @@ class YamlEmitter {
 
         void serializeAccount(MappingNode *map);
 
-        void serializePreference(MappingNode *map);
-
-        void serializeVoipPreference(MappingNode *map);
-
-        void serializeAddressbookPreference(MappingNode *map);
-
-        void serializeHooksPreference(MappingNode *map);
-
-        void serializeAudioPreference(MappingNode *map);
-
-#ifdef SFL_VIDEO
-        void serializeVideoPreference(MappingNode *map);
-#endif
-        void serializeShortcutPreference(MappingNode *map);
+        void serializePreference(MappingNode *map, const char *preference_str);
 
         void writeAudio();
 
@@ -91,7 +80,8 @@ class YamlEmitter {
     private:
 
         NON_COPYABLE(YamlEmitter);
-        void addMappingItem(int mappingid, std::string key, YamlNode *node);
+        void addMappingItems(int mappingid, std::map<std::string, YamlNode*> *mapping);
+        void addMappingItem(int mappingid, const std::string &key, YamlNode *node);
 
         std::string filename_;
 
@@ -133,4 +123,4 @@ class YamlEmitter {
 };
 }
 
-#endif // YAMLEMITTER_H_
+#endif  // YAMLEMITTER_H__
diff --git a/daemon/src/config/yamlnode.cpp b/daemon/src/config/yamlnode.cpp
index 16951e028037ec1d45d1b8b1b897c1614f58b191..32bdf2f27626648262d08d49a9d3683be2dea047 100644
--- a/daemon/src/config/yamlnode.cpp
+++ b/daemon/src/config/yamlnode.cpp
@@ -29,32 +29,30 @@
  */
 
 #include "yamlnode.h"
-#include "global.h"
+#include <cstdlib>
+#include "logger.h"
 
 namespace Conf {
 
-
 void YamlDocument::addNode(YamlNode *node)
 {
-    Sequence::iterator it = doc.end();
-    doc.insert(it, node);
+    Sequence::iterator it = doc_.end();
+    doc_.insert(it, node);
 }
 
 YamlNode *YamlDocument::popNode()
 {
-    YamlNode *node = doc.front();
+    YamlNode *node = doc_.front();
 
     //removed element's destructor is called
-    doc.pop_front();
+    doc_.pop_front();
 
     return node;
 }
 
 void YamlDocument::deleteChildNodes()
 {
-    Sequence::iterator it = doc.begin();
-
-    while (it != doc.end()) {
+    for (Sequence::iterator it = doc_.begin(); it != doc_.end(); ++it) {
         YamlNode *yamlNode = static_cast<YamlNode *>(*it);
 
         switch (yamlNode->getType()) {
@@ -83,36 +81,33 @@ void YamlDocument::deleteChildNodes()
             default:
                 break;
         }
-
-        it++;
     }
 }
 
 void MappingNode::addNode(YamlNode *node)
 {
-    Mapping::iterator it = map.end();
-    map.insert(it, std::pair<std::string, YamlNode *> (tmpKey, node));
+    setKeyValue(tmpKey_, node);
 }
 
+typedef std::map<std::string, YamlNode*> Mapping;
+
 void MappingNode::setKeyValue(const std::string &key, YamlNode *value)
 {
-    Mapping::iterator it = map.end();
-    map.insert(it, std::pair<std::string, YamlNode *> (key, value));
+    Mapping::iterator it = map_.end();
+    map_.insert(it, std::pair<std::string, YamlNode *>(key, value));
 }
 
 void MappingNode::removeKeyValue(const std::string &key)
 {
-
-    Mapping::iterator it = map.find(key);
-    map.erase(it);
+    Mapping::iterator it = map_.find(key);
+    map_.erase(it);
 }
 
-
 YamlNode *MappingNode::getValue(const std::string &key) const
 {
-    Mapping::const_iterator it = map.find(key);
+    Mapping::const_iterator it = map_.find(key);
 
-    if (it != map.end()) {
+    if (it != map_.end()) {
         return it->second;
     } else {
         DEBUG("MappingNode: Could not find %s", key.c_str());
@@ -123,7 +118,6 @@ YamlNode *MappingNode::getValue(const std::string &key) const
 void MappingNode::getValue(const std::string &key, bool *b) const
 {
     ScalarNode *node = static_cast<ScalarNode*>(getValue(key));
-
     if (!node)
         return;
 
@@ -137,7 +131,7 @@ void MappingNode::getValue(const std::string &key, int *i) const
     if (!node)
         return;
 
-    *i = atoi(node->getValue().c_str());
+    *i = std::atoi(node->getValue().c_str());
 }
 
 void MappingNode::getValue(const std::string &key, std::string *v) const
@@ -153,9 +147,7 @@ void MappingNode::getValue(const std::string &key, std::string *v) const
 
 void MappingNode::deleteChildNodes()
 {
-    Mapping::iterator it;
-
-    for (it = map.begin(); it != map.end(); ++it) {
+    for (Mapping::iterator it = map_.begin(); it != map_.end(); ++it) {
         YamlNode *yamlNode = static_cast<YamlNode *>(it->second);
 
         if (!yamlNode)
@@ -192,16 +184,13 @@ void MappingNode::deleteChildNodes()
 
 void SequenceNode::addNode(YamlNode *node)
 {
-    Sequence::iterator it = seq.end();
-    seq.insert(it, node);
+    Sequence::iterator it = seq_.end();
+    seq_.insert(it, node);
 }
 
-
 void SequenceNode::deleteChildNodes()
 {
-    Sequence::iterator it;
-
-    for (it = seq.begin(); it != seq.end(); ++it) {
+    for (Sequence::iterator it = seq_.begin(); it != seq_.end(); ++it) {
         YamlNode *yamlNode = static_cast<YamlNode *>(*it);
 
         switch (yamlNode->getType()) {
diff --git a/daemon/src/config/yamlnode.h b/daemon/src/config/yamlnode.h
index 5ca28b13111a44a96479876b3482f2c3c2559ed0..990b23733ccf4372fc7a96a4c22ec9437baa938a 100644
--- a/daemon/src/config/yamlnode.h
+++ b/daemon/src/config/yamlnode.h
@@ -42,57 +42,56 @@ namespace Conf {
 class YamlNode;
 
 typedef std::list<YamlNode *> Sequence;
-typedef std::map<std::string, YamlNode *> Mapping;
 
 enum NodeType { DOCUMENT, SCALAR, MAPPING, SEQUENCE };
 
 class YamlNode {
     public:
-        YamlNode(NodeType t, YamlNode *top = NULL) : type(t), topNode(top) {}
+        YamlNode(NodeType t, YamlNode *top = NULL) : type_(t), topNode_(top) {}
 
         virtual ~YamlNode() {}
 
-        NodeType getType() {
-            return type;
+        NodeType getType() const {
+            return type_;
         }
 
         YamlNode *getTopNode() {
-            return topNode;
+            return topNode_;
         }
 
         virtual void deleteChildNodes() = 0;
 
     private:
         NON_COPYABLE(YamlNode);
-        NodeType type;
-        YamlNode *topNode;
+        NodeType type_;
+        YamlNode *topNode_;
 };
 
 
 class YamlDocument : public YamlNode {
     public:
-        YamlDocument(YamlNode* top=NULL) : YamlNode(DOCUMENT, top), doc() {}
+        YamlDocument(YamlNode* top = NULL) : YamlNode(DOCUMENT, top), doc_() {}
 
         void addNode(YamlNode *node);
 
         YamlNode *popNode();
 
         Sequence *getSequence() {
-            return &doc;
+            return &doc_;
         }
 
         virtual void deleteChildNodes();
 
     private:
-        Sequence doc;
+        Sequence doc_;
 };
 
 class SequenceNode : public YamlNode {
     public:
-        SequenceNode(YamlNode *top) : YamlNode(SEQUENCE, top), seq() {}
+        SequenceNode(YamlNode *top) : YamlNode(SEQUENCE, top), seq_() {}
 
         Sequence *getSequence() {
-            return &seq;
+            return &seq_;
         }
 
         void addNode(YamlNode *node);
@@ -100,25 +99,27 @@ class SequenceNode : public YamlNode {
         virtual void deleteChildNodes();
 
     private:
-        Sequence seq;
+        Sequence seq_;
 };
 
 
 class MappingNode : public YamlNode {
     public:
-        MappingNode(YamlNode *top) : YamlNode(MAPPING, top), map(), tmpKey() {}
+        MappingNode(YamlNode *top) :
+            YamlNode(MAPPING, top), map_(), tmpKey_() {}
 
-        Mapping *getMapping() {
-            return &map;
+        std::map<std::string, YamlNode*> *
+        getMapping() {
+            return &map_;
         }
 
         void addNode(YamlNode *node);
 
         void setTmpKey(std::string key) {
-            tmpKey = key;
+            tmpKey_ = key;
         }
 
-        void  setKeyValue(const std::string &key, YamlNode *value);
+        void setKeyValue(const std::string &key, YamlNode *value);
 
         void removeKeyValue(const std::string &key);
 
@@ -130,27 +131,27 @@ class MappingNode : public YamlNode {
         virtual void deleteChildNodes();
 
     private:
-        Mapping map;
-        std::string tmpKey;
+        std::map<std::string, YamlNode*> map_;
+        std::string tmpKey_;
 };
 
 class ScalarNode : public YamlNode {
     public:
-        ScalarNode(std::string s="", YamlNode *top=NULL) : YamlNode(SCALAR, top), str(s) {}
-        ScalarNode(bool b, YamlNode *top=NULL) : YamlNode(SCALAR, top), str(b ? "true" : "false") {}
+        ScalarNode(std::string s="", YamlNode *top=NULL) : YamlNode(SCALAR, top), str_(s) {}
+        ScalarNode(bool b, YamlNode *top=NULL) : YamlNode(SCALAR, top), str_(b ? "true" : "false") {}
 
-        const std::string &getValue() {
-            return str;
+        const std::string &getValue() const {
+            return str_;
         }
 
         void setValue(const std::string &s) {
-            str = s;
+            str_ = s;
         }
 
         virtual void deleteChildNodes() {}
 
     private:
-        std::string str;
+        std::string str_;
 };
 
 }
diff --git a/daemon/src/config/yamlparser.cpp b/daemon/src/config/yamlparser.cpp
index 9a452a165e174abe2a6e7ac7a9ecc0f11693d9f2..059a28eaf28db76723b8cdb9b6161d8ace28377e 100644
--- a/daemon/src/config/yamlparser.cpp
+++ b/daemon/src/config/yamlparser.cpp
@@ -394,7 +394,7 @@ void YamlParser::constructNativeData()
 
 void YamlParser::mainNativeDataMapping(MappingNode *map)
 {
-	Mapping *mapping = map->getMapping();
+    std::map<std::string, YamlNode*> *mapping = map->getMapping();
 
 	accountSequence_    = (SequenceNode*)(*mapping)["accounts"];
     addressbookNode_    = (MappingNode*)(*mapping)["addressbook"];
diff --git a/daemon/src/dbus/Makefile.am b/daemon/src/dbus/Makefile.am
index b48b36b5fbcac4b2578235d8cb8c702838e3ce2c..e2027e0e9d5dbeefd665bf1780716f136c482cd5 100644
--- a/daemon/src/dbus/Makefile.am
+++ b/daemon/src/dbus/Makefile.am
@@ -39,6 +39,7 @@ libdbus_la_CXXFLAGS = \
             -DPROGSHAREDIR=\"${datadir}/sflphone\" \
             $(NETWORKMANAGER)
 
+
 noinst_HEADERS =            \
     callmanager.h           \
     configurationmanager.h  \
diff --git a/daemon/src/dbus/callmanager.cpp b/daemon/src/dbus/callmanager.cpp
index cd3d0d58def75b26c958e396c48a1e1bd2176647..c9b0923b130934b9b7a75f1bf9d5a0e394ecd7bc 100644
--- a/daemon/src/dbus/callmanager.cpp
+++ b/daemon/src/dbus/callmanager.cpp
@@ -39,6 +39,7 @@
 #include "audio/audiortp/audio_rtp_factory.h"
 #include "audio/audiortp/audio_zrtp_session.h"
 
+#include "logger.h"
 #include "manager.h"
 
 namespace {
diff --git a/daemon/src/dbus/configurationmanager.cpp b/daemon/src/dbus/configurationmanager.cpp
index a991393b0a0c3299b3a616c8b1caf65b7f1f221a..98e7494253810df5f1ce1948c09e9b67beb45d3d 100644
--- a/daemon/src/dbus/configurationmanager.cpp
+++ b/daemon/src/dbus/configurationmanager.cpp
@@ -30,15 +30,17 @@
  *  as that of the covered work.
  */
 
+#ifdef HAVE_CONFIG_H
 #include "config.h"
+#endif
 
 #include "configurationmanager.h"
 #include <sstream>
-#include "config.h"
 #include "../manager.h"
 #include "sip/sipvoiplink.h"
 #include "sip/siptransport.h"
 #include "account.h"
+#include "logger.h"
 #include "sip/sipaccount.h"
 
 namespace {
@@ -55,12 +57,12 @@ std::map<std::string, std::string> ConfigurationManager::getIp2IpDetails()
     SIPAccount *sipaccount = Manager::instance().getIP2IPAccount();
 
     if (!sipaccount) {
-        ERROR("ConfigurationManager: could not find account");
+        ERROR("ConfigurationManager: could not find IP2IP account");
         return ip2ipAccountDetails;
     } else
         return sipaccount->getIp2IpDetails();
 
-    std::map<std::string, std::string> tlsSettings = getTlsSettings();
+    std::map<std::string, std::string> tlsSettings(getTlsSettings());
     std::copy(tlsSettings.begin(), tlsSettings.end(),
               std::inserter(ip2ipAccountDetails, ip2ipAccountDetails.end()));
 
@@ -438,23 +440,19 @@ void ConfigurationManager::setShortcuts(
 std::vector<std::map<std::string, std::string> > ConfigurationManager::getCredentials(
     const std::string& accountID)
 {
-    Account *account = Manager::instance().getAccount(accountID);
+    SIPAccount *account = dynamic_cast<SIPAccount*>(Manager::instance().getAccount(accountID));
     std::vector<std::map<std::string, std::string> > credentialInformation;
 
-    if (!account or account->getType() != "SIP")
+    if (!account)
         return credentialInformation;
-
-    SIPAccount *sipaccount = static_cast<SIPAccount *>(account);
-    return sipaccount->getCredentials();
+    else
+        return account->getCredentials();
 }
 
 void ConfigurationManager::setCredentials(const std::string& accountID,
         const std::vector<std::map<std::string, std::string> >& details)
 {
-    Account *account = Manager::instance().getAccount(accountID);
-
-    if (account and account->getType() == "SIP") {
-        SIPAccount *sipaccount = static_cast<SIPAccount*>(account);
-        sipaccount->setCredentials(details);
-    }
+    SIPAccount *account = dynamic_cast<SIPAccount*>(Manager::instance().getAccount(accountID));
+    if (account)
+        account->setCredentials(details);
 }
diff --git a/daemon/src/dbus/dbusmanager.cpp b/daemon/src/dbus/dbusmanager.cpp
index f05824885a3b64d2edb89e60ce24cfd9258afcf8..600deb6d9c5c5fd372c0363bc256b567d2f9db01 100644
--- a/daemon/src/dbus/dbusmanager.cpp
+++ b/daemon/src/dbus/dbusmanager.cpp
@@ -32,6 +32,7 @@
 #include "dbusmanager.h"
 #include "global.h"
 #include "manager.h"
+#include "logger.h"
 #include "instance.h"
 
 #include "callmanager.h"
@@ -57,7 +58,7 @@ DBusManager::DBusManager() : callManager_(0)
         DBus::_init_threading();
         DBus::default_dispatcher = &dispatcher_;
 
-        DBus::Connection sessionConnection = DBus::Connection::SessionBus();
+        DBus::Connection sessionConnection(DBus::Connection::SessionBus());
         sessionConnection.request_name("org.sflphone.SFLphone");
 
         callManager_ = new CallManager(sessionConnection);
@@ -69,7 +70,7 @@ DBusManager::DBusManager() : callManager_(0)
 #endif
 
 #ifdef USE_NETWORKMANAGER
-        DBus::Connection systemConnection = DBus::Connection::SystemBus();
+        DBus::Connection systemConnection(DBus::Connection::SystemBus());
         networkManager_ = new NetworkManager(systemConnection, "/org/freedesktop/NetworkManager", "");
 #endif
 
@@ -100,7 +101,7 @@ void DBusManager::exec()
         ERROR("%s: %s, exiting\n", err.name(), err.what());
         ::exit(EXIT_FAILURE);
     } catch (const std::exception &err) {
-        ERROR("%s: %s, exiting\n", err.what());
+        ERROR("%s: exiting\n", err.what());
         ::exit(EXIT_FAILURE);
     }
 }
@@ -113,7 +114,7 @@ void DBusManager::exit()
         ERROR("%s: %s, exiting\n", err.name(), err.what());
         ::exit(EXIT_FAILURE);
     } catch (const std::exception &err) {
-        ERROR("%s: %s, exiting\n", err.what());
+        ERROR("%s: exiting\n", err.what());
         ::exit(EXIT_FAILURE);
     }
 }
diff --git a/daemon/src/dbus/networkmanager.cpp b/daemon/src/dbus/networkmanager.cpp
index ece8cc0115949062be6f7b75586bc2ef09a84c87..3bbc15d0043b449f4b2f62c3206beb481b8ac40c 100644
--- a/daemon/src/dbus/networkmanager.cpp
+++ b/daemon/src/dbus/networkmanager.cpp
@@ -30,19 +30,23 @@
 
 #include "networkmanager.h"
 #include "../manager.h"
+#include "array_size.h"
+#include "logger.h"
 
-const std::string NetworkManager::statesString[5] = {"unknown", "asleep",
-                                                     "connecting", "connected",
-                                                     "disconnected"};
+namespace {
+    const char *stateAsString(uint32_t state)
+    {
+        static const char * STATES[] = {"unknown", "asleep", "connecting",
+            "connected", "disconnected"};
 
-std::string NetworkManager::stateAsString(const uint32_t &state)
-{
-    return statesString[state];
+        const size_t idx = state < ARRAYSIZE(STATES) ? state : 0;
+        return STATES[idx];
+    }
 }
 
 void NetworkManager::StateChanged(const uint32_t &state)
 {
-    WARN("Network state changed: %s", stateAsString(state).c_str());
+    WARN("Network state changed: %s", stateAsString(state));
 }
 
 void NetworkManager::PropertiesChanged(const std::map<std::string, ::DBus::Variant> &argin0)
diff --git a/daemon/src/dbus/networkmanager.h b/daemon/src/dbus/networkmanager.h
index 0f005d9ef469fb2fdbd96ad3998fd86ca5781c16..252ec739a46be807b4b0d80a729bcba48a0808b9 100644
--- a/daemon/src/dbus/networkmanager.h
+++ b/daemon/src/dbus/networkmanager.h
@@ -45,7 +45,6 @@ class NetworkManager : public org::freedesktop::NetworkManager_proxy,
         NetworkManager(DBus::Connection &, const DBus::Path &, const char*);
         void StateChanged(const uint32_t &state);
         void PropertiesChanged(const std::map<std::string, ::DBus::Variant> &argin0);
-        std::string stateAsString(const uint32_t &state);
 
     private:
         enum NMState {
@@ -55,8 +54,6 @@ class NetworkManager : public org::freedesktop::NetworkManager_proxy,
             NM_STATE_CONNECTED,
             NM_STATE_DISCONNECTED
         };
-
-        static const std::string statesString[5];
 };
 #endif
 
diff --git a/daemon/src/dbus/video_controls.cpp b/daemon/src/dbus/video_controls.cpp
index 8e01ef9d1367f0a057491cef948eef6df89f0b45..bcf20ceb6bbf6970067763779bbf2ee8f60853e0 100644
--- a/daemon/src/dbus/video_controls.cpp
+++ b/daemon/src/dbus/video_controls.cpp
@@ -35,6 +35,7 @@
 #include "video/video_endpoint.h"
 #include "video/video_preview.h"
 #include "account.h"
+#include "logger.h"
 #include "manager.h"
 
 namespace {
diff --git a/daemon/src/eventthread.cpp b/daemon/src/eventthread.cpp
index f4e76bbd9b4e98c135fcbab401cc685e779f8440..36fbd7be5cf279315a8127b6dd5b2d6ff90fa40a 100644
--- a/daemon/src/eventthread.cpp
+++ b/daemon/src/eventthread.cpp
@@ -31,18 +31,13 @@
 #include "eventthread.h"
 #include "voiplink.h"
 
-EventThread::EventThread(VoIPLink *link) : Thread(), link_(link)
-{
-    setCancel(cancelDeferred);
-}
-
-EventThread::~EventThread() {
-    ost::Thread::terminate();
-}
+EventThread::EventThread(VoIPLink *link) : ost::Thread(), link_(link)
+{}
 
 void EventThread::run()
 {
-    while (!testCancel())
-        link_->getEvent();
+    while (link_->getEvent())
+        ;  // noop
+    ost::Thread::exit();
 }
 
diff --git a/daemon/src/eventthread.h b/daemon/src/eventthread.h
index 8d1b20e5ddb26fd6c84b81af1bcae6034d1bb895..af3aee58efb191202860f86bbe79fe7f3d4a2cb8 100644
--- a/daemon/src/eventthread.h
+++ b/daemon/src/eventthread.h
@@ -31,7 +31,7 @@
 #ifndef EVENT_THREAD_H_
 #define EVENT_THREAD_H_
 
-#include <cc++/thread.h>
+#include "cc_thread.h"
 #include "noncopyable.h"
 
 class VoIPLink;
@@ -44,8 +44,7 @@ class VoIPLink;
 class EventThread : public ost::Thread {
     public:
         EventThread(VoIPLink* link);
-        ~EventThread();
-        virtual void run();
+        void run();
 
     private:
         NON_COPYABLE(EventThread);
diff --git a/daemon/src/fileutils.cpp b/daemon/src/fileutils.cpp
index 744d002fb99c47c17e81cebe93c433aa4fb20d22..7a7240abd2c8cce14e1fd14a95f15d872f11762f 100644
--- a/daemon/src/fileutils.cpp
+++ b/daemon/src/fileutils.cpp
@@ -31,18 +31,21 @@
 #include <libgen.h>
 #include <dirent.h>
 #include <sys/stat.h>
-#include <cstdio>
+#include <fstream>
 #include <cstdlib>
 #include <signal.h>
-#include "global.h"
+#include <string>
+#include <sstream>
+#include <iostream>
+#include "fileutils.h"
 
-namespace {
+namespace fileutils {
 // returns true if directory exists
 bool check_dir(const char *path)
 {
     DIR *dir = opendir(path);
 
-    if (!dir) {	// doesn't exist
+    if (!dir) { // doesn't exist
         if (mkdir(path, 0755) != 0) {   // couldn't create the dir
             perror(path);
             return false;
@@ -52,9 +55,7 @@ bool check_dir(const char *path)
 
     return true;
 }
-}
 
-namespace fileutils {
 static char *program_dir = NULL;
 
 void set_program_dir(char *program_path)
@@ -81,38 +82,30 @@ bool create_pidfile()
         return false;
 
     std::string pidfile = path + "/" PIDFILE;
-    FILE *fp = fopen(pidfile.c_str(),"r");
+    std::ifstream is(pidfile.c_str());
 
-    if (fp) {
+    if (is) {
         // PID file exists. Check if the former process is still alive or
         // not. If alive, give user a hint.
         int oldPid;
-
-        if (fscanf(fp, "%d", &oldPid) != 1) {
-            ERROR("Couldn't read pidfile %s", pidfile.c_str());
-            return false;
-        }
-
-        fclose(fp);
+        is >> oldPid;
 
         if (kill(oldPid, 0) == 0) {
-            ERROR("There is already a sflphoned daemon running in the system. Starting Failed.");
+            // Use cerr because logging has not been initialized
+            std::cerr << "There is already a sflphoned daemon running in " <<
+                "the system. Starting Failed." << std::endl;
             return false;
         }
     }
 
     // write pid file
-    fp = fopen(pidfile.c_str(),"w");
+    std::ofstream os(pidfile.c_str());
 
-    if (!fp) {
+    if (!os) {
         perror(pidfile.c_str());
         return false;
     } else {
-        std::ostringstream pidstr;
-        pidstr << getpid();
-
-        fputs(pidstr.str().c_str(), fp);
-        fclose(fp);
+        os << getpid();
     }
 
     return true;
diff --git a/daemon/src/fileutils.h b/daemon/src/fileutils.h
index 8f8a7b66b104db06f44f8d536197f04738c6c38d..c513daed12d902efc88f53e81fa67ad865fe7c63 100644
--- a/daemon/src/fileutils.h
+++ b/daemon/src/fileutils.h
@@ -28,13 +28,24 @@
  *  as that of the covered work.
  */
 
-#ifndef __FILEUTILS_H__
-#define __FILEUTILS_H__
+#ifndef FILEUTILS_H_
+#define FILEUTILS_H_
+
+#define HOMEDIR					(getenv ("HOME"))				/** Home directory */
+#define XDG_DATA_HOME			(getenv ("XDG_DATA_HOME"))
+#define XDG_CONFIG_HOME			(getenv ("XDG_CONFIG_HOME"))
+#define XDG_CACHE_HOME			(getenv ("XDG_CACHE_HOME"))
+#define PIDFILE "sfl.pid"
+
+
+#define DIR_SEPARATOR_STR "/"   // Directory separator char
+#define DIR_SEPARATOR_CH = '/'  // Directory separator string
 
 namespace fileutils {
+    bool check_dir(const char *path);
     void set_program_dir(char *program_path);
     const char *get_program_dir();
     bool create_pidfile();
 }
 
-#endif	// __FILEUTILS_H__
+#endif	// FILEUTILS_H_
diff --git a/daemon/src/global.h b/daemon/src/global.h
index 7cdcf37e8e319432e4e5992163fb23da651c42c9..fd766c1a2448837b9d89b6bc2be473377a68a5c6 100644
--- a/daemon/src/global.h
+++ b/daemon/src/global.h
@@ -33,33 +33,18 @@
 #ifndef __GLOBAL_H__
 #define __GLOBAL_H__
 
-#include <stdio.h>
+#include <cstdio>
 #include <libintl.h>
 #include <locale.h>
 #include <string>
-#include <stdlib.h>
+#include <cstdlib>
 #include <sstream>
 #include <map>
 #include <vector>
-#include "logger.h"
 
-#define HOMEDIR					(getenv ("HOME"))				/** Home directory */
-#define XDG_DATA_HOME			(getenv ("XDG_DATA_HOME"))
-#define XDG_CONFIG_HOME			(getenv ("XDG_CONFIG_HOME"))
-#define XDG_CACHE_HOME			(getenv ("XDG_CACHE_HOME"))
 const char * const ZRTP_ZID_FILENAME = "sfl.zid";
 
-//useful typedefs.
-typedef signed short SINT16;
-typedef signed int SINT32;
-
-#define PIDFILE "sfl.pid"
-
-typedef short SFLDataFormat;
-
-#define SIZEBUF 		 400000 /** About 12 sec of buffering at 8000 Hz*/
-
-#define ALSA_DFT_CARD_ID     0			/** Index of the default soundcard */
+#define ALSA_DFT_CARD_ID 0          /** Index of the default soundcard */
 
 #define PCM_PLUGHW	"plughw"		/** Alsa plugin */
 #define PCM_DEFAULT	"default"		/** Default ALSA plugin */
@@ -121,7 +106,4 @@ enum {
 /** The struct to reflect the order the user wants to use the codecs */
 typedef std::vector<int> CodecOrder;
 
-#define DIR_SEPARATOR_STR "/" // Directory separator char
-#define DIR_SEPARATOR_CH = '/' /** Directory separator string */
-
 #endif	// __GLOBAL_H__
diff --git a/daemon/src/history/history.cpp b/daemon/src/history/history.cpp
index 423825fa70fa952b81d7676437338bdd10c649ed..42284b99fa755bbc75c42b57cfdf6ca8aedfa570 100644
--- a/daemon/src/history/history.cpp
+++ b/daemon/src/history/history.cpp
@@ -36,7 +36,7 @@
 #include <fstream>
 #include <sys/stat.h> // for mkdir
 #include <ctime>
-#include "global.h"
+#include "fileutils.h"
 #include "logger.h"
 #include "call.h"
 
diff --git a/daemon/src/iax/iaxaccount.cpp b/daemon/src/iax/iaxaccount.cpp
index 98d9c7fcb4a7d11bbc714edf1f774dc8af308c23..5fbc1dc913942a1094af99d054b06ed2ca0a4989 100644
--- a/daemon/src/iax/iaxaccount.cpp
+++ b/daemon/src/iax/iaxaccount.cpp
@@ -31,32 +31,23 @@
  *  as that of the covered work.
  */
 
+#ifdef HAVE_CONFIG_H
 #include "config.h"
+#endif
 
 #include "iaxaccount.h"
 #include "iaxvoiplink.h"
+#include "logger.h"
 #include "manager.h"
 #include "config/yamlnode.h"
 #include "config/yamlemitter.h"
 
 IAXAccount::IAXAccount(const std::string& accountID)
-    : Account(accountID, "iax2"), password_(),
-    link_(new IAXVoIPLink(accountID))
+    : Account(accountID, "iax2"), password_(), link_(accountID)
 {}
 
-
-IAXAccount::~IAXAccount()
-{
-    delete link_;
-}
-
-void IAXAccount::serialize(Conf::YamlEmitter *emitter)
+void IAXAccount::serialize(Conf::YamlEmitter &emitter)
 {
-    if (emitter == NULL) {
-        ERROR("IAXAccount: Error: emitter is NULL in serialize");
-        return;
-    }
-
     Conf::MappingNode accountmap(NULL);
 
     Conf::ScalarNode id(accountID_);
@@ -71,44 +62,39 @@ void IAXAccount::serialize(Conf::YamlEmitter *emitter)
     Conf::ScalarNode codecs(codecStr_);
     Conf::ScalarNode displayName(displayName_);
 
-    accountmap.setKeyValue(aliasKey, &alias);
-    accountmap.setKeyValue(typeKey, &type);
-    accountmap.setKeyValue(idKey, &id);
-    accountmap.setKeyValue(usernameKey, &username);
-    accountmap.setKeyValue(passwordKey, &password);
-    accountmap.setKeyValue(hostnameKey, &hostname);
-    accountmap.setKeyValue(accountEnableKey, &enable);
-    accountmap.setKeyValue(mailboxKey, &mailbox);
+    accountmap.setKeyValue(ALIAS_KEY, &alias);
+    accountmap.setKeyValue(TYPE_KEY, &type);
+    accountmap.setKeyValue(ID_KEY, &id);
+    accountmap.setKeyValue(USERNAME_KEY, &username);
+    accountmap.setKeyValue(PASSWORD_KEY, &password);
+    accountmap.setKeyValue(HOSTNAME_KEY, &hostname);
+    accountmap.setKeyValue(ACCOUNT_ENABLE_KEY, &enable);
+    accountmap.setKeyValue(MAILBOX_KEY, &mailbox);
 
-    accountmap.setKeyValue(displayNameKey, &displayName);
-    accountmap.setKeyValue(codecsKey, &codecs);
+    accountmap.setKeyValue(DISPLAY_NAME_KEY, &displayName);
+    accountmap.setKeyValue(CODECS_KEY, &codecs);
 
     try {
-        emitter->serializeAccount(&accountmap);
+        emitter.serializeAccount(&accountmap);
     } catch (const Conf::YamlEmitterException &e) {
         ERROR("ConfigTree: %s", e.what());
     }
 }
 
-void IAXAccount::unserialize(const Conf::MappingNode *map)
+void IAXAccount::unserialize(const Conf::MappingNode &map)
 {
-    if (map == NULL) {
-        ERROR("IAXAccount: Error: Map is NULL in unserialize");
-        return;
-    }
-
-    map->getValue(aliasKey, &alias_);
-    map->getValue(typeKey,  &type_);
-    map->getValue(usernameKey, &username_);
-    map->getValue(passwordKey, &password_);
-    map->getValue(hostnameKey, &hostname_);
-    map->getValue(accountEnableKey, &enabled_);
-    map->getValue(mailboxKey, &mailBox_);
-    map->getValue(codecsKey, &codecStr_);
+    map.getValue(ALIAS_KEY, &alias_);
+    map.getValue(TYPE_KEY,  &type_);
+    map.getValue(USERNAME_KEY, &username_);
+    map.getValue(PASSWORD_KEY, &password_);
+    map.getValue(HOSTNAME_KEY, &hostname_);
+    map.getValue(ACCOUNT_ENABLE_KEY, &enabled_);
+    map.getValue(MAILBOX_KEY, &mailBox_);
+    map.getValue(CODECS_KEY, &codecStr_);
 
     // Update codec list which one is used for SDP offer
     setActiveCodecs(ManagerImpl::unserialize(codecStr_));
-    map->getValue(displayNameKey, &displayName_);
+    map.getValue(DISPLAY_NAME_KEY, &displayName_);
 }
 
 void IAXAccount::setAccountDetails(std::map<std::string, std::string> details)
@@ -149,8 +135,8 @@ std::map<std::string, std::string> IAXAccount::getAccountDetails() const
 void IAXAccount::registerVoIPLink()
 {
     try {
-        link_->init();
-        link_->sendRegister(this);
+        link_.init();
+        link_.sendRegister(this);
     } catch (const VoipLinkException &e) {
         ERROR("IAXAccount: %s", e.what());
     }
@@ -160,8 +146,8 @@ void
 IAXAccount::unregisterVoIPLink()
 {
     try {
-        link_->sendUnregister(this);
-        link_->terminate();
+        link_.sendUnregister(this);
+        link_.terminate();
     } catch (const VoipLinkException &e) {
         ERROR("IAXAccount: %s", e.what());
     }
@@ -178,5 +164,5 @@ IAXAccount::loadConfig()
 
 VoIPLink* IAXAccount::getVoIPLink()
 {
-    return link_;
+    return &link_;
 }
diff --git a/daemon/src/iax/iaxaccount.h b/daemon/src/iax/iaxaccount.h
index 32a9c20aed30cba5f54192e6c6e5b509fbcb2731..35871972bb7051b5f26ebc04a99d7b99f55dce26 100644
--- a/daemon/src/iax/iaxaccount.h
+++ b/daemon/src/iax/iaxaccount.h
@@ -32,9 +32,7 @@
 #define IAXACCOUNT_H
 
 #include "account.h"
-#include "noncopyable.h"
-
-class IAXVoIPLink;
+#include "iaxvoiplink.h"
 
 /**
  * @file: iaxaccount.h
@@ -43,10 +41,9 @@ class IAXVoIPLink;
 class IAXAccount : public Account {
     public:
         IAXAccount(const std::string& accountID);
-        ~IAXAccount();
 
-        virtual void serialize(Conf::YamlEmitter *emitter);
-        virtual void unserialize(const Conf::MappingNode *map);
+        virtual void serialize(Conf::YamlEmitter &emitter);
+        virtual void unserialize(const Conf::MappingNode &map);
 
         void setAccountDetails(std::map<std::string, std::string> details);
 
@@ -66,10 +63,9 @@ class IAXAccount : public Account {
         }
 
     private:
-        NON_COPYABLE(IAXAccount);
          // Account login information: password
         std::string password_;
-        IAXVoIPLink *link_;
+        IAXVoIPLink link_;
         virtual VoIPLink* getVoIPLink();
 };
 
diff --git a/daemon/src/iax/iaxcall.cpp b/daemon/src/iax/iaxcall.cpp
index 29549425d2c778189c3be9dce3369d238eb8c7d1..635735490fe7c8044a2109ee108c9b0399a31f09 100644
--- a/daemon/src/iax/iaxcall.cpp
+++ b/daemon/src/iax/iaxcall.cpp
@@ -34,6 +34,7 @@
 #include <iax-client.h>
 #include "iaxcall.h"
 #include "iax2/frame.h"
+#include "logger.h"
 #include "account.h"
 #include "manager.h"
 
diff --git a/daemon/src/iax/iaxvoiplink.cpp b/daemon/src/iax/iaxvoiplink.cpp
index 9748d59df88bd745f42add175226fe42a90d0b0e..d8d2caa7b3108e547a4e3d4bd486d813c562b038 100644
--- a/daemon/src/iax/iaxvoiplink.cpp
+++ b/daemon/src/iax/iaxvoiplink.cpp
@@ -33,6 +33,7 @@
 #include "eventthread.h"
 #include "im/instant_messaging.h"
 #include "iaxaccount.h"
+#include "logger.h"
 #include "manager.h"
 #include "hooks/urlhook.h"
 #include "audio/audiolayer.h"
@@ -42,13 +43,16 @@
 #include <dlfcn.h>
 
 IAXVoIPLink::IAXVoIPLink(const std::string& accountID) :
-    evThread_(new EventThread(this))
-    , regSession_(NULL)
+    regSession_(NULL)
     , nextRefreshStamp_(0)
     , mutexIAX_()
+    , decData_()
+    , resampledData_()
+    , encodedData_()
     , converter_(44100)
     , initDone_(false)
     , accountID_(accountID)
+    , evThread_(this)
 {
     srand(time(NULL));    // to get random number for RANDOM_PORT
 }
@@ -56,8 +60,7 @@ IAXVoIPLink::IAXVoIPLink(const std::string& accountID) :
 
 IAXVoIPLink::~IAXVoIPLink()
 {
-    delete evThread_;
-
+    handlingEvents_ = false;
     regSession_ = NULL; // shall not delete it // XXX: but why?
     terminate();
 }
@@ -70,7 +73,8 @@ IAXVoIPLink::init()
 
     for (int port = IAX_DEFAULT_PORTNO, nbTry = 0; nbTry < 3 ; port = rand() % 64000 + 1024, nbTry++) {
         if (iax_init(port) >= 0) {
-            evThread_->start();
+            handlingEvents_ = true;
+            evThread_.start();
             initDone_ = true;
             break;
         }
@@ -100,13 +104,14 @@ IAXVoIPLink::terminate()
     initDone_ = false;
 }
 
-void
+bool
 IAXVoIPLink::getEvent()
 {
     mutexIAX_.enter();
     iax_event *event;
 
     while ((event = iax_get_event(0)) != NULL) {
+
         // If we received an 'ACK', libiax2 tells apps to ignore them.
         if (event->etype == IAX_EVENT_NULL) {
             iax_event_free(event);
@@ -115,10 +120,12 @@ IAXVoIPLink::getEvent()
 
         IAXCall *call = iaxFindCallBySession(event->session);
 
-        if (call)
+        if (call) {
             iaxHandleCallEvent(event, call);
-        else if (event->session && event->session == regSession_)
+        }
+        else if (event->session && event->session == regSession_) {
             iaxHandleRegReply(event);   // This is a registration session, deal with it
+        }
         else // We've got an event before it's associated with any call
             iaxHandlePrecallEvent(event);
 
@@ -133,7 +140,8 @@ IAXVoIPLink::getEvent()
     sendAudioFromMic();
 
     // thread wait 3 millisecond
-    evThread_->sleep(3);
+    ost::Thread::sleep(3);
+    return handlingEvents_;
 }
 
 void
@@ -163,7 +171,7 @@ IAXVoIPLink::sendAudioFromMic()
             continue;
 
         // Get bytes from micRingBuffer to data_from_mic
-        int bytes = Manager::instance().getMainBuffer()->getData(decData, bytesNeeded, currentCall->getCallId());
+        int bytes = Manager::instance().getMainBuffer()->getData(decData_, bytesNeeded, currentCall->getCallId());
         int samples = bytes / sizeof(SFLDataFormat);
 
         int compSize;
@@ -172,20 +180,20 @@ IAXVoIPLink::sendAudioFromMic()
         SFLDataFormat *in;
 
         if (audioRate != mainBufferSampleRate) {
-            converter_.resample(decData, resampledData, audioRate, mainBufferSampleRate, samples);
-            in = resampledData;
+            converter_.resample(decData_, resampledData_, audioRate, mainBufferSampleRate, samples);
+            in = resampledData_;
             outSamples = 0;
         } else {
             outSamples = samples;
-            in = decData;
+            in = decData_;
         }
 
-        compSize = audioCodec->encode(encodedData, in, DEC_BUFFER_SIZE);
+        compSize = audioCodec->encode(encodedData_, in, DEC_BUFFER_SIZE);
 
         if (currentCall->session and bytes > 0) {
             ost::MutexLock m(mutexIAX_);
 
-            if (iax_send_voice(currentCall->session, currentCall->format, encodedData, compSize, outSamples) == -1)
+            if (iax_send_voice(currentCall->session, currentCall->format, encodedData_, compSize, outSamples) == -1)
                 ERROR("IAX: Error sending voice data.");
         }
     }
@@ -201,6 +209,8 @@ IAXVoIPLink::getIAXCall(const std::string& id)
 void
 IAXVoIPLink::sendRegister(Account *a)
 {
+    DEBUG("Send register");
+
     IAXAccount *account = dynamic_cast<IAXAccount*>(a);
 
     if (account->getHostname().empty())
@@ -566,15 +576,15 @@ void IAXVoIPLink::iaxHandleVoiceEvent(iax_event* event, IAXCall* call)
     if (size > max)
         size = max;
 
-    int samples = audioCodec->decode(decData, data , size);
+    int samples = audioCodec->decode(decData_, data , size);
     int outSize = samples * sizeof(SFLDataFormat);
-    SFLDataFormat *out = decData;
+    SFLDataFormat *out = decData_;
     unsigned int audioRate = audioCodec->getClockRate();
 
     if (audioRate != mainBufferSampleRate) {
         outSize = (double)outSize * (mainBufferSampleRate / audioRate);
-        converter_.resample(decData, resampledData, mainBufferSampleRate, audioRate, samples);
-        out = resampledData;
+        converter_.resample(decData_, resampledData_, mainBufferSampleRate, audioRate, samples);
+        out = resampledData_;
     }
 
     Manager::instance().getMainBuffer()->putData(out, outSize, call->getCallId());
@@ -622,7 +632,7 @@ void IAXVoIPLink::iaxHandlePrecallEvent(iax_event* event)
 
             // if peerNumber exist append it to the name string
             call->initRecFilename(std::string(event->ies.calling_number));
-            Manager::instance().incomingCall(call, accountID_);
+            Manager::instance().incomingCall(*call, accountID_);
 
             format = call->getFirstMatchingFormat(event->ies.format, accountID_);
 
diff --git a/daemon/src/iax/iaxvoiplink.h b/daemon/src/iax/iaxvoiplink.h
index 228ae39ba4ee49d9116ed6a647081dc14e7de531..c848043d233d4272d8d6e78269bd032dbeb45ad3 100644
--- a/daemon/src/iax/iaxvoiplink.h
+++ b/daemon/src/iax/iaxvoiplink.h
@@ -37,20 +37,20 @@
 #endif
 
 #include "voiplink.h"
-#include <iax-client.h>
 #include "audio/codecs/audiocodec.h" // for DEC_BUFFER_SIZE
-#include "global.h"
+#include "sfl_types.h"
 #include "noncopyable.h"
 #include "audio/samplerateconverter.h"
+#include "eventthread.h"
+
+#include <iax-client.h>
 
-class EventThread;
 class IAXCall;
+class IAXAccount;
 
 class AudioCodec;
 class AudioLayer;
 
-class IAXAccount;
-
 /**
  * @file iaxvoiplink.h
  * @brief VoIPLink contains a thread that listen to external events
@@ -66,7 +66,7 @@ class IAXVoIPLink : public VoIPLink {
         /**
          *	Listen to events sent by the call manager ( asterisk, etc .. )
          */
-        void getEvent();
+        bool getEvent();
 
         /**
          * Init the voip link
@@ -120,7 +120,7 @@ class IAXVoIPLink : public VoIPLink {
          * Cancel a call
          * @param id The ID of the call
          */
-        virtual void cancel(const std::string& id UNUSED) {}
+        virtual void cancel(const std::string& /*id*/) {}
 
         /**
          * Put a call on hold
@@ -241,9 +241,6 @@ class IAXVoIPLink : public VoIPLink {
          */
         void iaxOutgoingInvite(IAXCall* call);
 
-        /** Threading object */
-        EventThread* evThread_;
-
         /** registration session : 0 if not register */
         iax_session* regSession_;
 
@@ -257,9 +254,9 @@ class IAXVoIPLink : public VoIPLink {
         ost::Mutex mutexIAX_;
 
         /** encoder/decoder/resampler buffers */
-        SFLDataFormat decData[DEC_BUFFER_SIZE];
-        SFLDataFormat resampledData[DEC_BUFFER_SIZE];
-        unsigned char encodedData[DEC_BUFFER_SIZE];
+        SFLDataFormat decData_[DEC_BUFFER_SIZE];
+        SFLDataFormat resampledData_[DEC_BUFFER_SIZE];
+        unsigned char encodedData_[DEC_BUFFER_SIZE];
 
         /** Sample rate converter object */
         SamplerateConverter converter_;
@@ -271,6 +268,11 @@ class IAXVoIPLink : public VoIPLink {
         bool initDone_;
 
         const std::string accountID_;
+
+        /**
+         * Threading object
+         */
+        EventThread evThread_;
 };
 
 #endif
diff --git a/daemon/src/im/instant_messaging.h b/daemon/src/im/instant_messaging.h
index be0a71ce354d117f4db8b9df7762fb6f35af1efe..7e9b0ee20f510369766692db90f2d843dad2ab2c 100644
--- a/daemon/src/im/instant_messaging.h
+++ b/daemon/src/im/instant_messaging.h
@@ -34,15 +34,13 @@
 
 #include <string>
 #include <iostream>
+#include <vector>
 #include <fstream>
 #include <pjsip.h>
 #include <pjlib.h>
 #include <pjsip_ua.h>
 #include <pjlib-util.h>
 
-#include "call.h"
-#include "sip/sipcall.h"
-
 #include <map>
 #include <list>
 #include <stdexcept>
diff --git a/daemon/src/main.cpp b/daemon/src/main.cpp
index bf29e61c34ff6507d6feef9e089733765885724d..bd7df2d020b79d1a8f496c66638edc68ce866a9e 100644
--- a/daemon/src/main.cpp
+++ b/daemon/src/main.cpp
@@ -35,60 +35,111 @@
 #endif
 
 #include <iostream>
-#include <memory> // for auto_ptr
-#include <string>
-#include <cc++/common.h>
+#include <getopt.h>
 #include "fileutils.h"
-
 #include "dbus/dbusmanager.h"
+#include "logger.h"
 #include "manager.h"
 
-ost::CommandOptionNoArg	console(
-    "console", "c", "Log in console (instead of syslog)"
-);
+namespace {
+    void print_title()
+    {
+        std::cout << "SFLphone Daemon " << VERSION <<
+            ", by Savoir-Faire Linux 2004-2012" << std::endl <<
+            "http://www.sflphone.org/" << std::endl;
+    }
 
-ost::CommandOptionNoArg	debug(
-    "debug", "d", "Debug mode (more verbose)"
-);
+    void print_usage()
+    {
+        std::cout << std::endl <<
+        "-c, --console \t- Log in console (instead of syslog)" << std::endl <<
+        "-d, --debug \t- Debug mode (more verbose)" << std::endl <<
+        "-h, --help \t- Print help" << std::endl;
+    }
 
-ost::CommandOptionNoArg	help(
-    "help", "h", "Print help"
-);
+    // Parse command line arguments, setting debug options or printing a help
+    // message accordingly.
+    // returns true if we should quit (i.e. help was printed), false otherwise
+    bool parse_args(int argc, char *argv[])
+    {
+        int consoleFlag = false;
+        int debugFlag = false;
+        int helpFlag = false;
+        int versionFlag = false;
+        static const struct option long_options[] = {
+            /* These options set a flag. */
+            {"debug", no_argument, NULL, 'd'},
+            {"console", no_argument, NULL, 'c'},
+            {"help", no_argument, NULL, 'h'},
+            {"version", no_argument, NULL, 'v'},
+            {0, 0, 0, 0} /* Sentinel */
+        };
 
-int main(int argc, char **argv)
-{
-    fileutils::set_program_dir(argv[0]);
-    // makeCommandOptionParse allocates the object with operator new, so
-    // auto_ptr is fine in this context.
-    // TODO: This should eventually be replaced with std::unique_ptr for C++0x
-    std::auto_ptr<ost::CommandOptionParse> args(ost::makeCommandOptionParse(argc, argv, ""));
+        while (true) {
+            /* getopt_long stores the option index here. */
+            int option_index = 0;
+            int c = getopt_long(argc, argv, "dchv", long_options, &option_index);
 
-    printf("SFLphone Daemon " VERSION ", by Savoir-Faire Linux 2004-2012\n" \
-           "http://www.sflphone.org/\n");
+            /* Detect the end of the options. */
+            if (c == -1)
+                break;
 
-    if (help.numSet) {
-        std::cerr << args->printUsage();
-        return 0;
-    } else if (args->argsHaveError()) {
-        std::cerr << args->printErrors();
-        std::cerr << args->printUsage();
-        return 1;
+            switch (c) {
+                case 'd':
+                    debugFlag = true;
+                    break;
+
+                case 'c':
+                    consoleFlag = true;
+                    break;
+
+                case 'h':
+                case '?':
+                    helpFlag = true;
+                    break;
+
+                case 'v':
+                    versionFlag = true;
+                    break;
+
+                default:
+                    break;
+            }
+        }
+
+        bool quit = false;
+        if (helpFlag) {
+            print_usage();
+            quit = true;
+        } else if (versionFlag) {
+            // We've always print the title/version, so we can just exit
+            quit = true;
+        } else {
+            Logger::setConsoleLog(consoleFlag);
+            Logger::setDebugMode(debugFlag);
+        }
+        return quit;
     }
+}
 
-    Logger::setConsoleLog(console.numSet);
-    Logger::setDebugMode(debug.numSet);
+int main(int argc, char *argv [])
+{
+    fileutils::set_program_dir(argv[0]);
+    print_title();
+    if (parse_args(argc, argv))
+        return 0;
 
     if (!fileutils::create_pidfile())
         return 1;
 
     try {
-        Manager::instance().init();
+        Manager::instance().init("");
     } catch (const std::exception &e) {
         std::cerr << e.what() << std::endl;
         return 1;
     } catch (...) {
-        std::cerr <<  "An unknown exception occured when initializing the " <<
-            "system." << std::endl;
+        std::cerr << "An exception occured when initializing " PACKAGE <<
+            std::endl;
         return 1;
     }
 
diff --git a/daemon/test/ringtonetest.h b/daemon/src/manager.cpp
similarity index 52%
rename from daemon/test/ringtonetest.h
rename to daemon/src/manager.cpp
index 8791629c2b0a20541d9533f87fe3a97c7eeed42f..b09fde7606417d2f2e8d59a30027dbf061d98627 100644
--- a/daemon/test/ringtonetest.h
+++ b/daemon/src/manager.cpp
@@ -1,6 +1,6 @@
 /*
- *  Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc.
- *  Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
+ *  Copyright (C) 2004-2012 Savoir-Faire Linux Inc.
+ *  Author : Tristan Matthews <tristan.matthews@savoirfairelinux.com>
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
@@ -28,47 +28,11 @@
  *  as that of the covered work.
  */
 
-/*
- * @file ringtonetest.cpp
- * @brief       Regroups unitary tests related to the ringtones.
- *              Check if the wave file has been successfully loaded
- */
-
-#ifndef _RINGTONE_TEST_
-#define _RINGTONE_TEST_
-
-// Cppunit import
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/TestCaller.h>
-#include <cppunit/TestCase.h>
-#include <cppunit/TestSuite.h>
-
-#include <assert.h>
-
-// Application import
 #include "manager.h"
-#include "audio/sound/audiofile.h"
-#include "global.h"
-#include "user_cfg.h"
-
-class RingtoneTest: public CppUnit::TestFixture {
-
-        /*
-         * Use cppunit library macros to add unit test the factory
-         */
-        CPPUNIT_TEST_SUITE(RingtoneTest);
-        CPPUNIT_TEST(testLoadWavefile);
-        CPPUNIT_TEST_SUITE_END();
-
-    public:
-        /*
-         * Unit tests related to the audio preferences
-         */
-        void testLoadWavefile();
-
-};
-/* Register our test module */
-CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(RingtoneTest, "RingtoneTest");
-CPPUNIT_TEST_SUITE_REGISTRATION(RingtoneTest);
 
-#endif
+ManagerImpl& Manager::instance()
+{
+    // Meyers singleton
+    static ManagerImpl instance_;
+    return instance_;
+}
diff --git a/daemon/src/manager.h b/daemon/src/manager.h
index 730b4d0b3f7376679745b83ed217119cb1b46a84..50d740679fdddb376934f7ddfcdaa537d8ee7d47 100644
--- a/daemon/src/manager.h
+++ b/daemon/src/manager.h
@@ -29,13 +29,16 @@
  *  as that of the covered work.
  */
 
-#ifndef SFLPHONE_MANAGER_H
-#define SFLPHONE_MANAGER_H
+#ifndef MANAGER_H_
+#define MANAGER_H_
 
-#include "utilspp/singleton.hpp"
+// we could forward declare ManagerImpl BUT anyone who will call instance
+// will need this include.
 #include "managerimpl.h"
 
-typedef utilspp::SingletonHolder<ManagerImpl> Manager;
+namespace Manager {
+    ManagerImpl& instance();
+}
 
-#endif
+#endif // MANAGER_H_
 
diff --git a/daemon/src/managerimpl.cpp b/daemon/src/managerimpl.cpp
index 398d21daae746b94d79a2a2ff0d68faeb4ed6ce9..01f7d85be139c143aa66be37a85eac2f24a52195 100644
--- a/daemon/src/managerimpl.cpp
+++ b/daemon/src/managerimpl.cpp
@@ -36,11 +36,13 @@
 #include "config.h"
 #endif
 
+#include "logger.h"
 #include "managerimpl.h"
 
 #include "account.h"
 #include "dbus/callmanager.h"
 #include "global.h"
+#include "fileutils.h"
 #include "sip/sipaccount.h"
 #include "im/instant_messaging.h"
 #include "iax/iaxaccount.h"
@@ -76,8 +78,8 @@ ManagerImpl::ManagerImpl() :
     preferences(), voipPreferences(), addressbookPreference(),
     hookPreference(),  audioPreference(), shortcutPreferences(),
     hasTriedToRegister_(false), audioCodecFactory(), dbus_(), config_(),
-    currentCallId_(), currentCallMutex_(), audiodriver_(0), dtmfKey_(0),
-    toneMutex_(), telephoneTone_(0), audiofile_(0), audioLayerMutex_(),
+    currentCallId_(), currentCallMutex_(), audiodriver_(0), dtmfKey_(),
+    toneMutex_(), telephoneTone_(), audiofile_(), audioLayerMutex_(),
     waitingCall_(), waitingCallMutex_(), nbIncomingWaitingCall_(0), path_(),
     callAccountMap_(), callAccountMapMutex_(), IPToIPMap_(), accountMap_(),
     mainBuffer_(), conferenceMap_(), history_()
@@ -86,11 +88,7 @@ ManagerImpl::ManagerImpl() :
     srand(time(NULL));
 }
 
-// never call if we use only the singleton...
-ManagerImpl::~ManagerImpl()
-{}
-
-void ManagerImpl::init(std::string config_file)
+void ManagerImpl::init(const std::string &config_file)
 {
     path_ = config_file.empty() ? createConfigFile() : config_file;
     DEBUG("Manager: configuration file path: %s", path_.c_str());
@@ -126,13 +124,15 @@ void ManagerImpl::terminate()
     std::vector<std::string> callList(getCallList());
     DEBUG("Manager: Hangup %zu remaining call", callList.size());
 
-    for (std::vector<std::string>::iterator iter = callList.begin(); iter != callList.end(); ++iter)
+    for (std::vector<std::string>::iterator iter = callList.begin();
+         iter != callList.end(); ++iter)
         hangupCall(*iter);
 
     saveConfig();
 
-    delete SIPVoIPLink::instance();
+    unregisterAllAccounts();
 
+    SIPVoIPLink::destroy();
     // Unload account map AFTER destroying
     // the SIPVoIPLink, the link still needs the accounts for pjsip cleanup
     unloadAccountMap();
@@ -197,14 +197,6 @@ bool ManagerImpl::outgoingCall(const std::string& account_id,
 
     std::string to_cleaned(NumberCleaner::clean(to, prefix));
 
-    static const char * const SIP_SCHEME = "sip:";
-    static const char * const SIPS_SCHEME = "sips:";
-
-    bool IPToIP = to_cleaned.find(SIP_SCHEME) == 0 or
-                  to_cleaned.find(SIPS_SCHEME) == 0;
-
-    setIPToIPForCall(call_id, IPToIP);
-
     // in any cases we have to detach from current communication
     if (hasCurrentCall()) {
         DEBUG("Manager: Has current call (%s) put it onhold", current_call_id.c_str());
@@ -213,32 +205,24 @@ bool ManagerImpl::outgoingCall(const std::string& account_id,
         if (not isConference(current_call_id) and not isConferenceParticipant(current_call_id))
             onHoldCall(current_call_id);
         else if (isConference(current_call_id) and not isConferenceParticipant(call_id))
-            detachParticipant(Call::DEFAULT_ID, current_call_id);
-    }
-
-    if (IPToIP) {
-        DEBUG("Manager: Start IP2IP call");
-
-        /* We need to retrieve the sip voiplink instance */
-        if (SIPVoIPLink::instance()->SIPNewIpToIpCall(call_id, to_cleaned)) {
-            switchCall(call_id);
-            return true;
-        } else
-            callFailure(call_id);
-
-        return false;
+            detachParticipant(MainBuffer::DEFAULT_ID, current_call_id);
     }
 
     DEBUG("Manager: Selecting account %s", account_id.c_str());
 
-    // Is this account exist
+    // fallback using the default sip account if the specied doesn't exist
+    std::string use_account_id = "";
     if (!accountExists(account_id)) {
-        ERROR("Manager: Error: Account doesn't exist in new outgoing call");
-        return false;
+        WARN("Manager: Account does not exist, trying with default SIP account");
+        use_account_id = SIPAccount::IP2IP_PROFILE;
+    }
+    else {
+        use_account_id = account_id;
     }
 
-    if (!associateCallToAccount(call_id, account_id))
-        WARN("Manager: Warning: Could not associate call id %s to account id %s", call_id.c_str(), account_id.c_str());
+    // Is this account exist
+    if (!associateCallToAccount(call_id, use_account_id))
+        WARN("Manager: Warning: Could not associate call id %s to account id %s", call_id.c_str(), use_account_id.c_str());
 
     try {
         Call *call = getAccountLink(account_id)->newOutgoingCall(call_id, to_cleaned);
@@ -286,7 +270,7 @@ bool ManagerImpl::answerCall(const std::string& call_id)
         } else if (isConference(current_call_id) and not isConferenceParticipant(call_id)) {
             // if we are talking to a conference and we are answering an incoming call
             DEBUG("Manager: Detach main participant from conference");
-            detachParticipant(Call::DEFAULT_ID, current_call_id);
+            detachParticipant(MainBuffer::DEFAULT_ID, current_call_id);
         }
     }
 
@@ -472,7 +456,7 @@ void ManagerImpl::offHoldCall(const std::string& callId)
             DEBUG("Manager: Has current call (%s), put on hold", currentCallId.c_str());
             onHoldCall(currentCallId);
         } else if (isConference(currentCallId) and not isConferenceParticipant(callId))
-            detachParticipant(Call::DEFAULT_ID, currentCallId);
+            detachParticipant(MainBuffer::DEFAULT_ID, currentCallId);
     }
 
     bool isRec = false;
@@ -641,7 +625,7 @@ void ManagerImpl::removeConference(const std::string& conference_id)
     // We now need to bind the audio to the remain participant
 
     // Unbind main participant audio from conference
-    getMainBuffer()->unBindAll(Call::DEFAULT_ID);
+    getMainBuffer()->unBindAll(MainBuffer::DEFAULT_ID);
 
     ParticipantSet participants(conf->getParticipantList());
 
@@ -649,7 +633,7 @@ void ManagerImpl::removeConference(const std::string& conference_id)
     ParticipantSet::iterator iter_p = participants.begin();
 
     if (iter_p != participants.end())
-        getMainBuffer()->bindCallID(*iter_p, Call::DEFAULT_ID);
+        getMainBuffer()->bindCallID(*iter_p, MainBuffer::DEFAULT_ID);
 
     // Then remove the conference from the conference map
     if (conferenceMap_.erase(conference_id) == 1)
@@ -762,7 +746,7 @@ void ManagerImpl::addParticipant(const std::string& callId, const std::string& c
     // detach from prior communication and switch to this conference
     if (current_call_id != callId) {
         if (isConference(current_call_id))
-            detachParticipant(Call::DEFAULT_ID, current_call_id);
+            detachParticipant(MainBuffer::DEFAULT_ID, current_call_id);
         else
             onHoldCall(current_call_id);
     }
@@ -808,7 +792,7 @@ void ManagerImpl::addParticipant(const std::string& callId, const std::string& c
             p != participants.end(); ++p)
         getMainBuffer()->flush(*p);
 
-    getMainBuffer()->flush(Call::DEFAULT_ID);
+    getMainBuffer()->flush(MainBuffer::DEFAULT_ID);
 
     // Connect stream
     addStream(callId);
@@ -820,7 +804,7 @@ void ManagerImpl::addMainParticipant(const std::string& conference_id)
         std::string current_call_id(getCurrentCallId());
 
         if (isConference(current_call_id))
-            detachParticipant(Call::DEFAULT_ID, current_call_id);
+            detachParticipant(MainBuffer::DEFAULT_ID, current_call_id);
         else
             onHoldCall(current_call_id);
     }
@@ -837,12 +821,12 @@ void ManagerImpl::addMainParticipant(const std::string& conference_id)
 
         for (ParticipantSet::const_iterator iter_p = participants.begin();
                 iter_p != participants.end(); ++iter_p) {
-            getMainBuffer()->bindCallID(*iter_p, Call::DEFAULT_ID);
+            getMainBuffer()->bindCallID(*iter_p, MainBuffer::DEFAULT_ID);
             // Reset ringbuffer's readpointers
             getMainBuffer()->flush(*iter_p);
         }
 
-        getMainBuffer()->flush(Call::DEFAULT_ID);
+        getMainBuffer()->flush(MainBuffer::DEFAULT_ID);
 
         if (conf->getState() == Conference::ACTIVE_DETACHED)
             conf->setState(Conference::ACTIVE_ATTACHED);
@@ -872,7 +856,7 @@ void ManagerImpl::joinParticipant(const std::string& callId1, const std::string&
     if ((current_call_id != callId1) and (current_call_id != callId2)) {
         // If currently in a conference
         if (isConference(current_call_id))
-            detachParticipant(Call::DEFAULT_ID, current_call_id);
+            detachParticipant(MainBuffer::DEFAULT_ID, current_call_id);
         else
             onHoldCall(current_call_id); // currently in a call
     }
@@ -1018,7 +1002,7 @@ void ManagerImpl::detachParticipant(const std::string& call_id,
            current_id.c_str());
     std::string current_call_id(getCurrentCallId());
 
-    if (call_id != Call::DEFAULT_ID) {
+    if (call_id != MainBuffer::DEFAULT_ID) {
         std::string currentAccountId(getAccountFromCall(call_id));
         Call *call = getAccountLink(currentAccountId)->getCall(call_id);
 
@@ -1058,7 +1042,7 @@ void ManagerImpl::detachParticipant(const std::string& call_id,
         dbus_.getCallManager()->conferenceChanged(conf->getConfID(), conf->getStateStr());
     } else {
         DEBUG("Manager: Unbind main participant from conference %d");
-        getMainBuffer()->unBindAll(Call::DEFAULT_ID);
+        getMainBuffer()->unBindAll(MainBuffer::DEFAULT_ID);
 
         if (not isConference(current_call_id)) {
             ERROR("Manager: Warning: Current call id (%s) is not a conference", current_call_id.c_str());
@@ -1126,7 +1110,7 @@ void ManagerImpl::processRemainingParticipants(const std::string &current_call_i
              p != participants.end(); ++p)
             getMainBuffer()->flush(*p);
 
-        getMainBuffer()->flush(Call::DEFAULT_ID);
+        getMainBuffer()->flush(MainBuffer::DEFAULT_ID);
     } else if (n == 1) {
         ParticipantSet::iterator p = participants.begin();
 
@@ -1207,14 +1191,14 @@ void ManagerImpl::addStream(const std::string& call_id)
                     iter_p != participants.end(); ++iter_p)
                 getMainBuffer()->flush(*iter_p);
 
-            getMainBuffer()->flush(Call::DEFAULT_ID);
+            getMainBuffer()->flush(MainBuffer::DEFAULT_ID);
         }
 
     } else {
         DEBUG("Manager: Add stream to call");
 
         // bind to main
-        getMainBuffer()->bindCallID(call_id);
+        getMainBuffer()->bindCallID(call_id, MainBuffer::DEFAULT_ID);
 
         ost::MutexLock lock(audioLayerMutex_);
         audiodriver_->flushUrgent();
@@ -1245,14 +1229,14 @@ void ManagerImpl::saveConfig()
         Conf::YamlEmitter emitter(path_.c_str());
 
         for (AccountMap::iterator iter = accountMap_.begin(); iter != accountMap_.end(); ++iter)
-            iter->second->serialize(&emitter);
+            iter->second->serialize(emitter);
 
-        preferences.serialize(&emitter);
-        voipPreferences.serialize(&emitter);
-        addressbookPreference.serialize(&emitter);
-        hookPreference.serialize(&emitter);
-        audioPreference.serialize(&emitter);
-        shortcutPreferences.serialize(&emitter);
+        preferences.serialize(emitter);
+        voipPreferences.serialize(emitter);
+        addressbookPreference.serialize(emitter);
+        hookPreference.serialize(emitter);
+        audioPreference.serialize(emitter);
+        shortcutPreferences.serialize(emitter);
 
         emitter.serializeData();
     } catch (const Conf::YamlEmitterException &e) {
@@ -1350,38 +1334,37 @@ void ManagerImpl::removeWaitingCall(const std::string& id)
 // Management of event peer IP-phone
 ////////////////////////////////////////////////////////////////////////////////
 // SipEvent Thread
-void ManagerImpl::incomingCall(Call* call, const std::string& accountId)
+void ManagerImpl::incomingCall(Call &call, const std::string& accountId)
 {
-    assert(call);
     stopTone();
 
-    associateCallToAccount(call->getCallId(), accountId);
+    associateCallToAccount(call.getCallId(), accountId);
 
     if (accountId.empty())
-        setIPToIPForCall(call->getCallId(), true);
+        setIPToIPForCall(call.getCallId(), true);
     else {
         // strip sip: which is not required and bring confusion with ip to ip calls
         // when placing new call from history (if call is IAX, do nothing)
-        std::string peerNumber(call->getPeerNumber());
+        std::string peerNumber(call.getPeerNumber());
 
         const char SIP_PREFIX[] = "sip:";
         size_t startIndex = peerNumber.find(SIP_PREFIX);
 
         if (startIndex != std::string::npos)
-            call->setPeerNumber(peerNumber.substr(startIndex + sizeof(SIP_PREFIX) - 1));
+            call.setPeerNumber(peerNumber.substr(startIndex + sizeof(SIP_PREFIX) - 1));
     }
 
     if (not hasCurrentCall()) {
-        call->setConnectionState(Call::RINGING);
+        call.setConnectionState(Call::RINGING);
         ringtone(accountId);
     }
 
-    addWaitingCall(call->getCallId());
+    addWaitingCall(call.getCallId());
 
-    std::string number(call->getPeerNumber());
+    std::string number(call.getPeerNumber());
 
     std::string from("<" + number + ">");
-    dbus_.getCallManager()->incomingCall(accountId, call->getCallId(), call->getDisplayName() + " " + from);
+    dbus_.getCallManager()->incomingCall(accountId, call.getCallId(), call.getDisplayName() + " " + from);
 }
 
 
@@ -1670,7 +1653,7 @@ void ManagerImpl::stopTone()
     if (audiofile_.get()) {
         std::string filepath(audiofile_->getFilePath());
         dbus_.getCallManager()->recordPlaybackStopped(filepath);
-        audiofile_.reset(0);
+        audiofile_.reset();
     }
 }
 
@@ -1749,7 +1732,7 @@ void ManagerImpl::ringtone(const std::string& accountID)
 
         if (audiofile_.get()) {
             dbus_.getCallManager()->recordPlaybackStopped(audiofile_->getFilePath());
-            audiofile_.reset(0);
+            audiofile_.reset();
         }
 
         try {
@@ -2092,7 +2075,7 @@ bool ManagerImpl::startRecordedFilePlayback(const std::string& filepath)
 
         if (audiofile_.get()) {
             dbus_.getCallManager()->recordPlaybackStopped(audiofile_->getFilePath());
-            audiofile_.reset(0);
+            audiofile_.reset();
         }
 
         try {
@@ -2120,7 +2103,7 @@ void ManagerImpl::stopRecordedFilePlayback(const std::string& filepath)
 
     {
         ost::MutexLock m(toneMutex_);
-        audiofile_.reset(0);
+        audiofile_.reset();
     }
 }
 
@@ -2501,6 +2484,8 @@ void ManagerImpl::removeAccount(const std::string& accountID)
 bool ManagerImpl::associateCallToAccount(const std::string& callID,
         const std::string& accountID)
 {
+    std::string useAccountID = accountID;
+
     if (getAccountFromCall(callID).empty() and accountExists(accountID)) {
         // account id exist in AccountMap
         ost::MutexLock m(callAccountMapMutex_);
@@ -2575,13 +2560,21 @@ namespace {
     bool isIP2IP(const Conf::YamlNode *node)
     {
         std::string id;
-        dynamic_cast<const Conf::MappingNode *>(node)->getValue("id", &id);
+        const Conf::MappingNode *m = dynamic_cast<const Conf::MappingNode *>(node);
+        if (!m)
+            return false;
+        m->getValue("id", &id);
         return id == "IP2IP";
     }
 
     void loadAccount(const Conf::YamlNode *item, AccountMap &accountMap)
     {
         const Conf::MappingNode *node = dynamic_cast<const Conf::MappingNode *>(item);
+        if (!node) {
+            ERROR("ManagerImpl: could not load account");
+            return;
+        }
+
         std::string accountType;
         node->getValue("type", &accountType);
 
@@ -2601,10 +2594,15 @@ namespace {
                 a = new SIPAccount(accountid);
 
             accountMap[accountid] = a;
-            a->unserialize(node);
+            a->unserialize(*node);
         }
     }
 
+    void unregisterAccount(std::pair<const std::string, Account*> &item)
+    {
+        item.second->unregisterVoIPLink();
+    }
+
     void unloadAccount(std::pair<const std::string, Account*> &item)
     {
         // avoid deleting IP2IP account twice
@@ -2613,6 +2611,7 @@ namespace {
             item.second = 0;
         }
     }
+
 } // end anonymous namespace
 
 void ManagerImpl::loadAccountMap(Conf::YamlParser &parser)
@@ -2626,7 +2625,8 @@ void ManagerImpl::loadAccountMap(Conf::YamlParser &parser)
     Sequence::const_iterator ip2ip = std::find_if(seq->begin(), seq->end(), isIP2IP);
     if (ip2ip != seq->end()) {
         MappingNode *node = dynamic_cast<MappingNode*>(*ip2ip);
-        accountMap_[SIPAccount::IP2IP_PROFILE]->unserialize(node);
+        if (node)
+            accountMap_[SIPAccount::IP2IP_PROFILE]->unserialize(node);
     }
 
     // Initialize default UDP transport according to
@@ -2638,12 +2638,12 @@ void ManagerImpl::loadAccountMap(Conf::YamlParser &parser)
     accountMap_[SIPAccount::IP2IP_PROFILE]->registerVoIPLink();
 
     // build preferences
-    preferences.unserialize(parser.getPreferenceNode());
-    voipPreferences.unserialize(parser.getVoipPreferenceNode());
-    addressbookPreference.unserialize(parser.getAddressbookNode());
-    hookPreference.unserialize(parser.getHookNode());
-    audioPreference.unserialize(parser.getAudioNode());
-    shortcutPreferences.unserialize(parser.getShortcutNode());
+    preferences.unserialize(*parser.getPreferenceNode());
+    voipPreferences.unserialize(*parser.getVoipPreferenceNode());
+    addressbookPreference.unserialize(*parser.getAddressbookNode());
+    hookPreference.unserialize(*parser.getHookNode());
+    audioPreference.unserialize(*parser.getAudioNode());
+    shortcutPreferences.unserialize(*parser.getShortcutNode());
 
     using namespace std::tr1; // for std::tr1::bind and std::tr1::ref
     using namespace std::tr1::placeholders;
@@ -2651,6 +2651,11 @@ void ManagerImpl::loadAccountMap(Conf::YamlParser &parser)
     std::for_each(seq->begin(), seq->end(), bind(loadAccount, _1, ref(accountMap_)));
 }
 
+void ManagerImpl::unregisterAllAccounts()
+{
+    std::for_each(accountMap_.begin(), accountMap_.end(), unregisterAccount);
+}
+
 void ManagerImpl::unloadAccountMap()
 {
     std::for_each(accountMap_.begin(), accountMap_.end(), unloadAccount);
@@ -2674,8 +2679,8 @@ ManagerImpl::getAccount(const std::string& accountID)
     AccountMap::const_iterator iter = accountMap_.find(accountID);
     if (iter != accountMap_.end())
         return iter->second;
-    else
-        return accountMap_[SIPAccount::IP2IP_PROFILE];
+
+    return accountMap_[SIPAccount::IP2IP_PROFILE];
 }
 
 std::string ManagerImpl::getAccountIdFromNameAndServer(const std::string& userName, const std::string& server) const
diff --git a/daemon/src/managerimpl.h b/daemon/src/managerimpl.h
index 1454fce90c6968e2cbfe11bb4f8b81af64810d10..52ff2322947cffd564bec266cd0fe126fe023779 100644
--- a/daemon/src/managerimpl.h
+++ b/daemon/src/managerimpl.h
@@ -32,15 +32,15 @@
  *  as that of the covered work.
  */
 
-#ifndef __SFL_MANAGER_H__
-#define __SFL_MANAGER_H__
+#ifndef MANAGER_IMPL_H_
+#define MANAGER_IMPL_H_
 
 #include <string>
 #include <vector>
 #include <set>
 #include <map>
-#include <cc++/thread.h>
-#include <memory>
+#include <tr1/memory>
+#include "cc_thread.h"
 #include "dbus/dbusmanager.h"
 
 #include "config/sfl_config.h"
@@ -93,7 +93,6 @@ static const char * const default_conf = "conf";
 class ManagerImpl {
     public:
         ManagerImpl();
-        ~ManagerImpl();
 
         /**
          * General preferences configuration
@@ -129,7 +128,7 @@ class ManagerImpl {
          * Initialisation of thread (sound) and map.
          * Init a new VoIPLink, audio codec and audio driver
          */
-        void init(std::string config_file = "");
+        void init(const std::string &config_file);
 
         /**
          * Terminate all thread (sound, link) and unload AccountMap
@@ -354,7 +353,7 @@ class ManagerImpl {
          * @param call A call pointer
          * @param accountId an account id
          */
-        void incomingCall(Call* call, const std::string& accountId);
+        void incomingCall(Call &call, const std::string& accountId);
 
         /**
          * Notify the user that the recipient of the call has answered and the put the
@@ -894,14 +893,14 @@ class ManagerImpl {
         AudioLayer* audiodriver_;
 
         // Main thread
-        std::auto_ptr<DTMF> dtmfKey_;
+        std::tr1::shared_ptr<DTMF> dtmfKey_;
 
         /////////////////////
         // Protected by Mutex
         /////////////////////
         ost::Mutex toneMutex_;
-        std::auto_ptr<TelephoneTone> telephoneTone_;
-        std::auto_ptr<AudioFile> audiofile_;
+        std::tr1::shared_ptr<TelephoneTone> telephoneTone_;
+        std::tr1::shared_ptr<AudioFile> audiofile_;
 
         // To handle volume control
         // short speakerVolume_;
@@ -965,7 +964,6 @@ class ManagerImpl {
 
         std::map<std::string, bool> IPToIPMap_;
 
-        void setIPToIPForCall(const std::string& callID, bool IPToIP);
 
         bool isIPToIP(const std::string& callID) const;
 
@@ -973,6 +971,11 @@ class ManagerImpl {
          *Contains a list of account (sip, aix, etc) and their respective voiplink/calls */
         AccountMap accountMap_;
 
+        /**
+         * Unregister all account in accountMap_
+         */
+        void unregisterAllAccounts();
+
         /**
          * Load the account map from configuration
          */
@@ -998,6 +1001,8 @@ class ManagerImpl {
 
     public:
 
+        void setIPToIPForCall(const std::string& callID, bool IPToIP);
+
         /** Associate a new std::string to a std::string
          * Protected by mutex
          * @param callID the new CallID not in the list yet
@@ -1094,4 +1099,4 @@ class ManagerImpl {
           */
         History history_;
 };
-#endif // __MANAGER_H__
+#endif // MANAGER_IMPL_H_
diff --git a/daemon/src/numbercleaner.cpp b/daemon/src/numbercleaner.cpp
index c49c2240ed345b6b732b36327171ba52971817b0..eae039454351ab0f1ad33c708e3bd9172487ec4c 100644
--- a/daemon/src/numbercleaner.cpp
+++ b/daemon/src/numbercleaner.cpp
@@ -30,6 +30,7 @@
  */
 
 #include "numbercleaner.h"
+#include "logger.h"
 #include <algorithm>
 
 namespace {
diff --git a/daemon/src/preferences.cpp b/daemon/src/preferences.cpp
index 44b314d193632b3102c3ffff15148031320b646e..5bbb07082e994f65ecd2524c2152127346ccbfde 100644
--- a/daemon/src/preferences.cpp
+++ b/daemon/src/preferences.cpp
@@ -29,6 +29,7 @@
  */
 
 #include "preferences.h"
+#include "logger.h"
 #include "audio/alsa/alsalayer.h"
 #include "audio/pulseaudio/pulselayer.h"
 #include "config/yamlemitter.h"
@@ -37,11 +38,74 @@
 #include "sip/sip_utils.h"
 #include <sstream>
 #include "global.h"
-#include <cassert>
 
 const char * const Preferences::DFT_ZONE = "North America";
+const char * const Preferences::REGISTRATION_EXPIRE_KEY = "registrationexpire";
 
 namespace {
+// general preferences
+static const char * const ORDER_KEY = "order";
+static const char * const AUDIO_API_KEY = "audioApi";
+static const char * const HISTORY_LIMIT_KEY = "historyLimit";
+static const char * const HISTORY_MAX_CALLS_KEY = "historyMaxCalls";
+static const char * const NOTIFY_MAILS_KEY = "notifyMails";
+static const char * const ZONE_TONE_CHOICE_KEY = "zoneToneChoice";
+static const char * const PORT_NUM_KEY = "portNum";
+static const char * const SEARCH_BAR_DISPLAY_KEY = "searchBarDisplay";
+static const char * const ZEROCONF_ENABLE_KEY = "zeroConfenable";
+static const char * const MD5_HASH_KEY = "md5Hash";
+
+// voip preferences
+static const char * const PLAY_DTMF_KEY = "playDtmf";
+static const char * const PLAY_TONES_KEY = "playTones";
+static const char * const PULSE_LENGTH_KEY = "pulseLength";
+static const char * const SYMMETRIC_RTP_KEY = "symmetric";
+static const char * const ZID_FILE_KEY = "zidFile";
+
+// addressbook preferences
+static const char * const PHOTO_KEY = "photo";
+static const char * const ENABLED_KEY = "enabled";
+static const char * const LIST_KEY = "list";
+static const char * const MAX_RESULTS_KEY = "maxResults";
+static const char * const BUSINESS_KEY = "business";
+static const char * const HOME_KEY = "home";
+static const char * const MOBILE_KEY = "mobile";
+
+// hooks preferences
+static const char * const IAX2_ENABLED_KEY = "iax2Enabled";
+static const char * const NUMBER_ADD_PREFIX_KEY = "numberAddPrefix";
+static const char * const NUMBER_ENABLED_KEY = "numberEnabled";
+static const char * const SIP_ENABLED_KEY = "sipEnabled";
+static const char * const URL_COMMAND_KEY = "urlCommand";
+static const char * const URL_SIP_FIELD_KEY = "urlSipField";
+
+// audio preferences
+static const char * const ALSAMAP_KEY = "alsa";
+static const char * const PULSEMAP_KEY = "pulse";
+static const char * const CARDIN_KEY = "cardIn";
+static const char * const CARDOUT_KEY = "cardOut";
+static const char * const CARDRING_KEY = "cardRing";
+static const char * const PLUGIN_KEY = "plugin";
+static const char * const SMPLRATE_KEY = "smplRate";
+static const char * const DEVICE_PLAYBACK_KEY = "devicePlayback";
+static const char * const DEVICE_RECORD_KEY = "deviceRecord";
+static const char * const DEVICE_RINGTONE_KEY = "deviceRingtone";
+static const char * const RECORDPATH_KEY = "recordPath";
+static const char * const ALWAYS_RECORDING_KEY = "alwaysRecording";
+static const char * const VOLUMEMIC_KEY = "volumeMic";
+static const char * const VOLUMESPKR_KEY = "volumeSpkr";
+static const char * const NOISE_REDUCE_KEY = "noiseReduce";
+static const char * const ECHO_CANCEL_KEY = "echoCancel";
+static const char * const ECHO_TAIL_KEY = "echoTailLength";
+static const char * const ECHO_DELAY_KEY = "echoDelayLength";
+
+// shortcut preferences
+static const char * const HANGUP_SHORT_KEY = "hangUp";
+static const char * const PICKUP_SHORT_KEY = "pickUp";
+static const char * const POPUP_SHORT_KEY = "popupWindow";
+static const char * const TOGGLE_HOLD_SHORT_KEY = "toggleHold";
+static const char * const TOGGLE_PICKUP_HANGUP_SHORT_KEY = "togglePickupHangup";
+
 static const char * const DFT_PULSE_LENGTH_STR ="250";  /** Default DTMF lenght */
 static const char * const ZRTP_ZIDFILE = "zidFile";     /** The filename used for storing ZIDs */
 static const char * const ALSA_DFT_CARD	= "0";          /** Default sound card index */
@@ -49,7 +113,8 @@ static const char * const DFT_VOL_SPKR_STR = "100";     /** Default speaker volu
 static const char * const DFT_VOL_MICRO_STR	= "100";    /** Default mic volume */
 } // end anonymous namespace
 
-Preferences::Preferences() : accountOrder_("")
+Preferences::Preferences() :
+    accountOrder_("")
     , historyLimit_(30)
     , historyMaxCalls_(20)
     , notifyMails_(false)
@@ -61,7 +126,7 @@ Preferences::Preferences() : accountOrder_("")
     , md5Hash_(false)
 {}
 
-void Preferences::serialize(Conf::YamlEmitter *emiter)
+void Preferences::serialize(Conf::YamlEmitter &emiter)
 {
     Conf::MappingNode preferencemap(NULL);
 
@@ -84,47 +149,43 @@ void Preferences::serialize(Conf::YamlEmitter *emiter)
     Conf::ScalarNode zeroConfenable(zeroConfenable_);
     Conf::ScalarNode md5Hash(md5Hash_);
 
-    preferencemap.setKeyValue(orderKey, &order);
-    preferencemap.setKeyValue(historyLimitKey, &historyLimit);
-    preferencemap.setKeyValue(historyMaxCallsKey, &historyMaxCalls);
-    preferencemap.setKeyValue(notifyMailsKey, &notifyMails);
-    preferencemap.setKeyValue(zoneToneChoiceKey, &zoneToneChoice);
-    preferencemap.setKeyValue(registrationExpireKey, &registrationExpire);
-    preferencemap.setKeyValue(portNumKey, &portNum);
-    preferencemap.setKeyValue(searchBarDisplayKey, &searchBarDisplay);
-    preferencemap.setKeyValue(zeroConfenableKey, &zeroConfenable);
-    preferencemap.setKeyValue(md5HashKey, &md5Hash);
-
-    emiter->serializePreference(&preferencemap);
+    preferencemap.setKeyValue(ORDER_KEY, &order);
+    preferencemap.setKeyValue(HISTORY_LIMIT_KEY, &historyLimit);
+    preferencemap.setKeyValue(HISTORY_MAX_CALLS_KEY, &historyMaxCalls);
+    preferencemap.setKeyValue(NOTIFY_MAILS_KEY, &notifyMails);
+    preferencemap.setKeyValue(ZONE_TONE_CHOICE_KEY, &zoneToneChoice);
+    preferencemap.setKeyValue(REGISTRATION_EXPIRE_KEY, &registrationExpire);
+    preferencemap.setKeyValue(PORT_NUM_KEY, &portNum);
+    preferencemap.setKeyValue(SEARCH_BAR_DISPLAY_KEY, &searchBarDisplay);
+    preferencemap.setKeyValue(ZEROCONF_ENABLE_KEY, &zeroConfenable);
+    preferencemap.setKeyValue(MD5_HASH_KEY, &md5Hash);
+
+    emiter.serializePreference(&preferencemap, "preferences");
 }
 
-void Preferences::unserialize(const Conf::MappingNode *map)
+void Preferences::unserialize(const Conf::MappingNode &map)
 {
-    if (map == NULL) {
-        ERROR("Preference: Error: Preference map is NULL");
-        return;
-    }
-
-    map->getValue(orderKey, &accountOrder_);
-    map->getValue(historyLimitKey, &historyLimit_);
-    map->getValue(historyMaxCallsKey, &historyMaxCalls_);
-    map->getValue(notifyMailsKey, &notifyMails_);
-    map->getValue(zoneToneChoiceKey, &zoneToneChoice_);
-    map->getValue(registrationExpireKey, &registrationExpire_);
-    map->getValue(portNumKey, &portNum_);
-    map->getValue(searchBarDisplayKey, &searchBarDisplay_);
-    map->getValue(zeroConfenableKey, &zeroConfenable_);
-    map->getValue(md5HashKey, &md5Hash_);
+    map.getValue(ORDER_KEY, &accountOrder_);
+    map.getValue(HISTORY_LIMIT_KEY, &historyLimit_);
+    map.getValue(HISTORY_MAX_CALLS_KEY, &historyMaxCalls_);
+    map.getValue(NOTIFY_MAILS_KEY, &notifyMails_);
+    map.getValue(ZONE_TONE_CHOICE_KEY, &zoneToneChoice_);
+    map.getValue(REGISTRATION_EXPIRE_KEY, &registrationExpire_);
+    map.getValue(PORT_NUM_KEY, &portNum_);
+    map.getValue(SEARCH_BAR_DISPLAY_KEY, &searchBarDisplay_);
+    map.getValue(ZEROCONF_ENABLE_KEY, &zeroConfenable_);
+    map.getValue(MD5_HASH_KEY, &md5Hash_);
 }
 
-VoipPreference::VoipPreference() : playDtmf_(true)
+VoipPreference::VoipPreference() :
+    playDtmf_(true)
     , playTones_(true)
     , pulseLength_(atoi(DFT_PULSE_LENGTH_STR))
     , symmetricRtp_(true)
     , zidFile_(ZRTP_ZIDFILE)
 {}
 
-void VoipPreference::serialize(Conf::YamlEmitter *emitter)
+void VoipPreference::serialize(Conf::YamlEmitter &emitter)
 {
     Conf::MappingNode preferencemap(NULL);
 
@@ -136,27 +197,22 @@ void VoipPreference::serialize(Conf::YamlEmitter *emitter)
     Conf::ScalarNode symmetricRtp(symmetricRtp_);
     Conf::ScalarNode zidFile(zidFile_.c_str());
 
-    preferencemap.setKeyValue(playDtmfKey, &playDtmf);
-    preferencemap.setKeyValue(playTonesKey, &playTones);
-    preferencemap.setKeyValue(pulseLengthKey, &pulseLength);
-    preferencemap.setKeyValue(symmetricRtpKey, &symmetricRtp);
-    preferencemap.setKeyValue(zidFileKey, &zidFile);
+    preferencemap.setKeyValue(PLAY_DTMF_KEY, &playDtmf);
+    preferencemap.setKeyValue(PLAY_TONES_KEY, &playTones);
+    preferencemap.setKeyValue(PULSE_LENGTH_KEY, &pulseLength);
+    preferencemap.setKeyValue(SYMMETRIC_RTP_KEY, &symmetricRtp);
+    preferencemap.setKeyValue(ZID_FILE_KEY, &zidFile);
 
-    emitter->serializeVoipPreference(&preferencemap);
+    emitter.serializePreference(&preferencemap, "voipPreferences");
 }
 
-void VoipPreference::unserialize(const Conf::MappingNode *map)
+void VoipPreference::unserialize(const Conf::MappingNode &map)
 {
-    if (!map) {
-        ERROR("VoipPreference: Error: Preference map is NULL");
-        return;
-    }
-
-    map->getValue(playDtmfKey, &playDtmf_);
-    map->getValue(playTonesKey, &playTones_);
-    map->getValue(pulseLengthKey, &pulseLength_);
-    map->getValue(symmetricRtpKey, &symmetricRtp_);
-    map->getValue(zidFileKey, &zidFile_);
+    map.getValue(PLAY_DTMF_KEY, &playDtmf_);
+    map.getValue(PLAY_TONES_KEY, &playTones_);
+    map.getValue(PULSE_LENGTH_KEY, &pulseLength_);
+    map.getValue(SYMMETRIC_RTP_KEY, &symmetricRtp_);
+    map.getValue(ZID_FILE_KEY, &zidFile_);
 }
 
 AddressbookPreference::AddressbookPreference() : photo_(true)
@@ -168,7 +224,7 @@ AddressbookPreference::AddressbookPreference() : photo_(true)
     , mobile_(true)
 {}
 
-void AddressbookPreference::serialize(Conf::YamlEmitter *emitter)
+void AddressbookPreference::serialize(Conf::YamlEmitter &emitter)
 {
     Conf::MappingNode preferencemap(NULL);
 
@@ -182,35 +238,30 @@ void AddressbookPreference::serialize(Conf::YamlEmitter *emitter)
     Conf::ScalarNode home(home_);
     Conf::ScalarNode mobile(mobile_);
 
-    preferencemap.setKeyValue(photoKey, &photo);
-    preferencemap.setKeyValue(enabledKey, &enabled);
-    preferencemap.setKeyValue(listKey, &list);
-    preferencemap.setKeyValue(maxResultsKey, &maxResults);
-    preferencemap.setKeyValue(businessKey, &business);
-    preferencemap.setKeyValue(homeKey, &home);
-    preferencemap.setKeyValue(mobileKey, &mobile);
-
-    emitter->serializeAddressbookPreference(&preferencemap);
+    preferencemap.setKeyValue(PHOTO_KEY, &photo);
+    preferencemap.setKeyValue(ENABLED_KEY, &enabled);
+    preferencemap.setKeyValue(LIST_KEY, &list);
+    preferencemap.setKeyValue(MAX_RESULTS_KEY, &maxResults);
+    preferencemap.setKeyValue(BUSINESS_KEY, &business);
+    preferencemap.setKeyValue(HOME_KEY, &home);
+    preferencemap.setKeyValue(MOBILE_KEY, &mobile);
 
+    emitter.serializePreference(&preferencemap, "addressbook");
 }
 
-void AddressbookPreference::unserialize(const Conf::MappingNode *map)
+void AddressbookPreference::unserialize(const Conf::MappingNode &map)
 {
-    if (!map) {
-        ERROR("Addressbook: Error: Preference map is NULL");
-        return;
-    }
-
-    map->getValue(photoKey, &photo_);
-    map->getValue(enabledKey, &enabled_);
-    map->getValue(listKey, &list_);
-    map->getValue(maxResultsKey, &maxResults_);
-    map->getValue(businessKey, &business_);
-    map->getValue(homeKey, &home_);
-    map->getValue(mobileKey, &mobile_);
+    map.getValue(PHOTO_KEY, &photo_);
+    map.getValue(ENABLED_KEY, &enabled_);
+    map.getValue(LIST_KEY, &list_);
+    map.getValue(MAX_RESULTS_KEY, &maxResults_);
+    map.getValue(BUSINESS_KEY, &business_);
+    map.getValue(HOME_KEY, &home_);
+    map.getValue(MOBILE_KEY, &mobile_);
 }
 
-HookPreference::HookPreference() : iax2Enabled_(false)
+HookPreference::HookPreference() :
+    iax2Enabled_(false)
     , numberAddPrefix_("")
     , numberEnabled_(false)
     , sipEnabled_(false)
@@ -240,7 +291,7 @@ std::map<std::string, std::string> HookPreference::toMap() const
     return settings;
 }
 
-void HookPreference::serialize(Conf::YamlEmitter *emitter)
+void HookPreference::serialize(Conf::YamlEmitter &emitter)
 {
     Conf::MappingNode preferencemap(NULL);
 
@@ -251,53 +302,48 @@ void HookPreference::serialize(Conf::YamlEmitter *emitter)
     Conf::ScalarNode urlCommand(urlCommand_);
     Conf::ScalarNode urlSipField(urlSipField_);
 
-    preferencemap.setKeyValue(iax2EnabledKey, &iax2Enabled);
-    preferencemap.setKeyValue(numberAddPrefixKey, &numberAddPrefix);
-    preferencemap.setKeyValue(numberEnabledKey, &numberEnabled);
-    preferencemap.setKeyValue(sipEnabledKey, &sipEnabled);
-    preferencemap.setKeyValue(urlCommandKey, &urlCommand);
-    preferencemap.setKeyValue(urlSipFieldKey, &urlSipField);
+    preferencemap.setKeyValue(IAX2_ENABLED_KEY, &iax2Enabled);
+    preferencemap.setKeyValue(NUMBER_ADD_PREFIX_KEY, &numberAddPrefix);
+    preferencemap.setKeyValue(NUMBER_ENABLED_KEY, &numberEnabled);
+    preferencemap.setKeyValue(SIP_ENABLED_KEY, &sipEnabled);
+    preferencemap.setKeyValue(URL_COMMAND_KEY, &urlCommand);
+    preferencemap.setKeyValue(URL_SIP_FIELD_KEY, &urlSipField);
 
-    emitter->serializeHooksPreference(&preferencemap);
+    emitter.serializePreference(&preferencemap, "hooks");
 }
 
-void HookPreference::unserialize(const Conf::MappingNode *map)
+void HookPreference::unserialize(const Conf::MappingNode &map)
 {
-    if (!map) {
-        ERROR("Hook: Error: Preference map is NULL");
-        return;
-    }
-
-    map->getValue(iax2EnabledKey, &iax2Enabled_);
-    map->getValue(numberAddPrefixKey, &numberAddPrefix_);
-    map->getValue(numberEnabledKey, &numberEnabled_);
-    map->getValue(sipEnabledKey, &sipEnabled_);
-    map->getValue(urlCommandKey, &urlCommand_);
-    map->getValue(urlSipFieldKey, &urlSipField_);
+    map.getValue(IAX2_ENABLED_KEY, &iax2Enabled_);
+    map.getValue(NUMBER_ADD_PREFIX_KEY, &numberAddPrefix_);
+    map.getValue(NUMBER_ENABLED_KEY, &numberEnabled_);
+    map.getValue(SIP_ENABLED_KEY, &sipEnabled_);
+    map.getValue(URL_COMMAND_KEY, &urlCommand_);
+    map.getValue(URL_SIP_FIELD_KEY, &urlSipField_);
 }
 
 void HookPreference::runHook(pjsip_msg *msg)
 {
     if (sipEnabled_) {
-        std::string header(sip_utils::fetchHeaderValue(msg, urlSipField_));
+        const std::string header(sip_utils::fetchHeaderValue(msg, urlSipField_));
         UrlHook::runAction(urlCommand_, header);
     }
 }
 
 AudioPreference::AudioPreference() :
     audioApi_(PULSEAUDIO_API_STR)
-    , cardin_(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD
-    , cardout_(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD
-    , cardring_(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD
-    , plugin_("default") // PCM_DEFAULT
-    , smplrate_(44100) // DFT_SAMPLE_RATE
+    , cardin_(atoi(ALSA_DFT_CARD))
+    , cardout_(atoi(ALSA_DFT_CARD))
+    , cardring_(atoi(ALSA_DFT_CARD))
+    , plugin_("default")
+    , smplrate_(44100)
     , devicePlayback_("")
     , deviceRecord_("")
     , deviceRingtone_("")
-    , recordpath_("") // DFT_RECORD_PATH
+    , recordpath_("")
     , alwaysRecording_(false)
-    , volumemic_(atoi(DFT_VOL_SPKR_STR)) // DFT_VOL_SPKR_STR
-    , volumespkr_(atoi(DFT_VOL_MICRO_STR)) // DFT_VOL_MICRO_STR
+    , volumemic_(atoi(DFT_VOL_SPKR_STR))
+    , volumespkr_(atoi(DFT_VOL_MICRO_STR))
     , noisereduce_(true)
     , echocancel_(false)
     , echoCancelTailLength_(100)
@@ -337,7 +383,7 @@ AudioLayer* AudioPreference::switchAndCreateAudioLayer()
     return createAudioLayer();
 }
 
-void AudioPreference::serialize(Conf::YamlEmitter *emitter)
+void AudioPreference::serialize(Conf::YamlEmitter &emitter)
 {
     Conf::MappingNode preferencemap(NULL);
     Conf::MappingNode alsapreferencemap(NULL);
@@ -383,60 +429,58 @@ void AudioPreference::serialize(Conf::YamlEmitter *emitter)
     delaystr << echoCancelDelay_;
     Conf::ScalarNode echodelay(delaystr.str());
 
-    preferencemap.setKeyValue(audioApiKey, &audioapi);
-    preferencemap.setKeyValue(recordpathKey, &recordpath);
-    preferencemap.setKeyValue(alwaysRecordingKey, &alwaysRecording);
-    preferencemap.setKeyValue(volumemicKey, &volumemic);
-    preferencemap.setKeyValue(volumespkrKey, &volumespkr);
-
-    preferencemap.setKeyValue(alsamapKey, &alsapreferencemap);
-    alsapreferencemap.setKeyValue(cardinKey, &cardin);
-    alsapreferencemap.setKeyValue(cardoutKey, &cardout);
-    alsapreferencemap.setKeyValue(cardringKey, &cardring);
-    alsapreferencemap.setKeyValue(pluginKey, &plugin);
-    alsapreferencemap.setKeyValue(smplrateKey, &smplrate);
-
-    preferencemap.setKeyValue(pulsemapKey, &pulsepreferencemap);
-    pulsepreferencemap.setKeyValue(devicePlaybackKey, &devicePlayback);
-    pulsepreferencemap.setKeyValue(deviceRecordKey, &deviceRecord);
-    pulsepreferencemap.setKeyValue(deviceRingtoneKey, &deviceRingtone);
-
-    preferencemap.setKeyValue(noiseReduceKey, &noise);
-    preferencemap.setKeyValue(echoCancelKey, &echo);
-    preferencemap.setKeyValue(echoTailKey, &echotail);
-    preferencemap.setKeyValue(echoDelayKey, &echodelay);
-
-    emitter->serializeAudioPreference(&preferencemap);
+    preferencemap.setKeyValue(AUDIO_API_KEY, &audioapi);
+    preferencemap.setKeyValue(RECORDPATH_KEY, &recordpath);
+    preferencemap.setKeyValue(ALWAYS_RECORDING_KEY, &alwaysRecording);
+    preferencemap.setKeyValue(VOLUMEMIC_KEY, &volumemic);
+    preferencemap.setKeyValue(VOLUMESPKR_KEY, &volumespkr);
+
+    preferencemap.setKeyValue(ALSAMAP_KEY, &alsapreferencemap);
+    alsapreferencemap.setKeyValue(CARDIN_KEY, &cardin);
+    alsapreferencemap.setKeyValue(CARDOUT_KEY, &cardout);
+    alsapreferencemap.setKeyValue(CARDRING_KEY, &cardring);
+    alsapreferencemap.setKeyValue(PLUGIN_KEY, &plugin);
+    alsapreferencemap.setKeyValue(SMPLRATE_KEY, &smplrate);
+
+    preferencemap.setKeyValue(PULSEMAP_KEY, &pulsepreferencemap);
+    pulsepreferencemap.setKeyValue(DEVICE_PLAYBACK_KEY, &devicePlayback);
+    pulsepreferencemap.setKeyValue(DEVICE_RECORD_KEY, &deviceRecord);
+    pulsepreferencemap.setKeyValue(DEVICE_RINGTONE_KEY, &deviceRingtone);
+
+    preferencemap.setKeyValue(NOISE_REDUCE_KEY, &noise);
+    preferencemap.setKeyValue(ECHO_CANCEL_KEY, &echo);
+    preferencemap.setKeyValue(ECHO_TAIL_KEY, &echotail);
+    preferencemap.setKeyValue(ECHO_DELAY_KEY, &echodelay);
+
+    emitter.serializePreference(&preferencemap, "audio");
 }
 
-void AudioPreference::unserialize(const Conf::MappingNode *map)
+void AudioPreference::unserialize(const Conf::MappingNode &map)
 {
-    assert(map);
-
-    map->getValue(audioApiKey, &audioApi_);
-    map->getValue(recordpathKey, &recordpath_);
-    map->getValue(alwaysRecordingKey, &alwaysRecording_);
-    map->getValue(volumemicKey, &volumemic_);
-    map->getValue(volumespkrKey, &volumespkr_);
-    map->getValue(noiseReduceKey, &noisereduce_);
-    map->getValue(echoCancelKey, &echocancel_);
+    map.getValue(AUDIO_API_KEY, &audioApi_);
+    map.getValue(RECORDPATH_KEY, &recordpath_);
+    map.getValue(ALWAYS_RECORDING_KEY, &alwaysRecording_);
+    map.getValue(VOLUMEMIC_KEY, &volumemic_);
+    map.getValue(VOLUMESPKR_KEY, &volumespkr_);
+    map.getValue(NOISE_REDUCE_KEY, &noisereduce_);
+    map.getValue(ECHO_CANCEL_KEY, &echocancel_);
 
-    Conf::MappingNode *alsamap =(Conf::MappingNode *)(map->getValue("alsa"));
+    Conf::MappingNode *alsamap =(Conf::MappingNode *) map.getValue("alsa");
 
     if (alsamap) {
-        alsamap->getValue(cardinKey, &cardin_);
-        alsamap->getValue(cardoutKey, &cardout_);
-        alsamap->getValue(cardringKey, &cardring_);
-        alsamap->getValue(smplrateKey, &smplrate_);
-        alsamap->getValue(pluginKey, &plugin_);
+        alsamap->getValue(CARDIN_KEY, &cardin_);
+        alsamap->getValue(CARDOUT_KEY, &cardout_);
+        alsamap->getValue(CARDRING_KEY, &cardring_);
+        alsamap->getValue(SMPLRATE_KEY, &smplrate_);
+        alsamap->getValue(PLUGIN_KEY, &plugin_);
     }
 
-    Conf::MappingNode *pulsemap =(Conf::MappingNode *)(map->getValue("pulse"));
+    Conf::MappingNode *pulsemap =(Conf::MappingNode *)(map.getValue("pulse"));
 
     if (pulsemap) {
-        pulsemap->getValue(devicePlaybackKey, &devicePlayback_);
-        pulsemap->getValue(deviceRecordKey, &deviceRecord_);
-        pulsemap->getValue(deviceRingtoneKey, &deviceRingtone_);
+        pulsemap->getValue(DEVICE_PLAYBACK_KEY, &devicePlayback_);
+        pulsemap->getValue(DEVICE_RECORD_KEY, &deviceRecord_);
+        pulsemap->getValue(DEVICE_RINGTONE_KEY, &deviceRingtone_);
     }
 }
 
@@ -447,25 +491,26 @@ std::map<std::string, std::string> ShortcutPreferences::getShortcuts() const
 {
     std::map<std::string, std::string> shortcutsMap;
 
-    shortcutsMap[hangupShortKey] = hangup_;
-    shortcutsMap[pickupShortKey] = pickup_;
-    shortcutsMap[popupShortKey] = popup_;
-    shortcutsMap[toggleHoldShortKey] = toggleHold_;
-    shortcutsMap[togglePickupHangupShortKey] = togglePickupHangup_;
+    shortcutsMap[HANGUP_SHORT_KEY] = hangup_;
+    shortcutsMap[PICKUP_SHORT_KEY] = pickup_;
+    shortcutsMap[POPUP_SHORT_KEY] = popup_;
+    shortcutsMap[TOGGLE_HOLD_SHORT_KEY] = toggleHold_;
+    shortcutsMap[TOGGLE_PICKUP_HANGUP_SHORT_KEY] = togglePickupHangup_;
 
     return shortcutsMap;
 }
 
 void ShortcutPreferences::setShortcuts(std::map<std::string, std::string> map)
 {
-    hangup_ = map[hangupShortKey];
-    pickup_ = map[pickupShortKey];
-    popup_ = map[popupShortKey];
-    toggleHold_ = map[toggleHoldShortKey];
-    togglePickupHangup_ = map[togglePickupHangupShortKey];
+    hangup_ = map[HANGUP_SHORT_KEY];
+    pickup_ = map[PICKUP_SHORT_KEY];
+    popup_ = map[POPUP_SHORT_KEY];
+    toggleHold_ = map[TOGGLE_HOLD_SHORT_KEY];
+    togglePickupHangup_ = map[TOGGLE_PICKUP_HANGUP_SHORT_KEY];
 }
 
-void ShortcutPreferences::serialize(Conf::YamlEmitter *emitter)
+
+void ShortcutPreferences::serialize(Conf::YamlEmitter &emitter)
 {
     Conf::MappingNode preferencemap(NULL);
 
@@ -475,26 +520,21 @@ void ShortcutPreferences::serialize(Conf::YamlEmitter *emitter)
     Conf::ScalarNode toggleHold(toggleHold_);
     Conf::ScalarNode togglePickupHangup(togglePickupHangup_);
 
-    preferencemap.setKeyValue(hangupShortKey, &hangup);
-    preferencemap.setKeyValue(pickupShortKey, &pickup);
-    preferencemap.setKeyValue(popupShortKey, &popup);
-    preferencemap.setKeyValue(toggleHoldShortKey, &toggleHold);
-    preferencemap.setKeyValue(togglePickupHangupShortKey, &togglePickupHangup);
+    preferencemap.setKeyValue(HANGUP_SHORT_KEY, &hangup);
+    preferencemap.setKeyValue(PICKUP_SHORT_KEY, &pickup);
+    preferencemap.setKeyValue(POPUP_SHORT_KEY, &popup);
+    preferencemap.setKeyValue(TOGGLE_HOLD_SHORT_KEY, &toggleHold);
+    preferencemap.setKeyValue(TOGGLE_PICKUP_HANGUP_SHORT_KEY, &togglePickupHangup);
 
-    emitter->serializeShortcutPreference(&preferencemap);
+    emitter.serializePreference(&preferencemap, "shortcuts");
 }
 
-void ShortcutPreferences::unserialize(const Conf::MappingNode *map)
+void ShortcutPreferences::unserialize(const Conf::MappingNode &map)
 {
-    if (map == NULL) {
-        ERROR("ShortcutPreference: Error: Preference map is NULL");
-        return;
-    }
-
-    map->getValue(hangupShortKey, &hangup_);
-    map->getValue(pickupShortKey, &pickup_);
-    map->getValue(popupShortKey, &popup_);
-    map->getValue(toggleHoldShortKey, &toggleHold_);
-    map->getValue(togglePickupHangupShortKey, &togglePickupHangup_);
+    map.getValue(HANGUP_SHORT_KEY, &hangup_);
+    map.getValue(PICKUP_SHORT_KEY, &pickup_);
+    map.getValue(POPUP_SHORT_KEY, &popup_);
+    map.getValue(TOGGLE_HOLD_SHORT_KEY, &toggleHold_);
+    map.getValue(TOGGLE_PICKUP_HANGUP_SHORT_KEY, &togglePickupHangup_);
 }
 
diff --git a/daemon/src/preferences.h b/daemon/src/preferences.h
index ea8564a24a36ee4a698e637b9dd3706621a14ad5..2dc73f4187f43ef7b5a03b50836e0356f9b9b168 100644
--- a/daemon/src/preferences.h
+++ b/daemon/src/preferences.h
@@ -35,81 +35,17 @@
 #include <string>
 #include <map>
 
-// general preferences
-static const char * const orderKey = "order";
-static const char * const audioApiKey = "audioApi";
-static const char * const historyLimitKey = "historyLimit";
-static const char * const historyMaxCallsKey = "historyMaxCalls";
-static const char * const notifyMailsKey = "notifyMails";
-static const char * const zoneToneChoiceKey = "zoneToneChoice";
-static const char * const registrationExpireKey = "registrationexpire";
-static const char * const portNumKey = "portNum";
-static const char * const searchBarDisplayKey = "searchBarDisplay";
-static const char * const zeroConfenableKey = "zeroConfenable";
-static const char * const md5HashKey = "md5Hash";
-
-// voip preferences
-static const char * const playDtmfKey = "playDtmf";
-static const char * const playTonesKey = "playTones";
-static const char * const pulseLengthKey = "pulseLength";
-static const char * const symmetricRtpKey = "symmetric";
-static const char * const zidFileKey = "zidFile";
-
-// addressbook preferences
-static const char * const photoKey = "photo";
-static const char * const enabledKey = "enabled";
-static const char * const listKey = "list";
-static const char * const maxResultsKey = "maxResults";
-static const char * const businessKey = "business";
-static const char * const homeKey = "home";
-static const char * const mobileKey = "mobile";
-
-// hooks preferences
-static const char * const iax2EnabledKey = "iax2Enabled";
-static const char * const numberAddPrefixKey = "numberAddPrefix";
-static const char * const numberEnabledKey = "numberEnabled";
-static const char * const sipEnabledKey = "sipEnabled";
-static const char * const urlCommandKey = "urlCommand";
-static const char * const urlSipFieldKey = "urlSipField";
-
-// audio preferences
-static const char * const alsamapKey = "alsa";
-static const char * const pulsemapKey = "pulse";
-static const char * const cardinKey = "cardIn";
-static const char * const cardoutKey = "cardOut";
-static const char * const cardringKey = "cardRing";
-static const char * const pluginKey = "plugin";
-static const char * const smplrateKey = "smplRate";
-static const char * const devicePlaybackKey = "devicePlayback";
-static const char * const deviceRecordKey = "deviceRecord";
-static const char * const deviceRingtoneKey = "deviceRingtone";
-static const char * const recordpathKey = "recordPath";
-static const char * const alwaysRecordingKey = "alwaysRecording";
-static const char * const volumemicKey = "volumeMic";
-static const char * const volumespkrKey = "volumeSpkr";
-static const char * const noiseReduceKey = "noiseReduce";
-static const char * const echoCancelKey = "echoCancel";
-static const char * const echoTailKey = "echoTailLength";
-static const char * const echoDelayKey = "echoDelayLength";
-
-// shortcut preferences
-static const char * const hangupShortKey = "hangUp";
-static const char * const pickupShortKey = "pickUp";
-static const char * const popupShortKey = "popupWindow";
-static const char * const toggleHoldShortKey = "toggleHold";
-static const char * const togglePickupHangupShortKey = "togglePickupHangup";
-
 class AudioLayer;
 
 class Preferences : public Serializable {
     public:
         static const char * const DFT_ZONE;
+        static const char * const REGISTRATION_EXPIRE_KEY;
 
         Preferences();
 
-        virtual void serialize(Conf::YamlEmitter *emitter);
-
-        virtual void unserialize(const Conf::MappingNode *map);
+        virtual void serialize(Conf::YamlEmitter &emitter);
+        virtual void unserialize(const Conf::MappingNode &map);
 
         std::string getAccountOrder() const {
             return accountOrder_;
@@ -206,9 +142,8 @@ class VoipPreference : public Serializable {
     public:
         VoipPreference();
 
-        virtual void serialize(Conf::YamlEmitter *emitter);
-
-        virtual void unserialize(const Conf::MappingNode *map);
+        virtual void serialize(Conf::YamlEmitter &emitter);
+        virtual void unserialize(const Conf::MappingNode &map);
 
         bool getPlayDtmf() const {
             return playDtmf_;
@@ -261,9 +196,8 @@ class AddressbookPreference : public Serializable {
     public:
         AddressbookPreference();
 
-        virtual void serialize(Conf::YamlEmitter *emitter);
-
-        virtual void unserialize(const Conf::MappingNode *map);
+        virtual void serialize(Conf::YamlEmitter &emitter);
+        virtual void unserialize(const Conf::MappingNode &map);
 
         bool getPhoto() const {
             return photo_;
@@ -338,9 +272,8 @@ class HookPreference : public Serializable {
         HookPreference();
         HookPreference(const std::map<std::string, std::string> &settings);
 
-        virtual void serialize(Conf::YamlEmitter *emitter);
-
-        virtual void unserialize(const Conf::MappingNode *map);
+        virtual void serialize(Conf::YamlEmitter &emitter);
+        virtual void unserialize(const Conf::MappingNode &map);
 
         std::string getNumberAddPrefix() const {
             if (numberEnabled_)
@@ -375,9 +308,8 @@ class AudioPreference : public Serializable {
             audioApi_ = api;
         }
 
-        virtual void serialize(Conf::YamlEmitter *emitter);
-
-        virtual void unserialize(const Conf::MappingNode *map);
+        virtual void serialize(Conf::YamlEmitter &emitter);
+        virtual void unserialize(const Conf::MappingNode &map);
 
         // alsa preference
         int getCardin() const {
@@ -534,8 +466,8 @@ class AudioPreference : public Serializable {
 class ShortcutPreferences : public Serializable {
     public:
         ShortcutPreferences();
-        virtual void serialize(Conf::YamlEmitter *emitter);
-        virtual void unserialize(const Conf::MappingNode *map);
+        virtual void serialize(Conf::YamlEmitter &emitter);
+        virtual void unserialize(const Conf::MappingNode &map);
 
         void setShortcuts(std::map<std::string, std::string> shortcuts);
         std::map<std::string, std::string> getShortcuts() const;
diff --git a/daemon/src/sfl_types.h b/daemon/src/sfl_types.h
new file mode 100644
index 0000000000000000000000000000000000000000..382eb1c84cd87bf7b286b01a2ad6bf89b150ea21
--- /dev/null
+++ b/daemon/src/sfl_types.h
@@ -0,0 +1,42 @@
+/*
+ *  Copyright (C) 2004-2012 Savoir-Faire Linux Inc.
+ *  Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ *  Additional permission under GNU GPL version 3 section 7:
+ *
+ *  If you modify this program, or any covered work, by linking or
+ *  combining it with the OpenSSL project's OpenSSL library (or a
+ *  modified version of that library), containing parts covered by the
+ *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
+ *  grants you additional permission to convey the resulting work.
+ *  Corresponding Source for a non-source form of such a combination
+ *  shall include the source code for the parts of OpenSSL used as well
+ *  as that of the covered work.
+ */
+
+#ifndef SFL_TYPES_H_
+#define SFL_TYPES_H_
+
+#include <cstddef> // for size_t
+
+typedef short SFLDataFormat;
+typedef signed short SINT16;
+typedef signed int SINT32;
+
+static const size_t SIZEBUF = 400000; /** About 12 sec of buffering at 8000 Hz*/
+
+#endif // SFL_TYPES_H_
diff --git a/daemon/src/sip/sdes_negotiator.cpp b/daemon/src/sip/sdes_negotiator.cpp
index 63bb00b8231cfd851da960d22c409b1ac7d3500c..a8eed12a7dc671daaef40ff38a78b0e962ab01ab 100644
--- a/daemon/src/sip/sdes_negotiator.cpp
+++ b/daemon/src/sip/sdes_negotiator.cpp
@@ -32,7 +32,7 @@
 #include "pattern.h"
 
 #include <cstdio>
-#include <memory>
+#include <tr1/memory>
 #include <iostream>
 #include <sstream>
 #include <algorithm>
@@ -61,7 +61,7 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse()
     // syntax :
     //a=crypto:tag 1*WSP crypto-suite 1*WSP key-params *(1*WSP session-param)
 
-    std::auto_ptr<Pattern> generalSyntaxPattern, tagPattern, cryptoSuitePattern,
+    std::tr1::shared_ptr<Pattern> generalSyntaxPattern, tagPattern, cryptoSuitePattern,
         keyParamsPattern;
 
     try {
@@ -178,7 +178,7 @@ bool SdesNegotiator::negotiate()
     std::vector<CryptoAttribute *> cryptoAttributeVector = parse();
     std::vector<CryptoAttribute *>::iterator iter_offer = cryptoAttributeVector.begin();
 
-    std::vector<CryptoSuiteDefinition>::iterator iter_local = localCapabilities_.begin();
+    std::vector<CryptoSuiteDefinition>::const_iterator iter_local = localCapabilities_.begin();
 
     bool negotiationSuccess = false;
 
@@ -197,10 +197,11 @@ bool SdesNegotiator::negotiate()
                     authTagLength_ = cryptoSuite_.substr(cryptoSuite_.size()-2, 2);
                 }
 
-                iter_local++;
+                ++iter_local;
             }
-            delete(*iter_offer);
-            iter_offer++;
+            delete *iter_offer;
+            *iter_offer = 0;
+            ++iter_offer;
         }
 
     } catch (const ParseError& exception) {
diff --git a/daemon/src/sip/sdp.cpp b/daemon/src/sip/sdp.cpp
index 2d81c57f2ab68315eb6a8feacac413cf676f03f4..aa474d8c75865d7d7436cee1ab5c2210eccbe04f 100644
--- a/daemon/src/sip/sdp.cpp
+++ b/daemon/src/sip/sdp.cpp
@@ -35,7 +35,7 @@
 #endif
 
 #include "sdp.h"
-#include "global.h"
+#include "logger.h"
 #include "manager.h"
 #include <cassert>
 
@@ -62,11 +62,11 @@ Sdp::Sdp(pj_pool_t *pool)
     , remoteIpAddr_()
     , localAudioPort_(1234)
 #ifdef SFL_VIDEO
-	, localVideoPort_(1235)
+    , localVideoPort_(1235)
 #endif
     , remoteAudioPort_(1236)
 #ifdef SFL_VIDEO
-	, remoteVideoPort_(1237)
+    , remoteVideoPort_(1237)
 #endif
     , zrtpHelloHash_()
     , srtpCrypto_()
@@ -82,26 +82,26 @@ void Sdp::setActiveLocalSdpSession(const pjmedia_sdp_session *sdp)
     pjmedia_sdp_media *current = activeLocalSession_->media[0];
     std::string type(current->desc.media.ptr, current->desc.media.slen);
 
-	for (unsigned j = 0; j < current->desc.fmt_count; j++) {
-		static const pj_str_t STR_RTPMAP = { (char*) "rtpmap", 6 };
-	    pjmedia_sdp_attr *attribute = pjmedia_sdp_media_find_attr(current, &STR_RTPMAP, NULL);
-		if (!attribute)
-			continue;
+    for (unsigned j = 0; j < current->desc.fmt_count; j++) {
+        static const pj_str_t STR_RTPMAP = { (char*) "rtpmap", 6 };
+        pjmedia_sdp_attr *attribute = pjmedia_sdp_media_find_attr(current, &STR_RTPMAP, NULL);
+        if (!attribute)
+            continue;
 
-	    pjmedia_sdp_rtpmap *rtpmap;
-		pjmedia_sdp_attr_to_rtpmap (memPool_, attribute, &rtpmap);
+        pjmedia_sdp_rtpmap *rtpmap;
+        pjmedia_sdp_attr_to_rtpmap (memPool_, attribute, &rtpmap);
 
-	    if (type == "audio") {
-			sfl::Codec *codec = Manager::instance().audioCodecFactory.getCodec((int) pj_strtoul (&rtpmap->pt));
-			if (codec)
-				sessionAudioMedia_.push_back(codec);
-	    }
+        if (type == "audio") {
+            sfl::Codec *codec = Manager::instance().audioCodecFactory.getCodec((int) pj_strtoul (&rtpmap->pt));
+            if (codec)
+                sessionAudioMedia_.push_back(codec);
+        }
 #ifdef SFL_VIDEO
         else if (type == "video") {
-	    	sessionVideoMedia_.push_back(std::string(rtpmap->enc_name.ptr, rtpmap->enc_name.slen));
-	    }
+            sessionVideoMedia_.push_back(std::string(rtpmap->enc_name.ptr, rtpmap->enc_name.slen));
+        }
 #endif
-	}
+    }
 }
 
 
@@ -138,19 +138,19 @@ void Sdp::setActiveRemoteSdpSession(const pjmedia_sdp_session *sdp)
 std::string Sdp::getSessionVideoCodec() const
 {
     if (sessionVideoMedia_.empty())
-    	return "";
+        return "";
     return sessionVideoMedia_[0];
 }
 #endif
 
 std::string Sdp::getAudioCodecName() const
 {
-	try {
-		sfl::AudioCodec *codec = getSessionAudioMedia();
-		return codec ? codec->getMimeSubtype() : "";
-	} catch (...) {
-		return "";
-	}
+    try {
+        sfl::AudioCodec *codec = getSessionAudioMedia();
+        return codec ? codec->getMimeSubtype() : "";
+    } catch (...) {
+        return "";
+    }
 }
 
 sfl::AudioCodec* Sdp::getSessionAudioMedia() const
@@ -177,27 +177,27 @@ pjmedia_sdp_media *Sdp::setMediaDescriptorLine(bool audio)
 
     med->desc.fmt_count = audio ? audio_codec_list_.size() : video_codec_list_.size();
     for (unsigned i = 0; i < med->desc.fmt_count; ++i) {
-    	unsigned clock_rate;
-    	std::string enc_name;
-    	int payload;
-
-    	if (audio) {
-    		sfl::Codec *codec = audio_codec_list_[i];
-    		payload = codec->getPayloadType();
-    		enc_name = codec->getMimeSubtype();
-			clock_rate = codec->getClockRate();
-    		// G722 require G722/8000 media description even if it is 16000 codec
-    		if (codec->getPayloadType () == 9)
-    			clock_rate = 8000;
-		} else {
-    		enc_name = video_codec_list_[i];
-    		clock_rate = 90000;
-    		payload = dynamic_payload++;
-    	}
-
-    	std::ostringstream s;
-    	s << payload;
-    	pj_strdup2 (memPool_, &med->desc.fmt[i], s.str().c_str());
+        unsigned clock_rate;
+        std::string enc_name;
+        int payload;
+
+        if (audio) {
+            sfl::Codec *codec = audio_codec_list_[i];
+            payload = codec->getPayloadType();
+            enc_name = codec->getMimeSubtype();
+            clock_rate = codec->getClockRate();
+            // G722 require G722/8000 media description even if it is 16000 codec
+            if (codec->getPayloadType () == 9)
+                clock_rate = 8000;
+        } else {
+            enc_name = video_codec_list_[i];
+            clock_rate = 90000;
+            payload = dynamic_payload++;
+        }
+
+        std::ostringstream s;
+        s << payload;
+        pj_strdup2 (memPool_, &med->desc.fmt[i], s.str().c_str());
 
         // Add a rtpmap field for each codec
         // We could add one only for dynamic payloads because the codecs with static RTP payloads
@@ -205,7 +205,7 @@ pjmedia_sdp_media *Sdp::setMediaDescriptorLine(bool audio)
         // connection, the rtpmap attribute will be useful to specify for which codec it is applicable
         pjmedia_sdp_rtpmap rtpmap;
 
-		rtpmap.pt = med->desc.fmt[i];
+        rtpmap.pt = med->desc.fmt[i];
         rtpmap.enc_name = pj_str((char*) enc_name.c_str());
         rtpmap.clock_rate = clock_rate;
         rtpmap.param.ptr = ((char* const)"");
@@ -239,9 +239,9 @@ pjmedia_sdp_media *Sdp::setMediaDescriptorLine(bool /*audio*/)
 
     med->desc.fmt_count = audio_codec_list_.size();
     for (unsigned i = 0; i < med->desc.fmt_count; ++i) {
-    	unsigned clock_rate;
-    	std::string enc_name;
-    	int payload;
+        unsigned clock_rate;
+        std::string enc_name;
+        int payload;
 
         sfl::Codec *codec = audio_codec_list_[i];
         payload = codec->getPayloadType();
@@ -252,8 +252,8 @@ pjmedia_sdp_media *Sdp::setMediaDescriptorLine(bool /*audio*/)
             clock_rate = 8000;
 
         std::ostringstream s;
-    	s << payload;
-    	pj_strdup2 (memPool_, &med->desc.fmt[i], s.str().c_str());
+        s << payload;
+        pj_strdup2 (memPool_, &med->desc.fmt[i], s.str().c_str());
 
         // Add a rtpmap field for each codec
         // We could add one only for dynamic payloads because the codecs with static RTP payloads
@@ -261,7 +261,7 @@ pjmedia_sdp_media *Sdp::setMediaDescriptorLine(bool /*audio*/)
         // connection, the rtpmap attribute will be useful to specify for which codec it is applicable
         pjmedia_sdp_rtpmap rtpmap;
 
-		rtpmap.pt = med->desc.fmt[i];
+        rtpmap.pt = med->desc.fmt[i];
         rtpmap.enc_name = pj_str ((char*) enc_name.c_str());
         rtpmap.clock_rate = clock_rate;
         rtpmap.param.ptr = ((char* const) "");
@@ -307,12 +307,12 @@ void Sdp::setLocalMediaVideoCapabilities(const std::vector<std::string> &videoCo
     video_codec_list_.clear();
     const std::vector<std::string> &codecs_list = sfl_video::getCodecList();
     for (unsigned i = 0; i < videoCodecs.size(); ++i) {
-    	const std::string &codec = videoCodecs[i];
+        const std::string &codec = videoCodecs[i];
         for (unsigned j = 0; j < codecs_list.size(); ++j) {
             if (codecs_list[j] == codec) {
                 video_codec_list_.push_back(codec);
                 break;
-			}
+            }
         }
     }
 }
@@ -324,13 +324,13 @@ void Sdp::setLocalMediaCapabilities(const std::vector<int> &selectedCodecs)
         WARN("No selected codec while building local SDP offer");
 
     audio_codec_list_.clear();
-	for (std::vector<int>::const_iterator i = selectedCodecs.begin(); i != selectedCodecs.end(); ++i) {
-		sfl::Codec *codec = Manager::instance().audioCodecFactory.getCodec(*i);
-		if (codec)
-			audio_codec_list_.push_back(codec);
-		else
-			WARN("SDP: Couldn't find audio codec");
-	}
+    for (std::vector<int>::const_iterator i = selectedCodecs.begin(); i != selectedCodecs.end(); ++i) {
+        sfl::Codec *codec = Manager::instance().audioCodecFactory.getCodec(*i);
+        if (codec)
+            audio_codec_list_.push_back(codec);
+        else
+            WARN("SDP: Couldn't find audio codec");
+    }
 }
 
 namespace {
@@ -338,7 +338,7 @@ namespace {
     {
         char buffer[2048];
         size_t size = pjmedia_sdp_print(session, buffer, sizeof(buffer));
-        std::string sessionStr(buffer, size);
+        std::string sessionStr(buffer, std::min(size, sizeof(buffer)));
         DEBUG("%s", sessionStr.c_str());
     }
 }
@@ -380,7 +380,7 @@ int Sdp::createLocalSession(const std::vector<int> &selectedCodecs, const std::v
     localSession_->media_count = 2;
     const bool audio = true;
     localSession_->media[0] = setMediaDescriptorLine(audio);
-	localSession_->media[1] = setMediaDescriptorLine(!audio);
+    localSession_->media[1] = setMediaDescriptorLine(!audio);
 
     if (!srtpCrypto_.empty())
         addSdesAttribute(srtpCrypto_);
@@ -396,6 +396,11 @@ int Sdp::createLocalSession(const std::vector<int> &selectedCodecs)
     setLocalMediaCapabilities(selectedCodecs);
 
     localSession_ = PJ_POOL_ZALLOC_T(memPool_, pjmedia_sdp_session);
+    if (!localSession_) {
+        ERROR("Sdp: Could not create local SDP session");
+        return !PJ_SUCCESS;
+    }
+
     localSession_->conn = PJ_POOL_ZALLOC_T(memPool_, pjmedia_sdp_conn);
 
     /* Initialize the fields of the struct */
@@ -460,15 +465,18 @@ void Sdp::receiveOffer(const pjmedia_sdp_session* remote,
                        const std::vector<int> &selectedCodecs,
                        const std::vector<std::string> &videoCodecs)
 {
-    assert(remote);
+    if (!remote) {
+        ERROR("SDP: Remote session is NULL");
+        return;
+    }
 
     DEBUG("SDP: Remote SDP Session:");
     printSession(remote);
 
     if (!localSession_ and createLocalSession (selectedCodecs, videoCodecs) != PJ_SUCCESS) {
-		ERROR("SDP: Failed to create initial offer");
-		return;
-	}
+        ERROR("SDP: Failed to create initial offer");
+        return;
+    }
 
     remoteSession_ = pjmedia_sdp_session_clone(memPool_, remote);
 
@@ -487,33 +495,30 @@ void Sdp::receiveOffer(const pjmedia_sdp_session* remote,
     printSession(remote);
 
     if (!localSession_ and createLocalSession(selectedCodecs) != PJ_SUCCESS) {
-		ERROR("SDP: Failed to create initial offer");
-		return;
-	}
+        ERROR("SDP: Failed to create initial offer");
+        return;
+    }
 
     remoteSession_ = pjmedia_sdp_session_clone(memPool_, remote);
 
-    pj_status_t status = pjmedia_sdp_neg_create_w_remote_offer(memPool_, localSession_,
-                         remoteSession_, &negotiator_);
-
-    assert(status == PJ_SUCCESS);
+    if (pjmedia_sdp_neg_create_w_remote_offer(memPool_, localSession_,
+                remoteSession_, &negotiator_) != PJ_SUCCESS) {
+        ERROR("Could not create negotiator with remote offer");
+        negotiator_ = NULL;
+    }
 }
 #endif
 
-void Sdp::receivingAnswerAfterInitialOffer(const pjmedia_sdp_session* remote)
-{
-    assert(pjmedia_sdp_neg_get_state(negotiator_) == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER);
-    assert(pjmedia_sdp_neg_set_remote_answer(memPool_, negotiator_, remote) == PJ_SUCCESS);
-    assert(pjmedia_sdp_neg_get_state(negotiator_) == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO);
-}
-
 void Sdp::startNegotiation()
 {
+    if (negotiator_ == NULL) {
+        ERROR("Sdp: Can't start negotiation with invalid negotiator");
+        return;
+    }
+
     const pjmedia_sdp_session *active_local;
     const pjmedia_sdp_session *active_remote;
 
-    assert(negotiator_);
-
     if (pjmedia_sdp_neg_get_state(negotiator_) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)
         WARN("SDP: Warning: negotiator not in right state for negotiation");
 
@@ -576,7 +581,7 @@ std::vector<std::string> Sdp::getActiveVideoDescription() const
 
     int payload;
     if (sscanf(videoLine.c_str(), "m=video %*d %*s %d", &payload) != 1)
-		payload = 0;
+        payload = 0;
 
     std::ostringstream s;
     s << "a=rtpmap:";
@@ -597,11 +602,11 @@ std::vector<std::string> Sdp::getActiveVideoDescription() const
 
     // get direction string
     static const pj_str_t DIRECTIONS[] = {
-		{(char*) "sendrecv", 8},
-		{(char*) "sendonly", 8},
-		{(char*) "recvonly", 8},
-		{(char*) "inactive", 8},
-		{NULL, 0}
+        {(char*) "sendrecv", 8},
+        {(char*) "sendonly", 8},
+        {(char*) "recvonly", 8},
+        {(char*) "inactive", 8},
+        {NULL, 0}
     };
     pjmedia_sdp_attr *direction = NULL;
 
@@ -648,9 +653,12 @@ void Sdp::addZrtpAttribute(pjmedia_sdp_media* media, std::string hash)
         throw SdpException("Could not add zrtp attribute to media");
 }
 
-
 void Sdp::addAttributeToLocalAudioMedia(const char *attr)
 {
+    if (!localSession_) {
+        ERROR("Sdp: Local session is NULL");
+        return;
+    }
     int i = 0;
     while (pj_stricmp2(&localSession_->media[i]->desc.media, "audio") != 0)
         ++i;
@@ -660,10 +668,14 @@ void Sdp::addAttributeToLocalAudioMedia(const char *attr)
 
 void Sdp::removeAttributeFromLocalAudioMedia(const char *attr)
 {
+   if (!localSession_) {
+        ERROR("Sdp: Local session is NULL");
+        return;
+    }
     int i = 0;
     while (pj_stricmp2(&localSession_->media[i]->desc.media, "audio") != 0)
         ++i;
-    pjmedia_sdp_media_remove_all_attr (localSession_->media[i], attr);
+    pjmedia_sdp_media_remove_all_attr(localSession_->media[i], attr);
 }
 
 #ifdef SFL_VIDEO
diff --git a/daemon/src/sip/sdp.h b/daemon/src/sip/sdp.h
index 4cc947c25264e64268cb183d6feeae6ae3877f3f..4423b3e4fb787b7ab1c6295d6205f8052c7dd18e 100644
--- a/daemon/src/sip/sdp.h
+++ b/daemon/src/sip/sdp.h
@@ -262,13 +262,11 @@ class Sdp {
 #ifdef SFL_VIDEO
         std::string getSessionVideoCodec() const;
 #endif
-
-        void receivingAnswerAfterInitialOffer(const pjmedia_sdp_session* remote);
-
         sfl::AudioCodec* getSessionAudioMedia() const;
 
     private:
         NON_COPYABLE(Sdp);
+        friend class SDPTest;
 
         std::string getLineFromLocalSDP(const std::string &keyword) const;
 
diff --git a/daemon/src/sip/sip_utils.cpp b/daemon/src/sip/sip_utils.cpp
index 8b98f0c44967b399ef4b7c1cb985b5321fdea296..a412c550a39761736c2ec2fc68d453c223ba55a5 100644
--- a/daemon/src/sip/sip_utils.cpp
+++ b/daemon/src/sip/sip_utils.cpp
@@ -29,9 +29,20 @@
  *  as that of the covered work.
  */
 
+#include <pjsip.h>
+#include <pjlib.h>
+#include <pjsip_ua.h>
+#include <pjlib-util.h>
+#include <pjnath.h>
+#include <pjnath/stun_config.h>
+#include <pj/string.h>
+#include <pjsip/sip_msg.h>
+#include <pjsip/sip_types.h>
+#include <pjsip/sip_uri.h>
+#include <pj/list.h>
+
+
 #include "sip_utils.h"
-#include "pj/string.h"
-#include "pjsip/sip_msg.h"
 
 std::string
 sip_utils::fetchHeaderValue(pjsip_msg *msg, const std::string &field)
@@ -51,3 +62,66 @@ sip_utils::fetchHeaderValue(pjsip_msg *msg, const std::string &field)
     else
         return "";
 }
+
+pjsip_route_hdr *
+sip_utils::createRouteSet(const std::string &route, pj_pool_t *hdr_pool)
+{
+    int port = 0;
+    std::string host;
+
+    size_t found = route.find(":");
+
+    if (found != std::string::npos) {
+        host = route.substr(0, found);
+        port = atoi(route.substr(found + 1, route.length()).c_str());
+    } else
+        host = route;
+
+    pjsip_route_hdr *route_set = pjsip_route_hdr_create(hdr_pool);
+    pjsip_route_hdr *routing = pjsip_route_hdr_create(hdr_pool);
+    pjsip_sip_uri *url = pjsip_sip_uri_create(hdr_pool, 0);
+    routing->name_addr.uri = (pjsip_uri*) url;
+    pj_strdup2(hdr_pool, &url->host, host.c_str());
+    url->port = port;
+
+    pj_list_push_back(route_set, pjsip_hdr_clone(hdr_pool, routing));
+
+    return route_set;
+}
+
+
+std::string
+sip_utils::parseDisplayName(const char * buffer)
+{
+    const char* from_header = strstr(buffer, "From: ");
+
+    if (!from_header)
+        return "";
+
+    std::string temp(from_header);
+    size_t begin_displayName = temp.find("\"") + 1;
+    size_t end_displayName = temp.rfind("\"");
+    std::string displayName(temp.substr(begin_displayName, end_displayName - begin_displayName));
+
+    static const size_t MAX_DISPLAY_NAME_SIZE = 25;
+    if (displayName.size() > MAX_DISPLAY_NAME_SIZE)
+        return "";
+
+    return displayName;
+}
+
+void
+sip_utils::stripSipUriPrefix(std::string& sipUri)
+{
+    // Remove sip: prefix
+    static const char SIP_PREFIX[] = "sip:";
+    size_t found = sipUri.find(SIP_PREFIX);
+
+    if (found != std::string::npos)
+        sipUri.erase(found, found + (sizeof SIP_PREFIX) - 1);
+
+    found = sipUri.find("@");
+
+    if (found != std::string::npos)
+        sipUri.erase(found);
+}
diff --git a/daemon/src/sip/sip_utils.h b/daemon/src/sip/sip_utils.h
index 1a8d8bff4200e02312286fd8cad5e3dedfa01e84..4d430af97c99fd307eb7e67483cedba6ee128ef9 100644
--- a/daemon/src/sip/sip_utils.h
+++ b/daemon/src/sip/sip_utils.h
@@ -34,6 +34,8 @@
 
 #include <string>
 
+#include <pjsip/sip_msg.h>
+
 class pjsip_msg;
 
 namespace sip_utils {
@@ -42,6 +44,12 @@ namespace sip_utils {
      * @return Header from SIP message
      */
     std::string fetchHeaderValue(pjsip_msg *msg, const std::string &field);
+
+    pjsip_route_hdr *createRouteSet(const std::string &route, pj_pool_t *hdr_pool);
+
+    void stripSipUriPrefix(std::string& sipUri);
+
+    std::string parseDisplayName(const char * buffer);
 }
 
 #endif // SIP_UTILS_H_
diff --git a/daemon/src/sip/sipaccount.cpp b/daemon/src/sip/sipaccount.cpp
index 7303c053b41af908f787e9d423e674ca5e726afb..3560443fdfb03426c5d22edbb395871381d15583 100644
--- a/daemon/src/sip/sipaccount.cpp
+++ b/daemon/src/sip/sipaccount.cpp
@@ -38,12 +38,12 @@
 #include "sipvoiplink.h"
 #include "config/yamlnode.h"
 #include "config/yamlemitter.h"
+#include "logger.h"
 #include "manager.h"
 #include <pwd.h>
 #include <sstream>
-#include <cassert>
 
-const char * const SIPAccount::IP2IP_PROFILE  = "IP2IP";
+const char * const SIPAccount::IP2IP_PROFILE = "IP2IP";
 const char * const SIPAccount::OVERRTP_STR = "overrtp";
 const char * const SIPAccount::SIPINFO_STR = "sipinfo";
 
@@ -74,7 +74,6 @@ SIPAccount::SIPAccount(const std::string& accountID)
     , stunPort_(PJ_STUN_PORT)
     , dtmfType_(OVERRTP_STR)
     , tlsEnable_("false")
-    , tlsPort_(DEFAULT_SIP_TLS_PORT)
     , tlsCaListFile_()
     , tlsCertificateFile_()
     , tlsPrivateKeyFile_()
@@ -101,7 +100,7 @@ SIPAccount::SIPAccount(const std::string& accountID)
     , link_(SIPVoIPLink::instance())
 {}
 
-void SIPAccount::serialize(Conf::YamlEmitter *emitter)
+void SIPAccount::serialize(Conf::YamlEmitter &emitter)
 {
     using namespace Conf;
     using std::vector;
@@ -166,8 +165,7 @@ void SIPAccount::serialize(Conf::YamlEmitter *emitter)
     ScalarNode notSuppWarning(zrtpNotSuppWarning_);
 
     portstr.str("");
-    portstr << tlsPort_;
-
+    portstr << tlsListenerPort_;
     ScalarNode tlsport(portstr.str());
     ScalarNode certificate(tlsCertificateFile_);
     ScalarNode calist(tlsCaListFile_);
@@ -182,45 +180,45 @@ void SIPAccount::serialize(Conf::YamlEmitter *emitter)
     ScalarNode verifyclient(tlsVerifyServer_);
     ScalarNode verifyserver(tlsVerifyClient_);
 
-    accountmap.setKeyValue(aliasKey, &alias);
-    accountmap.setKeyValue(typeKey, &type);
-    accountmap.setKeyValue(idKey, &id);
-    accountmap.setKeyValue(usernameKey, &username);
-    accountmap.setKeyValue(hostnameKey, &hostname);
-    accountmap.setKeyValue(accountEnableKey, &enable);
-    accountmap.setKeyValue(mailboxKey, &mailbox);
-    accountmap.setKeyValue(registrationExpireKey, &expire);
-    accountmap.setKeyValue(interfaceKey, &interface);
-    accountmap.setKeyValue(portKey, &port);
-    accountmap.setKeyValue(stunServerKey, &stunServer);
-    accountmap.setKeyValue(stunEnabledKey, &stunEnabled);
-    accountmap.setKeyValue(publishAddrKey, &publishAddr);
-    accountmap.setKeyValue(publishPortKey, &publishPort);
-    accountmap.setKeyValue(sameasLocalKey, &sameasLocal);
-    accountmap.setKeyValue(serviceRouteKey, &serviceRoute);
-    accountmap.setKeyValue(updateContactHeaderKey, &contactUpdateEnabled);
-    accountmap.setKeyValue(dtmfTypeKey, &dtmfType);
-    accountmap.setKeyValue(displayNameKey, &displayName);
-    accountmap.setKeyValue(codecsKey, &codecs);
+    accountmap.setKeyValue(ALIAS_KEY, &alias);
+    accountmap.setKeyValue(TYPE_KEY, &type);
+    accountmap.setKeyValue(ID_KEY, &id);
+    accountmap.setKeyValue(USERNAME_KEY, &username);
+    accountmap.setKeyValue(HOSTNAME_KEY, &hostname);
+    accountmap.setKeyValue(ACCOUNT_ENABLE_KEY, &enable);
+    accountmap.setKeyValue(MAILBOX_KEY, &mailbox);
+    accountmap.setKeyValue(Preferences::REGISTRATION_EXPIRE_KEY, &expire);
+    accountmap.setKeyValue(INTERFACE_KEY, &interface);
+    accountmap.setKeyValue(PORT_KEY, &port);
+    accountmap.setKeyValue(STUN_SERVER_KEY, &stunServer);
+    accountmap.setKeyValue(STUN_ENABLED_KEY, &stunEnabled);
+    accountmap.setKeyValue(PUBLISH_ADDR_KEY, &publishAddr);
+    accountmap.setKeyValue(PUBLISH_PORT_KEY, &publishPort);
+    accountmap.setKeyValue(SAME_AS_LOCAL_KEY, &sameasLocal);
+    accountmap.setKeyValue(SERVICE_ROUTE_KEY, &serviceRoute);
+    accountmap.setKeyValue(UPDATE_CONTACT_HEADER_KEY, &contactUpdateEnabled);
+    accountmap.setKeyValue(DTMF_TYPE_KEY, &dtmfType);
+    accountmap.setKeyValue(DISPLAY_NAME_KEY, &displayName);
+    accountmap.setKeyValue(CODECS_KEY, &codecs);
 #ifdef SFL_VIDEO
-    accountmap.setKeyValue(videocodecsKey, &vcodecs);
+    accountmap.setKeyValue(VIDEO_CODECS_KEY, &vcodecs);
 #endif
-    accountmap.setKeyValue(ringtonePathKey, &ringtonePath);
-    accountmap.setKeyValue(ringtoneEnabledKey, &ringtoneEnabled);
+    accountmap.setKeyValue(RINGTONE_PATH_KEY, &ringtonePath);
+    accountmap.setKeyValue(RINGTONE_ENABLED_KEY, &ringtoneEnabled);
 
-    accountmap.setKeyValue(srtpKey, &srtpmap);
-    srtpmap.setKeyValue(srtpEnableKey, &srtpenabled);
-    srtpmap.setKeyValue(keyExchangeKey, &keyExchange);
-    srtpmap.setKeyValue(rtpFallbackKey, &rtpFallback);
+    accountmap.setKeyValue(SRTP_KEY, &srtpmap);
+    srtpmap.setKeyValue(SRTP_ENABLE_KEY, &srtpenabled);
+    srtpmap.setKeyValue(KEY_EXCHANGE_KEY, &keyExchange);
+    srtpmap.setKeyValue(RTP_FALLBACK_KEY, &rtpFallback);
 
-    accountmap.setKeyValue(zrtpKey, &zrtpmap);
-    zrtpmap.setKeyValue(displaySasKey, &displaySas);
-    zrtpmap.setKeyValue(displaySasOnceKey, &displaySasOnce);
-    zrtpmap.setKeyValue(helloHashEnabledKey, &helloHashEnabled);
-    zrtpmap.setKeyValue(notSuppWarningKey, &notSuppWarning);
+    accountmap.setKeyValue(ZRTP_KEY, &zrtpmap);
+    zrtpmap.setKeyValue(DISPLAY_SAS_KEY, &displaySas);
+    zrtpmap.setKeyValue(DISPLAY_SAS_ONCE_KEY, &displaySasOnce);
+    zrtpmap.setKeyValue(HELLO_HASH_ENABLED_KEY, &helloHashEnabled);
+    zrtpmap.setKeyValue(NOT_SUPP_WARNING_KEY, &notSuppWarning);
 
     SequenceNode credentialseq(NULL);
-    accountmap.setKeyValue(credKey, &credentialseq);
+    accountmap.setKeyValue(CRED_KEY, &credentialseq);
 
     std::vector<std::map<std::string, std::string> >::const_iterator it;
 
@@ -233,23 +231,23 @@ void SIPAccount::serialize(Conf::YamlEmitter *emitter)
         credentialseq.addNode(map);
     }
 
-    accountmap.setKeyValue(tlsKey, &tlsmap);
-    tlsmap.setKeyValue(tlsPortKey, &tlsport);
-    tlsmap.setKeyValue(certificateKey, &certificate);
-    tlsmap.setKeyValue(calistKey, &calist);
-    tlsmap.setKeyValue(ciphersKey, &ciphers);
-    tlsmap.setKeyValue(tlsEnableKey, &tlsenabled);
-    tlsmap.setKeyValue(methodKey, &tlsmethod);
-    tlsmap.setKeyValue(timeoutKey, &timeout);
-    tlsmap.setKeyValue(tlsPasswordKey, &tlspassword);
-    tlsmap.setKeyValue(privateKeyKey, &privatekey);
-    tlsmap.setKeyValue(requireCertifKey, &requirecertif);
-    tlsmap.setKeyValue(serverKey, &server);
-    tlsmap.setKeyValue(verifyClientKey, &verifyclient);
-    tlsmap.setKeyValue(verifyServerKey, &verifyserver);
+    accountmap.setKeyValue(TLS_KEY, &tlsmap);
+    tlsmap.setKeyValue(TLS_PORT_KEY, &tlsport);
+    tlsmap.setKeyValue(CERTIFICATE_KEY, &certificate);
+    tlsmap.setKeyValue(CALIST_KEY, &calist);
+    tlsmap.setKeyValue(CIPHERS_KEY, &ciphers);
+    tlsmap.setKeyValue(TLS_ENABLE_KEY, &tlsenabled);
+    tlsmap.setKeyValue(METHOD_KEY, &tlsmethod);
+    tlsmap.setKeyValue(TIMEOUT_KEY, &timeout);
+    tlsmap.setKeyValue(TLS_PASSWORD_KEY, &tlspassword);
+    tlsmap.setKeyValue(PRIVATE_KEY_KEY, &privatekey);
+    tlsmap.setKeyValue(REQUIRE_CERTIF_KEY, &requirecertif);
+    tlsmap.setKeyValue(SERVER_KEY, &server);
+    tlsmap.setKeyValue(VERIFY_CLIENT_KEY, &verifyclient);
+    tlsmap.setKeyValue(VERIFY_SERVER_KEY, &verifyserver);
 
     try {
-        emitter->serializeAccount(&accountmap);
+        emitter.serializeAccount(&accountmap);
     } catch (const YamlEmitterException &e) {
         ERROR("ConfigTree: %s", e.what());
     }
@@ -258,7 +256,7 @@ void SIPAccount::serialize(Conf::YamlEmitter *emitter)
     Sequence::iterator seqit;
 
     for (seqit = seq->begin(); seqit != seq->end(); ++seqit) {
-        MappingNode *node = (MappingNode*)*seqit;
+        MappingNode *node = static_cast<MappingNode*>(*seqit);
         delete node->getValue(CONFIG_ACCOUNT_USERNAME);
         delete node->getValue(CONFIG_ACCOUNT_PASSWORD);
         delete node->getValue(CONFIG_ACCOUNT_REALM);
@@ -266,77 +264,67 @@ void SIPAccount::serialize(Conf::YamlEmitter *emitter)
     }
 }
 
-void SIPAccount::unserialize(const Conf::MappingNode *map)
+void SIPAccount::unserialize(const Conf::MappingNode &map)
 {
     using namespace Conf;
-    MappingNode *srtpMap;
-    MappingNode *tlsMap;
-    MappingNode *zrtpMap;
-
-    assert(map);
-
-    map->getValue(aliasKey, &alias_);
-    map->getValue(typeKey, &type_);
-    map->getValue(usernameKey, &username_);
-    map->getValue(hostnameKey, &hostname_);
-    map->getValue(accountEnableKey, &enabled_);
-    map->getValue(mailboxKey, &mailBox_);
-    map->getValue(codecsKey, &codecStr_);
+
+    map.getValue(ALIAS_KEY, &alias_);
+    map.getValue(TYPE_KEY, &type_);
+    map.getValue(USERNAME_KEY, &username_);
+    map.getValue(HOSTNAME_KEY, &hostname_);
+    map.getValue(ACCOUNT_ENABLE_KEY, &enabled_);
+    map.getValue(MAILBOX_KEY, &mailBox_);
+    map.getValue(CODECS_KEY, &codecStr_);
 #ifdef SFL_VIDEO
     std::string vcodecs;
-    map->getValue(videocodecsKey, &vcodecs);
+    map.getValue(VIDEO_CODECS_KEY, &vcodecs);
 #endif
-
     // Update codec list which one is used for SDP offer
     setActiveCodecs(ManagerImpl::unserialize(codecStr_));
 
-#ifdef SFL_VIDEO
-    setActiveVideoCodecs(Manager::instance().unserialize(vcodecs));
-#endif
-
-    map->getValue(ringtonePathKey, &ringtonePath_);
-    map->getValue(ringtoneEnabledKey, &ringtoneEnabled_);
-    map->getValue(registrationExpireKey, &registrationExpire_);
-    map->getValue(interfaceKey, &interface_);
-    int port;
-    map->getValue(portKey, &port);
+    map.getValue(RINGTONE_PATH_KEY, &ringtonePath_);
+    map.getValue(RINGTONE_ENABLED_KEY, &ringtoneEnabled_);
+    map.getValue(Preferences::REGISTRATION_EXPIRE_KEY, &registrationExpire_);
+    map.getValue(INTERFACE_KEY, &interface_);
+    int port = DEFAULT_SIP_PORT;
+    map.getValue(PORT_KEY, &port);
     localPort_ = port;
-    map->getValue(publishAddrKey, &publishedIpAddress_);
-    map->getValue(publishPortKey, &port);
+    map.getValue(PUBLISH_ADDR_KEY, &publishedIpAddress_);
+    map.getValue(PUBLISH_PORT_KEY, &port);
     publishedPort_ = port;
-    map->getValue(sameasLocalKey, &publishedSameasLocal_);
+    map.getValue(SAME_AS_LOCAL_KEY, &publishedSameasLocal_);
 
     std::string dtmfType;
-    map->getValue(dtmfTypeKey, &dtmfType);
+    map.getValue(DTMF_TYPE_KEY, &dtmfType);
     dtmfType_ = dtmfType;
 
-    map->getValue(serviceRouteKey, &serviceRoute_);
-    map->getValue(updateContactHeaderKey, &contactUpdateEnabled_);
+    map.getValue(SERVICE_ROUTE_KEY, &serviceRoute_);
+    map.getValue(UPDATE_CONTACT_HEADER_KEY, &contactUpdateEnabled_);
 
     // stun enabled
-    map->getValue(stunEnabledKey, &stunEnabled_);
-    map->getValue(stunServerKey, &stunServer_);
+    map.getValue(STUN_ENABLED_KEY, &stunEnabled_);
+    map.getValue(STUN_SERVER_KEY, &stunServer_);
 
     // Init stun server name with default server name
     stunServerName_ = pj_str((char*) stunServer_.data());
 
-    map->getValue(displayNameKey, &displayName_);
+    map.getValue(DISPLAY_NAME_KEY, &displayName_);
 
     std::vector<std::map<std::string, std::string> > creds;
 
-    YamlNode *credNode = map->getValue(credKey);
+    YamlNode *credNode = map.getValue(CRED_KEY);
 
     /* We check if the credential key is a sequence
      * because it was a mapping in a previous version of
      * the configuration file.
      */
     if (credNode && credNode->getType() == SEQUENCE) {
-        SequenceNode *credSeq = (SequenceNode *) credNode;
+        SequenceNode *credSeq = static_cast<SequenceNode *>(credNode);
         Sequence::iterator it;
         Sequence *seq = credSeq->getSequence();
 
         for (it = seq->begin(); it != seq->end(); ++it) {
-            MappingNode *cred = (MappingNode *)(*it);
+            MappingNode *cred = static_cast<MappingNode *>(*it);
             std::string user;
             std::string pass;
             std::string realm;
@@ -355,7 +343,7 @@ void SIPAccount::unserialize(const Conf::MappingNode *map)
         // migration from old file format
         std::map<std::string, std::string> credmap;
         std::string password;
-        map->getValue(passwordKey, &password);
+        map.getValue(PASSWORD_KEY, &password);
 
         credmap[CONFIG_ACCOUNT_USERNAME] = username_;
         credmap[CONFIG_ACCOUNT_PASSWORD] = password;
@@ -366,43 +354,45 @@ void SIPAccount::unserialize(const Conf::MappingNode *map)
     setCredentials(creds);
 
     // get srtp submap
-    srtpMap = (MappingNode *)(map->getValue(srtpKey));
+    MappingNode *srtpMap = static_cast<MappingNode *>(map.getValue(SRTP_KEY));
 
     if (srtpMap) {
-        srtpMap->getValue(srtpEnableKey, &srtpEnabled_);
-        srtpMap->getValue(keyExchangeKey, &srtpKeyExchange_);
-        srtpMap->getValue(rtpFallbackKey, &srtpFallback_);
+        srtpMap->getValue(SRTP_ENABLE_KEY, &srtpEnabled_);
+        srtpMap->getValue(KEY_EXCHANGE_KEY, &srtpKeyExchange_);
+        srtpMap->getValue(RTP_FALLBACK_KEY, &srtpFallback_);
     }
 
     // get zrtp submap
-    zrtpMap = (MappingNode *)(map->getValue(zrtpKey));
+    MappingNode *zrtpMap = static_cast<MappingNode *>(map.getValue(ZRTP_KEY));
 
     if (zrtpMap) {
-        zrtpMap->getValue(displaySasKey, &zrtpDisplaySas_);
-        zrtpMap->getValue(displaySasOnceKey, &zrtpDisplaySasOnce_);
-        zrtpMap->getValue(helloHashEnabledKey, &zrtpHelloHash_);
-        zrtpMap->getValue(notSuppWarningKey, &zrtpNotSuppWarning_);
+        zrtpMap->getValue(DISPLAY_SAS_KEY, &zrtpDisplaySas_);
+        zrtpMap->getValue(DISPLAY_SAS_ONCE_KEY, &zrtpDisplaySasOnce_);
+        zrtpMap->getValue(HELLO_HASH_ENABLED_KEY, &zrtpHelloHash_);
+        zrtpMap->getValue(NOT_SUPP_WARNING_KEY, &zrtpNotSuppWarning_);
     }
 
     // get tls submap
-    tlsMap = (MappingNode *)(map->getValue(tlsKey));
+    MappingNode *tlsMap = static_cast<MappingNode *>(map.getValue(TLS_KEY));
 
     if (tlsMap) {
-        tlsMap->getValue(tlsEnableKey, &tlsEnable_);
-        tlsMap->getValue(tlsPortKey, &tlsPort_);
-        tlsMap->getValue(certificateKey, &tlsCertificateFile_);
-        tlsMap->getValue(calistKey, &tlsCaListFile_);
-        tlsMap->getValue(ciphersKey, &tlsCiphers_);
-        tlsMap->getValue(methodKey, &tlsMethod_);
-        tlsMap->getValue(tlsPasswordKey, &tlsPassword_);
-        tlsMap->getValue(privateKeyKey, &tlsPrivateKeyFile_);
-        tlsMap->getValue(requireCertifKey, &tlsRequireClientCertificate_);
-        tlsMap->getValue(serverKey, &tlsServerName_);
-        tlsMap->getValue(verifyClientKey, &tlsVerifyServer_);
-        tlsMap->getValue(verifyServerKey, &tlsVerifyClient_);
+        tlsMap->getValue(TLS_ENABLE_KEY, &tlsEnable_);
+        std::string tlsPort;
+        tlsMap->getValue(TLS_PORT_KEY, &tlsPort);
+        tlsListenerPort_ = atoi(tlsPort.c_str());
+        tlsMap->getValue(CERTIFICATE_KEY, &tlsCertificateFile_);
+        tlsMap->getValue(CALIST_KEY, &tlsCaListFile_);
+        tlsMap->getValue(CIPHERS_KEY, &tlsCiphers_);
+        tlsMap->getValue(METHOD_KEY, &tlsMethod_);
+        tlsMap->getValue(TLS_PASSWORD_KEY, &tlsPassword_);
+        tlsMap->getValue(PRIVATE_KEY_KEY, &tlsPrivateKeyFile_);
+        tlsMap->getValue(REQUIRE_CERTIF_KEY, &tlsRequireClientCertificate_);
+        tlsMap->getValue(SERVER_KEY, &tlsServerName_);
+        tlsMap->getValue(VERIFY_CLIENT_KEY, &tlsVerifyServer_);
+        tlsMap->getValue(VERIFY_SERVER_KEY, &tlsVerifyClient_);
         // FIXME
-        tlsMap->getValue(timeoutKey, &tlsNegotiationTimeoutSec_);
-        tlsMap->getValue(timeoutKey, &tlsNegotiationTimeoutMsec_);
+        tlsMap->getValue(TIMEOUT_KEY, &tlsNegotiationTimeoutSec_);
+        tlsMap->getValue(TIMEOUT_KEY, &tlsNegotiationTimeoutMsec_);
     }
 }
 
@@ -451,10 +441,7 @@ void SIPAccount::setAccountDetails(std::map<std::string, std::string> details)
     srtpKeyExchange_ = details[CONFIG_SRTP_KEY_EXCHANGE];
 
     // TLS settings
-    // The TLS listener is unique and globally defined through IP2IP_PROFILE
-    if (isIP2IP())
-        tlsListenerPort_ = atoi(details[CONFIG_TLS_LISTENER_PORT].c_str());
-
+    tlsListenerPort_ = atoi(details[CONFIG_TLS_LISTENER_PORT].c_str());
     tlsEnable_ = details[CONFIG_TLS_ENABLE];
     tlsCaListFile_ = details[CONFIG_TLS_CA_LIST_FILE];
     tlsCertificateFile_ = details[CONFIG_TLS_CERTIFICATE_FILE];
@@ -665,8 +652,6 @@ pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum(const std::string& method)
 void SIPAccount::initTlsConfiguration()
 {
     // TLS listener is unique and should be only modified through IP2IP_PROFILE
-    tlsListenerPort_ = tlsPort_;
-
     pjsip_tls_setting_default(&tlsSetting_);
 
     pj_cstr(&tlsSetting_.ca_list_file, tlsCaListFile_.c_str());
@@ -901,6 +886,7 @@ std::string computeMd5HashFromCredential(const std::string& username,
     MD5_APPEND(&pms, realm.data(), realm.length());
     MD5_APPEND(&pms, ":", 1);
     MD5_APPEND(&pms, password.data(), password.length());
+#undef MD5_APPEND
 
     unsigned char digest[16];
     pj_md5_final(&pms, digest);
@@ -916,14 +902,18 @@ std::string computeMd5HashFromCredential(const std::string& username,
 
 void SIPAccount::setCredentials(const std::vector<std::map<std::string, std::string> >& creds)
 {
+    // we can not authenticate without credentials
+    if (creds.empty()) {
+        ERROR("SIPAccount: Cannot authenticate with empty credentials list");
+        return;
+    }
+
     using std::vector;
     using std::string;
     using std::map;
 
     bool md5HashingEnabled = Manager::instance().preferences.getMd5Hash();
 
-    assert(creds.size() > 0); // we can not authenticate without credentials
-
     credentials_ = creds;
 
     /* md5 hashing */
@@ -980,7 +970,8 @@ void SIPAccount::setCredentials(const std::vector<std::map<std::string, std::str
     }
 }
 
-const std::vector<std::map<std::string, std::string> > &SIPAccount::getCredentials()
+const std::vector<std::map<std::string, std::string> > &
+SIPAccount::getCredentials() const
 {
     return credentials_;
 }
@@ -1012,8 +1003,7 @@ std::map<std::string, std::string> SIPAccount::getIp2IpDetails() const
     portstr << localPort_;
     ip2ipAccountDetails[CONFIG_LOCAL_PORT] = portstr.str();
 
-    std::map<std::string, std::string> tlsSettings;
-    tlsSettings = getTlsSettings();
+    std::map<std::string, std::string> tlsSettings(getTlsSettings());
     std::copy(tlsSettings.begin(), tlsSettings.end(), std::inserter(
                   ip2ipAccountDetails, ip2ipAccountDetails.end()));
 
@@ -1022,8 +1012,8 @@ std::map<std::string, std::string> SIPAccount::getIp2IpDetails() const
 
 std::map<std::string, std::string> SIPAccount::getTlsSettings() const
 {
-    std::map<std::string, std::string> tlsSettings;
     assert(isIP2IP());
+    std::map<std::string, std::string> tlsSettings;
 
     std::stringstream portstr;
     portstr << tlsListenerPort_;
diff --git a/daemon/src/sip/sipaccount.h b/daemon/src/sip/sipaccount.h
index 0237f253f7dc658c12c03d63333aff74f0b72940..c116031b84d3ff03be06d3cf9d544dcb3b2b06f8 100644
--- a/daemon/src/sip/sipaccount.h
+++ b/daemon/src/sip/sipaccount.h
@@ -47,48 +47,47 @@ namespace Conf {
     class YamlEmitter;
     class MappingNode;
     // SIP specific configuration keys
-    const char *const interfaceKey = "interface";
-    const char *const portKey = "port";
-    const char *const publishAddrKey = "publishAddr";
-    const char *const publishPortKey = "publishPort";
-    const char *const sameasLocalKey = "sameasLocal";
-    const char *const dtmfTypeKey = "dtmfType";
-    const char *const serviceRouteKey = "serviceRoute";
-    const char *const updateContactHeaderKey = "updateContact";
+    const char *const INTERFACE_KEY = "interface";
+    const char *const PORT_KEY = "port";
+    const char *const PUBLISH_ADDR_KEY = "publishAddr";
+    const char *const PUBLISH_PORT_KEY = "publishPort";
+    const char *const SAME_AS_LOCAL_KEY = "sameasLocal";
+    const char *const DTMF_TYPE_KEY = "dtmfType";
+    const char *const SERVICE_ROUTE_KEY = "serviceRoute";
+    const char *const UPDATE_CONTACT_HEADER_KEY = "updateContact";
 
     // TODO: write an object to store credential which implement serializable
-    const char *const srtpKey = "srtp";
-    const char *const srtpEnableKey = "enable";
-    const char *const keyExchangeKey = "keyExchange";
-    const char *const rtpFallbackKey = "rtpFallback";
+    const char *const SRTP_KEY = "srtp";
+    const char *const SRTP_ENABLE_KEY = "enable";
+    const char *const KEY_EXCHANGE_KEY = "keyExchange";
+    const char *const RTP_FALLBACK_KEY = "rtpFallback";
 
     // TODO: wirte an object to store zrtp params wich implement serializable
-    const char *const zrtpKey = "zrtp";
-    const char *const displaySasKey = "displaySas";
-    const char *const displaySasOnceKey = "displaySasOnce";
-    const char *const helloHashEnabledKey = "helloHashEnabled";
-    const char *const notSuppWarningKey = "notSuppWarning";
+    const char *const ZRTP_KEY = "zrtp";
+    const char *const DISPLAY_SAS_KEY = "displaySas";
+    const char *const DISPLAY_SAS_ONCE_KEY = "displaySasOnce";
+    const char *const HELLO_HASH_ENABLED_KEY = "helloHashEnabled";
+    const char *const NOT_SUPP_WARNING_KEY = "notSuppWarning";
 
     // TODO: write an object to store tls params which implement serializable
-    const char *const tlsKey = "tls";
-    const char *const tlsPortKey = "tlsPort";
-    const char *const certificateKey = "certificate";
-    const char *const calistKey = "calist";
-    const char *const ciphersKey = "ciphers";
-    const char *const tlsEnableKey = "enable";
-    const char *const methodKey = "method";
-    const char *const timeoutKey = "timeout";
-    const char *const tlsPasswordKey = "password";
-    const char *const privateKeyKey = "privateKey";
-    const char *const requireCertifKey = "requireCertif";
-    const char *const serverKey = "server";
-    const char *const verifyClientKey = "verifyClient";
-    const char *const verifyServerKey = "verifyServer";
-
-    const char *const stunEnabledKey = "stunEnabled";
-    const char *const stunServerKey = "stunServer";
-
-    const char *const credKey = "credential";
+    const char *const TLS_KEY = "tls";
+    const char *const TLS_PORT_KEY = "tlsPort";
+    const char *const CERTIFICATE_KEY = "certificate";
+    const char *const CALIST_KEY = "calist";
+    const char *const CIPHERS_KEY = "ciphers";
+    const char *const TLS_ENABLE_KEY = "enable";
+    const char *const METHOD_KEY = "method";
+    const char *const TIMEOUT_KEY = "timeout";
+    const char *const TLS_PASSWORD_KEY = "password";
+    const char *const PRIVATE_KEY_KEY = "privateKey";
+    const char *const REQUIRE_CERTIF_KEY = "requireCertif";
+    const char *const SERVER_KEY = "server";
+    const char *const VERIFY_CLIENT_KEY = "verifyClient";
+    const char *const VERIFY_SERVER_KEY = "verifyServer";
+
+    const char *const STUN_ENABLED_KEY = "stunEnabled";
+    const char *const STUN_SERVER_KEY = "stunServer";
+    const char *const CRED_KEY = "credential";
 }
 
 class SIPVoIPLink;
@@ -126,13 +125,13 @@ class SIPAccount : public Account {
          * Serialize internal state of this account for configuration
          * @param YamlEmitter the configuration engine which generate the configuration file
          */
-        virtual void serialize(Conf::YamlEmitter *emitter);
+        virtual void serialize(Conf::YamlEmitter &emitter);
 
         /**
          * Populate the internal state for this account based on info stored in the configuration file
          * @param The configuration node for this account
          */
-        virtual void unserialize(const Conf::MappingNode *map);
+        virtual void unserialize(const Conf::MappingNode &map);
 
         /**
          * Set the internal state for this account, mainly used to manage account details from the client application.
@@ -206,7 +205,9 @@ class SIPAccount : public Account {
         }
 
         void setCredentials(const std::vector<std::map<std::string, std::string> >& details);
-        const std::vector<std::map<std::string, std::string> > &getCredentials();
+
+        const std::vector<std::map<std::string, std::string> > &
+        getCredentials() const;
 
         /**
          * A client sendings a REGISTER request MAY suggest an expiration
@@ -640,11 +641,6 @@ class SIPAccount : public Account {
          */
         std::string tlsEnable_;
 
-        /**
-         * Specify the TLS port
-         */
-        int tlsPort_;
-
         /**
          * Certificate autority file
          */
diff --git a/daemon/src/sip/siptransport.cpp b/daemon/src/sip/siptransport.cpp
index c43ed74c52a7a8a490674ddda9eeedc8a4b31909..ece189460152aec6e91facca6c2fd6891f3ddb88 100644
--- a/daemon/src/sip/siptransport.cpp
+++ b/daemon/src/sip/siptransport.cpp
@@ -43,22 +43,22 @@
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <sys/ioctl.h>
-#include <unistd.h>
-#include <linux/if.h>
+#include <arpa/inet.h>
+#include <net/if.h>
+#include <stdexcept>
+#include <sstream>
 
+#include "logger.h"
 #include "siptransport.h"
 #include "manager.h"
 
-#include "sip/sdp.h"
-#include "sipcall.h"
 #include "sipaccount.h"
-#include "eventthread.h"
-#include "sdes_negotiator.h"
 
 #include "dbus/dbusmanager.h"
-#include "dbus/callmanager.h"
 #include "dbus/configurationmanager.h"
 
+static const char * const DEFAULT_INTERFACE = "default";
+
 static pjsip_transport *localUDPTransport_ = NULL; /** The default transport (5060) */
 
 std::string SipTransport::getSIPLocalIP()
@@ -137,12 +137,7 @@ std::vector<std::string> SipTransport::getAllIpInterface()
 }
 
 SipTransport::SipTransport(pjsip_endpoint *endpt, pj_caching_pool *cp, pj_pool_t *pool) : transportMap_(), stunSocketMap_(), cp_(cp), pool_(pool), endpt_(endpt)
-{
-}
-
-SipTransport::~SipTransport()
-{
-}
+{}
 
 pj_bool_t
 stun_sock_on_status_cb(pj_stun_sock * /*stun_sock*/, pj_stun_sock_op op,
@@ -188,10 +183,15 @@ stun_sock_on_rx_data_cb(pj_stun_sock * /*stun_sock*/, void * /*pkt*/,
 
 pj_status_t SipTransport::createStunResolver(pj_str_t serverName, pj_uint16_t port)
 {
-    pj_stun_config stunCfg;
-    pj_stun_config_init(&stunCfg, &cp_->factory, 0, pjsip_endpt_get_ioqueue(endpt_), pjsip_endpt_get_timer_heap(endpt_));
+    std::string stunResolverName(serverName.ptr, serverName.slen);
+    if (stunSocketMap_.find(stunResolverName) != stunSocketMap_.end()) {
+        DEBUG("SipTransport: %s already added", stunResolverName.c_str());
+        return PJ_SUCCESS;
+    }
 
-    DEBUG("***************** Create Stun Resolver *********************");
+    pj_stun_config stunCfg;
+    pj_stun_config_init(&stunCfg, &cp_->factory, 0,
+            pjsip_endpt_get_ioqueue(endpt_), pjsip_endpt_get_timer_heap(endpt_));
 
     static const pj_stun_sock_cb stun_sock_cb = {
         stun_sock_on_rx_data_cb,
@@ -199,27 +199,30 @@ pj_status_t SipTransport::createStunResolver(pj_str_t serverName, pj_uint16_t po
         stun_sock_on_status_cb
     };
 
-    pj_stun_sock *stun_sock;
-    std::string stunResolverName(serverName.ptr, serverName.slen);
-    pj_status_t status = pj_stun_sock_create(&stunCfg, stunResolverName.c_str(), pj_AF_INET(), &stun_sock_cb, NULL, NULL, &stun_sock);
-
-    // store socket inside list
-    DEBUG("     insert %s resolver in map", stunResolverName.c_str());
-    stunSocketMap_.insert(std::pair<std::string, pj_stun_sock *>(stunResolverName, stun_sock));
+    pj_stun_sock *stun_sock = NULL;
+    pj_status_t status = pj_stun_sock_create(&stunCfg,
+            stunResolverName.c_str(), pj_AF_INET(), &stun_sock_cb, NULL, NULL,
+            &stun_sock);
 
     if (status != PJ_SUCCESS) {
         char errmsg[PJ_ERR_MSG_SIZE];
         pj_strerror(status, errmsg, sizeof(errmsg));
-        ERROR("SipTransport: Error creating STUN socket for %.*s: %s", (int) serverName.slen, serverName.ptr, errmsg);
+        ERROR("SipTransport: Error creating STUN socket for %.*s: %s",
+                (int) serverName.slen, serverName.ptr, errmsg);
         return status;
     }
 
     status = pj_stun_sock_start(stun_sock, &serverName, port, NULL);
 
-    if (status != PJ_SUCCESS) {
+    // store socket inside list
+    if (status == PJ_SUCCESS) {
+        DEBUG("SipTransport: Adding %s resolver", stunResolverName.c_str());
+        stunSocketMap_[stunResolverName] = stun_sock;
+    } else {
         char errmsg[PJ_ERR_MSG_SIZE];
         pj_strerror(status, errmsg, sizeof(errmsg));
-        DEBUG("SipTransport: Error starting STUN socket for %.*s: %s", (int) serverName.slen, serverName.ptr, errmsg);
+        DEBUG("SipTransport: Error starting STUN socket for %.*s: %s",
+                (int) serverName.slen, serverName.ptr, errmsg);
         pj_stun_sock_destroy(stun_sock);
     }
 
@@ -235,7 +238,8 @@ pj_status_t SipTransport::destroyStunResolver(const std::string &serverName)
 
     if (it != stunSocketMap_.end()) {
         DEBUG("SipTransport: Deleting stun resolver %s", it->first.c_str());
-        pj_stun_sock_destroy(it->second);
+        if (it->second)
+            pj_stun_sock_destroy(it->second);
         stunSocketMap_.erase(it);
     }
 
@@ -243,116 +247,129 @@ pj_status_t SipTransport::destroyStunResolver(const std::string &serverName)
 }
 
 
-void SipTransport::createTlsListener(pj_uint16_t tlsListenerPort, pjsip_tls_setting *tlsSetting, pjsip_tpfactory **listener)
+pjsip_tpfactory* SipTransport::createTlsListener(SIPAccount &account)
 {
     pj_sockaddr_in local_addr;
     pj_sockaddr_in_init(&local_addr, 0, 0);
-    local_addr.sin_port = pj_htons(tlsListenerPort);
+    local_addr.sin_port = pj_htons(account.getTlsListenerPort());
 
-    if (tlsSetting == NULL) {
+    if (account.getTlsSetting() == NULL) {
         ERROR("SipTransport: Error TLS settings not specified");
-        return;
+        return NULL;
     }
 
-    if (listener == NULL) {
-        ERROR("SipTransport: Error no pointer to store new TLS listener");
-        return;
-    }
+    std::string interface(account.getLocalInterface());
+    std::string listeningAddress;
+    if (interface == DEFAULT_INTERFACE)
+        listeningAddress = getSIPLocalIP();
+    else
+        listeningAddress = getInterfaceAddrFromName(interface);
+
+    if (listeningAddress.empty())
+        ERROR("SipTransport: Could not determine ip address for this transport");
 
     pj_str_t pjAddress;
-    pj_cstr(&pjAddress, PJ_INADDR_ANY);
+    pj_cstr(&pjAddress, listeningAddress.c_str());
     pj_sockaddr_in_set_str_addr(&local_addr, &pjAddress);
-    std::string localIP(getSIPLocalIP());
-
-    pjsip_host_port a_name = {
-        pj_str((char*) localIP.c_str()),
-        local_addr.sin_port
-    };
+    pj_sockaddr_in_set_port(&local_addr, account.getTlsListenerPort());
 
-    pjsip_tls_transport_start(endpt_, tlsSetting, &local_addr, &a_name, 1, listener);
+    pjsip_tpfactory *listener = NULL;
+    if (pjsip_tls_transport_start(endpt_, account.getTlsSetting(), &local_addr,
+                NULL, 1, &listener) != PJ_SUCCESS) {
+        ERROR("SipTransport: Error Failed to start tls listener");
+        listener = NULL;
+    }
+    return listener;
 }
 
 
 pjsip_transport *
-SipTransport::createTlsTransport(const std::string &remoteAddr,
-                                pj_uint16_t tlsListenerPort,
-                                pjsip_tls_setting *tlsSettings)
+SipTransport::createTlsTransport(SIPAccount &account)
 {
-    pjsip_transport *transport = NULL;
+    std::string remoteSipUri(account.getServerUri());
+    static const char SIPS_PREFIX[] = "<sips:";
+    size_t sips = remoteSipUri.find(SIPS_PREFIX) + (sizeof SIPS_PREFIX) - 1;
+    size_t trns = remoteSipUri.find(";transport");
+    std::string remoteAddr(remoteSipUri.substr(sips, trns-sips));
+    std::string ipAddr = "";
+    int port = DEFAULT_SIP_TLS_PORT;
+
+    // parse c string
+    size_t pos = remoteAddr.find(":");
+    if (pos != std::string::npos) {
+        ipAddr = remoteAddr.substr(0, pos);
+        port = atoi(remoteAddr.substr(pos + 1, remoteAddr.length() - pos).c_str());
+    } else {
+        ipAddr = remoteAddr;
+    }
 
     pj_str_t remote;
-    pj_cstr(&remote, remoteAddr.c_str());
+    pj_cstr(&remote, ipAddr.c_str());
 
     pj_sockaddr_in rem_addr;
-    pj_sockaddr_in_init(&rem_addr, &remote, (pj_uint16_t) DEFAULT_SIP_TLS_PORT);
+    pj_sockaddr_in_init(&rem_addr, &remote, (pj_uint16_t) port);
 
     // The local tls listener
     static pjsip_tpfactory *localTlsListener = NULL;
 
     if (localTlsListener == NULL)
-        createTlsListener(tlsListenerPort, tlsSettings, &localTlsListener);
+        localTlsListener = createTlsListener(account);
 
+    DEBUG("SipTransport: Get new tls transport from transport manager");
+    pjsip_transport *transport = NULL;
     pjsip_endpt_acquire_transport(endpt_, PJSIP_TRANSPORT_TLS, &rem_addr,
                                   sizeof rem_addr, NULL, &transport);
-
     if (transport == NULL)
         ERROR("SipTransport: Could not create new TLS transport\n");
 
     return transport;
 }
 
-void SipTransport::createSipTransport(SIPAccount *account)
+void SipTransport::createSipTransport(SIPAccount &account)
 {
-    if (account == NULL) {
-        ERROR("SipTransport: Account is NULL while creating sip transport");
-        return;
-    }
-
     shutdownSipTransport(account);
 
-    if (account->isTlsEnabled()) {
-        std::string remoteSipUri(account->getServerUri());
-        static const char SIPS_PREFIX[] = "<sips:";
-        size_t sips = remoteSipUri.find(SIPS_PREFIX) + (sizeof SIPS_PREFIX) - 1;
-        size_t trns = remoteSipUri.find(";transport");
-        std::string remoteAddr(remoteSipUri.substr(sips, trns-sips));
-
-        pjsip_transport *transport = createTlsTransport(remoteAddr, account->getTlsListenerPort(), account->getTlsSetting());
-        account->transport_ = transport;
-    } else if (account->isStunEnabled()) {
-        pjsip_transport *transport = createStunTransport(account->getStunServerName(), account->getStunPort());
-        account->transport_ = transport;
-    }
-    else {
-        pjsip_transport *transport = createUdpTransport(account->getLocalInterface(), account->getLocalPort());
-        account->transport_ = transport;
+    if (account.isTlsEnabled()) {
+        account.transport_ = createTlsTransport(account);
+    } else if (account.isStunEnabled()) {
+        account.transport_ = createStunTransport(account);
+        if (account.transport_ == NULL) {
+            WARN("SipTransport: falling back to UDP transport");
+            account.transport_ = createUdpTransport(account.getLocalInterface(), account.getLocalPort());
+        }
+    } else {
+        account.transport_ = createUdpTransport(account.getLocalInterface(), account.getLocalPort());
     }
 
-    if (!account->transport_) {
+    if (!account.transport_) {
+        DEBUG("SipTransport: Looking into previously created transport map for %s:%d",
+                account.getLocalInterface().c_str(), account.getLocalPort());
         // Could not create new transport, this transport may already exists
-        account->transport_ = transportMap_[account->getLocalPort()];
-
-        if (account->transport_)
-            pjsip_transport_add_ref(account->transport_);
-        else {
-            account->transport_ = localUDPTransport_;
-            account->setLocalPort(localUDPTransport_->local_name.port);
+        pjsip_transport *cachedTransport = transportMap_[account.getLocalPort()];
+
+        if (cachedTransport) {
+            account.transport_ = cachedTransport;
+            pjsip_transport_add_ref(account.transport_);
+        } else {
+            if (account.isTlsEnabled())
+                throw std::runtime_error("SipTransport: Could not create TLS connection");
+            assert(localUDPTransport_);
+            account.transport_ = localUDPTransport_;
+            account.setLocalPort(localUDPTransport_->local_name.port);
         }
     }
 }
 
 void SipTransport::createDefaultSipUdpTransport()
 {
-    pj_uint16_t port = 0;
-    int counter = 0;
-
     DEBUG("SipTransport: Create default sip udp transport");
 
     SIPAccount *account = Manager::instance().getIP2IPAccount();
 
     pjsip_transport *transport = NULL;
+    pj_uint16_t port = 0;
     static const int DEFAULT_TRANSPORT_ATTEMPTS = 5;
-    for (; transport == NULL and counter < DEFAULT_TRANSPORT_ATTEMPTS; ++counter) {
+    for (int counter = 0; transport == NULL and counter < DEFAULT_TRANSPORT_ATTEMPTS; ++counter) {
         // if default udp transport fails to init on 5060, try other ports
         // with 2 step size increment (i.e. 5062, 5064, ...)
         port = account->getLocalPort() + (counter * 2);
@@ -382,7 +399,6 @@ SipTransport::createUdpTransport(const std::string &interface, unsigned int port
     DEBUG("SipTransport: Create UDP transport on %s:%d", interface.c_str(), port);
 
     // determine the ip address for this transport
-    static const char * const DEFAULT_INTERFACE = "default";
     std::string listeningAddress;
     if (interface == DEFAULT_INTERFACE)
         listeningAddress = getSIPLocalIP();
@@ -399,22 +415,22 @@ SipTransport::createUdpTransport(const std::string &interface, unsigned int port
         return NULL;
     }
 
-    pj_sockaddr boundAddr;
+    std::ostringstream fullAddress;
+    fullAddress << listeningAddress << ":" << listeningPort;
     pj_str_t udpString;
-    pj_cstr(&udpString, listeningAddress.c_str());
+    pj_cstr(&udpString, fullAddress.str().c_str());
+    pj_sockaddr boundAddr;
     pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &udpString, &boundAddr);
     pj_status_t status;
     pjsip_transport *transport = NULL;
     if (boundAddr.addr.sa_family == pj_AF_INET()) {
         status = pjsip_udp_transport_start(endpt_, &boundAddr.ipv4, NULL, 1, &transport);
         if (status != PJ_SUCCESS) {
-            ERROR("Failed to create IPv4 UDP transport");
             return NULL;
         }
     } else if (boundAddr.addr.sa_family == pj_AF_INET6()) {
         status = pjsip_udp_transport_start6(endpt_, &boundAddr.ipv6, NULL, 1, &transport);
         if (status != PJ_SUCCESS) {
-            ERROR("Failed to create IPv6 UDP transport");
             return NULL;
         }
     }
@@ -429,21 +445,25 @@ SipTransport::createUdpTransport(const std::string &interface, unsigned int port
 
 pjsip_tpselector *SipTransport::initTransportSelector(pjsip_transport *transport, pj_pool_t *tp_pool) const
 {
-    assert(transport);
+    if (!transport) {
+        ERROR("SipTransport: transport is not initialized");
+        return NULL;
+    }
     pjsip_tpselector *tp = (pjsip_tpselector *) pj_pool_zalloc(tp_pool, sizeof(pjsip_tpselector));
     tp->type = PJSIP_TPSELECTOR_TRANSPORT;
     tp->u.transport = transport;
     return tp;
 }
 
-pjsip_transport *SipTransport::createStunTransport(pj_str_t serverName, pj_uint16_t port)
+pjsip_transport *SipTransport::createStunTransport(SIPAccount &account)
 {
-    pjsip_transport *transport;
+    pj_str_t serverName = account.getStunServerName();
+    pj_uint16_t port = account.getStunPort();
 
-    DEBUG("SipTransport: Create stun transport  server name: %s, port: %d", serverName, port);// account->getStunPort());
+    DEBUG("SipTransport: Create STUN transport  server name: %s, port: %d", serverName, port);
     if (createStunResolver(serverName, port) != PJ_SUCCESS) {
         ERROR("SipTransport: Can't resolve STUN server");
-        Manager::instance().getDbusManager()->getConfigurationManager()->stunStatusFailure("");
+        Manager::instance().getDbusManager()->getConfigurationManager()->stunStatusFailure(account.getAccountID());
         return NULL;
     }
 
@@ -453,13 +473,13 @@ pjsip_transport *SipTransport::createStunTransport(pj_str_t serverName, pj_uint1
 
     if (pj_sockaddr_in_init(&boundAddr, &serverName, 0) != PJ_SUCCESS) {
         ERROR("SipTransport: Can't initialize IPv4 socket on %*s:%i", serverName.slen, serverName.ptr, port);
-        Manager::instance().getDbusManager()->getConfigurationManager()->stunStatusFailure("");
+        Manager::instance().getDbusManager()->getConfigurationManager()->stunStatusFailure(account.getAccountID());
         return NULL;
     }
 
     if (pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, &sock) != PJ_SUCCESS) {
         ERROR("SipTransport: Can't create or bind socket");
-        Manager::instance().getDbusManager()->getConfigurationManager()->stunStatusFailure("");
+        Manager::instance().getDbusManager()->getConfigurationManager()->stunStatusFailure(account.getAccountID());
         return NULL;
     }
 
@@ -469,7 +489,7 @@ pjsip_transport *SipTransport::createStunTransport(pj_str_t serverName, pj_uint1
     if (pjstun_get_mapped_addr(&cp_->factory, 1, &sock, &serverName, port, &serverName, port, &pub_addr) != PJ_SUCCESS) {
         ERROR("SipTransport: Can't contact STUN server");
         pj_sock_close(sock);
-        Manager::instance().getDbusManager()->getConfigurationManager()->stunStatusFailure("");
+        Manager::instance().getDbusManager()->getConfigurationManager()->stunStatusFailure(account.getAccountID());
         return NULL;
     }
 
@@ -478,6 +498,7 @@ pjsip_transport *SipTransport::createStunTransport(pj_str_t serverName, pj_uint1
         pj_ntohs(pub_addr.sin_port)
     };
 
+    pjsip_transport *transport;
     pjsip_udp_transport_attach2(endpt_, PJSIP_TRANSPORT_UDP, sock, &a_name, 1,
                                 &transport);
 
@@ -486,17 +507,17 @@ pjsip_transport *SipTransport::createStunTransport(pj_str_t serverName, pj_uint1
     return transport;
 }
 
-void SipTransport::shutdownSipTransport(SIPAccount *account)
+void SipTransport::shutdownSipTransport(SIPAccount &account)
 {
-    if (account->isStunEnabled()) {
-        pj_str_t stunServerName = account->getStunServerName();
+    if (account.isStunEnabled()) {
+        pj_str_t stunServerName = account.getStunServerName();
         std::string server(stunServerName.ptr, stunServerName.slen);
         destroyStunResolver(server);
     }
 
-    if (account->transport_) {
-        pjsip_transport_dec_ref(account->transport_);
-        account->transport_ = NULL;
+    if (account.transport_) {
+        pjsip_transport_dec_ref(account.transport_);
+        account.transport_ = NULL;
     }
 }
 
diff --git a/daemon/src/sip/siptransport.h b/daemon/src/sip/siptransport.h
index 21e2c8780157f153f81f01f5357afca75a97a0fd..79b874b705844ff30190454a6286b19f0bd21a87 100644
--- a/daemon/src/sip/siptransport.h
+++ b/daemon/src/sip/siptransport.h
@@ -48,8 +48,6 @@ class SIPAccount;
 class SipTransport {
     public:
         SipTransport(pjsip_endpoint *endpt, pj_caching_pool *cp, pj_pool_t *pool);
-        ~SipTransport();
-
         static std::string getSIPLocalIP();
 
         /**
@@ -94,14 +92,6 @@ class SipTransport {
             pool_ = pool;
         }
 
-        /**
-         * Create a new stun resolver. Store it inside the array. Resolve public address for this
-         * server name.
-         * @param serverName The name of the stun server
-         * @param port number
-         */
-        pj_status_t createStunResolver(pj_str_t serverName, pj_uint16_t port);
-
         pj_status_t destroyStunResolver(const std::string &serverName);
 
         /**
@@ -109,17 +99,10 @@ class SipTransport {
          * transport type specified in account settings
          * @param account The account for which a transport must be created.
          */
-        void createSipTransport(SIPAccount *account);
+        void createSipTransport(SIPAccount &account);
 
         void createDefaultSipUdpTransport();
 
-        /**
-        * Create SIP UDP transport from account's setting
-        * @param account The account for which a transport must be created.
-        */
-        pjsip_transport *createUdpTransport(const std::string &interface,
-                                            unsigned int port);
-
         /**
          * Initialize the transport selector
          * @param transport		A transport associated with an account
@@ -129,56 +112,58 @@ class SipTransport {
         pjsip_tpselector *initTransportSelector(pjsip_transport *transport, pj_pool_t *tp_pool) const;
 
         /**
-         * Create The default TLS listener which is global to the application. This means that
-         * only one TLS connection can be established for the momment.
-         * @param the port number to create the TCP socket
-         * @param pjsip's tls settings for the transport to be created which contains:
-         *      - path to ca certificate list file
-         *      - path to certertificate file
-         *      - path to private key file
-         *      - the password for the file
-         *      - the TLS method
-         * @param a pointer to store the listener created, in our case this is a static pointer
+         * This function unset the transport for a given account.
+         */
+        void shutdownSipTransport(SIPAccount &account);
+
+        /**
+         * Get the correct address to use (ie advertised) from
+         * a uri. The corresponding transport that should be used
+         * with that uri will be discovered.
+         *
+         * @param uri The uri from which we want to discover the address to use
+         * @param transport The transport to use to discover the address
          */
-        void createTlsListener(pj_uint16_t, pjsip_tls_setting *, pjsip_tpfactory **);
+        void findLocalAddressFromTransport(pjsip_transport *transport, pjsip_transport_type_e transportType, std::string &address, std::string &port) const;
 
+    private:
+        NON_COPYABLE(SipTransport);
+
+        pjsip_transport *
+        createStunTransport(SIPAccount &account);
         /**
          * Create a connection oriented TLS transport and register to the specified remote address.
          * First, initialize the TLS listener sole instance. This means that, for the momment, only one TLS transport
          * is allowed to be created in the application. Any subsequent account attempting to
          * register a new using this transport even if new settings are specified.
-         * @param the remote address for this transport to be connected
-         * @param the local port to initialize the TCP socket
-         * @param pjsip's tls transport parameters
+         * @param the account that is creating the TLS transport
          */
         pjsip_transport *
-        createTlsTransport(const std::string &remoteAddr,
-                           pj_uint16_t tlsListenerPort,
-                           pjsip_tls_setting *tlsSetting);
+        createTlsTransport(SIPAccount &account);
 
         /**
-         * Create a UDP transport using stun server to resove public address
-         * @param account The account for which a transport must be created.
+         * Create The default TLS listener which is global to the application. This means that
+         * only one TLS connection can be established for the momment.
+         * @param the SIPAccount for which we are creating the TLS listener
+         * @return a pointer to the new listener
          */
-        pjsip_transport *createStunTransport(pj_str_t serverName, pj_uint16_t port);
+        pjsip_tpfactory *
+        createTlsListener(SIPAccount &account);
 
         /**
-         * This function unset the transport for a given account.
+         * Create a new stun resolver. Store it inside the array. Resolve public address for this
+         * server name.
+         * @param serverName The name of the stun server
+         * @param port number
          */
-        void shutdownSipTransport(SIPAccount *account);
+        pj_status_t createStunResolver(pj_str_t serverName, pj_uint16_t port);
 
         /**
-         * Get the correct address to use (ie advertised) from
-         * a uri. The corresponding transport that should be used
-         * with that uri will be discovered.
-         *
-         * @param uri The uri from which we want to discover the address to use
-         * @param transport The transport to use to discover the address
-         */
-        void findLocalAddressFromTransport(pjsip_transport *transport, pjsip_transport_type_e transportType, std::string &address, std::string &port) const;
-
-    private:
-        NON_COPYABLE(SipTransport);
+        * Create SIP UDP transport from account's setting
+        * @param account The account for which a transport must be created.
+        */
+        pjsip_transport *createUdpTransport(const std::string &interface,
+                                            unsigned int port);
 
         /**
          * UDP Transports are stored in this map in order to retreive them in case
diff --git a/daemon/src/sip/sipvoiplink.cpp b/daemon/src/sip/sipvoiplink.cpp
index bb1b6da1cca027dca08149abca1fb349975fc655..79328eda1eb4f8c3e13ebb3de9686f2284e182c4 100644
--- a/daemon/src/sip/sipvoiplink.cpp
+++ b/daemon/src/sip/sipvoiplink.cpp
@@ -1,6 +1,5 @@
 /*
  *  Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc.
- *
  *  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
  *  Author: Yun Liu <yun.liu@savoirfairelinux.com>
  *  Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com>
@@ -36,9 +35,11 @@
 #include "config.h"
 #endif
 
+#include "sip_utils.h"
 
 #include "sipvoiplink.h"
 #include "manager.h"
+#include "logger.h"
 
 #include "sip/sdp.h"
 #include "sip/pattern.h"
@@ -70,15 +71,13 @@
 #include <istream>
 #include <utility> // for std::pair
 
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/ioctl.h>
-#include <linux/if.h>
-
 #include <map>
 
 using namespace sfl;
 
+SIPVoIPLink *SIPVoIPLink::instance_ = 0;
+bool SIPVoIPLink::destroyed_ = false;
+
 namespace {
 
 /** A map to retreive SFLphone internal call id
@@ -98,7 +97,7 @@ static pj_caching_pool pool_cache, *cp_ = &pool_cache;
 static pj_pool_t *pool_;
 static pjsip_endpoint *endpt_;
 static pjsip_module mod_ua_;
-static pj_thread_t *thread;
+static pj_thread_t *thread_;
 
 void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status);
 void sdp_request_offer_cb(pjsip_inv_session *inv, const pjmedia_sdp_session *offer);
@@ -124,31 +123,6 @@ int SIPSessionReinvite(SIPCall *);
  */
 void onCallTransfered(pjsip_inv_session *inv, pjsip_rx_data *rdata);
 
-pjsip_route_hdr *createRouteSet(const std::string &route, pj_pool_t *hdr_pool)
-{
-    int port = 0;
-    std::string host;
-
-    size_t found = route.find(":");
-
-    if (found != std::string::npos) {
-        host = route.substr(0, found);
-        port = atoi(route.substr(found + 1, route.length()).c_str());
-    } else
-        host = route;
-
-    pjsip_route_hdr *route_set = pjsip_route_hdr_create(hdr_pool);
-    pjsip_route_hdr *routing = pjsip_route_hdr_create(hdr_pool);
-    pjsip_sip_uri *url = pjsip_sip_uri_create(hdr_pool, 0);
-    routing->name_addr.uri = (pjsip_uri*) url;
-    pj_strdup2(hdr_pool, &url->host, host.c_str());
-    url->port = port;
-
-    pj_list_push_back(route_set, pjsip_hdr_clone(hdr_pool, routing));
-
-    return route_set;
-}
-
 void handleIncomingOptions(pjsip_rx_data *rdata)
 {
     pjsip_tx_data *tdata;
@@ -200,40 +174,6 @@ pj_bool_t transaction_response_cb(pjsip_rx_data *rdata)
     return PJ_SUCCESS;
 }
 
-std::string parseDisplayName(const char * buffer)
-{
-    const char* from_header = strstr(buffer, "From: ");
-
-    if (!from_header)
-        return "";
-
-    std::string temp(from_header);
-    size_t begin_displayName = temp.find("\"") + 1;
-    size_t end_displayName = temp.rfind("\"");
-    std::string displayName(temp.substr(begin_displayName, end_displayName - begin_displayName));
-
-    static const size_t MAX_DISPLAY_NAME_SIZE = 25;
-    if (displayName.size() > MAX_DISPLAY_NAME_SIZE)
-        return "";
-
-    return displayName;
-}
-
-void stripSipUriPrefix(std::string& sipUri)
-{
-    // Remove sip: prefix
-    static const char SIP_PREFIX[] = "sip:";
-    size_t found = sipUri.find(SIP_PREFIX);
-
-    if (found != std::string::npos)
-        sipUri.erase(found, found + (sizeof SIP_PREFIX) - 1);
-
-    found = sipUri.find("@");
-
-    if (found != std::string::npos)
-        sipUri.erase(found);
-}
-
 pj_bool_t transaction_request_cb(pjsip_rx_data *rdata)
 {
     pjsip_method *method = &rdata->msg_info.msg->line.req.method;
@@ -247,7 +187,7 @@ pj_bool_t transaction_request_cb(pjsip_rx_data *rdata)
     std::string server(sip_from_uri->host.ptr, sip_from_uri->host.slen);
     std::string account_id(Manager::instance().getAccountIdFromNameAndServer(userName, server));
 
-    std::string displayName(parseDisplayName(rdata->msg_info.msg_buf));
+    std::string displayName(sip_utils::parseDisplayName(rdata->msg_info.msg_buf));
 
     if (method->id == PJSIP_OTHER_METHOD) {
         pj_str_t *str = &method->name;
@@ -316,7 +256,7 @@ pj_bool_t transaction_request_cb(pjsip_rx_data *rdata)
     char tmp[PJSIP_MAX_URL_SIZE];
     int length = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, sip_from_uri, tmp, PJSIP_MAX_URL_SIZE);
     std::string peerNumber(tmp, length);
-    stripSipUriPrefix(peerNumber);
+    sip_utils::stripSipUriPrefix(peerNumber);
 
     call->setConnectionState(Call::PROGRESSING);
     call->setPeerNumber(peerNumber);
@@ -380,6 +320,12 @@ pj_bool_t transaction_request_cb(pjsip_rx_data *rdata)
 
     PJ_ASSERT_RETURN(pjsip_dlg_set_transport(dialog, tp) == PJ_SUCCESS, 1);
 
+    if (!call->inv) {
+        ERROR("SIPVoIPLink: Call invite is not initialized");
+        delete call;
+        return false;
+    }
+
     call->inv->mod_data[mod_ua_.id] = call;
 
     // Check whether Replaces header is present in the request and process accordingly.
@@ -412,7 +358,7 @@ pj_bool_t transaction_request_cb(pjsip_rx_data *rdata)
 
         call->setConnectionState(Call::RINGING);
 
-        Manager::instance().incomingCall(call, account_id);
+        Manager::instance().incomingCall(*call, account_id);
         Manager::instance().getAccountLink(account_id)->addCall(call);
     }
 
@@ -422,7 +368,7 @@ pj_bool_t transaction_request_cb(pjsip_rx_data *rdata)
 
 /*************************************************************************************************/
 
-SIPVoIPLink::SIPVoIPLink() : sipTransport(endpt_, cp_, pool_), evThread_(new EventThread(this))
+SIPVoIPLink::SIPVoIPLink() : sipTransport(endpt_, cp_, pool_), evThread_(this)
 {
 #define TRY(ret) do { \
     if (ret != PJ_SUCCESS) \
@@ -494,14 +440,19 @@ SIPVoIPLink::SIPVoIPLink() : sipTransport(endpt_, cp_, pool_), evThread_(new Eve
     TRY(pjsip_replaces_init_module(endpt_));
 #undef TRY
 
-    evThread_->start();
+    handlingEvents_ = true;
+    evThread_.start();
 }
 
 SIPVoIPLink::~SIPVoIPLink()
 {
-    delete evThread_;
-    pj_thread_join(thread);
-    pj_thread_destroy(thread);
+    handlingEvents_ = false;
+    if (thread_) {
+        pj_thread_join(thread_);
+        pj_thread_destroy(thread_);
+        DEBUG("PJ thread destroy finished");
+        thread_ = 0;
+    }
 
     const pj_time_val tv = {0, 10};
     pjsip_endpt_handle_events(endpt_, &tv);
@@ -515,31 +466,41 @@ SIPVoIPLink::~SIPVoIPLink()
 
 SIPVoIPLink* SIPVoIPLink::instance()
 {
-    static SIPVoIPLink* instance = NULL;
-
-    if (!instance)
-        instance = new SIPVoIPLink;
+    assert(!destroyed_);
+    if (!instance_)
+        instance_ = new SIPVoIPLink;
+    return instance_;
+}
 
-    return instance;
+void SIPVoIPLink::destroy()
+{
+    delete instance_;
+    destroyed_ = true;
+    instance_ = 0;
 }
 
-void
-SIPVoIPLink::getEvent()
+// Called from EventThread::run (not main thread)
+bool SIPVoIPLink::getEvent()
 {
     static pj_thread_desc desc;
 
     // We have to register the external thread so it could access the pjsip frameworks
-    if (!pj_thread_is_registered())
-        pj_thread_register(NULL, desc, &thread);
+    if (!pj_thread_is_registered()) {
+        DEBUG("%s: Registering thread", __PRETTY_FUNCTION__);
+        pj_thread_register(NULL, desc, &thread_);
+    }
 
     static const pj_time_val timeout = {0, 10};
     pjsip_endpt_handle_events(endpt_, &timeout);
+    return handlingEvents_;
 }
 
 void SIPVoIPLink::sendRegister(Account *a)
 {
     SIPAccount *account = dynamic_cast<SIPAccount*>(a);
-    sipTransport.createSipTransport(account);
+    if (!account)
+        throw VoipLinkException("SipVoipLink: Account is not SIPAccount");
+    sipTransport.createSipTransport(*account);
 
     account->setRegister(true);
     account->setRegistrationState(Trying);
@@ -567,7 +528,7 @@ void SIPVoIPLink::sendRegister(Account *a)
         throw VoipLinkException("Unable to initialize account registration structure");
 
     if (!account->getServiceRoute().empty())
-        pjsip_regc_set_route_set(regc, createRouteSet(account->getServiceRoute(), pool_));
+        pjsip_regc_set_route_set(regc, sip_utils::createRouteSet(account->getServiceRoute(), pool_));
 
     pjsip_regc_set_credentials(regc, account->getCredentialCount(), account->getCredInfo());
 
@@ -665,6 +626,81 @@ void SIPVoIPLink::cancelKeepAliveTimer(pj_timer_entry& timer)
 
 Call *SIPVoIPLink::newOutgoingCall(const std::string& id, const std::string& toUrl)
 {
+    static const char * const SIP_SCHEME = "sip:";
+    static const char * const SIPS_SCHEME = "sips:";
+
+    DEBUG("UserAgent: New outgoing call");
+
+    bool IPToIP = toUrl.find(SIP_SCHEME) == 0 or
+                  toUrl.find(SIPS_SCHEME) == 0;
+
+    Manager::instance().setIPToIPForCall(id, IPToIP);
+
+    try {
+        if (IPToIP) {
+            return SIPNewIpToIpCall(id, toUrl);
+        }
+        else {
+            return newRegisteredAccountCall(id, toUrl);
+        }
+    }
+    catch(...) {
+        throw;
+    }
+}
+
+Call *SIPVoIPLink::SIPNewIpToIpCall(const std::string& id, const std::string& to)
+{
+    DEBUG("UserAgent: New IP to IP call to %s", to.c_str());
+
+    SIPAccount *account = Manager::instance().getIP2IPAccount();
+
+    if (!account)
+        throw VoipLinkException("Could not retrieve default account for IP2IP call");
+
+    SIPCall *call = new SIPCall(id, Call::OUTGOING, cp_);
+
+    call->setIPToIP(true);
+    call->initRecFilename(to);
+
+    std::string localAddress(SipTransport::getInterfaceAddrFromName(account->getLocalInterface()));
+
+    if (localAddress == "0.0.0.0")
+        localAddress = SipTransport::getSIPLocalIP();
+
+    setCallMediaLocal(call, localAddress);
+
+    std::string toUri = account->getToUri(to);
+    call->setPeerNumber(toUri);
+
+    sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(PAYLOAD_CODEC_ULAW);
+
+    // Audio Rtp Session must be initialized before creating initial offer in SDP session
+    // since SDES require crypto attribute.
+    call->getAudioRtp().initConfig();
+    call->getAudioRtp().initSession();
+    call->getAudioRtp().initLocalCryptoInfo();
+    call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec));
+
+    // Building the local SDP offer
+    call->getLocalSDP()->setLocalIP(localAddress);
+#ifdef SFL_VIDEO
+    call->getLocalSDP()->createOffer(account->getActiveCodecs(), account->getActiveVideoCodecs());
+#else
+    call->getLocalSDP()->createOffer(account->getActiveCodecs());
+#endif
+    if (!SIPStartCall(call)) {
+        delete call;
+        throw VoipLinkException("Could not create new call");
+    }
+
+    return call;
+}
+
+Call *SIPVoIPLink::newRegisteredAccountCall(const std::string& id, const std::string& toUrl)
+{
+    DEBUG("UserAgent: New registered account call to %s", toUrl.c_str());
+
     SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(Manager::instance().getAccountFromCall(id)));
 
     if (account == NULL) // TODO: We should investigate how we could get rid of this error and create a IP2IP call instead
@@ -760,7 +796,7 @@ SIPVoIPLink::hangup(const std::string& id)
 
     // Looks for sip routes
     if (not account->getServiceRoute().empty()) {
-        pjsip_route_hdr *route_set = createRouteSet(account->getServiceRoute(), inv->pool);
+        pjsip_route_hdr *route_set = sip_utils::createRouteSet(account->getServiceRoute(), inv->pool);
         pjsip_dlg_set_route_set(inv->dlg, route_set);
     }
 
@@ -1118,31 +1154,44 @@ SIPVoIPLink::SIPStartCall(SIPCall *call)
 
     pjsip_dialog *dialog = NULL;
 
-    if (pjsip_dlg_create_uac(pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog) != PJ_SUCCESS)
+    if (pjsip_dlg_create_uac(pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog) != PJ_SUCCESS) {
+        ERROR("UserAgent: Unable to sip create dialogs for user agent client");
         return false;
+    }
 
-    if (pjsip_inv_create_uac(dialog, call->getLocalSDP()->getLocalSdpSession(), 0, &call->inv) != PJ_SUCCESS)
+    if (pjsip_inv_create_uac(dialog, call->getLocalSDP()->getLocalSdpSession(), 0, &call->inv) != PJ_SUCCESS) {
+        ERROR("UserAgent: Unable to create invite session for user agent client");
         return false;
+    }
 
     if (not account->getServiceRoute().empty())
-        pjsip_dlg_set_route_set(dialog, createRouteSet(account->getServiceRoute(), call->inv->pool));
+        pjsip_dlg_set_route_set(dialog, sip_utils::createRouteSet(account->getServiceRoute(), call->inv->pool));
 
-    pjsip_auth_clt_set_credentials(&dialog->auth_sess, account->getCredentialCount(), account->getCredInfo());
+    if (pjsip_auth_clt_set_credentials(&dialog->auth_sess, account->getCredentialCount(), account->getCredInfo()) != PJ_SUCCESS) {
+        ERROR("UserAgent: Could not initiaize credential for invite session  authentication");
+        return false;
+    }
 
     call->inv->mod_data[mod_ua_.id] = call;
 
     pjsip_tx_data *tdata;
 
-    if (pjsip_inv_invite(call->inv, &tdata) != PJ_SUCCESS)
+    if (pjsip_inv_invite(call->inv, &tdata) != PJ_SUCCESS) {
+        ERROR("UserAgent: Could not initialize invite messager for this call");
         return false;
+    }
 
     pjsip_tpselector *tp = sipTransport.initTransportSelector(account->transport_, call->inv->pool);
 
-    if (pjsip_dlg_set_transport(dialog, tp) != PJ_SUCCESS)
+    if (pjsip_dlg_set_transport(dialog, tp) != PJ_SUCCESS) {
+        ERROR("UserAgent: Unable to associate transport fir invite session dialog");
         return false;
+    }
 
-    if (pjsip_inv_send_msg(call->inv, tdata) != PJ_SUCCESS)
+    if (pjsip_inv_send_msg(call->inv, tdata) != PJ_SUCCESS) {
+        ERROR("UserAgent: Unable to send invite message for this call");
         return false;
+    }
 
     call->setConnectionState(Call::PROGRESSING);
     call->setState(Call::ACTIVE);
@@ -1197,107 +1246,6 @@ SIPVoIPLink::getSIPCall(const std::string& id)
     return result;
 }
 
-namespace
-{
-    std::string getIPFromSIP(std::string sipURI)
-    {
-        //Remove sip: prefix
-        size_t found = sipURI.find(":");
-        if (found != std::string::npos)
-            sipURI.erase(0, found + 1);
-
-        found = sipURI.find("@");
-        if (found != std::string::npos)
-            sipURI.erase(found);
-
-        found = sipURI.find(">");
-
-        if (found != std::string::npos)
-            sipURI.erase(found);
-        return sipURI;
-    }
-}
-
-bool SIPVoIPLink::SIPNewIpToIpCall(const std::string& id, const std::string& to)
-{
-    SIPAccount *account = Manager::instance().getIP2IPAccount();
-
-    if (!account) {
-        ERROR("Error could not retrieve default account for IP2IP call");
-        return false;
-    }
-
-    SIPCall *call = new SIPCall(id, Call::OUTGOING, cp_);
-    call->setIPToIP(true);
-    call->initRecFilename(to);
-
-    std::string localAddress(SipTransport::getInterfaceAddrFromName(account->getLocalInterface()));
-
-    if (localAddress == "0.0.0.0")
-        localAddress = SipTransport::getSIPLocalIP();
-
-    setCallMediaLocal(call, localAddress);
-
-    std::string toUri = account->getToUri(to);
-    call->setPeerNumber(toUri);
-
-    sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(PAYLOAD_CODEC_ULAW);
-
-    // Audio Rtp Session must be initialized before creating initial offer in SDP session
-    // since SDES require crypto attribute.
-    call->getAudioRtp().initConfig();
-    call->getAudioRtp().initSession();
-    call->getAudioRtp().initLocalCryptoInfo();
-    call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec));
-
-    // Building the local SDP offer
-    call->getLocalSDP()->setLocalIP(localAddress);
-#ifdef SFL_VIDEO
-    call->getLocalSDP()->createOffer(account->getActiveCodecs(), account->getActiveVideoCodecs());
-#else
-    call->getLocalSDP()->createOffer(account->getActiveCodecs());
-#endif
-
-    // Init TLS transport if enabled
-    if (account->isTlsEnabled()) {
-        size_t at = toUri.find("@");
-        size_t trns = toUri.find(";transport");
-        if (at == std::string::npos or trns == std::string::npos) {
-            ERROR("UserAgent: Error \"@\" or \";transport\" not in URI %s", toUri.c_str());
-            delete call;
-            return false;
-        }
-
-        std::string remoteAddr(toUri.substr(at + 1, trns - at - 1));
-
-        if (toUri.find("sips:") != 1) {
-            DEBUG("UserAgent: Error \"sips\" scheme required for TLS call");
-            delete call;
-            return false;
-        }
-
-        sipTransport.shutdownSipTransport(account);
-        pjsip_transport *transport = sipTransport.createTlsTransport(remoteAddr, account->getTlsListenerPort(),
-                                                              account->getTlsSetting());
-
-        if (transport == NULL) {
-            ERROR("Error could not create TLS transport for IP2IP call");
-            delete call;
-            return false;
-        }
-
-        account->transport_ = transport;
-    }
-
-    if (!SIPStartCall(call)) {
-        delete call;
-        return false;
-    }
-
-    return true;
-}
-
-
 ///////////////////////////////////////////////////////////////////////////////
 // Private functions
 ///////////////////////////////////////////////////////////////////////////////
@@ -1546,14 +1494,13 @@ void outgoing_request_forked_cb(pjsip_inv_session * /*inv*/, pjsip_event * /*e*/
 void transaction_state_changed_cb(pjsip_inv_session * inv,
                                   pjsip_transaction *tsx, pjsip_event *event)
 {
-    assert(tsx);
-    assert(event);
-
-    if (tsx->role != PJSIP_ROLE_UAS || tsx->state != PJSIP_TSX_STATE_TRYING)
+    if (!tsx or !event or tsx->role != PJSIP_ROLE_UAS or
+            tsx->state != PJSIP_TSX_STATE_TRYING)
         return;
 
-    if (pjsip_method_cmp(&tsx->method, &pjsip_refer_method) ==0) {
-        onCallTransfered(inv, event->body.tsx_state.src.rdata);          /** Handle the refer method **/
+    // Handle the refer method
+    if (pjsip_method_cmp(&tsx->method, &pjsip_refer_method) == 0) {
+        onCallTransfered(inv, event->body.tsx_state.src.rdata);
         return;
     }
 
@@ -1687,6 +1634,11 @@ void update_contact_header(pjsip_regc_cbparam *param, SIPAccount *account)
 
 void registration_cb(pjsip_regc_cbparam *param)
 {
+    if (param == NULL) {
+        ERROR("SipVoipLink: registration callback parameter is NULL");
+        return;
+    }
+
     SIPAccount *account = static_cast<SIPAccount *>(param->token);
 
     if (account == NULL) {
@@ -1694,11 +1646,6 @@ void registration_cb(pjsip_regc_cbparam *param)
         return;
     }
 
-    if (param == NULL) {
-        ERROR("SipVoipLink: registration callback parameter is NULL");
-        return;
-    }
-
     if (account->isContactUpdateEnabled())
         update_contact_header(param, account);
 
@@ -1717,14 +1664,14 @@ void registration_cb(pjsip_regc_cbparam *param)
         account->setRegistrationState(ErrorAuth);
         account->setRegister(false);
 
-        SIPVoIPLink::instance()->sipTransport.shutdownSipTransport(account);
+        SIPVoIPLink::instance()->sipTransport.shutdownSipTransport(*account);
         return;
     }
 
     if (param->code < 0 || param->code >= 300) {
         switch (param->code) {
             case 606:
-                account->setRegistrationState(ErrorConfStun);
+                account->setRegistrationState(ErrorNotAcceptable);
                 break;
 
             case 503:
@@ -1751,14 +1698,14 @@ void registration_cb(pjsip_regc_cbparam *param)
 
         account->setRegister(false);
 
-        SIPVoIPLink::instance()->sipTransport.shutdownSipTransport(account);
+        SIPVoIPLink::instance()->sipTransport.shutdownSipTransport(*account);
 
     } else {
         if (account->isRegistered())
             account->setRegistrationState(Registered);
         else {
             account->setRegistrationState(Unregistered);
-            SIPVoIPLink::instance()->sipTransport.shutdownSipTransport(account);
+            SIPVoIPLink::instance()->sipTransport.shutdownSipTransport(*account);
         }
     }
 }
diff --git a/daemon/src/sip/sipvoiplink.h b/daemon/src/sip/sipvoiplink.h
index cb15c0a49cad9ca7b99f3e5467b970f2c57b31fd..681bfacc00264cd8511c6b978b43fc14b074e49e 100644
--- a/daemon/src/sip/sipvoiplink.h
+++ b/daemon/src/sip/sipvoiplink.h
@@ -13,6 +13,7 @@
  *
  *  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.
  *
@@ -41,21 +42,18 @@
 
 #include <map>
 
-//////////////////////////////
-/* PJSIP imports */
 #include <pjsip.h>
 #include <pjlib.h>
 #include <pjsip_ua.h>
 #include <pjlib-util.h>
 #include <pjnath.h>
 #include <pjnath/stun_config.h>
-///////////////////////////////
 
 #include "sipaccount.h"
 #include "voiplink.h"
 #include "siptransport.h"
+#include "eventthread.h"
 
-class EventThread;
 class SIPCall;
 class SIPAccount;
 
@@ -68,7 +66,6 @@ class SIPAccount;
 
 class SIPVoIPLink : public VoIPLink {
     public:
-        ~SIPVoIPLink();
 
         /**
          * Singleton method. Enable to retrieve the unique static instance
@@ -76,10 +73,15 @@ class SIPVoIPLink : public VoIPLink {
          */
         static SIPVoIPLink* instance();
 
+        /**
+         * Destroy the singleton instance
+         */
+        static void destroy();
+
         /**
          * Event listener. Each event send by the call manager is received and handled from here
          */
-        virtual void getEvent();
+        virtual bool getEvent();
 
         /**
          * Build and send SIP registration request
@@ -109,6 +111,20 @@ class SIPVoIPLink : public VoIPLink {
          */
         virtual Call* newOutgoingCall(const std::string& id, const std::string& toUrl);
 
+        /**
+         * Start a new SIP call using the IP2IP profile
+         * @param The call id
+         * @param The target sip uri
+         */
+        Call *SIPNewIpToIpCall(const std::string& id, const std::string& to);
+
+        /**
+         * Place a call using the currently selected account
+         * @param The call id
+         * @param The target sip uri
+         */
+        Call *newRegisteredAccountCall(const std::string& id, const std::string& toUrl);
+
         /**
          * Answer the call
          * @param c The call
@@ -171,13 +187,6 @@ class SIPVoIPLink : public VoIPLink {
          */
         virtual void carryingDTMFdigits(const std::string& id, char code);
 
-        /**
-         * Start a new SIP call using the IP2IP profile
-         * @param The call id
-         * @param The target sip uri
-         */
-        bool SIPNewIpToIpCall(const std::string& id, const std::string& to);
-
         /**
          * Tell the user that the call was answered
          * @param
@@ -236,7 +245,13 @@ class SIPVoIPLink : public VoIPLink {
         void createDefaultSipUdpTransport();
 
         SipTransport sipTransport;
+
     private:
+
+        NON_COPYABLE(SIPVoIPLink);
+
+        SIPVoIPLink();
+        ~SIPVoIPLink();
         /**
          * Start a SIP Call
          * @param call  The current call
@@ -246,16 +261,14 @@ class SIPVoIPLink : public VoIPLink {
 
         void dtmfSend(SIPCall *call, char code, const std::string &type);
 
-        NON_COPYABLE(SIPVoIPLink);
-
-        SIPVoIPLink();
-
         /**
          * Threading object
          */
-        EventThread *evThread_;
+        EventThread evThread_;
 
         friend class SIPTest;
+        static bool destroyed_;
+        static SIPVoIPLink *instance_;
 };
 
 #endif // SIPVOIPLINK_H_
diff --git a/daemon/src/video/shared_memory.cpp b/daemon/src/video/shared_memory.cpp
index a7ce6333be2e5705bc9bc4804c5d4452fac2be05..ef104cccff36627ba7d16d2cc02a8fcb0eef7ae0 100644
--- a/daemon/src/video/shared_memory.cpp
+++ b/daemon/src/video/shared_memory.cpp
@@ -38,8 +38,10 @@
 #include <sys/shm.h>
 
 #include <cstdlib>
+#include <stdexcept>
 
 #include "manager.h"
+#include "logger.h"
 #include "dbus/video_controls.h"
 #include "fileutils.h"
 
diff --git a/daemon/src/video/video_preferences.cpp b/daemon/src/video/video_preferences.cpp
index 20eb67c1109546abb1b577a4a2c34c3321a3731a..14468da79ca54a1c64113b2d2d667cf756d63646 100644
--- a/daemon/src/video/video_preferences.cpp
+++ b/daemon/src/video/video_preferences.cpp
@@ -40,12 +40,12 @@ using namespace sfl_video;
 VideoPreference::VideoPreference() :
     v4l2_list_(new VideoV4l2ListThread), device_(), channel_(), size_(), rate_()
 {
-	v4l2_list_->start();
+    v4l2_list_->start();
 }
 
 VideoPreference::~VideoPreference()
 {
-	delete v4l2_list_;
+    delete v4l2_list_;
 }
 
 std::map<std::string, std::string> VideoPreference::getSettings() const
@@ -64,13 +64,8 @@ std::map<std::string, std::string> VideoPreference::getSettings() const
     return args;
 }
 
-void VideoPreference::serialize(Conf::YamlEmitter *emitter)
+void VideoPreference::serialize(Conf::YamlEmitter &emitter)
 {
-	if (emitter == NULL) {
-		ERROR("VideoPreference: Error: emitter is NULL while serializing");
-		return;
-	}
-
     Conf::MappingNode preferencemap(NULL);
 
     Conf::ScalarNode device(device_);
@@ -83,19 +78,14 @@ void VideoPreference::serialize(Conf::YamlEmitter *emitter)
     preferencemap.setKeyValue(videoSizeKey, &size);
     preferencemap.setKeyValue(videoRateKey, &rate);
 
-    emitter->serializeVideoPreference(&preferencemap);
+    emitter.serializePreference(&preferencemap, "videoPreferences");
 }
 
-void VideoPreference::unserialize(const Conf::MappingNode *map)
+void VideoPreference::unserialize(const Conf::MappingNode &map)
 {
-    if (map == NULL) {
-        ERROR("VideoPreference: Error: Preference map is NULL");
-        return;
-    }
-
-    map->getValue(videoDeviceKey, &device_);
-    map->getValue(videoChannelKey, &channel_);
-    map->getValue(videoSizeKey, &size_);
-    map->getValue(videoRateKey, &rate_);
+    map.getValue(videoDeviceKey, &device_);
+    map.getValue(videoChannelKey, &channel_);
+    map.getValue(videoSizeKey, &size_);
+    map.getValue(videoRateKey, &rate_);
 }
 
diff --git a/daemon/src/video/video_preferences.h b/daemon/src/video/video_preferences.h
index 6afc00438ca0f1f220738a044610687101160442..d17a7dbf170596030696fbe7862655071da4889d 100644
--- a/daemon/src/video/video_preferences.h
+++ b/daemon/src/video/video_preferences.h
@@ -54,9 +54,9 @@ class VideoPreference : public Serializable
         VideoPreference();
         ~VideoPreference();
 
-        virtual void serialize(Conf::YamlEmitter *emitter);
+        virtual void serialize(Conf::YamlEmitter &emitter);
 
-        virtual void unserialize(const Conf::MappingNode *map);
+        virtual void unserialize(const Conf::MappingNode &map);
 
         std::map<std::string, std::string> getSettings() const;
 
@@ -93,19 +93,19 @@ class VideoPreference : public Serializable
         }
 
         std::vector<std::string> getDeviceList() const {
-        	return v4l2_list_->getDeviceList();
+            return v4l2_list_->getDeviceList();
         }
 
         std::vector<std::string> getChannelList(const std::string &dev) const {
-        	return v4l2_list_->getChannelList(dev);
+            return v4l2_list_->getChannelList(dev);
         }
 
         std::vector<std::string> getSizeList(const std::string &dev, const std::string &channel) const {
-        	return v4l2_list_->getSizeList(dev, channel);
+            return v4l2_list_->getSizeList(dev, channel);
         }
 
         std::vector<std::string> getRateList(const std::string &dev, const std::string &channel, const std::string &size) const {
-        	return v4l2_list_->getRateList(dev, channel, size);
+            return v4l2_list_->getRateList(dev, channel, size);
         }
 
     private:
diff --git a/daemon/src/video/video_receive_thread.cpp b/daemon/src/video/video_receive_thread.cpp
index 68a3dd2e07284cb025f7b5dc697d447a9409c294..bd4728f3f5d76e743950dbff1888bca33e2fe4e0 100644
--- a/daemon/src/video/video_receive_thread.cpp
+++ b/daemon/src/video/video_receive_thread.cpp
@@ -43,6 +43,7 @@ extern "C" {
 #include <libswscale/swscale.h>
 }
 
+#include <stdexcept>
 #include <ctime>
 #include <cstdlib>
 
diff --git a/daemon/src/video/video_rtp_session.cpp b/daemon/src/video/video_rtp_session.cpp
index a072f8138e403093569e63ebad01b4fd0772ef9a..269946ef3b0395ee02e651375337d934c0ef666e 100644
--- a/daemon/src/video/video_rtp_session.cpp
+++ b/daemon/src/video/video_rtp_session.cpp
@@ -39,6 +39,7 @@
 #include "sip/sdp.h"
 #include "libav_utils.h"
 #include "manager.h"
+#include "logger.h"
 
 namespace sfl_video {
 
diff --git a/daemon/src/voiplink.cpp b/daemon/src/voiplink.cpp
index 6a34ea5f4cf704ba933bfbd3f17ce70d6ca49cf2..d46954f14afd21e5d970e535ee217827b52c2887 100644
--- a/daemon/src/voiplink.cpp
+++ b/daemon/src/voiplink.cpp
@@ -32,9 +32,10 @@
  */
 
 #include "call.h"
+#include "logger.h"
 #include "voiplink.h"
 
-VoIPLink::VoIPLink() : callMap_(), callMapMutex_() {}
+VoIPLink::VoIPLink() : callMap_(), callMapMutex_(), handlingEvents_(false) {}
 
 VoIPLink::~VoIPLink()
 {
diff --git a/daemon/src/voiplink.h b/daemon/src/voiplink.h
index b5c556062ce1c7570db6e4da8f55823b18f868d3..a049d4a5cab32096abb5ebc2a56a4725ec989d5e 100644
--- a/daemon/src/voiplink.h
+++ b/daemon/src/voiplink.h
@@ -36,7 +36,7 @@
 
 #include <stdexcept>
 #include <map>
-#include <cc++/thread.h> // for ost::Mutex
+#include "cc_thread.h" // for ost::Mutex
 
 class Call;
 class Account;
@@ -63,7 +63,7 @@ class VoIPLink {
          * Virtual method
          * Event listener. Each event send by the call manager is received and handled from here
          */
-        virtual void getEvent() = 0;
+        virtual bool getEvent() = 0;
 
         /**
          * Virtual method
@@ -186,6 +186,8 @@ class VoIPLink {
         /** Mutex to protect call map */
         ost::Mutex callMapMutex_;
 
+        bool handlingEvents_;
+
         /** Remove a call from the call map (protected by mutex)
          * @param id A Call ID
          */
diff --git a/daemon/test/Makefile.am b/daemon/test/Makefile.am
index 111e599a8b178255158eff256cb51ad4c6c58108..58e13b52da92a7be72991c244e2b1a85a61d8bc0 100644
--- a/daemon/test/Makefile.am
+++ b/daemon/test/Makefile.am
@@ -5,50 +5,40 @@ check_PROGRAMS = test
 
 TESTS = run_tests.sh
 
-test_CXXFLAGS = -I .
+test_CXXFLAGS = -DWORKSPACE="$(top_srcdir)/test/"
 test_LDADD = $(top_builddir)/src/libsflphone.la @ZRTPCPP_LIBS@ @LIBCRYPTO_LIBS@ @CPPUNIT_LIBS@ @YAML_LIBS@
 
-EXTRA_DIST = $(test_SOURCES) sflphoned-sample.yml history-sample.tpl run_tests.sh
-test_SOURCES = \
-	constants.h \
-	main.cpp \
-	validator.cpp \
-	validator.h \
-	accounttest.h \
-	accounttest.cpp \
-	audiolayertest.h \
-	audiolayertest.cpp \
-	configurationtest.h \
-	configurationtest.cpp \
-	historytest.h \
-	historytest.cpp \
-	numbercleanertest.h \
-	numbercleanertest.cpp \
-	sdesnegotiatortest.h \
-	sdesnegotiatortest.cpp \
-	instantmessagingtest.h \
-	instantmessagingtest.cpp \
-	siptest.h \
-	siptest.cpp \
-	sdptest.h \
-	sdptest.cpp \
-	echocanceltest.h \
-	echocanceltest.cpp \
-	gaincontroltest.h \
-	gaincontroltest.cpp
-	accounttest.h \
-	audiolayertest.h \
-	configurationtest.h \
-	constants.h \
-	delaydetectiontest.h \
-	echocanceltest.h \
-	gaincontroltest.h \
-	historytest.h \
-	instantmessagingtest.h \
-	mainbuffertest.h \
-	numbercleanertest.h \
-	ringtonetest.h \
-	sdesnegotiatortest.h \
-	sdptest.h \
-	siptest.h \
-	validator.h
+EXTRA_DIST = sflphoned-sample.yml history-sample.tpl run_tests.sh
+test_SOURCES = constants.h \
+			   test_utils.h \
+			   main.cpp \
+			   validator.h \
+			   validator.cpp \
+			   accounttest.h \
+			   accounttest.cpp \
+			   audiolayertest.h \
+			   audiolayertest.cpp \
+			   configurationtest.h \
+			   configurationtest.cpp \
+			   historytest.h \
+			   historytest.cpp \
+			   numbercleanertest.h \
+			   numbercleanertest.cpp \
+			   sdesnegotiatortest.h \
+			   sdesnegotiatortest.cpp \
+			   instantmessagingtest.h \
+			   instantmessagingtest.cpp \
+			   siptest.h \
+			   siptest.cpp \
+			   sdptest.h \
+			   sdptest.cpp \
+			   echocanceltest.h \
+			   echocanceltest.cpp \
+			   gaincontroltest.h \
+			   gaincontroltest.cpp \
+			   mainbuffertest.h \
+			   mainbuffertest.cpp
+
+clean-local:
+	rm -rf cppunitresults.xml im:testfile1.txt im:testfile2.txt \
+		sample_echocancel_500ms_8kHz_16bit.raw
diff --git a/daemon/test/accounttest.cpp b/daemon/test/accounttest.cpp
index 3df3153c230e7662d4d8fb61f853dab2eea4912d..57bd49dbf8c1e7c5481ac36ce4c86a87419abc84 100644
--- a/daemon/test/accounttest.cpp
+++ b/daemon/test/accounttest.cpp
@@ -36,9 +36,9 @@
 #include "logger.h"
 #include "validator.h"
 
-void AccountTest::TestAddRemove(void)
+void AccountTest::TestAddRemove()
 {
-    DEBUG("-------------------- AccountTest::TestAddRemove --------------------\n");
+    DEBUG("-------------------- %s --------------------\n", __PRETTY_FUNCTION__);
 
     std::map<std::string, std::string> details;
     details[CONFIG_ACCOUNT_TYPE] = "SIP";
diff --git a/daemon/test/accounttest.h b/daemon/test/accounttest.h
index 486117fa3c384d462da3ab6cfdff18d6c79e2475..ce880cfcb70e41b195ad997723fb90367670847d 100644
--- a/daemon/test/accounttest.h
+++ b/daemon/test/accounttest.h
@@ -41,7 +41,7 @@ class AccountTest : public CppUnit::TestFixture {
         CPPUNIT_TEST_SUITE_END();
 
     public:
-        void TestAddRemove(void);
+        void TestAddRemove();
 };
 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AccountTest, "AccountTest");
 CPPUNIT_TEST_SUITE_REGISTRATION(AccountTest);
diff --git a/daemon/test/audiolayertest.cpp b/daemon/test/audiolayertest.cpp
index 589271f04b33ef3d5d47ad93762c031b7719b174..3e80ef2f1fc0395c1bf14610ebe78ead56232b9c 100644
--- a/daemon/test/audiolayertest.cpp
+++ b/daemon/test/audiolayertest.cpp
@@ -28,23 +28,21 @@
  *  as that of the covered work.
  */
 
-#include <stdio.h>
-#include <sstream>
-
 #include "audiolayertest.h"
-#include "audio/pulseaudio/audiostream.h"
 
+#include "logger.h"
+#include "manager.h"
+#include "audio/alsa/alsalayer.h"
+#include "audio/pulseaudio/pulselayer.h"
+#include "test_utils.h"
 #include <unistd.h>
 
-using std::cout;
-using std::endl;
-
 AudioLayerTest::AudioLayerTest() : manager_(0), pulselayer_(0), layer_(0)
 {}
 
 void AudioLayerTest::testAudioLayerConfig()
 {
-   DEBUG("-------------------- AudioLayerTest::testAudioLayerConfig --------------------\n");
+    TITLE();
 
     CPPUNIT_ASSERT(Manager::instance().audioPreference.getSmplrate() == 44100);
 
@@ -68,12 +66,12 @@ void AudioLayerTest::testAudioLayerConfig()
 
 void AudioLayerTest::testAudioLayerSwitch()
 {
-   DEBUG("-------------------- AudioLayerTest::testAudioLayerSwitch --------------------\n");
+    TITLE();
 
     bool wasAlsa = dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver()) != 0;
 
     for (int i = 0; i < 2; i++) {
-       DEBUG("iter - %i", i);
+        DEBUG("iter - %i", i);
         Manager::instance().switchAudioManager();
 
         if (wasAlsa)
@@ -82,17 +80,19 @@ void AudioLayerTest::testAudioLayerSwitch()
             CPPUNIT_ASSERT(dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver()));
 
         wasAlsa = dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver()) != 0;
-        usleep(100000);
+        const struct timespec req = {0, 100000000};
+        nanosleep(&req, 0);
     }
 }
 
 void AudioLayerTest::testPulseConnect()
 {
-   DEBUG("-------------------- AudioLayerTest::testPulseConnect --------------------\n");
+    TITLE();
 
     if (dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver())) {
         Manager::instance().switchAudioManager();
-        usleep(100000);
+        const struct timespec req = {0, 100000000};
+        nanosleep(&req, 0);
     }
 
     pulselayer_ = dynamic_cast<PulseLayer*>(Manager::instance().getAudioDriver());
diff --git a/daemon/test/audiolayertest.h b/daemon/test/audiolayertest.h
index 06e857c1fc081db18d07043d5c01eb6ce004e240..cdd7bfaeabc83f021ff45964b760e2d3e4281eda 100644
--- a/daemon/test/audiolayertest.h
+++ b/daemon/test/audiolayertest.h
@@ -33,8 +33,8 @@
  * @brief       Regroups unitary tests related to the plugin manager.
  */
 
-#ifndef _AUDIOLAYER_TEST_
-#define _AUDIOLAYER_TEST_
+#ifndef AUDIOLAYER_TEST_
+#define AUDIOLAYER_TEST_
 
 // Cppunit import
 #include <cppunit/extensions/HelperMacros.h>
@@ -42,18 +42,11 @@
 #include <cppunit/TestCase.h>
 #include <cppunit/TestSuite.h>
 
-#include <cassert>
-
-// Application import
-#include "manager.h"
-
-#include "config/sfl_config.h"
-
-#include "audio/audiolayer.h"
-#include "audio/alsa/alsalayer.h"
-#include "audio/pulseaudio/pulselayer.h"
 #include "noncopyable.h"
 
+class ManagerImpl;
+class PulseLayer;
+
 class AudioLayerTest: public CppUnit::TestFixture {
 
         CPPUNIT_TEST_SUITE(AudioLayerTest);
@@ -79,4 +72,4 @@ class AudioLayerTest: public CppUnit::TestFixture {
 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AudioLayerTest, "AudioLayerTest");
 CPPUNIT_TEST_SUITE_REGISTRATION(AudioLayerTest);
 
-#endif
+#endif // AUDIOLAYER_TEST_
diff --git a/daemon/test/configurationtest.cpp b/daemon/test/configurationtest.cpp
index b670351c1e11482378a03316cfab6214a42bc8ab..a3553bc55990819e7b68051d6c133dbef29ef9bf 100644
--- a/daemon/test/configurationtest.cpp
+++ b/daemon/test/configurationtest.cpp
@@ -28,24 +28,24 @@
  *  as that of the covered work.
  */
 
-#include <stdio.h>
-#include <sstream>
-
 #include "configurationtest.h"
-#include "constants.h"
+#include "manager.h"
+#include "config/yamlemitter.h"
+#include "config/yamlparser.h"
+#include "account.h"
+#include "logger.h"
 #include "audio/alsa/alsalayer.h"
 #include "audio/pulseaudio/pulselayer.h"
-
-using std::cout;
-using std::endl;
+#include "sip/sipaccount.h"
+#include "test_utils.h"
 
 void ConfigurationTest::testDefaultValueAudio()
 {
-    DEBUG("-------------------- ConfigurationTest::testDefaultValueAudio() --------------------\n");
+    TITLE();
 
-    CPPUNIT_ASSERT(Manager::instance().audioPreference.getCardin() == 0);  // ALSA_DFT_CARD);
-    CPPUNIT_ASSERT(Manager::instance().audioPreference.getCardout() == 0);  // ALSA_DFT_CARD);
-    CPPUNIT_ASSERT(Manager::instance().audioPreference.getSmplrate() == 44100);  // DFT_SAMPLE_RATE);
+    CPPUNIT_ASSERT(Manager::instance().audioPreference.getCardin() == ALSA_DFT_CARD_ID);
+    CPPUNIT_ASSERT(Manager::instance().audioPreference.getCardout() == ALSA_DFT_CARD_ID);
+    CPPUNIT_ASSERT(Manager::instance().audioPreference.getSmplrate() == 44100);
     CPPUNIT_ASSERT(Manager::instance().audioPreference.getPlugin() == PCM_DEFAULT);
     CPPUNIT_ASSERT(Manager::instance().audioPreference.getVolumespkr() == 100);
     CPPUNIT_ASSERT(Manager::instance().audioPreference.getVolumemic() == 100);
@@ -53,15 +53,13 @@ void ConfigurationTest::testDefaultValueAudio()
 
 void ConfigurationTest::testDefaultValuePreferences()
 {
-    DEBUG("-------------------- ConfigurationTest::testDefaultValuePreferences --------------------\n");
-
+    TITLE();
     CPPUNIT_ASSERT(Manager::instance().preferences.getZoneToneChoice() == Preferences::DFT_ZONE);
 }
 
 void ConfigurationTest::testDefaultValueSignalisation()
 {
-    DEBUG("-------------------- ConfigurationTest::testDefaultValueSignalisation --------------------\n");
-
+    TITLE();
     CPPUNIT_ASSERT(Manager::instance().voipPreferences.getSymmetricRtp());
     CPPUNIT_ASSERT(Manager::instance().voipPreferences.getPlayDtmf());
     CPPUNIT_ASSERT(Manager::instance().voipPreferences.getPlayTones());
@@ -70,8 +68,7 @@ void ConfigurationTest::testDefaultValueSignalisation()
 
 void ConfigurationTest::testInitAudioDriver()
 {
-    DEBUG("-------------------- ConfigurationTest::testInitAudioDriver --------------------\n");
-
+    TITLE();
     // Load the audio driver
     Manager::instance().initAudioDriver();
 
@@ -156,37 +153,37 @@ void ConfigurationTest::testYamlEmitter()
     ScalarNode verifyclient(true);
     ScalarNode verifyserver(true);
 
-    accountmap.setKeyValue(aliasKey, &alias);
-    accountmap.setKeyValue(typeKey, &type);
-    accountmap.setKeyValue(idKey, &id);
-    accountmap.setKeyValue(usernameKey, &username);
-    accountmap.setKeyValue(passwordKey, &password);
-    accountmap.setKeyValue(hostnameKey, &hostname);
-    accountmap.setKeyValue(accountEnableKey, &enable);
-    accountmap.setKeyValue(mailboxKey, &mailbox);
-    accountmap.setKeyValue(registrationExpireKey, &expire);
-    accountmap.setKeyValue(interfaceKey, &interface);
-    accountmap.setKeyValue(portKey, &port);
-    accountmap.setKeyValue(publishAddrKey, &publishAddr);
-    accountmap.setKeyValue(publishPortKey, &publishPort);
-    accountmap.setKeyValue(sameasLocalKey, &sameasLocal);
-    accountmap.setKeyValue(dtmfTypeKey, &dtmfType);
-    accountmap.setKeyValue(displayNameKey, &displayName);
-
-    accountmap.setKeyValue(srtpKey, &srtpmap);
-    srtpmap.setKeyValue(srtpEnableKey, &srtpenabled);
-    srtpmap.setKeyValue(keyExchangeKey, &keyExchange);
-    srtpmap.setKeyValue(rtpFallbackKey, &rtpFallback);
-
-    accountmap.setKeyValue(zrtpKey, &zrtpmap);
-    zrtpmap.setKeyValue(displaySasKey, &displaySas);
-    zrtpmap.setKeyValue(displaySasOnceKey, &displaySasOnce);
-    zrtpmap.setKeyValue(helloHashEnabledKey, &helloHashEnabled);
-    zrtpmap.setKeyValue(notSuppWarningKey, &notSuppWarning);
-
-    accountmap.setKeyValue(credKey, &credentialmap);
+    accountmap.setKeyValue(ALIAS_KEY, &alias);
+    accountmap.setKeyValue(TYPE_KEY, &type);
+    accountmap.setKeyValue(ID_KEY, &id);
+    accountmap.setKeyValue(USERNAME_KEY, &username);
+    accountmap.setKeyValue(PASSWORD_KEY, &password);
+    accountmap.setKeyValue(HOSTNAME_KEY, &hostname);
+    accountmap.setKeyValue(ACCOUNT_ENABLE_KEY, &enable);
+    accountmap.setKeyValue(MAILBOX_KEY, &mailbox);
+    accountmap.setKeyValue(Preferences::REGISTRATION_EXPIRE_KEY, &expire);
+    accountmap.setKeyValue(INTERFACE_KEY, &interface);
+    accountmap.setKeyValue(PORT_KEY, &port);
+    accountmap.setKeyValue(PUBLISH_ADDR_KEY, &publishAddr);
+    accountmap.setKeyValue(PUBLISH_PORT_KEY, &publishPort);
+    accountmap.setKeyValue(SAME_AS_LOCAL_KEY, &sameasLocal);
+    accountmap.setKeyValue(DTMF_TYPE_KEY, &dtmfType);
+    accountmap.setKeyValue(DISPLAY_NAME_KEY, &displayName);
+
+    accountmap.setKeyValue(SRTP_KEY, &srtpmap);
+    srtpmap.setKeyValue(SRTP_ENABLE_KEY, &srtpenabled);
+    srtpmap.setKeyValue(KEY_EXCHANGE_KEY, &keyExchange);
+    srtpmap.setKeyValue(RTP_FALLBACK_KEY, &rtpFallback);
+
+    accountmap.setKeyValue(ZRTP_KEY, &zrtpmap);
+    zrtpmap.setKeyValue(DISPLAY_SAS_KEY, &displaySas);
+    zrtpmap.setKeyValue(DISPLAY_SAS_ONCE_KEY, &displaySasOnce);
+    zrtpmap.setKeyValue(HELLO_HASH_ENABLED_KEY, &helloHashEnabled);
+    zrtpmap.setKeyValue(NOT_SUPP_WARNING_KEY, &notSuppWarning);
+
+    accountmap.setKeyValue(CRED_KEY, &credentialmap);
     SequenceNode credentialseq(NULL);
-    accountmap.setKeyValue(credKey, &credentialseq);
+    accountmap.setKeyValue(CRED_KEY, &credentialseq);
 
     MappingNode credmap1(NULL);
     MappingNode credmap2(NULL);
@@ -205,20 +202,20 @@ void ConfigurationTest::testYamlEmitter()
     credentialseq.addNode(&credmap1);
     credentialseq.addNode(&credmap2);
 
-    accountmap.setKeyValue(tlsKey, &tlsmap);
-    tlsmap.setKeyValue(tlsPortKey, &tlsport);
-    tlsmap.setKeyValue(certificateKey, &certificate);
-    tlsmap.setKeyValue(calistKey, &calist);
-    tlsmap.setKeyValue(ciphersKey, &ciphers);
-    tlsmap.setKeyValue(tlsEnableKey, &tlsenabled);
-    tlsmap.setKeyValue(methodKey, &tlsmethod);
-    tlsmap.setKeyValue(timeoutKey, &timeout);
-    tlsmap.setKeyValue(tlsPasswordKey, &tlspassword);
-    tlsmap.setKeyValue(privateKeyKey, &privatekey);
-    tlsmap.setKeyValue(requireCertifKey, &requirecertif);
-    tlsmap.setKeyValue(serverKey, &server);
-    tlsmap.setKeyValue(verifyClientKey, &verifyclient);
-    tlsmap.setKeyValue(verifyServerKey, &verifyserver);
+    accountmap.setKeyValue(TLS_KEY, &tlsmap);
+    tlsmap.setKeyValue(TLS_PORT_KEY, &tlsport);
+    tlsmap.setKeyValue(CERTIFICATE_KEY, &certificate);
+    tlsmap.setKeyValue(CALIST_KEY, &calist);
+    tlsmap.setKeyValue(CIPHERS_KEY, &ciphers);
+    tlsmap.setKeyValue(TLS_ENABLE_KEY, &tlsenabled);
+    tlsmap.setKeyValue(METHOD_KEY, &tlsmethod);
+    tlsmap.setKeyValue(TIMEOUT_KEY, &timeout);
+    tlsmap.setKeyValue(TLS_PASSWORD_KEY, &tlspassword);
+    tlsmap.setKeyValue(PRIVATE_KEY_KEY, &privatekey);
+    tlsmap.setKeyValue(REQUIRE_CERTIF_KEY, &requirecertif);
+    tlsmap.setKeyValue(SERVER_KEY, &server);
+    tlsmap.setKeyValue(VERIFY_CLIENT_KEY, &verifyclient);
+    tlsmap.setKeyValue(VERIFY_SERVER_KEY, &verifyserver);
 
     try {
         YamlEmitter emitter("/tmp/ymlEmiter.txt");
diff --git a/daemon/test/configurationtest.h b/daemon/test/configurationtest.h
index f8705d3dadec3c0004e77b48b5d7422fb8d063a2..d9f014db2a72e1dbaa1eae1a85b1df8ea61ed2dc 100644
--- a/daemon/test/configurationtest.h
+++ b/daemon/test/configurationtest.h
@@ -34,8 +34,8 @@
  *              Check if the default configuration has been successfully loaded
  */
 
-#ifndef _CONFIGURATION_TEST_
-#define _CONFIGURATION_TEST_
+#ifndef CONFIGURATION_TEST_
+#define CONFIGURATION_TEST_
 
 // Cppunit import
 #include <cppunit/extensions/HelperMacros.h>
@@ -43,29 +43,12 @@
 #include <cppunit/TestCase.h>
 #include <cppunit/TestSuite.h>
 
-#include <assert.h>
-
-// Application import
-#include "manager.h"
-#include "audio/audiolayer.h"
-#include "global.h"
-#include "config/yamlparser.h"
-#include "config/yamlemitter.h"
-#include "config/yamlnode.h"
-#include "sip/sipaccount.h"
-#include "account.h"
-
 class ConfigurationTest: public CppUnit::TestFixture {
 
         /*
          * Use cppunit library macros to add unit test the factory
          */
         CPPUNIT_TEST_SUITE(ConfigurationTest);
-//      CPPUNIT_TEST( testDefaultValueAudio );
-//	CPPUNIT_TEST( testDefaultValuePreferences );
-//	CPPUNIT_TEST( testDefaultValueSignalisation );
-//	CPPUNIT_TEST( testInitAudioDriver );
-//      CPPUNIT_TEST( testYamlParser );
         CPPUNIT_TEST(testYamlEmitter);
         CPPUNIT_TEST_SUITE_END();
 
@@ -103,4 +86,4 @@ class ConfigurationTest: public CppUnit::TestFixture {
 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(ConfigurationTest, "ConfigurationTest");
 CPPUNIT_TEST_SUITE_REGISTRATION(ConfigurationTest);
 
-#endif
+#endif // CONFIGURATION_TEST_
diff --git a/daemon/test/constants.h b/daemon/test/constants.h
index 684f00ebacce91ca15600f75aa1f50485a2607dd..74b8374dd6b6b242a5aa1b310f969ab049ef13e5 100644
--- a/daemon/test/constants.h
+++ b/daemon/test/constants.h
@@ -31,9 +31,15 @@
 #ifndef CONSTANTS_H_
 #define CONSTANTS_H_
 
-#define HISTORY_SAMPLE  "history-sample.tpl"
-#define HISTORY_SAMPLE_SIZE     3
-#define CONFIG_SAMPLE   "sflphoned-sample.yml"
+#define XSTRINGIFY(s) STRINGIFY(s)
+#define STRINGIFY(s) #s
+#define HISTORY_SAMPLE XSTRINGIFY(WORKSPACE) "history-sample.tpl"
+#define HISTORY_SAMPLE_BAK HISTORY_SAMPLE ".bak"
+
+#define CONFIG_SAMPLE XSTRINGIFY(WORKSPACE) "sflphoned-sample.yml"
+#define CONFIG_SAMPLE_BAK CONFIG_SAMPLE ".bak"
+
+#define HISTORY_SAMPLE_SIZE 3
 #define HISTORY_LIMIT 30
 
 #endif /* CONSTANTS_H_ */
diff --git a/daemon/test/delaydetectiontest.cpp b/daemon/test/delaydetectiontest.cpp
index a140d208d52531599c62fd8b836d25072c92692d..6b744c79f1e97d1152ae55859f8f8a7ca006d359 100644
--- a/daemon/test/delaydetectiontest.cpp
+++ b/daemon/test/delaydetectiontest.cpp
@@ -30,14 +30,8 @@
 
 
 #include "delaydetectiontest.h"
-
-#include <iostream>
-#include <math.h>
-#include <string.h>
-
-void DelayDetectionTest::setUp() {}
-
-void DelayDetectionTest::tearDown() {}
+#include <cstring>
+#include "array_size.h"
 
 void DelayDetectionTest::testCrossCorrelation()
 {
@@ -54,7 +48,7 @@ void DelayDetectionTest::testCrossCorrelation()
 
     float tmp;
 
-    for (int i = 0; i < 10; i++) {
+    for (int i = 0; i < ARRAYSIZE(result); i++) {
         tmp = result[i] - expected[i];
 
         if (tmp < 0.0)
@@ -73,53 +67,46 @@ void DelayDetectionTest::testCrossCorrelationDelay()
 
     delaydetect_.crossCorrelate(ref, signal, result, 3, 10);
 
-    float expected[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0};
-
+//    float expected[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0};
 }
 
 void DelayDetectionTest::testFirFilter()
 {
-    float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03630817, 0.02944626,
-                               0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722,
-                               -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204,
-                               0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179,
-                               0.1160644,  0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299,
-                               0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834,
-                               -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367,
-                               0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337,
-                               0.05616626,  0.07473655, -0.09870257
-                              };
-    std::vector<double> ird(decimationCoefs, decimationCoefs + sizeof(decimationCoefs) /sizeof(float));
-
-    float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113,
-                             0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507,
-                             -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563,
-                             0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507,
-                             -0.03214543, -0.07568665, -0.03433526, -0.02412049,  0.06436469, 0.05986113,
-                             0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034
-                            };
-    std::vector<double> irb(bandpassCoefs, bandpassCoefs + sizeof(bandpassCoefs) /sizeof(float));
+    const float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03630817, 0.02944626,
+        0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722,
+        -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204,
+        0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179,
+        0.1160644,  0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299,
+        0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834,
+        -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367,
+        0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337,
+        0.05616626,  0.07473655, -0.09870257};
+    const std::vector<double> ird(decimationCoefs, decimationCoefs + ARRAYSIZE(decimationCoefs));
+
+    const float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113,
+        0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507,
+        -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563,
+        0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507,
+        -0.03214543, -0.07568665, -0.03433526, -0.02412049,  0.06436469, 0.05986113,
+        0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034};
+    const std::vector<double> irb(bandpassCoefs, bandpassCoefs + ARRAYSIZE(bandpassCoefs));
 
     float impulse[100];
-    memset(impulse, 0, sizeof(float) *100);
+    memset(impulse, 0, sizeof(impulse))
     impulse[0] = 1.0;
 
     FirFilter decimationFilter_(ird);
     FirFilter bandpassFilter_(irb);
 
     float impulseresponse[100];
-    memset(impulseresponse, 0, sizeof(float) *100);
+    memset(impulseresponse, 0, sizeof impulseresponse);
 
     // compute impulse response
-    for (int i = 0; i < 100; i++) {
+    for (int i = 0; i < ARRAYSIZE(impulse); i++)
         impulseresponse[i] = decimationFilter_.getOutputSample(impulse[i]);
-    }
-
-    float tmp;
-    int size = sizeof(decimationCoefs) /sizeof(float);
 
-    for (int i = 0; i < size; i++) {
-        tmp = decimationCoefs[i] - impulseresponse[i];
+    for (int i = 0; i < ARRAYSIZE(decimationCoefs); ++i) {
+        float tmp = decimationCoefs[i] - impulseresponse[i];
 
         if (tmp < 0.0)
             CPPUNIT_ASSERT(tmp > -0.000001);
@@ -128,13 +115,10 @@ void DelayDetectionTest::testFirFilter()
     }
 
 
-    for (int i = 0; i < 100; i++) {
+    for (size_t i = 0; i < ARRAYSIZE(impulseresponse); ++i)
         impulseresponse[i] = bandpassFilter_.getOutputSample(impulse[i]);
-    }
 
-    size = sizeof(bandpassCoefs) /sizeof(float);
-
-    for (int i = 0; i < size; i++) {
+    for (size_t i = 0; i < ARRAYSIZE(bandpassCoefs); ++i) {
         tmp = bandpassCoefs[i] - impulseresponse[i];
 
         if (tmp < 0.0)
@@ -142,51 +126,48 @@ void DelayDetectionTest::testFirFilter()
         else
             CPPUNIT_ASSERT(tmp < 0.000001);
     }
-
 }
 
 void DelayDetectionTest::testIntToFloatConversion()
 {
-
-    SFLDataFormat data[32768*2];
-    float converted[32768*2];
+    SFLDataFormat data[32768 * 2];
+    float converted[ARRAYSIZE(data)];
 
     for (int i = -32768; i < 32768; i++)
-        data[i+32768] = i;
+        data[i + 32768] = i;
 
-    delaydetect_.convertInt16ToFloat32(data, converted, 32768*2);
+    delaydetect_.convertInt16ToFloat32(data, converted, ARRAYSIZE(data));
 
     for (int i = -32768; i < 0; i++) {
-        CPPUNIT_ASSERT(converted[i+32768] >= -1.0);
-        CPPUNIT_ASSERT(converted[i+32768] <= 0.0);
+        CPPUNIT_ASSERT(converted[i + 32768] >= -1.0);
+        CPPUNIT_ASSERT(converted[i + 32768] <= 0.0);
     }
 
     for (int i = 0; i < 32768; i++) {
-        CPPUNIT_ASSERT(converted[i+32768] >= 0.0);
-        CPPUNIT_ASSERT(converted[i+32768] <= 1.0);
+        CPPUNIT_ASSERT(converted[i + 32768] >= 0.0);
+        CPPUNIT_ASSERT(converted[i + 32768] <= 1.0);
     }
 }
 
 void DelayDetectionTest::testDownSamplingData()
 {
-
-    SFLDataFormat data[32768*2];
-    float converted[32768*2];
-    float resampled[32768*2];
+    SFLDataFormat data[32768 * 2];
+    float converted[ARRAYSIZE(data)];
+    float resampled[ARRAYSIZE(data)];
 
     for (int i = -32768; i < 32768; i++)
-        data[i+32768] = i;
+        data[i + 32768] = i;
 
-    delaydetect_.convertInt16ToFloat32(data, converted, 32768*2);
+    delaydetect_.convertInt16ToFloat32(data, converted, 32768 * 2);
 
-    delaydetect_.downsampleData(converted, resampled, 32768*2, 8);
+    delaydetect_.downsampleData(converted, resampled, 32768 * 2, 8);
 
-    for (int i = 0; i < 32768/8; i++) {
+    for (size_t i = 0; i < 32768 / 8; ++i) {
         CPPUNIT_ASSERT(resampled[i] >= -1.0);
         CPPUNIT_ASSERT(resampled[i] <= 0.0);
     }
 
-    for (int i = 32768/8+1; i < 32768/4; i++) {
+    for (size_t i = 32768 / 8 + 1; i < 32768 / 4; i++) {
         CPPUNIT_ASSERT(resampled[i] >= 0.0);
         CPPUNIT_ASSERT(resampled[i] <= 1.0);
     }
@@ -197,25 +178,16 @@ void DelayDetectionTest::testDownSamplingData()
 
 void DelayDetectionTest::testDelayDetection()
 {
-
-    int delay = 100;
-
     SFLDataFormat spkr[WINDOW_SIZE];
-    memset(spkr, 0, sizeof(SFLDataFormat) *WINDOW_SIZE);
-    spkr[0] = 32000;
-    spkr[1] = 32000;
-    spkr[2] = 32000;
-    spkr[3] = 32000;
-    spkr[4] = 32000;
+    memset(spkr, 0, sizeof spkr);
+    for (size_t i = 0; i < 5; ++i)
+        spkr[i] = 32000;
 
     SFLDataFormat mic[DELAY_BUFF_SIZE];
-    memset(mic, 0, sizeof(SFLDataFormat) *DELAY_BUFF_SIZE);
-    mic[delay] = 32000;
-    mic[delay+1] = 32000;
-    mic[delay+2] = 32000;
-    mic[delay+3] = 32000;
-    mic[delay+4] = 32000;
-
-    delaydetect_.putData(spkr, WINDOW_SIZE);
-    delaydetect_.process(mic, DELAY_BUFF_SIZE);
+    memset(mic, 0, sizeof mic);
+    for (size_t delay = 100; delay < 105; ++delay)
+        mic[delay] = 32000;
+
+    delaydetect_.putData(spkr, ARRAYSIZE(spkr));
+    delaydetect_.process(mic, ARRAYSIZE(mic));
 }
diff --git a/daemon/test/delaydetectiontest.h b/daemon/test/delaydetectiontest.h
index 11d4eef7d5a3afc917ebdbc7217a969fb7e0b2ba..3075fb6186b4dfd23edeb01d547b3eaf9dd3425b 100644
--- a/daemon/test/delaydetectiontest.h
+++ b/daemon/test/delaydetectiontest.h
@@ -35,33 +35,10 @@
 #include <cppunit/TestCase.h>
 #include <cppunit/TestSuite.h>
 
-#include <assert.h>
-
-#include <stdio.h>
-#include <sstream>
-#include <ccrtp/rtp.h>
-
-
-// pjsip import
-#include <pjsip.h>
-#include <pjlib.h>
-#include <pjsip_ua.h>
-#include <pjlib-util.h>
-#include <pjnath/stun_config.h>
-
-// Application import
-#include "manager.h"
-#include "audio/mainbuffer.h"
-#include "audio/ringbuffer.h"
-#include "call.h"
-// #include "config/config.h"
-// #include "user_cfg.h"
-
-
 #include "audio/delaydetection.h"
 
-#ifndef _DELAYDETECTION_TEST_
-#define _DELAYDETECTION_TEST_
+#ifndef DELAYDETECTION_TEST_
+#define DELAYDETECTION_TEST_
 
 /*
  * @file delaydetection.cpp
@@ -83,10 +60,6 @@ class DelayDetectionTest : public CppUnit::TestCase {
 
         DelayDetectionTest() : CppUnit::TestCase("Delay Detection Tests") {}
 
-        void setUp();
-
-        void tearDown();
-
         void testCrossCorrelation();
 
         void testCrossCorrelationDelay();
@@ -109,4 +82,4 @@ class DelayDetectionTest : public CppUnit::TestCase {
 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(DelayDetectionTest, "DelayDetectionTest");
 CPPUNIT_TEST_SUITE_REGISTRATION(DelayDetectionTest);
 
-#endif
+#endif // DELAYDETECTION_TEST_
diff --git a/daemon/test/echocanceltest.cpp b/daemon/test/echocanceltest.cpp
index 832b9ed0d996b07ac765de0d29b5098cb3cd3958..c872003641eb081dd9d4cb8972f2427eaa511b43 100644
--- a/daemon/test/echocanceltest.cpp
+++ b/daemon/test/echocanceltest.cpp
@@ -33,15 +33,12 @@
 #include "echocanceltest.h"
 #include "config/sfl_config.h"
 
-using namespace std;
-
 EchoCancelTest::EchoCancelTest() : echoCanceller_() {}
 
 void EchoCancelTest::testEchoCancelProcessing()
 {
-    const int nbSamples = 160;
-    int inputFileLength = 0;
-    int remainingLength = 0;
+    using std::ifstream;
+    using std::ofstream;
 
     SFLDataFormat micData[1000];
     SFLDataFormat spkrData[1000];
@@ -54,13 +51,12 @@ void EchoCancelTest::testEchoCancelProcessing()
     // echo cancelled output
     ofstream echoCancelFile("sample_echocancel_500ms_8kHz_16bit.raw", ofstream::out);
 
-    micFile.seekg(0, ios::end);
-    inputFileLength = micFile.tellg() / sizeof(SFLDataFormat);
-    micFile.seekg(0, ios::beg);
-
-    remainingLength = inputFileLength;
+    micFile.seekg(0, std::ios::end);
+    size_t inputFileLength = micFile.tellg() / sizeof(SFLDataFormat);
+    micFile.seekg(0, std::ios::beg);
 
-    while (remainingLength >= nbSamples) {
+    const int nbSamples = 160;
+    for (int remainingLength = inputFileLength; remainingLength >= nbSamples; remainingLength -= nbSamples) {
         micFile.read(reinterpret_cast<char *>(micData), nbSamples * sizeof(SFLDataFormat));
         spkrFile.read(reinterpret_cast<char *>(spkrData), nbSamples * sizeof(SFLDataFormat));
 
@@ -68,8 +64,6 @@ void EchoCancelTest::testEchoCancelProcessing()
         echoCanceller_.process(micData, echoCancelData, nbSamples);
 
         echoCancelFile.write(reinterpret_cast<char *>(echoCancelData), nbSamples * sizeof(SFLDataFormat));
-
-        remainingLength -= nbSamples;
     }
 
     CPPUNIT_ASSERT(true);
diff --git a/daemon/test/echocanceltest.h b/daemon/test/echocanceltest.h
index 6bd8f3a4c8358e2a8e82ddd11ea3e1d16e7cc370..7c378fc9f054dbb2a7ee574454890fc64687856d 100644
--- a/daemon/test/echocanceltest.h
+++ b/daemon/test/echocanceltest.h
@@ -42,8 +42,6 @@
 #include <cppunit/TestCase.h>
 #include <cppunit/TestSuite.h>
 
-#include <cassert>
-
 #include "audio/speexechocancel.h"
 
 class EchoCancelTest: public CppUnit::TestFixture {
diff --git a/daemon/test/gaincontroltest.cpp b/daemon/test/gaincontroltest.cpp
index fa3968ddcaeca4b06234a78db85c1f4bae03bd73..ed5492099b141bf04b61b8be2fb8b6d966f8f3b0 100644
--- a/daemon/test/gaincontroltest.cpp
+++ b/daemon/test/gaincontroltest.cpp
@@ -28,13 +28,10 @@
  *  as that of the covered work.
  */
 
-#include <iostream>
-
 #include "gaincontroltest.h"
+#include "audio/gaincontrol.h"
 #include "config/sfl_config.h"
 
-using namespace std;
-
 void GainControlTest::testGainProcessing()
 {
 #if 0
diff --git a/daemon/test/gaincontroltest.h b/daemon/test/gaincontroltest.h
index 14f55d09b36a209961efd5893eba6e16c021941d..1f1bef03607bf39cce561d98f25eaabcb79b4c91 100644
--- a/daemon/test/gaincontroltest.h
+++ b/daemon/test/gaincontroltest.h
@@ -33,8 +33,8 @@
  * @brief       Regroups unitary tests related to the plugin manager.
  */
 
-#ifndef _GAINCONTROL_TEST_
-#define _GAINCONTROL_TEST_
+#ifndef GAINCONTROL_TEST_
+#define GAINCONTROL_TEST_
 
 // Cppunit import
 #include <cppunit/extensions/HelperMacros.h>
@@ -42,9 +42,7 @@
 #include <cppunit/TestCase.h>
 #include <cppunit/TestSuite.h>
 
-#include <assert.h>
-
-#include "audio/gaincontrol.h"
+#include "sfl_types.h"
 
 class GainControlTest: public CppUnit::TestFixture {
 
@@ -55,12 +53,8 @@ class GainControlTest: public CppUnit::TestFixture {
     public:
 
         void testGainProcessing();
-
-    private:
-
-
 };
 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(GainControlTest, "GainControlTest");
 CPPUNIT_TEST_SUITE_REGISTRATION(GainControlTest);
 
-#endif
+#endif // GAINCONTROL_TEST_
diff --git a/daemon/test/historytest.cpp b/daemon/test/historytest.cpp
index 1c6ec3596cf47fef70163e357ed7123df42e6bf4..fe6aa20baed4d2764e77dc9f0427973bf6328cee 100644
--- a/daemon/test/historytest.cpp
+++ b/daemon/test/historytest.cpp
@@ -28,28 +28,23 @@
  *  as that of the covered work.
  */
 
-#include <cstdio>
-#include <sstream>
 #include <cstdlib>
 
 #include "historytest.h"
+#include "history/history.h"
 #include "logger.h"
 #include "constants.h"
-#include "validator.h"
-
-using std::cout;
-using std::endl;
 
 namespace {
 void restore()
 {
-    if (system("mv " HISTORY_SAMPLE ".bak " HISTORY_SAMPLE) < 0)
-        ERROR("Restoration of %s failed" HISTORY_SAMPLE);
+    if (system("mv " HISTORY_SAMPLE_BAK " " HISTORY_SAMPLE) < 0)
+        ERROR("Restoration of %s failed", HISTORY_SAMPLE);
 }
 
 void backup()
 {
-    if (system("cp " HISTORY_SAMPLE " " HISTORY_SAMPLE ".bak") < 0)
+    if (system("cp " HISTORY_SAMPLE " " HISTORY_SAMPLE_BAK) < 0)
         ERROR("Backup of %s failed", HISTORY_SAMPLE);
 }
 }
diff --git a/daemon/test/historytest.h b/daemon/test/historytest.h
index 19f2b372e8b5b45579394a80e27f2b197b601901..5f92cf38e2c82fd106c94e99fb13f9d13c0ce718 100644
--- a/daemon/test/historytest.h
+++ b/daemon/test/historytest.h
@@ -38,8 +38,8 @@
 
 // Application import
 #include "noncopyable.h"
-#include "history/history.h"
 
+class History;
 /*
  * @file historyTest.h
  * @brief       Regroups unitary tests related to the phone number cleanup function.
diff --git a/daemon/test/instantmessagingtest.cpp b/daemon/test/instantmessagingtest.cpp
index 99bfa259a2a80021d76f26dd0dea9a66fa247d0b..82571a2f3c7ab23fbcf6dbde186634391ec6200a 100644
--- a/daemon/test/instantmessagingtest.cpp
+++ b/daemon/test/instantmessagingtest.cpp
@@ -30,25 +30,21 @@
 
 #include <iostream>
 #include <fstream>
+#include <expat.h>
+#include "test_utils.h"
 
 #include "instantmessagingtest.h"
 #include "im/instant_messaging.h"
-
-#include "expat.h"
-#include <cstdio>
+#include "logger.h"
 
 #define MAXIMUM_SIZE	10
 #define DELIMITER_CHAR	"\n\n"
 
-using std::cout;
-using std::endl;
 using namespace sfl::InstantMessaging;
 
 void InstantMessagingTest::testSaveSingleMessage()
 {
-    DEBUG("-------------------- InstantMessagingTest::testSaveSingleMessage --------------------\n");
-
-    std::string input, tmp;
+    TITLE();
     std::string callID = "testfile1.txt";
     std::string filename = "im:";
 
@@ -60,7 +56,9 @@ void InstantMessagingTest::testSaveSingleMessage()
     std::ifstream testfile(filename.c_str(), std::ios::in);
     CPPUNIT_ASSERT(testfile.is_open());
 
+    std::string input;
     while (!testfile.eof()) {
+        std::string tmp;
         std::getline(testfile, tmp);
         input.append(tmp);
     }
@@ -71,9 +69,8 @@ void InstantMessagingTest::testSaveSingleMessage()
 
 void InstantMessagingTest::testSaveMultipleMessage()
 {
-    DEBUG("-------------------- InstantMessagingTest::testSaveMultipleMessage --------------------\n");
+    TITLE();
 
-    std::string input, tmp;
     std::string callID = "testfile2.txt";
     std::string filename = "im:";
 
@@ -86,7 +83,9 @@ void InstantMessagingTest::testSaveMultipleMessage()
     std::ifstream testfile(filename.c_str(), std::ios::in);
     CPPUNIT_ASSERT(testfile.is_open());
 
+    std::string input;
     while (!testfile.eof()) {
+        std::string tmp;
         std::getline(testfile, tmp);
         input.append(tmp);
     }
@@ -108,14 +107,12 @@ static void XMLCALL startElementCallback(void *userData, const char *name, const
 
     std::cout << "startElement " << name << std::endl;
 
-    int *nbEntry = (int *)userData;
+    int *nbEntry = (int *) userData;
 
     char attribute[50];
     char value[50];
 
-    const char **att;
-
-    for (att = atts; *att; att += 2) {
+    for (const char **att = atts; *att; att += 2) {
 
         const char **val = att+1;
 
@@ -169,13 +166,11 @@ void InstantMessagingTest::testGenerateXmlUriList()
     XML_SetElementHandler(parser, startElementCallback, endElementCallback);
 
     if (XML_Parse(parser, buffer.c_str(), buffer.size(), 1) == XML_STATUS_ERROR) {
-        std::cout << "Error: " << XML_ErrorString(XML_GetErrorCode(parser))
-                  << " at line " << XML_GetCurrentLineNumber(parser) << std::endl;
+        ERROR("%s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
         CPPUNIT_ASSERT(false);
     }
 
     XML_ParserFree(parser);
-
     CPPUNIT_ASSERT(nbEntry == 4);
 }
 
@@ -197,20 +192,13 @@ void InstantMessagingTest::testXmlUriListParsing()
     sfl::InstantMessaging::UriEntry::iterator iterAttr;
 
     // An iterator over list entries
-    sfl::InstantMessaging::UriList::iterator iterEntry = list.begin();
-
-
-    while (iterEntry != list.end()) {
+    for (sfl::InstantMessaging::UriList::iterator iterEntry = list.begin();
+            iterEntry != list.end(); ++iterEntry) {
         sfl::InstantMessaging::UriEntry entry = static_cast<sfl::InstantMessaging::UriEntry>(*iterEntry);
         iterAttr = entry.find(sfl::IM_XML_URI);
 
-        if ((iterAttr->second == std::string("sip:alex@example.com")) ||
-                (iterAttr->second == std::string("sip:manu@example.com")))
-            CPPUNIT_ASSERT(true);
-        else
-            CPPUNIT_ASSERT(false);
-
-        iterEntry++;
+        CPPUNIT_ASSERT((iterAttr->second == std::string("sip:alex@example.com")) or
+                (iterAttr->second == std::string("sip:manu@example.com")));
     }
 }
 
@@ -232,8 +220,7 @@ void InstantMessagingTest::testGetTextArea()
     formatedText.append("--boundary--");
 
     std::string message(findTextMessage(formatedText));
-
-    std::cout << "message " << message << std::endl;
+    DEBUG("Message %s", message.c_str());
 
     CPPUNIT_ASSERT(message == "Here is the text area");
 }
@@ -270,7 +257,7 @@ void InstantMessagingTest::testGetUriListArea()
     sfl::InstantMessaging::UriEntry::iterator iterAttr = entry.find(sfl::IM_XML_URI);
 
     if (iterAttr == entry.end()) {
-        std::cout << "Error, did not found attribute" << std::endl;
+        ERROR("Did not find attribute");
         CPPUNIT_ASSERT(false);
     }
 
@@ -303,8 +290,5 @@ void InstantMessagingTest::testIllFormatedMessage()
         exceptionCaught = true;
     }
 
-    if (exceptionCaught)
-        CPPUNIT_ASSERT(true);
-    else
-        CPPUNIT_ASSERT(false);
+    CPPUNIT_ASSERT(exceptionCaught);
 }
diff --git a/daemon/test/main.cpp b/daemon/test/main.cpp
index 36521769f316ad6923e4345be68bf3a534315036..624c6531e33ab4299ea1b1c1c553cce1a498700f 100644
--- a/daemon/test/main.cpp
+++ b/daemon/test/main.cpp
@@ -43,12 +43,12 @@
 namespace {
     void restore()
     {
-        if (system("mv " CONFIG_SAMPLE ".bak " CONFIG_SAMPLE) < 0)
+        if (system("mv " CONFIG_SAMPLE_BAK " " CONFIG_SAMPLE) < 0)
             ERROR("Restoration of %s failed", CONFIG_SAMPLE);
     }
     void backup()
     {
-        if (system("cp " CONFIG_SAMPLE " " CONFIG_SAMPLE ".bak") < 0)
+        if (system("cp " CONFIG_SAMPLE " " CONFIG_SAMPLE_BAK) < 0)
             ERROR("Backup of %s failed", CONFIG_SAMPLE);
     }
 }
diff --git a/daemon/test/mainbuffertest.cpp b/daemon/test/mainbuffertest.cpp
index 2b5e80371cd65d7fe2a00e792518fd501d9a5d42..5a3f40790509c837efac373b371984805752e245 100644
--- a/daemon/test/mainbuffertest.cpp
+++ b/daemon/test/mainbuffertest.cpp
@@ -28,44 +28,16 @@
  *  as that of the covered work.
  */
 
-#include <stdio.h>
-#include <sstream>
-#include <ccrtp/rtp.h>
-#include <assert.h>
 #include <string>
-#include <cstring>
-#include <math.h>
-#include <dlfcn.h>
-#include <iostream>
-#include <sstream>
-
-
 #include "mainbuffertest.h"
-
-#include <unistd.h>
-
-
-using std::cout;
-using std::endl;
-
-
-void MainBufferTest::setUp()
-{
-
-
-}
-
-
-void MainBufferTest::tearDown()
-{
-
-}
-
+#include "audio/mainbuffer.h"
+#include "audio/ringbuffer.h"
+#include "logger.h"
+#include "test_utils.h"
 
 void MainBufferTest::testRingBufferCreation()
 {
-    DEBUG("-------------------- MainBufferTest::testRingBufferCreation --------------------\n");
-
+    TITLE();
     std::string test_id = "1234";
     std::string null_id = "null id";
 
@@ -73,46 +45,45 @@ void MainBufferTest::testRingBufferCreation()
     RingBufferMap::iterator iter;
 
     // test mainbuffer ringbuffer map size
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.empty());
-    test_ring_buffer = mainbuffer_.createRingBuffer(test_id);
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 1);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.empty());
+    test_ring_buffer = mainbuffer_->createRingBuffer(test_id);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 1);
 
-    // test mainbuffer_.getRingBuffer method
+    // test mainbuffer_->getRingBuffer method
     CPPUNIT_ASSERT(test_ring_buffer != NULL);
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(null_id) == NULL);
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 1);
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id) == test_ring_buffer);
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(null_id) == NULL);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 1);
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(test_id) == test_ring_buffer);
 
     // test mainbuffer_ ringBufferMap_
-    iter = mainbuffer_.ringBufferMap_.find(null_id);
-    CPPUNIT_ASSERT(iter == mainbuffer_.ringBufferMap_.end());
-    iter = mainbuffer_.ringBufferMap_.find(test_id);
+    iter = mainbuffer_->ringBufferMap_.find(null_id);
+    CPPUNIT_ASSERT(iter == mainbuffer_->ringBufferMap_.end());
+    iter = mainbuffer_->ringBufferMap_.find(test_id);
     CPPUNIT_ASSERT(iter->first == test_id);
     CPPUNIT_ASSERT(iter->second == test_ring_buffer);
-    CPPUNIT_ASSERT(iter->second == mainbuffer_.getRingBuffer(test_id));
+    CPPUNIT_ASSERT(iter->second == mainbuffer_->getRingBuffer(test_id));
 
     // test creating twice a buffer (should not create it)
-    mainbuffer_.createRingBuffer(test_id);
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 1);
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id) == test_ring_buffer);
+    mainbuffer_->createRingBuffer(test_id);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 1);
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(test_id) == test_ring_buffer);
 
     // test remove ring buffer
-    CPPUNIT_ASSERT(mainbuffer_.removeRingBuffer(null_id));
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 1);
-    CPPUNIT_ASSERT(mainbuffer_.removeRingBuffer(test_id));
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.empty());
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id) == NULL);
+    CPPUNIT_ASSERT(mainbuffer_->removeRingBuffer(null_id));
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 1);
+    CPPUNIT_ASSERT(mainbuffer_->removeRingBuffer(test_id));
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.empty());
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(test_id) == NULL);
 
-    iter = mainbuffer_.ringBufferMap_.find(test_id);
-    CPPUNIT_ASSERT(iter == mainbuffer_.ringBufferMap_.end());
+    iter = mainbuffer_->ringBufferMap_.find(test_id);
+    CPPUNIT_ASSERT(iter == mainbuffer_->ringBufferMap_.end());
 
 }
 
 
 void MainBufferTest::testRingBufferReadPointer()
 {
-    DEBUG("-------------------- MainBufferTest::testRingBufferReadPointer --------------------\n");
-
+    TITLE();
     std::string call_id = "call id";
     std::string read_id = "read id";
     std::string null_id = "null id";
@@ -121,7 +92,7 @@ void MainBufferTest::testRingBufferReadPointer()
     RingBuffer* test_ring_buffer;
 
     // test ring buffer read pointers (one per participant)
-    test_ring_buffer = mainbuffer_.createRingBuffer(call_id);
+    test_ring_buffer = mainbuffer_->createRingBuffer(call_id);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 0);
     CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(read_id) == (int) NULL);
 
@@ -158,7 +129,7 @@ void MainBufferTest::testRingBufferReadPointer()
 
 void MainBufferTest::testCallIDSet()
 {
-    DEBUG("-------------------- MainBufferTest::testCallIDSet --------------------\n");
+    TITLE();
 
     std::string test_id = "set id";
     std::string false_id = "false set id";
@@ -171,46 +142,45 @@ void MainBufferTest::testCallIDSet()
     std::string call_id_2 = "call id 2";
 
     // test initial settings
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.empty());
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.empty());
-    iter_map = mainbuffer_.callIDMap_.find(test_id);
-    CPPUNIT_ASSERT(iter_map ==mainbuffer_.callIDMap_.end());
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.empty());
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.empty());
+    iter_map = mainbuffer_->callIDMap_.find(test_id);
+    CPPUNIT_ASSERT(iter_map == mainbuffer_->callIDMap_.end());
 
     // test callidset creation
-    mainbuffer_.createCallIDSet(test_id);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 1);
-    iter_map = mainbuffer_.callIDMap_.find(test_id);
+    mainbuffer_->createCallIDSet(test_id);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 1);
+    iter_map = mainbuffer_->callIDMap_.find(test_id);
     CPPUNIT_ASSERT(iter_map->first == test_id);
-    CPPUNIT_ASSERT(iter_map->second == mainbuffer_.getCallIDSet(test_id));
-
-    CPPUNIT_ASSERT(mainbuffer_.getCallIDSet(false_id) == NULL);
-    CPPUNIT_ASSERT(mainbuffer_.getCallIDSet(test_id) != NULL);
+    CPPUNIT_ASSERT(iter_map->second == mainbuffer_->getCallIDSet(test_id));
 
+    CPPUNIT_ASSERT(mainbuffer_->getCallIDSet(false_id) == NULL);
+    CPPUNIT_ASSERT(mainbuffer_->getCallIDSet(test_id) != NULL);
 
     // Test callIDSet add call_ids
-    mainbuffer_.addCallIDtoSet(test_id, call_id_1);
-    iter_map = mainbuffer_.callIDMap_.find(test_id);
+    mainbuffer_->addCallIDtoSet(test_id, call_id_1);
+    iter_map = mainbuffer_->callIDMap_.find(test_id);
     CPPUNIT_ASSERT(iter_map->second->size() == 1);
     iter_set = iter_map->second->find(call_id_1);
     CPPUNIT_ASSERT(*iter_set == call_id_1);
 
     // test add second call id to set
-    mainbuffer_.addCallIDtoSet(test_id, call_id_2);
-    iter_map = mainbuffer_.callIDMap_.find(test_id);
+    mainbuffer_->addCallIDtoSet(test_id, call_id_2);
+    iter_map = mainbuffer_->callIDMap_.find(test_id);
     CPPUNIT_ASSERT(iter_map->second->size() == 2);
     iter_set = iter_map->second->find(call_id_2);
     CPPUNIT_ASSERT(*iter_set == call_id_2);
 
     // test add a call id twice
-    mainbuffer_.addCallIDtoSet(test_id, call_id_2);
-    iter_map = mainbuffer_.callIDMap_.find(test_id);
+    mainbuffer_->addCallIDtoSet(test_id, call_id_2);
+    iter_map = mainbuffer_->callIDMap_.find(test_id);
     CPPUNIT_ASSERT(iter_map->second->size() == 2);
     iter_set = iter_map->second->find(call_id_2);
     CPPUNIT_ASSERT(*iter_set == call_id_2);
 
     // test remove a call id
-    mainbuffer_.removeCallIDfromSet(test_id, call_id_2);
-    iter_map = mainbuffer_.callIDMap_.find(test_id);
+    mainbuffer_->removeCallIDfromSet(test_id, call_id_2);
+    iter_map = mainbuffer_->callIDMap_.find(test_id);
     CPPUNIT_ASSERT(iter_map->second->size() == 1);
     iter_set = iter_map->second->find(call_id_1);
     CPPUNIT_ASSERT(*iter_set == call_id_1);
@@ -218,8 +188,8 @@ void MainBufferTest::testCallIDSet()
     CPPUNIT_ASSERT(iter_set == iter_map->second->end());
 
     // test remove a call id twice
-    mainbuffer_.removeCallIDfromSet(test_id, call_id_2);
-    iter_map = mainbuffer_.callIDMap_.find(test_id);
+    mainbuffer_->removeCallIDfromSet(test_id, call_id_2);
+    iter_map = mainbuffer_->callIDMap_.find(test_id);
     CPPUNIT_ASSERT(iter_map->second->size() == 1);
     iter_set = iter_map->second->find(call_id_1);
     CPPUNIT_ASSERT(*iter_set == call_id_1);
@@ -227,158 +197,119 @@ void MainBufferTest::testCallIDSet()
     CPPUNIT_ASSERT(iter_set == iter_map->second->end());
 
     // Test removeCallIDSet
-    CPPUNIT_ASSERT(!mainbuffer_.removeCallIDSet(false_id));
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 1);
-    CPPUNIT_ASSERT(mainbuffer_.removeCallIDSet(test_id));
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.empty());
+    CPPUNIT_ASSERT(!mainbuffer_->removeCallIDSet(false_id));
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 1);
+    CPPUNIT_ASSERT(mainbuffer_->removeCallIDSet(test_id));
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.empty());
 
-    iter_map = mainbuffer_.callIDMap_.find(test_id);
-    CPPUNIT_ASSERT(iter_map == mainbuffer_.callIDMap_.end());
+    iter_map = mainbuffer_->callIDMap_.find(test_id);
+    CPPUNIT_ASSERT(iter_map == mainbuffer_->callIDMap_.end());
 }
 
 
 void MainBufferTest::testRingBufferInt()
 {
-    DEBUG("-------------------- MainBufferTest::testRingBufferInt --------------------\n");
-
-    // CallID test_id = "test_int";
+    TITLE();
 
     int testint1 = 12;
     int testint2 = 13;
 
     // test with default ring buffer
-    RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(default_id);
+    RingBuffer* test_ring_buffer = mainbuffer_->createRingBuffer(MainBuffer::DEFAULT_ID);
 
     // initial state
-    int init_put_size = test_ring_buffer->AvailForPut();
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 0);
 
     // add some data
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint1, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 0);
 
     // add some other data
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint2, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint2, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 0);
 
     int testget = (int) NULL;
 
     // get some data (without any read pointers)
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 2*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == 2*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int)) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 2*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == 2*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 2*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->getLen(MainBuffer::DEFAULT_ID) == 2*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int), MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 2*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->getLen(MainBuffer::DEFAULT_ID) == 2*sizeof(int));
     CPPUNIT_ASSERT(testget == (int) NULL);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 0);
 
     // get some data (with a read pointer)
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 0);
-    test_ring_buffer->createReadPointer(default_id);
+    test_ring_buffer->createReadPointer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getLen(MainBuffer::DEFAULT_ID) == 0);
 
     // add some data
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint1, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 2*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 2*sizeof(int));
 
     // add some other data
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint2, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint2, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 2*sizeof(int));
-
-    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int), 100, default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == sizeof(int));
-    CPPUNIT_ASSERT(testget == testint1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 3*sizeof(int));
-
-    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int)) == sizeof(int));
-    CPPUNIT_ASSERT(testget == testint2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size);
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 4*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 2*sizeof(int));
 
+    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int), MainBuffer::DEFAULT_ID) == sizeof(int));
 
     // test flush data
-    init_put_size = test_ring_buffer->AvailForPut();
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == sizeof(int));
+    test_ring_buffer->Put(&testint1, sizeof(int));
 
-
-    test_ring_buffer->flush();
+    test_ring_buffer->flush(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size);
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 5*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->getLen(MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 5*sizeof(int));
 
     // test flush data
-    init_put_size = test_ring_buffer->AvailForPut();
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint1, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 5*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->getLen(MainBuffer::DEFAULT_ID) == sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 5*sizeof(int));
 
-    test_ring_buffer->Discard(sizeof(int));
+    test_ring_buffer->Discard(sizeof(int), MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size);
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 6*sizeof(int));
-
-
+    CPPUNIT_ASSERT(test_ring_buffer->getLen(MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 6*sizeof(int));
 }
 
 
 void MainBufferTest::testRingBufferNonDefaultID()
 {
-    DEBUG("-------------------- MainBufferTest::testRingBufferNonDefaultID --------------------\n");
+    TITLE();
 
     std::string test_id = "test_int";
 
     int testint1 = 12;
     int testint2 = 13;
-    int init_put_size;
-
 
     // test putData, getData with arbitrary read pointer id
-    RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(default_id);
+    RingBuffer* test_ring_buffer = mainbuffer_->createRingBuffer(MainBuffer::DEFAULT_ID);
     test_ring_buffer->createReadPointer(test_id);
 
-    init_put_size = test_ring_buffer->AvailForPut();
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(default_id) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 0);
 
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint1, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(default_id) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 0);
 
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint2, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint2, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(default_id) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 0);
 
     int testget;
 
@@ -388,47 +319,39 @@ void MainBufferTest::testRingBufferNonDefaultID()
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == sizeof(int));
     CPPUNIT_ASSERT(testget == testint1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int)));
     CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == sizeof(int));
 
-    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int), 100, test_id) == sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, 100, test_id) == sizeof(int));
     CPPUNIT_ASSERT(testget == testint2);
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == 0);
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size);
     CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 2*sizeof(int));
 
 
     // test flush data
-    init_put_size = test_ring_buffer->AvailForPut();
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint1, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int)));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == sizeof(int));
 
 
     test_ring_buffer->flush(test_id);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size);
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == 0);
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == 0);
     CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 3*sizeof(int));
 
     // test flush data
-    init_put_size = test_ring_buffer->AvailForPut();
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint1, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int)));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 3*sizeof(int));
 
     test_ring_buffer->Discard(sizeof(int), test_id);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size);
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == 0);
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == 0);
     CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 4*sizeof(int));
@@ -440,33 +363,32 @@ void MainBufferTest::testRingBufferNonDefaultID()
 
 void MainBufferTest::testRingBufferFloat()
 {
-    DEBUG("-------------------- MainBufferTest::testRingBufferFloat --------------------\n");
-
+    TITLE();
     float testfloat1 = 12.5;
     float testfloat2 = 13.4;
 
-    RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(default_id);
-    test_ring_buffer->createReadPointer(default_id);
+    RingBuffer* test_ring_buffer = mainbuffer_->createRingBuffer(MainBuffer::DEFAULT_ID);
+    test_ring_buffer->createReadPointer(MainBuffer::DEFAULT_ID);
 
 
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testfloat1, sizeof(float)) == sizeof(float));
+    test_ring_buffer->Put(&testfloat1, sizeof(float));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(float));
 
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testfloat2, sizeof(float)) == sizeof(float));
+    test_ring_buffer->Put(&testfloat2, sizeof(float));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(float));
 
     float testget;
 
-    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(float)) == sizeof(float));
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == sizeof(float));
+    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(float), MainBuffer::DEFAULT_ID) == sizeof(float));
+    CPPUNIT_ASSERT(test_ring_buffer->getLen(MainBuffer::DEFAULT_ID) == sizeof(float));
     CPPUNIT_ASSERT(testget == testfloat1);
 
-    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(float)) == sizeof(float));
+    CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(float), MainBuffer::DEFAULT_ID) == sizeof(float));
     CPPUNIT_ASSERT(testget == testfloat2);
-    CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->getLen(MainBuffer::DEFAULT_ID) == 0);
 
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testfloat1, sizeof(float)) == sizeof(float));
-    test_ring_buffer->flush();
+    test_ring_buffer->Put(&testfloat1, sizeof(float));
+    test_ring_buffer->flush(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
 
 }
@@ -474,24 +396,23 @@ void MainBufferTest::testRingBufferFloat()
 
 void MainBufferTest::testTwoPointer()
 {
-    DEBUG("-------------------- MainBufferTest::testTwoPointer --------------------\n");
-
-    RingBuffer* input_buffer = mainbuffer_.createRingBuffer(default_id);
-    input_buffer->createReadPointer(default_id);
-    RingBuffer* output_buffer = mainbuffer_.getRingBuffer(default_id);
+    TITLE();
+    RingBuffer* input_buffer = mainbuffer_->createRingBuffer(MainBuffer::DEFAULT_ID);
+    input_buffer->createReadPointer(MainBuffer::DEFAULT_ID);
+    RingBuffer* output_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
 
     int test_input = 12;
-    int test_output;
+    int test_output = 0;
 
-    CPPUNIT_ASSERT(input_buffer->Put(&test_input, sizeof(int)) == sizeof(int));
-    CPPUNIT_ASSERT(output_buffer->Get(&test_output, sizeof(float)) == sizeof(float));
+    input_buffer->Put(&test_input, sizeof(int));
+    CPPUNIT_ASSERT(output_buffer->Get(&test_output, sizeof(float), MainBuffer::DEFAULT_ID) == sizeof(float));
     CPPUNIT_ASSERT(test_input == test_output);
 
 }
 
 void MainBufferTest::testBindUnbindBuffer()
 {
-    DEBUG("-------------------- MainBufferTest::testBindUnbindBuffer --------------------\n");
+    TITLE();
 
     std::string test_id1 = "bind unbind 1";
     std::string test_id2 = "bind unbind 2";
@@ -505,266 +426,266 @@ void MainBufferTest::testBindUnbindBuffer()
     RingBuffer* ringbuffer;
 
     // test initial state with no ring brffer created
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 0);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 0);
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_buffer == mainbuffer_.ringBufferMap_.end());
-    iter_idset = mainbuffer_.callIDMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_idset == mainbuffer_.callIDMap_.end());
+    iter_buffer = mainbuffer_->ringBufferMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer == mainbuffer_->ringBufferMap_.end());
+    iter_idset = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_idset == mainbuffer_->callIDMap_.end());
 
-    // bind test_id1 with default_id (both buffer not already created)
-    mainbuffer_.bindCallID(test_id1);
+    // bind test_id1 with MainBuffer::DEFAULT_ID (both buffer not already created)
+    mainbuffer_->bindCallID(test_id1, MainBuffer::DEFAULT_ID);
 
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 2);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 2);
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_buffer->first == default_id);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id));
+    iter_buffer = mainbuffer_->ringBufferMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->first == MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1);
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_buffer->first == test_id1);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1));
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(test_id1));
 
-    iter_idset = mainbuffer_.callIDMap_.find(default_id);
+    iter_idset = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
     iter_id = iter_idset->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_id == test_id1);
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id1);
+    iter_idset = mainbuffer_->callIDMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
-    iter_id = iter_idset->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_id == default_id);
+    iter_id = iter_idset->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_id == MainBuffer::DEFAULT_ID);
 
-    ringbuffer = mainbuffer_.getRingBuffer(default_id);
+    ringbuffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id1);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
-    ringbuffer = mainbuffer_.getRingBuffer(test_id1);
+    ringbuffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = ringbuffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
 
-    // unbind test_id1 with default_id
-    mainbuffer_.unBindCallID(test_id1);
+    // unbind test_id1 with MainBuffer::DEFAULT_ID
+    mainbuffer_->unBindCallID(test_id1, MainBuffer::DEFAULT_ID);
 
-    DEBUG("%i", (int)(mainbuffer_.ringBufferMap_.size()));
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0);
+    DEBUG("%i", (int)(mainbuffer_->ringBufferMap_.size()));
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 0);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 0);
 
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id) == NULL);
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id1) == NULL);
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID) == NULL);
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(test_id1) == NULL);
 
 
-    // bind test_id2 with default_id (default_id already created)
+    // bind test_id2 with MainBuffer::DEFAULT_ID (MainBuffer::DEFAULT_ID already created)
     // calling it twice not supposed to break anything
-    mainbuffer_.bindCallID(test_id1, default_id);
-    mainbuffer_.bindCallID(test_id1, default_id);
+    mainbuffer_->bindCallID(test_id1, MainBuffer::DEFAULT_ID);
+    mainbuffer_->bindCallID(test_id1, MainBuffer::DEFAULT_ID);
 
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 2);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 2);
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2);
-    CPPUNIT_ASSERT(iter_buffer == mainbuffer_.ringBufferMap_.end());
-    iter_idset = mainbuffer_.callIDMap_.find(test_id2);
-    CPPUNIT_ASSERT(iter_idset == mainbuffer_.callIDMap_.end());
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id2);
+    CPPUNIT_ASSERT(iter_buffer == mainbuffer_->ringBufferMap_.end());
+    iter_idset = mainbuffer_->callIDMap_.find(test_id2);
+    CPPUNIT_ASSERT(iter_idset == mainbuffer_->callIDMap_.end());
 
-    mainbuffer_.bindCallID(test_id2, default_id);
-    mainbuffer_.bindCallID(test_id2, default_id);
+    mainbuffer_->bindCallID(test_id2, MainBuffer::DEFAULT_ID);
+    mainbuffer_->bindCallID(test_id2, MainBuffer::DEFAULT_ID);
 
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 3);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 3);
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_buffer->first == default_id);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id));
+    iter_buffer = mainbuffer_->ringBufferMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->first == MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1);
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_buffer->first == test_id1);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1));
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(test_id1));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2);
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id2);
     CPPUNIT_ASSERT(iter_buffer->first == test_id2);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id2));
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(test_id2));
 
-    iter_idset = mainbuffer_.callIDMap_.find(default_id);
+    iter_idset = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_idset->second->size() == 2);
     iter_id = iter_idset->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_id == test_id1);
     iter_id = iter_idset->second->find(test_id2);
     CPPUNIT_ASSERT(*iter_id == test_id2);
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id1);
+    iter_idset = mainbuffer_->callIDMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
-    iter_id = iter_idset->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_id == default_id);
+    iter_id = iter_idset->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_id == MainBuffer::DEFAULT_ID);
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id2);
+    iter_idset = mainbuffer_->callIDMap_.find(test_id2);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
-    iter_id = iter_idset->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_id == default_id);
+    iter_id = iter_idset->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_id == MainBuffer::DEFAULT_ID);
 
-    ringbuffer = mainbuffer_.getRingBuffer(default_id);
+    ringbuffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id1);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id2);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id2);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id2);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
-    ringbuffer = mainbuffer_.getRingBuffer(test_id1);
+    ringbuffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = ringbuffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
-    ringbuffer = mainbuffer_.getRingBuffer(test_id2);
+    ringbuffer = mainbuffer_->getRingBuffer(test_id2);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = ringbuffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
     // bind test_id1 with test_id2 (both testid1 and test_id2 already created)
     // calling it twice not supposed to break anything
-    mainbuffer_.bindCallID(test_id1, test_id2);
-    mainbuffer_.bindCallID(test_id1, test_id2);
+    mainbuffer_->bindCallID(test_id1, test_id2);
+    mainbuffer_->bindCallID(test_id1, test_id2);
 
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 3);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 3);
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_buffer->first == default_id);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id));
+    iter_buffer = mainbuffer_->ringBufferMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->first == MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1);
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_buffer->first == test_id1);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1));
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(test_id1));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2);
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id2);
     CPPUNIT_ASSERT(iter_buffer->first == test_id2);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id2));
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(test_id2));
 
-    iter_idset = mainbuffer_.callIDMap_.find(default_id);
+    iter_idset = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_idset->second->size() == 2);
     iter_id = iter_idset->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_id == test_id1);
     iter_id = iter_idset->second->find(test_id2);
     CPPUNIT_ASSERT(*iter_id == test_id2);
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id1);
+    iter_idset = mainbuffer_->callIDMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_idset->second->size() == 2);
-    iter_id = iter_idset->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_id == default_id);
+    iter_id = iter_idset->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_id == MainBuffer::DEFAULT_ID);
     iter_id = iter_idset->second->find(test_id2);
     CPPUNIT_ASSERT(*iter_id == test_id2);
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id2);
+    iter_idset = mainbuffer_->callIDMap_.find(test_id2);
     CPPUNIT_ASSERT(iter_idset->second->size() == 2);
-    iter_id = iter_idset->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_id == default_id);
+    iter_id = iter_idset->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_id == MainBuffer::DEFAULT_ID);
     iter_id = iter_idset->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_id == test_id1);
 
-    ringbuffer = mainbuffer_.getRingBuffer(default_id);
+    ringbuffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id1);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id2);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id2);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id2);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
-    ringbuffer = mainbuffer_.getRingBuffer(test_id1);
+    ringbuffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2);
-    iter_readpointer = ringbuffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = ringbuffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id2);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id2);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id2);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
-    ringbuffer = mainbuffer_.getRingBuffer(test_id2);
+    ringbuffer = mainbuffer_->getRingBuffer(test_id2);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2);
-    iter_readpointer = ringbuffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = ringbuffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id1);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
     // unbind test_id1 with test_id2
     // calling it twice not supposed to break anything
-    mainbuffer_.unBindCallID(test_id1, test_id2);
-    mainbuffer_.unBindCallID(test_id1, test_id2);
+    mainbuffer_->unBindCallID(test_id1, test_id2);
+    mainbuffer_->unBindCallID(test_id1, test_id2);
 
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 3);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 3);
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_buffer->first == default_id);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id));
+    iter_buffer = mainbuffer_->ringBufferMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->first == MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1);
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_buffer->first == test_id1);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1));
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(test_id1));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2);
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id2);
     CPPUNIT_ASSERT(iter_buffer->first == test_id2);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id2));
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(test_id2));
 
-    iter_idset = mainbuffer_.callIDMap_.find(default_id);
+    iter_idset = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_idset->second->size() == 2);
     iter_id = iter_idset->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_id == test_id1);
     iter_id = iter_idset->second->find(test_id2);
     CPPUNIT_ASSERT(*iter_id == test_id2);
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id1);
+    iter_idset = mainbuffer_->callIDMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
-    iter_id = iter_idset->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_id == default_id);
+    iter_id = iter_idset->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_id == MainBuffer::DEFAULT_ID);
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id2);
+    iter_idset = mainbuffer_->callIDMap_.find(test_id2);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
-    iter_id = iter_idset->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_id == default_id);
+    iter_id = iter_idset->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_id == MainBuffer::DEFAULT_ID);
 
-    ringbuffer = mainbuffer_.getRingBuffer(default_id);
+    ringbuffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id1);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id2);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id2);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id2);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
-    ringbuffer = mainbuffer_.getRingBuffer(test_id1);
+    ringbuffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = ringbuffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
-    ringbuffer = mainbuffer_.getRingBuffer(test_id2);
+    ringbuffer = mainbuffer_->getRingBuffer(test_id2);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = ringbuffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
 
 
@@ -772,281 +693,249 @@ void MainBufferTest::testBindUnbindBuffer()
 
     // unbind test_id1 with test_id2
     // calling it twice not supposed to break anything
-    mainbuffer_.unBindCallID(default_id, test_id2);
-    mainbuffer_.unBindCallID(default_id, test_id2);
+    mainbuffer_->unBindCallID(MainBuffer::DEFAULT_ID, test_id2);
+    mainbuffer_->unBindCallID(MainBuffer::DEFAULT_ID, test_id2);
 
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 2);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 2);
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_buffer->first == default_id);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id));
+    iter_buffer = mainbuffer_->ringBufferMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->first == MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1);
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_buffer->first == test_id1);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1));
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(test_id1));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2);
-    CPPUNIT_ASSERT(iter_buffer == mainbuffer_.ringBufferMap_.end());
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id2);
+    CPPUNIT_ASSERT(iter_buffer == mainbuffer_->ringBufferMap_.end());
 
-    iter_idset = mainbuffer_.callIDMap_.find(default_id);
+    iter_idset = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
     iter_id = iter_idset->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_id == test_id1);
     iter_id = iter_idset->second->find(test_id2);
     CPPUNIT_ASSERT(iter_id == iter_idset->second->end());
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id1);
+    iter_idset = mainbuffer_->callIDMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
-    iter_id = iter_idset->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_id == default_id);
+    iter_id = iter_idset->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_id == MainBuffer::DEFAULT_ID);
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id2);
-    CPPUNIT_ASSERT(iter_idset == mainbuffer_.callIDMap_.end());
+    iter_idset = mainbuffer_->callIDMap_.find(test_id2);
+    CPPUNIT_ASSERT(iter_idset == mainbuffer_->callIDMap_.end());
 
-    ringbuffer = mainbuffer_.getRingBuffer(default_id);
+    ringbuffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id1);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id2);
-    CPPUNIT_ASSERT(iter_readpointer == ringbuffer->_readpointer.end());
+    iter_readpointer = ringbuffer->readpointer_.find(test_id2);
+    CPPUNIT_ASSERT(iter_readpointer == ringbuffer->readpointer_.end());
 
-    ringbuffer = mainbuffer_.getRingBuffer(test_id1);
+    ringbuffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = ringbuffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id2);
-    CPPUNIT_ASSERT(iter_readpointer == ringbuffer->_readpointer.end());
+    iter_readpointer = ringbuffer->readpointer_.find(test_id2);
+    CPPUNIT_ASSERT(iter_readpointer == ringbuffer->readpointer_.end());
 
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id2) == NULL);
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(test_id2) == NULL);
 
 
-    mainbuffer_.unBindCallID(default_id, test_id1);
+    mainbuffer_->unBindCallID(MainBuffer::DEFAULT_ID, test_id1);
 
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 0);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 0);
 
     // test unbind all function
-    mainbuffer_.bindCallID(default_id, test_id1);
-    mainbuffer_.bindCallID(default_id, test_id2);
-    mainbuffer_.bindCallID(test_id1, test_id2);
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3);
+    mainbuffer_->bindCallID(MainBuffer::DEFAULT_ID, test_id1);
+    mainbuffer_->bindCallID(MainBuffer::DEFAULT_ID, test_id2);
+    mainbuffer_->bindCallID(test_id1, test_id2);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 3);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 3);
 
-    mainbuffer_.unBindAll(test_id2);
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2);
+    mainbuffer_->unBindAll(test_id2);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 2);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 2);
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_buffer->first == default_id);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id));
+    iter_buffer = mainbuffer_->ringBufferMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->first == MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1);
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_buffer->first == test_id1);
-    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1));
+    CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_->getRingBuffer(test_id1));
 
-    iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2);
-    CPPUNIT_ASSERT(iter_buffer == mainbuffer_.ringBufferMap_.end());
+    iter_buffer = mainbuffer_->ringBufferMap_.find(test_id2);
+    CPPUNIT_ASSERT(iter_buffer == mainbuffer_->ringBufferMap_.end());
 
-    iter_idset = mainbuffer_.callIDMap_.find(default_id);
+    iter_idset = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
     iter_id = iter_idset->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_id == test_id1);
     iter_id = iter_idset->second->find(test_id2);
     CPPUNIT_ASSERT(iter_id == iter_idset->second->end());
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id1);
+    iter_idset = mainbuffer_->callIDMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_idset->second->size() == 1);
-    iter_id = iter_idset->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_id == default_id);
+    iter_id = iter_idset->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_id == MainBuffer::DEFAULT_ID);
 
-    iter_idset = mainbuffer_.callIDMap_.find(test_id2);
-    CPPUNIT_ASSERT(iter_idset == mainbuffer_.callIDMap_.end());
+    iter_idset = mainbuffer_->callIDMap_.find(test_id2);
+    CPPUNIT_ASSERT(iter_idset == mainbuffer_->callIDMap_.end());
 
-    ringbuffer = mainbuffer_.getRingBuffer(default_id);
+    ringbuffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id1);
+    iter_readpointer = ringbuffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id2);
-    CPPUNIT_ASSERT(iter_readpointer == ringbuffer->_readpointer.end());
+    iter_readpointer = ringbuffer->readpointer_.find(test_id2);
+    CPPUNIT_ASSERT(iter_readpointer == ringbuffer->readpointer_.end());
 
-    ringbuffer = mainbuffer_.getRingBuffer(test_id1);
+    ringbuffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(ringbuffer != NULL);
     CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1);
-    iter_readpointer = ringbuffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = ringbuffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = ringbuffer->_readpointer.find(test_id2);
-    CPPUNIT_ASSERT(iter_readpointer == ringbuffer->_readpointer.end());
+    iter_readpointer = ringbuffer->readpointer_.find(test_id2);
+    CPPUNIT_ASSERT(iter_readpointer == ringbuffer->readpointer_.end());
 
 
 }
 
 void MainBufferTest::testGetPutDataByID()
 {
-    DEBUG("-------------------- MainBufferTest::testGetPutDataByID --------------------\n");
-
+    TITLE();
     std::string test_id = "getData putData";
     std::string false_id = "false id";
 
-    mainbuffer_.bindCallID(test_id);
+    mainbuffer_->bindCallID(test_id, MainBuffer::DEFAULT_ID);
 
     int test_input1 = 12;
     int test_input2 = 13;
-    int test_output;
+    int test_output = 0;
 
-    int avail_for_put_testid;
-    int avail_for_put_defaultid;
-
-    // put by default_id get by test_id without preleminary put
-    avail_for_put_defaultid = mainbuffer_.availForPut();
-    CPPUNIT_ASSERT(mainbuffer_.availForGetByID(default_id, test_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_output, sizeof(int), default_id, test_id) == 0);
-
-    // put by default_id, get by test_id
-    CPPUNIT_ASSERT(mainbuffer_.availForPut() == avail_for_put_defaultid);
-    CPPUNIT_ASSERT(mainbuffer_.putData(&test_input1, sizeof(int)) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForPut() == (avail_for_put_defaultid - (int) sizeof(int)));
-    CPPUNIT_ASSERT(mainbuffer_.availForGetByID(default_id, test_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_output, sizeof(int), 100, default_id, test_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGetByID(default_id, test_id) == 0);
-    CPPUNIT_ASSERT(test_input1 == test_output);
+    // put by MainBuffer::DEFAULT_ID get by test_id without preleminary put
+    CPPUNIT_ASSERT(mainbuffer_->availForGetByID(MainBuffer::DEFAULT_ID, test_id) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->getDataByID(&test_output, sizeof(int), MainBuffer::DEFAULT_ID, test_id) == 0);
+
+    // put by MainBuffer::DEFAULT_ID, get by test_id
+    mainbuffer_->putData(&test_input1, sizeof(int), MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(mainbuffer_->availForGetByID(MainBuffer::DEFAULT_ID, test_id) == sizeof(int));
 
-    // get by default_id without preliminary input
-    avail_for_put_testid = mainbuffer_.availForPut(test_id);
-    CPPUNIT_ASSERT(mainbuffer_.availForGetByID(test_id, default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_output, sizeof(int), 100, test_id, default_id) == 0);
+    // get by MainBuffer::DEFAULT_ID without preliminary input
+    CPPUNIT_ASSERT(mainbuffer_->availForGetByID(test_id, MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->getDataByID(&test_output, 100, test_id, MainBuffer::DEFAULT_ID) == 0);
 
     // pu by test_id get by test_id
-    CPPUNIT_ASSERT(mainbuffer_.availForPut(test_id) == avail_for_put_defaultid);
-    CPPUNIT_ASSERT(mainbuffer_.putData(&test_input2, sizeof(int), test_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGetByID(test_id, default_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_output, sizeof(int), 100, test_id, default_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGetByID(test_id, default_id) == 0);
+    mainbuffer_->putData(&test_input2, sizeof(int), test_id);
+    CPPUNIT_ASSERT(mainbuffer_->availForGetByID(test_id, MainBuffer::DEFAULT_ID) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->getDataByID(&test_output, 100, test_id, MainBuffer::DEFAULT_ID) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->availForGetByID(test_id, MainBuffer::DEFAULT_ID) == 0);
     CPPUNIT_ASSERT(test_input2 == test_output);
 
     // put/get by false id
-    CPPUNIT_ASSERT(mainbuffer_.putData(&test_input2, sizeof(int), false_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_input2, sizeof(int), 100, false_id, false_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_input2, sizeof(int), 100, default_id, false_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_input2, sizeof(int), 100, false_id, default_id) == 0);
-
-    mainbuffer_.unBindCallID(test_id);
+    mainbuffer_->putData(&test_input2, sizeof(int), false_id);
+    CPPUNIT_ASSERT(mainbuffer_->getDataByID(&test_input2, 100, false_id, false_id) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->getDataByID(&test_input2, 100, MainBuffer::DEFAULT_ID, false_id) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->getDataByID(&test_input2, 100, false_id, MainBuffer::DEFAULT_ID) == 0);
 
+    mainbuffer_->unBindCallID(test_id, MainBuffer::DEFAULT_ID);
 }
 
 
-
 void MainBufferTest::testGetPutData()
 {
-    DEBUG("-------------------- MainBufferTest::testGetPutData --------------------\n");
+    TITLE();
 
     std::string test_id = "incoming rtp session";
 
-    mainbuffer_.bindCallID(test_id);
+    mainbuffer_->bindCallID(test_id, MainBuffer::DEFAULT_ID);
 
     int test_input1 = 12;
     int test_input2 = 13;
     int test_output;
 
-    int avail_for_put_testid;
-    int avail_for_put_defaultid;
-
     // get by test_id without preleminary put
-    avail_for_put_defaultid = mainbuffer_.availForPut();
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100,  test_id) == 0);
-
-    // put by default_id, get by test_id
-    CPPUNIT_ASSERT(mainbuffer_.availForPut() == avail_for_put_defaultid);
-    CPPUNIT_ASSERT(mainbuffer_.putData(&test_input1, sizeof(int)) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForPut() == (avail_for_put_defaultid - (int) sizeof(int)));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100, test_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->getData(&test_output, 100, test_id) == 0);
+
+    // put by MainBuffer::DEFAULT_ID, get by test_id
+    mainbuffer_->putData(&test_input1, sizeof(int), MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->getData(&test_output, 100, test_id) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id) == 0);
     CPPUNIT_ASSERT(test_input1 == test_output);
 
-    // get by default_id without preleminary put
-    avail_for_put_testid = mainbuffer_.availForPut(test_id);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet() == 0);
-    CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int)) == 0);
-
-    // put by test_id, get by default_id
-    CPPUNIT_ASSERT(mainbuffer_.availForPut(test_id) == avail_for_put_testid);
-    CPPUNIT_ASSERT(mainbuffer_.putData(&test_input2, sizeof(int), test_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForPut(test_id) == (avail_for_put_testid - (int) sizeof(int)));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet() == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet() == 0);
+    // get by MainBuffer::DEFAULT_ID without preleminary put
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->getData(&test_output, sizeof(int), MainBuffer::DEFAULT_ID) == 0);
+
+    // put by test_id, get by MainBuffer::DEFAULT_ID
+    mainbuffer_->putData(&test_input2, sizeof(int), test_id);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(MainBuffer::DEFAULT_ID) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->getData(&test_output, 100, MainBuffer::DEFAULT_ID) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(MainBuffer::DEFAULT_ID) == 0);
     CPPUNIT_ASSERT(test_input2 == test_output);
 
-    mainbuffer_.unBindCallID(test_id);
+    mainbuffer_->unBindCallID(test_id, MainBuffer::DEFAULT_ID);
 
 }
 
 
 void MainBufferTest::testDiscardFlush()
 {
-    DEBUG("-------------------- MainBufferTest::testDiscardFlush --------------------\n");
-
+    TITLE();
     std::string test_id = "flush discard";
-    // mainbuffer_.createRingBuffer(test_id);
-    mainbuffer_.bindCallID(test_id);
+    // mainbuffer_->createRingBuffer(test_id);
+    mainbuffer_->bindCallID(test_id, MainBuffer::DEFAULT_ID);
 
     int test_input1 = 12;
     // int test_output_size;
     // int init_size;
 
-    CPPUNIT_ASSERT(mainbuffer_.putData(&test_input1, sizeof(int), test_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet() == sizeof(int));
-    mainbuffer_.discard(sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet() == 0);
-
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0);
-    mainbuffer_.discard(sizeof(int), test_id);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0);
+    mainbuffer_->putData(&test_input1, sizeof(int), test_id);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(MainBuffer::DEFAULT_ID) == sizeof(int));
+    mainbuffer_->discard(sizeof(int), MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(MainBuffer::DEFAULT_ID) == 0);
 
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id)->getReadPointer(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id)->getReadPointer(test_id) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id) == 0);
+    mainbuffer_->discard(sizeof(int), test_id);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id) == 0);
 
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(test_id)->getReadPointer(MainBuffer::DEFAULT_ID) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(test_id)->getReadPointer(test_id) == 0);
 
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id)->getReadPointer(test_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.putData(&test_input1, sizeof(int), 100) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id)->getReadPointer(test_id) == 0);
 
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID)->getReadPointer(test_id) == 0);
+    mainbuffer_->putData(&test_input1, 100, MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID)->getReadPointer(test_id) == 0);
 
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id)->getReadPointer(test_id) == 0);
-    mainbuffer_.discard(sizeof(int), test_id);
-    CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id)->getReadPointer(test_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0);
-
-    // mainbuffer_.removeRingBuffer(test_id);
-    mainbuffer_.unBindCallID(test_id);
+    mainbuffer_->discard(sizeof(int), test_id);
+    CPPUNIT_ASSERT(mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID)->getReadPointer(test_id) == sizeof(int));
 
+    mainbuffer_->unBindCallID(test_id, MainBuffer::DEFAULT_ID);
 }
 
 
 void MainBufferTest::testReadPointerInit()
 {
-    DEBUG("-------------------- MainBufferTest::testReadPointerInit --------------------\n");
-
+    TITLE();
     std::string test_id = "test read pointer init";
-    // RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(test_id);
 
-    mainbuffer_.bindCallID(test_id);
+    mainbuffer_->bindCallID(test_id, MainBuffer::DEFAULT_ID);
 
-    RingBuffer* test_ring_buffer = mainbuffer_.getRingBuffer(test_id);
+    RingBuffer* test_ring_buffer = mainbuffer_->getRingBuffer(test_id);
 
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0);
-    test_ring_buffer->storeReadPointer(30);
-    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 30);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 0);
+    test_ring_buffer->storeReadPointer(30, MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(MainBuffer::DEFAULT_ID) == 30);
 
     test_ring_buffer->createReadPointer(test_id);
     CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 0);
@@ -1056,17 +945,17 @@ void MainBufferTest::testReadPointerInit()
     CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == (int) NULL);
     test_ring_buffer->removeReadPointer("false id");
 
-    // mainbuffer_.removeRingBuffer(test_id);
-    mainbuffer_.unBindCallID(test_id);
+    // mainbuffer_->removeRingBuffer(test_id);
+    mainbuffer_->unBindCallID(test_id, MainBuffer::DEFAULT_ID);
 }
 
 
 void MainBufferTest::testRingBufferSeveralPointers()
 {
-    DEBUG("-------------------- MainBufferTest::testRingBufferSeveralPointers --------------------\n");
+    TITLE();
 
     std::string test_id = "test multiple read pointer";
-    RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(test_id);
+    RingBuffer* test_ring_buffer = mainbuffer_->createRingBuffer(test_id);
 
     std::string test_pointer1 = "test pointer 1";
     std::string test_pointer2 = "test pointer 2";
@@ -1081,35 +970,29 @@ void MainBufferTest::testRingBufferSeveralPointers()
 
     int testoutput;
 
-    int initPutLen = test_ring_buffer->AvailForPut();
-
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint1, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - (int) sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer1) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer2) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == sizeof(int));
 
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint2, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint2, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 2* (int) sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer1) == 2*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer2) == 2*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 2*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 2*sizeof(int));
 
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint3, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint3, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 3*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 3* (int) sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer1) == 3*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer2) == 3*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 3*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 3*sizeof(int));
 
-    CPPUNIT_ASSERT(test_ring_buffer->Put(&testint4, sizeof(int)) == sizeof(int));
+    test_ring_buffer->Put(&testint4, sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 4*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 4* (int) sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer1) == 4*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer2) == 4*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 4*sizeof(int));
@@ -1118,65 +1001,40 @@ void MainBufferTest::testRingBufferSeveralPointers()
 
     CPPUNIT_ASSERT(test_ring_buffer->Get(&testoutput, sizeof(int), test_pointer1) == sizeof(int));
     CPPUNIT_ASSERT(testoutput == testint1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 4* (int) sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 3*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 4*sizeof(int));
 
     CPPUNIT_ASSERT(test_ring_buffer->Get(&testoutput, sizeof(int), test_pointer2) == sizeof(int));
     CPPUNIT_ASSERT(testoutput == testint1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 3* (int) sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 3*sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 3*sizeof(int));
 
-    // AvailForPut() is ok but AvailForGet(default_id) is not ok
     // However, we should no be alowed to read in our own ring buffer
     // if we are either an AudioLayer or and RTP session
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 4*sizeof(int));
-
-    CPPUNIT_ASSERT(test_ring_buffer->Get(&testoutput, sizeof(int), 100, test_pointer1) == sizeof(int));
-    CPPUNIT_ASSERT(testoutput == testint2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 3* (int) sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 2*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 3*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 4*sizeof(int));
 
-    // AvailForPut() is ok but AvailForGet(default_id) is not ok
     // However, we should no be alowed to read in our own ring buffer
     // if we are either an AudioLayer or and RTP session
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 4*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 4*sizeof(int));
 
-    CPPUNIT_ASSERT(test_ring_buffer->Get(&testoutput, sizeof(int), 100, test_pointer2) == sizeof(int));
-    CPPUNIT_ASSERT(testoutput == testint2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 2* (int) sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 2*sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 2*sizeof(int));
-
-    // AvailForPut() is ok but AvailForGet(default_id) is not ok
     // However, we should no be alowed to read in our own ring buffer
     // if we are either an AudioLayer or and RTP session
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 4*sizeof(int));
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 4*sizeof(int));
 
     CPPUNIT_ASSERT(test_ring_buffer->Discard(sizeof(int), test_pointer1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 2* (int) sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 2*sizeof(int));
-
     CPPUNIT_ASSERT(test_ring_buffer->Discard(sizeof(int), test_pointer2) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - (int) sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == sizeof(int));
-
 
     test_ring_buffer->removeReadPointer(test_pointer1);
     test_ring_buffer->removeReadPointer(test_pointer2);
 
-    mainbuffer_.removeRingBuffer(test_id);
+    mainbuffer_->removeRingBuffer(test_id);
 }
 
 
 
 void MainBufferTest::testConference()
 {
-    DEBUG("-------------------- MainBufferTest::testConference --------------------\n");
+    TITLE();
 
     std::string test_id1 = "participant A";
     std::string test_id2 = "participant B";
@@ -1187,579 +1045,211 @@ void MainBufferTest::testConference()
     CallIDMap::iterator iter_callidmap;
     CallIDSet::iterator iter_callidset;
 
-
-
     // test initial setup
     // ringbuffers
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 0);
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer == NULL);
 
     // callidmap
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0);
-    iter_callidmap = mainbuffer_.callIDMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_callidmap == mainbuffer_.callIDMap_.end());
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 0);
+    iter_callidmap = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_callidmap == mainbuffer_->callIDMap_.end());
 
 
     // test bind Participant A with default
-    mainbuffer_.bindCallID(test_id1);
+    mainbuffer_->bindCallID(test_id1, MainBuffer::DEFAULT_ID);
     // ringbuffers
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2);
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 2);
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1);
-    iter_readpointer = test_ring_buffer->_readpointer.find(test_id1);
+    iter_readpointer = test_ring_buffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1);
-    iter_readpointer = test_ring_buffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = test_ring_buffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
     // callidmap
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2);
-    iter_callidmap = mainbuffer_.callIDMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_callidmap->first == default_id);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 2);
+    iter_callidmap = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_callidmap->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_callidmap->second->size() == 1);
     iter_callidset = iter_callidmap->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_callidset == test_id1);
-    iter_callidmap = mainbuffer_.callIDMap_.find(test_id1);
+    iter_callidmap = mainbuffer_->callIDMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_callidmap->first == test_id1);
     CPPUNIT_ASSERT(iter_callidmap->second->size() == 1);
-    iter_callidset = iter_callidmap->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_callidset == default_id);
+    iter_callidset = iter_callidmap->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_callidset == MainBuffer::DEFAULT_ID);
 
     // test bind Participant B with default
-    mainbuffer_.bindCallID(test_id2);
+    mainbuffer_->bindCallID(test_id2, MainBuffer::DEFAULT_ID);
     // ringbuffers
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3);
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 3);
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 2);
-    iter_readpointer = test_ring_buffer->_readpointer.find(test_id1);
+    iter_readpointer = test_ring_buffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = test_ring_buffer->_readpointer.find(test_id2);
+    iter_readpointer = test_ring_buffer->readpointer_.find(test_id2);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id2);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1);
-    iter_readpointer = test_ring_buffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = test_ring_buffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id2);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1);
-    iter_readpointer = test_ring_buffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = test_ring_buffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
     // callidmap
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3);
-    iter_callidmap = mainbuffer_.callIDMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_callidmap->first == default_id);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 3);
+    iter_callidmap = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_callidmap->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_callidmap->second->size() == 2);
     iter_callidset = iter_callidmap->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_callidset == test_id1);
     iter_callidset = iter_callidmap->second->find(test_id2);
     CPPUNIT_ASSERT(*iter_callidset == test_id2);
-    iter_callidmap = mainbuffer_.callIDMap_.find(test_id1);
+    iter_callidmap = mainbuffer_->callIDMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_callidmap->first == test_id1);
     CPPUNIT_ASSERT(iter_callidmap->second->size() == 1);
-    iter_callidset = iter_callidmap->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_callidset == default_id);
-    iter_callidmap = mainbuffer_.callIDMap_.find(test_id2);
+    iter_callidset = iter_callidmap->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_callidset == MainBuffer::DEFAULT_ID);
+    iter_callidmap = mainbuffer_->callIDMap_.find(test_id2);
     CPPUNIT_ASSERT(iter_callidmap->first == test_id2);
     CPPUNIT_ASSERT(iter_callidmap->second->size() == 1);
-    iter_callidset = iter_callidmap->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_callidset == default_id);
+    iter_callidset = iter_callidmap->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_callidset == MainBuffer::DEFAULT_ID);
 
 
     // test bind Participant A with Participant B
-    mainbuffer_.bindCallID(test_id1, test_id2);
+    mainbuffer_->bindCallID(test_id1, test_id2);
     // ringbuffers
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3);
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
+    CPPUNIT_ASSERT(mainbuffer_->ringBufferMap_.size() == 3);
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 2);
-    iter_readpointer = test_ring_buffer->_readpointer.find(test_id1);
+    iter_readpointer = test_ring_buffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = test_ring_buffer->_readpointer.find(test_id2);
+    iter_readpointer = test_ring_buffer->readpointer_.find(test_id2);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id2);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 2);
-    iter_readpointer = test_ring_buffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = test_ring_buffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = test_ring_buffer->_readpointer.find(test_id2);
+    iter_readpointer = test_ring_buffer->readpointer_.find(test_id2);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id2);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id2);
     CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 2);
-    iter_readpointer = test_ring_buffer->_readpointer.find(default_id);
-    CPPUNIT_ASSERT(iter_readpointer->first == default_id);
+    iter_readpointer = test_ring_buffer->readpointer_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_readpointer->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
-    iter_readpointer = test_ring_buffer->_readpointer.find(test_id1);
+    iter_readpointer = test_ring_buffer->readpointer_.find(test_id1);
     CPPUNIT_ASSERT(iter_readpointer->first == test_id1);
     CPPUNIT_ASSERT(iter_readpointer->second == 0);
     // callidmap
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3);
-    iter_callidmap = mainbuffer_.callIDMap_.find(default_id);
-    CPPUNIT_ASSERT(iter_callidmap->first == default_id);
+    CPPUNIT_ASSERT(mainbuffer_->callIDMap_.size() == 3);
+    iter_callidmap = mainbuffer_->callIDMap_.find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(iter_callidmap->first == MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(iter_callidmap->second->size() == 2);
     iter_callidset = iter_callidmap->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_callidset == test_id1);
     iter_callidset = iter_callidmap->second->find(test_id2);
     CPPUNIT_ASSERT(*iter_callidset == test_id2);
-    iter_callidmap = mainbuffer_.callIDMap_.find(test_id1);
+    iter_callidmap = mainbuffer_->callIDMap_.find(test_id1);
     CPPUNIT_ASSERT(iter_callidmap->first == test_id1);
     CPPUNIT_ASSERT(iter_callidmap->second->size() == 2);
-    iter_callidset = iter_callidmap->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_callidset == default_id);
+    iter_callidset = iter_callidmap->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_callidset == MainBuffer::DEFAULT_ID);
     iter_callidset = iter_callidmap->second->find(test_id2);
     CPPUNIT_ASSERT(*iter_callidset == test_id2);
-    iter_callidmap = mainbuffer_.callIDMap_.find(test_id2);
+    iter_callidmap = mainbuffer_->callIDMap_.find(test_id2);
     CPPUNIT_ASSERT(iter_callidmap->first == test_id2);
     CPPUNIT_ASSERT(iter_callidmap->second->size() == 2);
-    iter_callidset = iter_callidmap->second->find(default_id);
-    CPPUNIT_ASSERT(*iter_callidset == default_id);
+    iter_callidset = iter_callidmap->second->find(MainBuffer::DEFAULT_ID);
+    CPPUNIT_ASSERT(*iter_callidset == MainBuffer::DEFAULT_ID);
     iter_callidset = iter_callidmap->second->find(test_id1);
     CPPUNIT_ASSERT(*iter_callidset == test_id1);
 
 
     // test putData default
     int testint = 12;
-    int init_put_defaultid;
-    int init_put_id1;
-    int init_put_id2;
-
-    init_put_defaultid = mainbuffer_.getRingBuffer(default_id)->AvailForPut();
-    init_put_id1 = mainbuffer_.getRingBuffer(test_id1)->AvailForPut();
-    init_put_id2 = mainbuffer_.getRingBuffer(test_id2)->AvailForPut();
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0);
+
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id1) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id2) == 0);
     // put data test ring buffers
-    CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int)) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
+    mainbuffer_->putData(&testint, sizeof(int), MainBuffer::DEFAULT_ID);
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id1);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 0);
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id2);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 0);
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
     // test mainbuffer availforget (get data even if some participant missing)
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(MainBuffer::DEFAULT_ID) == 0);
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id1) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id2) == sizeof(int));
     //putdata test ring buffers
-    CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id1) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
+    mainbuffer_->putData(&testint, 100, test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id2);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
+    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(MainBuffer::DEFAULT_ID) == 0);
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget (get data even if some participant missing)
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-    //putdata test ring buffers
-    CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
+
+    mainbuffer_->putData(&testint, 100, test_id2);
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id2);
     // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-
-
-    int test_output;
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id1) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id2) == sizeof(int));
 
     // test getData default id (audio layer)
-    CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100) == sizeof(int));
-    CPPUNIT_ASSERT(test_output == (testint + testint));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id2);
     // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id1) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id2) == sizeof(int));
     // test getData test_id1 (audio layer)
-    CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100, test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_output == (testint + testint));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
     CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
     CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id2);
+
     // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
+    CPPUNIT_ASSERT(mainbuffer_->availForGet(test_id2) == sizeof(int));
     // test getData test_id2 (audio layer)
-    CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100, test_id2) == sizeof(int));
-    CPPUNIT_ASSERT(test_output == (testint + testint));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_defaultid);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0);
-
-
-    // test putData default (for discarting)
-    init_put_defaultid = mainbuffer_.getRingBuffer(default_id)->AvailForPut();
-    init_put_id1 = mainbuffer_.getRingBuffer(test_id1)->AvailForPut();
-    init_put_id2 = mainbuffer_.getRingBuffer(test_id2)->AvailForPut();
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0);
-    // put data test ring buffers
-    CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-    //putdata test ring buffers
-    CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id1) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-    //putdata test ring buffers
-    CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-
-    // test discardData default id (audio layer)
-    CPPUNIT_ASSERT(mainbuffer_.discard(sizeof(int)) == sizeof(int));
-    CPPUNIT_ASSERT(test_output == (testint + testint));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-    // test discardData test_id1 (audio layer)
-    CPPUNIT_ASSERT(mainbuffer_.discard(sizeof(int), test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_output == (testint + testint));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-    // test discardData test_id2 (audio layer)
-    CPPUNIT_ASSERT(mainbuffer_.discard(sizeof(int), test_id2) == sizeof(int));
-    CPPUNIT_ASSERT(test_output == (testint + testint));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_defaultid);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0);
-
-
-    // test putData default (for flushing)
-    init_put_defaultid = mainbuffer_.getRingBuffer(default_id)->AvailForPut();
-    init_put_id1 = mainbuffer_.getRingBuffer(test_id1)->AvailForPut();
-    init_put_id2 = mainbuffer_.getRingBuffer(test_id2)->AvailForPut();
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0);
-    // put data test ring buffers
-    CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-    //putdata test ring buffers
-    CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id1) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-    //putdata test ring buffers
-    CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-
-    // test flush default id (audio layer)
-    mainbuffer_.flush();
-    CPPUNIT_ASSERT(test_output == (testint + testint));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    DEBUG("%i", test_ring_buffer->putLen());
-    test_ring_buffer->debug();
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int));
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int));
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-    // test flush test_id1 (audio layer)
-    mainbuffer_.flush(test_id1);
-    CPPUNIT_ASSERT(test_output == (testint + testint));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int)));
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int));
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int));
-    // test flush test_id2 (audio layer)
-    mainbuffer_.flush(test_id2);
-    CPPUNIT_ASSERT(test_output == (testint + testint));
-    test_ring_buffer = mainbuffer_.getRingBuffer(default_id);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_defaultid);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0);
-    test_ring_buffer = mainbuffer_.getRingBuffer(test_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0);
-    CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0);
-    // test mainbuffer availforget
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0);
-    CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0);
-
-
-    mainbuffer_.unBindCallID(test_id1, test_id2);
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3);
-
-    mainbuffer_.unBindCallID(test_id1);
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2);
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2);
-
-    mainbuffer_.unBindCallID(test_id2);
-    CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.empty());
-    CPPUNIT_ASSERT(mainbuffer_.callIDMap_.empty());
+    test_ring_buffer = mainbuffer_->getRingBuffer(MainBuffer::DEFAULT_ID);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id1);
+    test_ring_buffer = mainbuffer_->getRingBuffer(test_id2);
 }
+
+MainBufferTest::MainBufferTest() : CppUnit::TestCase("Audio Layer Tests"), mainbuffer_(new MainBuffer) {}
diff --git a/daemon/test/mainbuffertest.h b/daemon/test/mainbuffertest.h
index 316191f4964ab92f8d1c3fbc2e10f8d5eefb2e65..98139ed0d80457d4fb29ddcc4a0334397e3bf314 100644
--- a/daemon/test/mainbuffertest.h
+++ b/daemon/test/mainbuffertest.h
@@ -28,46 +28,23 @@
  *  as that of the covered work.
  */
 
+#ifndef MAINBUFFER_TEST_
+#define MAINBUFFER_TEST_
+
 // Cppunit import
 #include <cppunit/extensions/HelperMacros.h>
 #include <cppunit/TestCaller.h>
 #include <cppunit/TestCase.h>
 #include <cppunit/TestSuite.h>
 
-#include <assert.h>
-
-#include <stdio.h>
-#include <sstream>
-#include <ccrtp/rtp.h>
-
-
-// pjsip import
-#include <pjsip.h>
-#include <pjlib.h>
-#include <pjsip_ua.h>
-#include <pjlib-util.h>
-#include <pjnath/stun_config.h>
-
-// Application import
-#include "manager.h"
-#include "audio/mainbuffer.h"
-#include "audio/ringbuffer.h"
-#include "call.h"
-// #include "config/config.h"
-// #include "user_cfg.h"
-
-
+#include <tr1/memory>
 
+class MainBuffer;
 /*
  * @file audiorecorderTest.cpp
- * @brief       Regroups unitary tests related to the plugin manager.
+ * @brief       Regroups unit tests related to the main buffer.
  */
 
-#ifndef _MAINBUFFER_TEST_
-#define _MAINBUFFER_TEST_
-
-
-
 class MainBufferTest : public CppUnit::TestCase {
 
         /*
@@ -92,19 +69,7 @@ class MainBufferTest : public CppUnit::TestCase {
 
     public:
 
-        MainBufferTest() : CppUnit::TestCase("Audio Layer Tests") {}
-
-        /*
-         * Code factoring - Common resources can be initialized here.
-         * This method is called by unitcpp before each test
-         */
-        void setUp();
-
-        /*
-         * Code factoring - Common resources can be released here.
-         * This method is called by unitcpp after each test
-         */
-        void tearDown();
+        MainBufferTest();
 
         void testRingBufferCreation();
 
@@ -138,11 +103,11 @@ class MainBufferTest : public CppUnit::TestCase {
 
     private:
 
-        MainBuffer mainbuffer_;
+        std::tr1::shared_ptr<MainBuffer> mainbuffer_;
 };
 
 /* Register our test module */
 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MainBufferTest, "MainBufferTest");
 CPPUNIT_TEST_SUITE_REGISTRATION(MainBufferTest);
 
-#endif
+#endif  // MAINBUFFER_TEST_
diff --git a/daemon/test/numbercleanertest.cpp b/daemon/test/numbercleanertest.cpp
index d9642a7201aae83b6d2b95506f0d8969776c547f..7cbb28f885d9a5be2a986986b8d86db64c9ab41f 100644
--- a/daemon/test/numbercleanertest.cpp
+++ b/daemon/test/numbercleanertest.cpp
@@ -28,11 +28,11 @@
  *  as that of the covered work.
  */
 
-#include <stdio.h>
+#include <cstdio>
 #include <sstream>
 #include <dlfcn.h>
 
-#include "global.h"
+#include "logger.h"
 
 #include "numbercleanertest.h"
 
diff --git a/daemon/test/sdesnegotiatortest.cpp b/daemon/test/sdesnegotiatortest.cpp
index cd3f0402be6003fed577c2d400fb6f17507250fd..0d71d6bb635bd6081ca605615ff498f0c8f4a44c 100644
--- a/daemon/test/sdesnegotiatortest.cpp
+++ b/daemon/test/sdesnegotiatortest.cpp
@@ -46,15 +46,15 @@
 #include "sip/sdes_negotiator.h"
 
 #include <unistd.h>
-#include "global.h"
+#include "test_utils.h"
+#include "logger.h"
 
 using std::cout;
 using std::endl;
 
 void SdesNegotiatorTest::testTagPattern()
 {
-    DEBUG("-------------------- SdesNegotiatorTest::testTagPattern --------------------\n");
-
+    TITLE();
     std::string subject = "a=crypto:4";
 
     sfl::Pattern pattern("^a=crypto:(?P<tag>[0-9]{1,9})");
@@ -67,8 +67,7 @@ void SdesNegotiatorTest::testTagPattern()
 
 void SdesNegotiatorTest::testCryptoSuitePattern()
 {
-    DEBUG("-------------------- SdesNegotiatorTest::testCryptoSuitePattern --------------------\n");
-
+    TITLE();
     std::string subject = "AES_CM_128_HMAC_SHA1_80";
 
     sfl::Pattern pattern("(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \
@@ -84,7 +83,7 @@ void SdesNegotiatorTest::testCryptoSuitePattern()
 
 void SdesNegotiatorTest::testKeyParamsPattern()
 {
-    DEBUG("-------------------- SdesNegotiatorTest::testKeyParamsPattern --------------------\n");
+    TITLE();
 
     std::string subject = "inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj|2^20|1:32";
 
@@ -108,7 +107,7 @@ void SdesNegotiatorTest::testKeyParamsPattern()
 
 void SdesNegotiatorTest::testKeyParamsPatternWithoutMKI()
 {
-    DEBUG("-------------------- SdesNegotiatorTest::testKeyParamsPatternWithoutMKI --------------------\n");
+    TITLE();
 
     std::string subject("inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj");
 
@@ -132,7 +131,7 @@ void SdesNegotiatorTest::testKeyParamsPatternWithoutMKI()
  */
 void SdesNegotiatorTest::testNegotiation()
 {
-    DEBUG("-------------------- SdesNegotiatorTest::testNegotiation --------------------\n");
+    TITLE();
 
     // Add a new SDES crypto line to be processed.
     std::vector<std::string> remoteOffer;
@@ -155,7 +154,7 @@ void SdesNegotiatorTest::testNegotiation()
  */
 void SdesNegotiatorTest::testComponent()
 {
-    DEBUG("-------------------- SdesNegotiatorTest::testComponent --------------------\n");
+    TITLE();
 
     // Register the local capabilities.
     std::vector<sfl::CryptoSuiteDefinition> capabilities;
@@ -178,7 +177,7 @@ void SdesNegotiatorTest::testComponent()
  */
 void SdesNegotiatorTest::testMostSimpleCase()
 {
-    DEBUG("-------------------- SdesNegotiatorTest::testMostSimpleCase --------------------\n");
+    TITLE();
 
     // Register the local capabilities.
     std::vector<sfl::CryptoSuiteDefinition> capabilities;
@@ -208,7 +207,7 @@ void SdesNegotiatorTest::testMostSimpleCase()
 
 void SdesNegotiatorTest::test32ByteKeyLength()
 {
-    DEBUG("-------------------- SdesNegotiatorTest::test32ByteKeyLength --------------------\n");
+    TITLE();
 
     // Register the local capabilities.
     std::vector<sfl::CryptoSuiteDefinition> capabilities;
diff --git a/daemon/test/sdptest.cpp b/daemon/test/sdptest.cpp
index f8d95e2fb80309aa0521d1920139b690625a6a17..02c94f2694f6c09898e71fadaea6baddbe27f9aa 100644
--- a/daemon/test/sdptest.cpp
+++ b/daemon/test/sdptest.cpp
@@ -134,6 +134,13 @@ void SDPTest::tearDown()
     pj_pool_release(testPool_);
 }
 
+void SDPTest::receiveAnswerAfterInitialOffer(const pjmedia_sdp_session* remote)
+{
+    assert(pjmedia_sdp_neg_get_state(session_->negotiator_) == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER);
+    assert(pjmedia_sdp_neg_set_remote_answer(session_->memPool_, session_->negotiator_, remote) == PJ_SUCCESS);
+    assert(pjmedia_sdp_neg_get_state(session_->negotiator_) == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO);
+}
+
 void SDPTest::testInitialOfferFirstCodec()
 {
     std::cout << "------------ SDPTest::testInitialOfferFirstCodec --------------" << std::endl;
@@ -164,7 +171,7 @@ void SDPTest::testInitialOfferFirstCodec()
     pjmedia_sdp_session *remoteAnswer;
     pjmedia_sdp_parse(testPool_, (char*) sdp_answer1, strlen(sdp_answer1), &remoteAnswer);
 
-    session_->receivingAnswerAfterInitialOffer(remoteAnswer);
+    receiveAnswerAfterInitialOffer(remoteAnswer);
     session_->startNegotiation();
 
     session_->setMediaTransportInfoFromRemoteSdp();
@@ -241,7 +248,7 @@ void SDPTest::testInitialOfferLastCodec()
     pjmedia_sdp_session *remoteAnswer;
     pjmedia_sdp_parse(testPool_, (char*) sdp_answer2, strlen(sdp_answer2), &remoteAnswer);
 
-    session_->receivingAnswerAfterInitialOffer(remoteAnswer);
+    receiveAnswerAfterInitialOffer(remoteAnswer);
     session_->startNegotiation();
 
     session_->setMediaTransportInfoFromRemoteSdp();
@@ -319,13 +326,14 @@ void SDPTest::testReinvite()
     // pjmedia_sdp_parse(testPool_, test[0].offer_answer[0].sdp2, strlen(test[0].offer_answer[0].sdp2), &remoteAnswer);
     pjmedia_sdp_parse(testPool_, (char*) sdp_answer1, strlen(sdp_answer1), &remoteAnswer);
 
-    session_->receivingAnswerAfterInitialOffer(remoteAnswer);
+    receiveAnswerAfterInitialOffer(remoteAnswer);
     session_->startNegotiation();
 
     session_->setMediaTransportInfoFromRemoteSdp();
 
     CPPUNIT_ASSERT(session_->getLocalIP() == LOCALHOST);
     CPPUNIT_ASSERT(session_->getRemoteIP() == "host.example.com");
+    CPPUNIT_ASSERT(session_->getSessionAudioMedia()->getMimeSubtype() == "PCMU");
 
     pjmedia_sdp_session *reinviteOffer;
     pjmedia_sdp_parse(testPool_, (char*) sdp_reinvite, strlen(sdp_reinvite), &reinviteOffer);
diff --git a/daemon/test/sdptest.h b/daemon/test/sdptest.h
index e149f9b03aa25e434f406607b362df640a7e97b3..54b362b1f8eb0a41bdca4073f08827cc95a84fb1 100644
--- a/daemon/test/sdptest.h
+++ b/daemon/test/sdptest.h
@@ -118,6 +118,7 @@ class SDPTest : public CppUnit::TestCase {
 
     private:
         NON_COPYABLE(SDPTest);
+        void receiveAnswerAfterInitialOffer(const pjmedia_sdp_session* remote);
 
         Sdp *session_;
         pj_pool_t *testPool_;
diff --git a/daemon/test/siptest.cpp b/daemon/test/siptest.cpp
index 06b8f7bf4dfcd0f747f8799a01da96755c4cb8dc..f11699748b47816b614d652aa9a19a0cd2a5fdd2 100644
--- a/daemon/test/siptest.cpp
+++ b/daemon/test/siptest.cpp
@@ -125,7 +125,7 @@ void SIPTest::testSimpleOutgoingIpCall()
     pthread_t thethread;
 
     // command to be executed by the thread, user agent server waiting for a call
-    std::string command("sipp -sn uas -i 127.0.0.1 -p 5062 -m 1 -bg");
+    std::string command("sipp -sn uas -i 127.0.0.1 -p 5068 -m 1 -bg");
 
     int rc = pthread_create(&thethread, NULL, sippThread, &command);
 
@@ -134,7 +134,7 @@ void SIPTest::testSimpleOutgoingIpCall()
 
     std::string testaccount("IP2IP");
     std::string testcallid("callid1234");
-    std::string testcallnumber("sip:test@127.0.0.1:5062");
+    std::string testcallnumber("sip:test@127.0.0.1:5068");
 
     CPPUNIT_ASSERT(!Manager::instance().hasCurrentCall());
 
@@ -144,9 +144,6 @@ void SIPTest::testSimpleOutgoingIpCall()
     // must sleep here until receiving 180 and 200 message from peer
     sleep(2);
 
-    // call list should be empty for outgoing calls, only used for incoming calls
-    CPPUNIT_ASSERT(Manager::instance().getCallList().empty());
-
     CPPUNIT_ASSERT(Manager::instance().hasCurrentCall());
     CPPUNIT_ASSERT(Manager::instance().getCurrentCallId() == testcallid);
 
@@ -184,9 +181,6 @@ void SIPTest::testSimpleIncomingIpCall()
     CallMap::iterator iterCallId = siplink->callMap_.begin();
     std::string testcallid = iterCallId->first;
 
-    // TODO: hmmm, should IP2IP call be stored in call list....
-    CPPUNIT_ASSERT(Manager::instance().getCallList().size() == 0);
-
     // Answer this call
     CPPUNIT_ASSERT(Manager::instance().answerCall(testcallid));
 
diff --git a/daemon/test/test_utils.h b/daemon/test/test_utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..4102a28131d66ff5462acacb17206cabec05d13c
--- /dev/null
+++ b/daemon/test/test_utils.h
@@ -0,0 +1,37 @@
+/*
+ *  Copyright (C) 2004-2012 Savoir-Faire Linux Inc.
+ *  Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ *  Additional permission under GNU GPL version 3 section 7:
+ *
+ *  If you modify this program, or any covered work, by linking or
+ *  combining it with the OpenSSL project's OpenSSL library (or a
+ *  modified version of that library), containing parts covered by the
+ *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
+ *  grants you additional permission to convey the resulting work.
+ *  Corresponding Source for a non-source form of such a combination
+ *  shall include the source code for the parts of OpenSSL used as well
+ *  as that of the covered work.
+ */
+
+#ifndef TEST_UTILS_H_
+#define TEST_UTILS_H_
+
+#define TITLE() DEBUG("-------------------- %s --------------------\n", \
+        __PRETTY_FUNCTION__)
+
+#endif // TEST_UTILS_H_
diff --git a/gnome/configure.ac b/gnome/configure.ac
index 0c40b0c28b1380c0643ba944284e29359ae94daf..0b1f2d823016730d08d786b85b4c72f3627802ae 100644
--- a/gnome/configure.ac
+++ b/gnome/configure.ac
@@ -15,9 +15,7 @@ AC_PROG_INSTALL
 AC_HEADER_STDC
 LT_INIT
 
-dnl Only need these for moving to gtk3
-MIGRATION_CFLAGS="-DGDK_DISABLE_DEPRECATED -DGTK_DISABLE_DEPRECATED -DGTK_DISABLE_SINGLE_INCLUDES"
-CFLAGS="$CFLAGS -Wall -Wextra -Wshadow $MIGRATION_CFLAGS"
+CFLAGS="$CFLAGS -Wall -Wextra -Wshadow"
 
 dnl GCONF utilities
 AM_GCONF_SOURCE_2
@@ -44,15 +42,21 @@ AS_IF([test "x$enable_video" != "xno"], [
 
 AM_CONDITIONAL(SFL_VIDEO, test "x$enable_video" != "xno")
 
-PKG_CHECK_MODULES(GTK, gtk+-3.0)
+# Check for gtk+-3.0 and if found, check for webkitgtk-3.0, otherwise
+# check for gtk+-2.0 and if found, check for webkitgtk-1.0.
+PKG_CHECK_MODULES(GTK, gtk+-3.0, [PKG_CHECK_MODULES(WEBKIT, webkitgtk-3.0)],
+        [PKG_CHECK_MODULES(GTK, gtk+-2.0,
+            [PKG_CHECK_MODULES(WEBKIT, webkit-1.0)],
+            [AC_MSG_ERROR(gtk-2 not found)])])
+
 PKG_CHECK_MODULES(GCONF, gconf-2.0)
 PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.24)
-PKG_CHECK_MODULES(WEBKIT, webkitgtk-3.0)
 PKG_CHECK_MODULES(X11, x11)
 PKG_CHECK_MODULES(JAVASCRIPT_CORE_GTK, javascriptcoregtk-3.0, ,
 		  AC_MSG_RESULT(javascriptcoregtk not installed))
 
-PKG_CHECK_MODULES([CHECK], [check >= 0.9.4])
+PKG_CHECK_MODULES([CHECK], [check >= 0.9.4],,
+                  AC_MSG_RESULT([check not installed]))
 
 AC_CONFIG_FILES([
 Makefile
diff --git a/gnome/src/Makefile.am b/gnome/src/Makefile.am
index d5ed7f9321efa2fa94a9cb869409ce466b649699..444e884f33f431bd477d481f194aec52755603d9 100644
--- a/gnome/src/Makefile.am
+++ b/gnome/src/Makefile.am
@@ -36,13 +36,14 @@ sflphone_client_gnome_SOURCES = \
   reqaccount.c \
   eel-gconf-extensions.c \
   shortcuts.c \
-  str_utils.c
+  str_utils.c \
+  gtk2_wrappers.c
 
 noinst_HEADERS =  actions.h sflnotify.h mainwindow.h dialpad.h codeclist.h \
                   reqaccount.h sflphone_const.h uimanager.h accountlist.h \
 				  sliders.h statusicon.h callable_obj.h conference_obj.h \
                   shortcuts.h eel-gconf-extensions.h logger.h imwindow.h \
-				  unused.h str_utils.h
+				  unused.h str_utils.h gtk2_wrappers.h
 
 sflphone_client_gnome_LDADD = $(DBUSGLIB_LIBS) $(LIBNOTIFY_LIBS) \
                               $(NOTIFY_LIBS) $(SFLPHONEGTK_LIBS) $(X11_LIBS) \
diff --git a/gnome/src/accountlist.c b/gnome/src/accountlist.c
index 91b649826b84b6265244fc50a6763472fbb780c7..c0356736d1789172af495ae1548b39201a97eae7 100644
--- a/gnome/src/accountlist.c
+++ b/gnome/src/accountlist.c
@@ -162,8 +162,8 @@ const gchar * account_state_name(account_state_t s)
             return _("Network unreachable");
         case ACCOUNT_STATE_ERROR_HOST:
             return _("Host unreachable");
-        case ACCOUNT_STATE_ERROR_CONF_STUN:
-            return _("Stun configuration error");
+        case ACCOUNT_STATE_ERROR_NOT_ACCEPTABLE:
+            return _("Not acceptable");
         case ACCOUNT_STATE_ERROR_EXIST_STUN:
             return _("Stun server invalid");
         case ACCOUNT_STATE_IP2IP_READY:
diff --git a/gnome/src/accountlist.h b/gnome/src/accountlist.h
index cad7bd9a0abad686fc87bceaf4170aed6e1de05c..b35386a9e5b4f6402468add1e9bea62cbad913e0 100644
--- a/gnome/src/accountlist.h
+++ b/gnome/src/accountlist.h
@@ -29,8 +29,8 @@
  *  as that of the covered work.
  */
 
-#ifndef ACCOUNTLIST_H__
-#define ACCOUNTLIST_H__
+#ifndef ACCOUNTLIST_H_
+#define ACCOUNTLIST_H_
 
 #include <gtk/gtk.h>
 /** @file accountlist.h
@@ -58,7 +58,7 @@ typedef enum {
     /** Stun server is not existing. The account is not registered */
     ACCOUNT_STATE_ERROR_EXIST_STUN,
     /** Stun server configuration error. The account is not registered */
-    ACCOUNT_STATE_ERROR_CONF_STUN,
+    ACCOUNT_STATE_ERROR_NOT_ACCEPTABLE,
     /** IP2IP Account is always ready */
     ACCOUNT_STATE_IP2IP_READY,
     /** Invalid state */
@@ -172,7 +172,7 @@ void account_list_move_down(guint index);
  * Return the ID of the current default account
  * @return gchar* The id
  */
-const gchar* account_list_get_current_id (void);
+const gchar* account_list_get_current_id(void);
 
 gchar * account_list_get_ordered_list(void);
 
@@ -198,4 +198,4 @@ void account_insert(account_t *account, const gchar *key, const gchar *value);
 gpointer account_lookup(const account_t *account, gconstpointer key);
 void account_list_remove(const gchar *accountID);
 
-#endif
+#endif  // ACCOUNTLIST_H_
diff --git a/gnome/src/actions.c b/gnome/src/actions.c
index 491481c0daf70e11c5edfb039fc2e7e8a7fb2d2d..fc938d035ddf9be7568053e9dcbb6d4ff4afad4e 100644
--- a/gnome/src/actions.c
+++ b/gnome/src/actions.c
@@ -230,17 +230,17 @@ void sflphone_fill_account_list(void)
             acc->state = ACCOUNT_STATE_TRYING;
         else if (g_strcmp0(status, "ERROR") == 0)
             acc->state = ACCOUNT_STATE_ERROR;
-        else if (g_strcmp0(status , "ERROR_AUTH") == 0)
+        else if (g_strcmp0(status, "ERROR_AUTH") == 0)
             acc->state = ACCOUNT_STATE_ERROR_AUTH;
-        else if (g_strcmp0(status , "ERROR_NETWORK") == 0)
+        else if (g_strcmp0(status, "ERROR_NETWORK") == 0)
             acc->state = ACCOUNT_STATE_ERROR_NETWORK;
-        else if (g_strcmp0(status , "ERROR_HOST") == 0)
+        else if (g_strcmp0(status, "ERROR_HOST") == 0)
             acc->state = ACCOUNT_STATE_ERROR_HOST;
-        else if (g_strcmp0(status , "ERROR_CONF_STUN") == 0)
-            acc->state = ACCOUNT_STATE_ERROR_CONF_STUN;
-        else if (g_strcmp0(status , "ERROR_EXIST_STUN") == 0)
+        else if (g_strcmp0(status, "ERROR_NOT_ACCEPTABLE") == 0)
+            acc->state = ACCOUNT_STATE_ERROR_NOT_ACCEPTABLE;
+        else if (g_strcmp0(status, "ERROR_EXIST_STUN") == 0)
             acc->state = ACCOUNT_STATE_ERROR_EXIST_STUN;
-        else if (g_strcmp0(status , "ACCOUNT_STATE_IP2IP_READY") == 0)
+        else if (g_strcmp0(status, "ACCOUNT_STATE_IP2IP_READY") == 0)
             acc->state = ACCOUNT_STATE_IP2IP_READY;
         else
             acc->state = ACCOUNT_STATE_INVALID;
@@ -812,7 +812,9 @@ void
 sflphone_place_call(callable_obj_t * c)
 {
     DEBUG("Actions: Placing call with %s @ %s and accountid %s", c->_display_name, c->_peer_number, c->_accountID);
-
+    if (place_registered_call(c) < 0)
+        DEBUG("An error occured while placing registered call in %s at %d", __FILE__, __LINE__);
+/*
     if (is_direct_call(c)) {
         gchar *msg = g_markup_printf_escaped(_("Direct SIP call"));
         statusbar_pop_message(__MSG_ACCOUNT_DEFAULT);
@@ -822,6 +824,7 @@ sflphone_place_call(callable_obj_t * c)
         place_direct_call(c);
     } else if (place_registered_call(c) < 0)
         DEBUG("An error occured while placing registered call in %s at %d", __FILE__, __LINE__);
+*/
 }
 
 
diff --git a/gnome/src/actions.h b/gnome/src/actions.h
index 4c3899836a2eab2e4140838b0a0344db18677391..5dc304885850c2dcccf9772b2a6f6ed27753111a 100644
--- a/gnome/src/actions.h
+++ b/gnome/src/actions.h
@@ -52,7 +52,7 @@
  * Initialize lists and configurations
  * @return TRUE if succeeded, FALSE otherwise
  */
-gboolean sflphone_init();
+gboolean sflphone_init(GError **error);
 
 /**
  * Steps when closing the application.  Will ask for confirmation if a call is in progress.
diff --git a/gnome/src/config/accountconfigdialog.c b/gnome/src/config/accountconfigdialog.c
index c5562d3fb0b78b5ccb73a9b738bb350e4e7687fb..fc456f63619eb86ab9764705c280066829c4ca38 100644
--- a/gnome/src/config/accountconfigdialog.c
+++ b/gnome/src/config/accountconfigdialog.c
@@ -44,6 +44,7 @@
 #include <gtk/gtk.h>
 
 #include "config.h"
+#include "gtk2_wrappers.h"
 #include "str_utils.h"
 #include "logger.h"
 #include "actions.h"
@@ -494,7 +495,6 @@ key_exchange_changed_cb(GtkWidget *widget UNUSED, gpointer data UNUSED)
     gtk_widget_set_sensitive(zrtp_button, sensitive);
 }
 
-
 static void use_sip_tls_cb(GtkWidget *widget, gpointer data)
 {
     if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))) {
@@ -601,6 +601,10 @@ static void set_published_addr_manually_cb(GtkWidget * widget, gpointer data UNU
 
 static void use_stun_cb(GtkWidget *widget, gpointer data UNUSED)
 {
+    /* Widgets have not been created yet */
+    if (!stun_server_label)
+        return;
+
     if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))) {
         DEBUG("Config: Showing stun options, hiding Local/Published info");
         gtk_widget_show(stun_server_label);
@@ -626,8 +630,6 @@ static void use_stun_cb(GtkWidget *widget, gpointer data UNUSED)
             gtk_widget_show(published_port_spin_box);
         }
     }
-
-    DEBUG("DONE");
 }
 
 
@@ -879,7 +881,7 @@ create_network(const account_t *account)
 
     int idx = 0;
     for (gchar **iface = iface_list; iface && *iface; iface++, idx++) {
-        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(local_address_combo), NULL, *iface);
+        gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(local_address_combo), *iface);
         if (g_strcmp0(*iface, local_interface) == 0)
             gtk_combo_box_set_active(GTK_COMBO_BOX(local_address_combo), idx);
     }
@@ -1153,9 +1155,6 @@ static GtkWidget* create_direct_ip_calls_tab(const account_t *account)
     GtkWidget *frame = create_network(account);
     gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0);
 
-    frame = create_security_widget(account);
-    gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0);
-
     gtk_widget_show_all(vbox);
     return vbox;
 }
diff --git a/gnome/src/config/accountconfigdialog.h b/gnome/src/config/accountconfigdialog.h
index 43cfe666e6c6fd57ece795a41bbc113280138b27..1b72a153cf7b973a6dfd8170f74e399185b7b0fa 100644
--- a/gnome/src/config/accountconfigdialog.h
+++ b/gnome/src/config/accountconfigdialog.h
@@ -50,8 +50,4 @@ GtkWidget *show_account_window(const account_t *a);
  */
 void update_account_from_dialog(GtkWidget *dialog, account_t *a);
 
-/**
- * Resets local cache of account pointers */
-void reset_account_store();
-
 #endif
diff --git a/gnome/src/config/accountlistconfigdialog.c b/gnome/src/config/accountlistconfigdialog.c
index 27560b0200c74d898e506bc36f84768f53563fb5..6a8b47f0bff79753dde29220942560adbe7ad779 100644
--- a/gnome/src/config/accountlistconfigdialog.c
+++ b/gnome/src/config/accountlistconfigdialog.c
@@ -39,6 +39,7 @@
 #include "utils.h"
 #include "unused.h"
 #include "logger.h"
+#include "gtk2_wrappers.h"
 #include <glib/gi18n.h>
 #include <string.h>
 
diff --git a/gnome/src/config/addressbook-config.c b/gnome/src/config/addressbook-config.c
index 3eb74d378f9db063988bbffe9c3dc1ff3959b0f2..1832d38e8136395bae6d6fc2f882382aedd371ce 100644
--- a/gnome/src/config/addressbook-config.c
+++ b/gnome/src/config/addressbook-config.c
@@ -29,6 +29,7 @@
  */
 
 #include "addressbook-config.h"
+#include "gtk2_wrappers.h"
 #include "str_utils.h"
 #include "dbus.h"
 #include "unused.h"
diff --git a/gnome/src/config/assistant.c b/gnome/src/config/assistant.c
index bc74e9cf2c4122655ce2a14d17f8f1ebf06247a0..beeda0b8adc7efa96725e3068eb087ec99948209 100644
--- a/gnome/src/config/assistant.c
+++ b/gnome/src/config/assistant.c
@@ -30,6 +30,7 @@
 
 #include <string.h>
 #include <glib/gi18n.h>
+#include "gtk2_wrappers.h"
 #include "unused.h"
 #include "assistant.h"
 #include "logger.h"
diff --git a/gnome/src/config/audioconf.c b/gnome/src/config/audioconf.c
index 759220b166a39891982a59d180a393805e672c7d..da8e18771ba02fcf7d817e66da9a22e8c3deec26 100644
--- a/gnome/src/config/audioconf.c
+++ b/gnome/src/config/audioconf.c
@@ -29,6 +29,7 @@
  */
 
 #include <glib/gi18n.h>
+#include "gtk2_wrappers.h"
 #include "str_utils.h"
 #include "audioconf.h"
 #include "utils.h"
diff --git a/gnome/src/config/hooks-config.c b/gnome/src/config/hooks-config.c
index 2ff4dc500346fc4cf39a6248acbd2e68dbb8f821..cfbc79e44d4a2d766132089f63c85e2a8370784f 100644
--- a/gnome/src/config/hooks-config.c
+++ b/gnome/src/config/hooks-config.c
@@ -29,6 +29,7 @@
  */
 
 #include <glib/gi18n.h>
+#include "gtk2_wrappers.h"
 #include "str_utils.h"
 #include "hooks-config.h"
 #include "dbus.h"
diff --git a/gnome/src/config/preferencesdialog.c b/gnome/src/config/preferencesdialog.c
index 69df9066c5f080f992d88032faf82d44631887b4..e84d7b24064e533940a874f7f41c33ba01ff2429 100644
--- a/gnome/src/config/preferencesdialog.c
+++ b/gnome/src/config/preferencesdialog.c
@@ -43,6 +43,7 @@
 #include <string.h>
 #include <assert.h>
 
+#include "gtk2_wrappers.h"
 #include "eel-gconf-extensions.h"
 #include "dbus.h"
 #include "logger.h"
diff --git a/gnome/src/config/shortcuts-config.c b/gnome/src/config/shortcuts-config.c
index 4c8365dff85cd31feecc6d7fb65bcf6a296d8c2f..f6a31c82c03a17ab84bae5cba7e8b28ecd71bf66 100644
--- a/gnome/src/config/shortcuts-config.c
+++ b/gnome/src/config/shortcuts-config.c
@@ -28,6 +28,7 @@
  *  as that of the covered work.
  */
 
+#include "gtk2_wrappers.h"
 #include <glib/gi18n.h>
 #include <gdk/gdk.h>
 #include <X11/XKBlib.h>
diff --git a/gnome/src/config/tlsadvanceddialog.c b/gnome/src/config/tlsadvanceddialog.c
index 7c77eba19ae67b3268fbc1f8b515fa0899b8a135..2ae6f2b8c611a97cf9ccfcecc7a0f9bdc90d9937 100644
--- a/gnome/src/config/tlsadvanceddialog.c
+++ b/gnome/src/config/tlsadvanceddialog.c
@@ -29,6 +29,7 @@
  */
 
 #include "tlsadvanceddialog.h"
+#include "gtk2_wrappers.h"
 #include "str_utils.h"
 #include "sflphone_const.h"
 #include "mainwindow.h"
@@ -126,9 +127,6 @@ void show_advanced_tls_options(account_t *account)
     gtk_spin_button_set_value(GTK_SPIN_BUTTON(tlsListenerPort), g_ascii_strtod(tls_listener_port, NULL));
     gtk_box_pack_start(GTK_BOX(hbox), tlsListenerPort, TRUE, TRUE, 0);
 
-    if (!account_is_IP2IP(account))
-        gtk_widget_set_sensitive(tlsListenerPort, FALSE);
-
     label = gtk_label_new(_("Certificate of Authority list"));
     gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
     gtk_table_attach(GTK_TABLE(table), label, 0, 1, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0);
diff --git a/gnome/src/contacts/calltree.c b/gnome/src/contacts/calltree.c
index 80800010eed9acec1bce652846419353bebaef6a..c8168e9006e68f855ad1d9b3c82af5a79a1ebab4 100644
--- a/gnome/src/contacts/calltree.c
+++ b/gnome/src/contacts/calltree.c
@@ -36,6 +36,7 @@
 #include <string.h>
 #include <stdlib.h>
 
+#include "gtk2_wrappers.h"
 #include "eel-gconf-extensions.h"
 #include "unused.h"
 #include "dbus.h"
diff --git a/gnome/src/contacts/searchbar.c b/gnome/src/contacts/searchbar.c
index d6469317d9e8caaea62b073a10ae8423866c2c19..876893eba6178f2d7f0918837798105450970c2a 100644
--- a/gnome/src/contacts/searchbar.c
+++ b/gnome/src/contacts/searchbar.c
@@ -32,6 +32,7 @@
  */
 
 #include <glib/gi18n.h>
+#include "gtk2_wrappers.h"
 #include "searchbar.h"
 #include "calltree.h"
 #include "calltab.h"
@@ -46,18 +47,18 @@ static GtkWidget * searchbox;
 static GtkWidget * addressbookentry;
 
 static GtkWidget * cbox;
-static GtkListStore * liststore = NULL;
+static GtkListStore * liststore;
 
 static gint cboxSignalId;
 
-static GtkWidget *menu = NULL;
+static GtkWidget *menu;
 
 /**
  * Searchbar icons
  */
-static GdkPixbuf *incoming_pixbuf = NULL;
-static GdkPixbuf *outgoing_pixbuf = NULL;
-static GdkPixbuf *missed_pixbuf = NULL;
+static GdkPixbuf *incoming_pixbuf;
+static GdkPixbuf *outgoing_pixbuf;
+static GdkPixbuf *missed_pixbuf;
 
 void searchbar_addressbook_activated(GtkEntry *entry, gchar *arg1 UNUSED, gpointer data UNUSED)
 {
diff --git a/gnome/src/dbus/dbus.c b/gnome/src/dbus/dbus.c
index 6f96d63ea3ac25e1deba37ed9614be6f112fa02b..fc26fbf5681b01607d162516ef2f441d7cc1de4c 100644
--- a/gnome/src/dbus/dbus.c
+++ b/gnome/src/dbus/dbus.c
@@ -50,6 +50,7 @@
 #include "sliders.h"
 #include "statusicon.h"
 #include "assistant.h"
+#include "accountlist.h"
 #include "accountlistconfigdialog.h"
 
 #include "dbus.h"
@@ -454,14 +455,22 @@ accounts_changed_cb(DBusGProxy *proxy UNUSED, void *foo UNUSED)
 }
 
 static void
-stun_status_failure_cb(DBusGProxy *proxy UNUSED, const gchar *reason, void *foo UNUSED)
-{
-    ERROR("Error: Stun status failure: %s failed", reason);
+stun_status_failure_cb(DBusGProxy *proxy UNUSED, const gchar *accountID, void *foo UNUSED)
+{
+    ERROR("Error: Stun status failure: account %s failed to setup STUN",
+          accountID);
+    // Disable STUN for the account that tried to create the STUN transport
+    account_t *account = account_list_get_by_id(accountID);
+    if (account) {
+        account_replace(account, ACCOUNT_SIP_STUN_ENABLED, "false");
+        dbus_set_account_details(account);
+    }
 }
 
 static void
 stun_status_success_cb(DBusGProxy *proxy UNUSED, const gchar *message UNUSED, void *foo UNUSED)
 {
+    DEBUG("STUN setup successful");
 }
 
 static void
@@ -620,7 +629,7 @@ screensaver_dbus_proxy_new_cb (GObject * source UNUSED, GAsyncResult *result, gp
 gboolean dbus_connect_session_manager(DBusGConnection *connection)
 {
 
-    if(connection == NULL) {
+    if (connection == NULL) {
         ERROR("DBUS: Error connection is NULL");
         return FALSE;
     }
@@ -635,8 +644,10 @@ gboolean dbus_connect_session_manager(DBusGConnection *connection)
     }
 */
 
-    g_dbus_proxy_new_for_bus(G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
-                             NULL, GS_SERVICE, GS_PATH, GS_INTERFACE, NULL, screensaver_dbus_proxy_new_cb, NULL);
+    g_dbus_proxy_new_for_bus(G_BUS_TYPE_SESSION,
+                             G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
+                             NULL, GS_SERVICE, GS_PATH, GS_INTERFACE, NULL,
+                             screensaver_dbus_proxy_new_cb, NULL);
 
     DEBUG("DBUS: Connected to gnome session manager");
 
@@ -2200,86 +2211,87 @@ dbus_stop_video_preview()
 static guint cookie;
 #define GNOME_SESSION_NO_IDLE_FLAG 8
 
-static void screensaver_inhibit_cb (GObject * source_object, GAsyncResult * res, gpointer user_data UNUSED)
+static void screensaver_inhibit_cb(GObject * source_object, GAsyncResult * res,
+                                   gpointer user_data UNUSED)
 {
-    DEBUG("Screensaver: Inhibit callback");
-
-    GDBusProxy *proxy = G_DBUS_PROXY (source_object);
-    // ScreenSaver *screensaver = (ScreenSaver *) user_data;
-    GVariant *value;
+    DEBUG(__PRETTY_FUNCTION__);
+    GDBusProxy *proxy = G_DBUS_PROXY(source_object);
     GError *error = NULL;
-
-    value = g_dbus_proxy_call_finish (proxy, res, &error);
+    GVariant *value = g_dbus_proxy_call_finish(proxy, res, &error);
     if (!value) {
-        ERROR ("Screensaver: Error: inhibiting the screensaver: %s", error->message);
-        g_error_free (error);
+        ERROR("Screensaver: Error: inhibiting the screensaver: %s", error->message);
+        g_error_free(error);
         return;
     }
 
     /* save the cookie */
-    if (g_variant_is_of_type (value, G_VARIANT_TYPE ("(u)")))
-        g_variant_get (value, "(u)", &cookie);
+    if (g_variant_is_of_type(value, G_VARIANT_TYPE("(u)")))
+        g_variant_get(value, "(u)", &cookie);
     else
         cookie = 0;
 
-    g_variant_unref (value);
+    g_variant_unref(value);
 }
 
-static void screensaver_uninhibit_cb (GObject * source_object, GAsyncResult * res, gpointer user_data UNUSED)
+static void screensaver_uninhibit_cb(GObject * source_object,
+                                     GAsyncResult * res,
+                                     gpointer user_data UNUSED)
 {
-    DEBUG("Screensaver: Uninhibit callback");
-
-    GDBusProxy *proxy = G_DBUS_PROXY (source_object);
-    // ScreenSaver *screensaver = (ScreenSaver *) user_data;
-    GVariant *value;
+    DEBUG(__PRETTY_FUNCTION__);
+    GDBusProxy *proxy = G_DBUS_PROXY(source_object);
     GError *error = NULL;
 
-    value = g_dbus_proxy_call_finish (proxy, res, &error);
+    GVariant *value = g_dbus_proxy_call_finish(proxy, res, &error);
     if (!value) {
-        ERROR ("Screensaver: Error uninhibiting the screensaver: %s", error->message);
-        g_error_free (error);
+        ERROR ("Screensaver: Error uninhibiting the screensaver: %s",
+               error->message);
+        g_error_free(error);
         return;
     }
 
     /* clear the cookie */
     cookie = 0;
-    g_variant_unref (value);
-
+    g_variant_unref(value);
 }
 
 void dbus_screensaver_inhibit(void)
 {
-    guint xid = 0;
-
-    DEBUG("Screensaver: inhibit");
-
     const gchar *appname = g_get_application_name();
-    if(appname == NULL) {
-        ERROR("Screensaver: Could not retreive application name");
+    if (appname == NULL) {
+        ERROR("Screensaver: Could not retrieve application name");
         return;
     }
 
-    GVariant *parameters = g_variant_new ("(susu)", appname, xid, "Phone call ongoing", GNOME_SESSION_NO_IDLE_FLAG);
-    if(parameters == NULL) {
+    guint xid = 0;
+    GVariant *parameters = g_variant_new("(susu)", appname, xid,
+                                         "Phone call ongoing",
+                                         GNOME_SESSION_NO_IDLE_FLAG);
+    if (parameters == NULL) {
         ERROR("Screensaver: Could not create session manager inhibit parameters");
         return;
     }
 
-    g_dbus_proxy_call (session_manager_proxy, "Inhibit", parameters,
-        G_DBUS_CALL_FLAGS_NO_AUTO_START, -1, NULL, screensaver_inhibit_cb, NULL);
+    g_dbus_proxy_call(session_manager_proxy, "Inhibit", parameters,
+                      G_DBUS_CALL_FLAGS_NO_AUTO_START, -1, NULL,
+                      screensaver_inhibit_cb, NULL);
 }
 
 void
 dbus_screensaver_uninhibit(void)
 {
+    if (cookie == 0)
+        return;
     DEBUG("Screensaver: uninhibit");
 
     GVariant *parameters = g_variant_new("(u)", cookie);
-    if(parameters == NULL) {
-        ERROR("Screensaver: Could not create session manager uninhibit parameters");
+    if (parameters == NULL) {
+        ERROR("Screensaver: Could not create session manager uninhibit "
+               "parameters");
         return;
-    };
+    }
 
-    g_dbus_proxy_call (session_manager_proxy, "Uninhibit", g_variant_new ("(u)", cookie),
-        G_DBUS_CALL_FLAGS_NO_AUTO_START, -1, NULL, screensaver_uninhibit_cb, NULL);
+    g_dbus_proxy_call(session_manager_proxy, "Uninhibit",
+                      g_variant_new("(u)", cookie),
+                      G_DBUS_CALL_FLAGS_NO_AUTO_START, -1, NULL,
+                      screensaver_uninhibit_cb, NULL);
 }
diff --git a/gnome/src/gtk2_wrappers.c b/gnome/src/gtk2_wrappers.c
new file mode 100644
index 0000000000000000000000000000000000000000..72f3bc9559f774bd6a302c4b00ddc09cc1c45018
--- /dev/null
+++ b/gnome/src/gtk2_wrappers.c
@@ -0,0 +1,74 @@
+/*
+ *  Copyright (C) 2004-2012 Savoir-Faire Linux Inc.
+ *  Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ *  Additional permission under GNU GPL version 3 section 7:
+ *
+ *  If you modify this program, or any covered work, by linking or
+ *  combining it with the OpenSSL project's OpenSSL library (or a
+ *  modified version of that library), containing parts covered by the
+ *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
+ *  grants you additional permission to convey the resulting work.
+ *  Corresponding Source for a non-source form of such a combination
+ *  shall include the source code for the parts of OpenSSL used as well
+ *  as that of the covered work.
+ */
+
+#include "gtk2_wrappers.h"
+#include "unused.h"
+
+#if !GTK_CHECK_VERSION(3, 0, 0)
+
+GtkWidget *gtk_box_new(GtkOrientation orientation, gint spacing)
+{
+    if (orientation == GTK_ORIENTATION_HORIZONTAL)
+        return gtk_hbox_new(FALSE, spacing);
+    else
+        return gtk_vbox_new(FALSE, spacing);
+}
+
+GtkWidget* gtk_button_box_new(GtkOrientation orientation)
+{
+    if (orientation == GTK_ORIENTATION_HORIZONTAL)
+        return gtk_hbutton_box_new();
+    else
+        return gtk_vbutton_box_new();
+}
+
+void
+gtk_widget_get_preferred_size(GtkWidget* widget, GtkRequisition *min_size UNUSED, GtkRequisition *natural_size)
+{
+    gtk_widget_size_request(widget, natural_size);
+}
+
+GdkPixbuf *
+gtk_widget_render_icon_pixbuf(GtkWidget *widget, const gchar *stock_id, GtkIconSize size)
+{
+    return gtk_widget_render_icon(widget, stock_id, size, NULL);
+}
+
+GtkWidget *
+gtk_scale_new_with_range(GtkOrientation orientation, gdouble min, gdouble max,
+                         gdouble step)
+{
+    if (orientation == GTK_ORIENTATION_HORIZONTAL)
+        return gtk_hscale_new_with_range(min, max, step);
+    else
+        return gtk_vscale_new_with_range(min, max, step);
+}
+
+#endif
diff --git a/gnome/src/gtk2_wrappers.h b/gnome/src/gtk2_wrappers.h
new file mode 100644
index 0000000000000000000000000000000000000000..6b2d72328f4d3820c596017b6a8a9b1cdbbbd32c
--- /dev/null
+++ b/gnome/src/gtk2_wrappers.h
@@ -0,0 +1,56 @@
+/*
+ *  Copyright (C) 2004-2012 Savoir-Faire Linux Inc.
+ *  Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ *  Additional permission under GNU GPL version 3 section 7:
+ *
+ *  If you modify this program, or any covered work, by linking or
+ *  combining it with the OpenSSL project's OpenSSL library (or a
+ *  modified version of that library), containing parts covered by the
+ *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
+ *  grants you additional permission to convey the resulting work.
+ *  Corresponding Source for a non-source form of such a combination
+ *  shall include the source code for the parts of OpenSSL used as well
+ *  as that of the covered work.
+ */
+
+#ifndef BOX_H_
+#define BOX_H_
+
+#include <gtk/gtk.h>
+
+/* Wrappers needed if using gtk2 */
+#if !GTK_CHECK_VERSION(3, 0, 0)
+GtkWidget*
+gtk_box_new(GtkOrientation orientation, gint spacing);
+
+GtkWidget*
+gtk_button_box_new(GtkOrientation orientation);
+
+void
+gtk_widget_get_preferred_size(GtkWidget* widget, GtkRequisition *min_size, GtkRequisition *natural_size);
+
+GdkPixbuf *
+gtk_widget_render_icon_pixbuf(GtkWidget *widget, const gchar *stock_id, GtkIconSize size);
+
+GtkWidget *
+gtk_scale_new_with_range(GtkOrientation orientation, gdouble min, gdouble max,
+                         gdouble step);
+
+#endif
+
+#endif // BOX_H_
diff --git a/gnome/src/imwindow.c b/gnome/src/imwindow.c
index d7841631faf03ba3e6d63419bd60e6b08e31e444..0ddd14d135815e1c8ef954ebcff511c3e0fd3406 100644
--- a/gnome/src/imwindow.c
+++ b/gnome/src/imwindow.c
@@ -30,7 +30,11 @@
  *  as that of the covered work.
  */
 
+#ifdef HAVE_CONFIG_H
 #include "config.h"
+#endif
+
+#include "gtk2_wrappers.h"
 #include "eel-gconf-extensions.h"
 #include "logger.h"
 #include "imwindow.h"
@@ -41,9 +45,8 @@
 #include <sys/stat.h>
 
 /** Local variables */
-static GtkWidget *im_window = NULL;
-static GtkWidget *im_notebook = NULL;
-
+static GtkWidget *im_window;
+static GtkWidget *im_notebook;
 
 static void im_window_init();
 
diff --git a/gnome/src/mainwindow.c b/gnome/src/mainwindow.c
index 9b079d739650c89ed326e95d7d4b9303b3af8ed1..c57a325fc22573a65a128a813ca9d123fb69aca5 100644
--- a/gnome/src/mainwindow.c
+++ b/gnome/src/mainwindow.c
@@ -30,8 +30,11 @@
  *  as that of the covered work.
  */
 
+#ifdef HAVE_CONFIG_H
 #include "config.h"
-#include "str_utils.h"
+#endif
+
+#include "gtk2_wrappers.h"
 #include "actions.h"
 #include "dbus.h"
 #include "calltree.h"
diff --git a/gnome/src/sliders.c b/gnome/src/sliders.c
index 68f336e185abc2ee88c9312a241c1cd1fea83374..d34f3979a68aeff907a0436c2b3e98f622a60b33 100644
--- a/gnome/src/sliders.c
+++ b/gnome/src/sliders.c
@@ -29,6 +29,7 @@
  */
 
 #include <glib/gi18n.h>
+#include "gtk2_wrappers.h"
 #include "sliders.h"
 #include "dbus/dbus.h"
 #include "actions.h"
diff --git a/gnome/src/uimanager.c b/gnome/src/uimanager.c
index b2b16d5d2ef0b42687a0e2d0130a300161348942..8010757981da22d18dd54e37c43bdbb0f2ab1c9a 100644
--- a/gnome/src/uimanager.c
+++ b/gnome/src/uimanager.c
@@ -28,7 +28,11 @@
  *  as that of the covered work.
  */
 
+#ifdef HAVE_CONFIG_H
 #include "config.h"
+#endif
+
+#include "gtk2_wrappers.h"
 #include "str_utils.h"
 #include "preferencesdialog.h"
 #include "logger.h"
diff --git a/gnome/src/widget/minidialog.c b/gnome/src/widget/minidialog.c
index 46de0379601c3fa128dbf11716d039d7260b6f31..c844bc28e1b524f59f325b098a30ad71641658a7 100644
--- a/gnome/src/widget/minidialog.c
+++ b/gnome/src/widget/minidialog.c
@@ -26,6 +26,7 @@
 #include <gtk/gtk.h>
 #include "unused.h"
 #include "sflphone_const.h"
+#include "gtk2_wrappers.h"
 #include "minidialog.h"
 
 #define HIG_BOX_SPACE 6
diff --git a/hudson-sflphone-script.sh b/hudson-sflphone-script.sh
index ec45e5088d9c888ee2340a738e733b204bffff4b..699bff42b77e6e99d6ab683b57a13dd90c02c9e0 100755
--- a/hudson-sflphone-script.sh
+++ b/hudson-sflphone-script.sh
@@ -10,6 +10,9 @@ BUILD=
 CODE_ANALYSIS=0
 DOXYGEN=0
 
+CONFIGDIR=~/.config
+SFLCONFDIR=${CONFIGDIR}/sflphone
+
 function run_code_analysis {
 	# Check if cppcheck is installed on the system
 	if [ `which cppcheck &>/dev/null ; echo $?` -ne 1 ] ; then
@@ -19,6 +22,7 @@ function run_code_analysis {
 	fi
 }
 
+
 function gen_doxygen {
 	# Check if doxygen is installed on the system
 	if [ `which doxygen &>/dev/null ; echo $?` -ne 1 ] ; then
@@ -28,6 +32,58 @@ function gen_doxygen {
 	fi
 }
 
+
+function launch_unit_test_daemon {
+        # Run the unit tests for the daemon
+        pushd daemon/test
+        # Remove the previous XML test file
+        rm -rf $XML_RESULTS
+        ./run_tests.sh || exit 1
+        popd
+}
+
+
+function launch_functional_test_daemon {
+        # Run the python functional tests for the daemon
+
+        # make sure no other instance are currently running
+        killall sflphoned
+        killall sipp
+
+        # make sure the configuration directory created
+        CONFDIR=~/.config
+        SFLCONFDIR=${CONFDIR}/sflphone
+
+        eval `dbus-launch --auto-syntax`
+
+        if [ ! -d ${CONFDIR} ]; then
+            mkdir ${CONFDIR}
+        fi
+
+        if [ ! -d ${SFLCONFDIR} ]; then
+            mkdir ${SFLCONFDIR}
+        fi
+
+        # make sure the most recent version of the configuration
+        # is installed
+        pushd tools/pysflphone
+            cp -f sflphoned.functest.yml ${SFLCONFDIR}
+        popd
+
+        # launch sflphone daemon, wait some time for
+        # dbus registration to complete
+        pushd daemon
+            ./src/sflphoned &
+            sleep 3
+        popd
+
+        # launch the test script
+        pushd tools/pysflphone
+            nosetests --with-xunit test_sflphone_dbus_interface.py
+        popd
+}
+
+
 function build_daemon {
 	# Compile the daemon
 	pushd daemon
@@ -55,15 +111,6 @@ function build_daemon {
 	# Compile unit tests
 	make check
 	popd
-
-	if [ $TEST == 1 ]; then
-		# Run the unit tests for the daemon
-		pushd daemon/test
-		# Remove the previous XML test file
-		rm -rf $XML_RESULTS
-		./run_tests.sh || exit 1
-		popd
-	fi
 }
 
 function build_gnome {
@@ -128,5 +175,10 @@ done
 # Call appropriate build function, with parameters if needed
 build_$BUILD
 
+if [ $TEST == 1 ]; then
+    # launch_unit_test_daemon
+    launch_functional_test_daemon
+fi
+
 # SUCCESS
 exit 0
diff --git a/tools/asterisk/extensions.conf b/tools/asterisk/extensions.conf
new file mode 100644
index 0000000000000000000000000000000000000000..7c92a2d2f166c3fe6f3fe1fbd57418c6c18968b8
--- /dev/null
+++ b/tools/asterisk/extensions.conf
@@ -0,0 +1,838 @@
+; extensions.conf - the Asterisk dial plan
+;
+; Static extension configuration file, used by
+; the pbx_config module. This is where you configure all your
+; inbound and outbound calls in Asterisk.
+;
+; This configuration file is reloaded
+; - With the "dialplan reload" command in the CLI
+; - With the "reload" command (that reloads everything) in the CLI
+
+;
+; The "General" category is for certain variables.
+;
+[general]
+;
+; If static is set to no, or omitted, then the pbx_config will rewrite
+; this file when extensions are modified.  Remember that all comments
+; made in the file will be lost when that happens.
+;
+; XXX Not yet implemented XXX
+;
+static=yes
+;
+; if static=yes and writeprotect=no, you can save dialplan by
+; CLI command "dialplan save" too
+;
+writeprotect=no
+;
+; If autofallthrough is set, then if an extension runs out of
+; things to do, it will terminate the call with BUSY, CONGESTION
+; or HANGUP depending on Asterisk's best guess. This is the default.
+;
+; If autofallthrough is not set, then if an extension runs out of
+; things to do, Asterisk will wait for a new extension to be dialed
+; (this is the original behavior of Asterisk 1.0 and earlier).
+;
+;autofallthrough=no
+;
+;
+;
+; If extenpatternmatchnew is set (true, yes, etc), then a new algorithm that uses
+; a Trie to find the best matching pattern is used. In dialplans
+; with more than about 20-40 extensions in a single context, this
+; new algorithm can provide a noticeable speedup.
+; With 50 extensions, the speedup is 1.32x
+; with 88 extensions, the speedup is 2.23x
+; with 138 extensions, the speedup is 3.44x
+; with 238 extensions, the speedup is 5.8x
+; with 438 extensions, the speedup is 10.4x
+; With 1000 extensions, the speedup is ~25x
+; with 10,000 extensions, the speedup is 374x
+; Basically, the new algorithm provides a flat response
+; time, no matter the number of extensions.
+;
+; By default, the old pattern matcher is used.
+;
+; ****This is a new feature! *********************
+; The new pattern matcher is for the brave, the bold, and
+; the desperate. If you have large dialplans (more than about 50 extensions
+; in a context), and/or high call volume, you might consider setting
+; this value to "yes" !!
+; Please, if you try this out, and are forced to return to the
+; old pattern matcher, please report your reasons in a bug report
+; on https://issues.asterisk.org. We have made good progress in providing
+; something compatible with the old matcher; help us finish the job!
+;
+; This value can be switched at runtime using the cli command "dialplan set extenpatternmatchnew true"
+; or "dialplan set extenpatternmatchnew false", so you can experiment to your hearts content.
+;
+;extenpatternmatchnew=no
+;
+; If clearglobalvars is set, global variables will be cleared
+; and reparsed on a dialplan reload, or Asterisk reload.
+;
+; If clearglobalvars is not set, then global variables will persist
+; through reloads, and even if deleted from the extensions.conf or
+; one of its included files, will remain set to the previous value.
+;
+; NOTE: A complication sets in, if you put your global variables into
+; the AEL file, instead of the extensions.conf file. With clearglobalvars
+; set, a "reload" will often leave the globals vars cleared, because it
+; is not unusual to have extensions.conf (which will have no globals)
+; load after the extensions.ael file (where the global vars are stored).
+; So, with "reload" in this particular situation, first the AEL file will
+; clear and then set all the global vars, then, later, when the extensions.conf
+; file is loaded, the global vars are all cleared, and then not set, because
+; they are not stored in the extensions.conf file.
+;
+clearglobalvars=no
+;
+; User context is where entries from users.conf are registered.  The
+; default value is 'default'
+;
+;userscontext=default
+;
+; You can include other config files, use the #include command
+; (without the ';'). Note that this is different from the "include" command
+; that includes contexts within other contexts. The #include command works
+; in all asterisk configuration files.
+;#include "filename.conf"
+;#include <filename.conf>
+;#include filename.conf
+;
+; You can execute a program or script that produces config files, and they
+; will be inserted where you insert the #exec command. The #exec command
+; works on all asterisk configuration files.  However, you will need to
+; activate them within asterisk.conf with the "execincludes" option.  They
+; are otherwise considered a security risk.
+;#exec /opt/bin/build-extra-contexts.sh
+;#exec /opt/bin/build-extra-contexts.sh --foo="bar"
+;#exec </opt/bin/build-extra-contexts.sh --foo="bar">
+;#exec "/opt/bin/build-extra-contexts.sh --foo=\"bar\""
+;
+
+; The "Globals" category contains global variables that can be referenced
+; in the dialplan with the GLOBAL dialplan function:
+; ${GLOBAL(VARIABLE)}
+; ${${GLOBAL(VARIABLE)}} or ${text${GLOBAL(VARIABLE)}} or any hybrid
+; Unix/Linux environmental variables can be reached with the ENV dialplan
+; function: ${ENV(VARIABLE)}
+;
+[globals]
+CONSOLE=Console/dsp				; Console interface for demo
+;CONSOLE=DAHDI/1
+;CONSOLE=Phone/phone0
+IAXINFO=guest					; IAXtel username/password
+;IAXINFO=myuser:mypass
+TRUNK=DAHDI/G2					; Trunk interface
+;
+; Note the 'G2' in the TRUNK variable above. It specifies which group (defined
+; in chan_dahdi.conf) to dial, i.e. group 2, and how to choose a channel to use
+; in the specified group. The four possible options are:
+;
+; g: select the lowest-numbered non-busy DAHDI channel
+;    (aka. ascending sequential hunt group).
+; G: select the highest-numbered non-busy DAHDI channel
+;    (aka. descending sequential hunt group).
+; r: use a round-robin search, starting at the next highest channel than last
+;    time (aka. ascending rotary hunt group).
+; R: use a round-robin search, starting at the next lowest channel than last
+;    time (aka. descending rotary hunt group).
+;
+TRUNKMSD=1					; MSD digits to strip (usually 1 or 0)
+;TRUNK=IAX2/user:pass@provider
+
+;FREENUMDOMAIN=mydomain.com                     ; domain to send on outbound
+                                                ; freenum calls (uses outbound-freenum
+                                                ; context)
+
+;
+; WARNING WARNING WARNING WARNING
+; If you load any other extension configuration engine, such as pbx_ael.so,
+; your global variables may be overridden by that file.  Please take care to
+; use only one location to set global variables, and you will likely save
+; yourself a ton of grief.
+; WARNING WARNING WARNING WARNING
+;
+; Any category other than "General" and "Globals" represent
+; extension contexts, which are collections of extensions.
+;
+; Extension names may be numbers, letters, or combinations
+; thereof. If an extension name is prefixed by a '_'
+; character, it is interpreted as a pattern rather than a
+; literal.  In patterns, some characters have special meanings:
+;
+;   X - any digit from 0-9
+;   Z - any digit from 1-9
+;   N - any digit from 2-9
+;   [1235-9] - any digit in the brackets (in this example, 1,2,3,5,6,7,8,9)
+;   . - wildcard, matches anything remaining (e.g. _9011. matches
+;	anything starting with 9011 excluding 9011 itself)
+;   ! - wildcard, causes the matching process to complete as soon as
+;       it can unambiguously determine that no other matches are possible
+;
+; For example, the extension _NXXXXXX would match normal 7 digit dialings,
+; while _1NXXNXXXXXX would represent an area code plus phone number
+; preceded by a one.
+;
+; Each step of an extension is ordered by priority, which must always start
+; with 1 to be considered a valid extension.  The priority "next" or "n" means
+; the previous priority plus one, regardless of whether the previous priority
+; was associated with the current extension or not.  The priority "same" or "s"
+; means the same as the previously specified priority, again regardless of
+; whether the previous entry was for the same extension.  Priorities may be
+; immediately followed by a plus sign and another integer to add that amount
+; (most useful with 's' or 'n').  Priorities may then also have an alias, or
+; label, in parentheses after their name which can be used in goto situations.
+;
+; Contexts contain several lines, one for each step of each extension.  One may
+; include another context in the current one as well, optionally with a date
+; and time.  Included contexts are included in the order they are listed.
+; Switches may also be included within a context.  The order of matching within
+; a context is always exact extensions, pattern match extensions, includes, and
+; switches.  Includes are always processed depth-first.  So for example, if you
+; would like a switch "A" to match before context "B", simply put switch "A" in
+; an included context "C", where "C" is included in your original context
+; before "B".
+;
+;[context]
+;exten => someexten,{priority|label{+|-}offset}[(alias)],application(arg1,arg2,...)
+;
+; Timing list for includes is
+;
+;   <time range>,<days of week>,<days of month>,<months>[,<timezone>]
+;
+; Note that ranges may be specified to wrap around the ends.  Also, minutes are
+; fine-grained only down to the closest even minute.
+;
+;include => daytime,9:00-17:00,mon-fri,*,*
+;include => weekend,*,sat-sun,*,*
+;include => weeknights,17:02-8:58,mon-fri,*,*
+;
+; ignorepat can be used to instruct drivers to not cancel dialtone upon receipt
+; of a particular pattern.  The most commonly used example is of course '9'
+; like this:
+;
+;ignorepat => 9
+;
+; so that dialtone remains even after dialing a 9.  Please note that ignorepat
+; only works with channels which receive dialtone from the PBX, such as DAHDI,
+; Phone, and VPB.  Other channels, such as SIP and MGCP, which generate their
+; own dialtone and converse with the PBX only after a number is complete, are
+; generally unaffected by ignorepat (unless DISA or another method is used to
+; generate a dialtone after answering the channel).
+;
+
+;
+; Sample entries for extensions.conf
+;
+;
+[dundi-e164-canonical]
+;include => stdexten
+;
+; List canonical entries here
+;
+;exten => 12564286000,1,Gosub(6000,stdexten(IAX2/foo))
+;exten => 12564286000,n,Goto(default,s,1)	; exited Voicemail
+;exten => _125642860XX,1,Dial(IAX2/otherbox/${EXTEN:7})
+
+[dundi-e164-customers]
+;
+; If you are an ITSP or Reseller, list your customers here.
+;
+;exten => _12564286000,1,Dial(SIP/customer1)
+;exten => _12564286001,1,Dial(IAX2/customer2)
+
+[dundi-e164-via-pstn]
+;
+; If you are freely delivering calls to the PSTN, list them here
+;
+;exten => _1256428XXXX,1,Dial(DAHDI/G2/${EXTEN:7}) ; Expose all of 256-428
+;exten => _1256325XXXX,1,Dial(DAHDI/G2/${EXTEN:7}) ; Ditto for 256-325
+
+[dundi-e164-local]
+;
+; Context to put your dundi IAX2 or SIP user in for
+; full access
+;
+include => dundi-e164-canonical
+include => dundi-e164-customers
+include => dundi-e164-via-pstn
+
+[dundi-e164-switch]
+;
+; Just a wrapper for the switch
+;
+switch => DUNDi/e164
+
+[dundi-e164-lookup]
+;
+; Locally to lookup, try looking for a local E.164 solution
+; then try DUNDi if we don't have one.
+;
+include => dundi-e164-local
+include => dundi-e164-switch
+;
+; DUNDi can also be implemented as a Macro instead of using
+; the Local channel driver.
+;
+[macro-dundi-e164]
+;
+; ARG1 is the extension to Dial
+;
+; Extension "s" is not a wildcard extension that matches "anything".
+; In macros, it is the start extension. In most other cases,
+; you have to goto "s" to execute that extension.
+;
+; For wildcard matches, see above - all pattern matches start with
+; an underscore.
+exten => s,1,Goto(${ARG1},1)
+include => dundi-e164-lookup
+
+;
+; Here are the entries you need to participate in the IAXTEL
+; call routing system.  Most IAXTEL numbers begin with 1-700, but
+; there are exceptions.  For more information, and to sign
+; up, please go to www.gnophone.com or www.iaxtel.com
+;
+[iaxtel700]
+exten => _91700XXXXXXX,1,Dial(IAX2/${GLOBAL(IAXINFO)}@iaxtel.com/${EXTEN:1}@iaxtel)
+
+;
+; The SWITCH statement permits a server to share the dialplan with
+; another server. Use with care: Reciprocal switch statements are not
+; allowed (e.g. both A -> B and B -> A), and the switched server needs
+; to be on-line or else dialing can be severly delayed.
+;
+[iaxprovider]
+;switch => IAX2/user:[key]@myserver/mycontext
+
+[trunkint]
+;
+; International long distance through trunk
+;
+exten => _9011.,1,Macro(dundi-e164,${EXTEN:4})
+exten => _9011.,n,Dial(${GLOBAL(TRUNK)}/${FILTER(0-9,${EXTEN:${GLOBAL(TRUNKMSD)}})})
+
+[trunkld]
+;
+; Long distance context accessed through trunk
+;
+exten => _91NXXNXXXXXX,1,Macro(dundi-e164,${EXTEN:1})
+exten => _91NXXNXXXXXX,n,Dial(${GLOBAL(TRUNK)}/${EXTEN:${GLOBAL(TRUNKMSD)}})
+
+[trunklocal]
+;
+; Local seven-digit dialing accessed through trunk interface
+;
+exten => _9NXXXXXX,1,Dial(${GLOBAL(TRUNK)}/${EXTEN:${GLOBAL(TRUNKMSD)}})
+
+[trunktollfree]
+;
+; Long distance context accessed through trunk interface
+;
+exten => _91800NXXXXXX,1,Dial(${GLOBAL(TRUNK)}/${EXTEN:${GLOBAL(TRUNKMSD)}})
+exten => _91888NXXXXXX,1,Dial(${GLOBAL(TRUNK)}/${EXTEN:${GLOBAL(TRUNKMSD)}})
+exten => _91877NXXXXXX,1,Dial(${GLOBAL(TRUNK)}/${EXTEN:${GLOBAL(TRUNKMSD)}})
+exten => _91866NXXXXXX,1,Dial(${GLOBAL(TRUNK)}/${EXTEN:${GLOBAL(TRUNKMSD)}})
+
+[international]
+;
+; Master context for international long distance
+;
+ignorepat => 9
+include => longdistance
+include => trunkint
+
+[longdistance]
+;
+; Master context for long distance
+;
+ignorepat => 9
+include => local
+include => trunkld
+
+[local]
+;
+; Master context for local, toll-free, and iaxtel calls only
+;
+ignorepat => 9
+include => default
+include => trunklocal
+include => iaxtel700
+include => trunktollfree
+include => iaxprovider
+
+;Include parkedcalls (or the context you define in features conf)
+;to enable call parking.
+include => parkedcalls
+;
+; You can use an alternative switch type as well, to resolve
+; extensions that are not known here, for example with remote
+; IAX switching you transparently get access to the remote
+; Asterisk PBX
+;
+; switch => IAX2/user:password@bigserver/local
+;
+; An "lswitch" is like a switch but is literal, in that
+; variable substitution is not performed at load time
+; but is passed to the switch directly (presumably to
+; be substituted in the switch routine itself)
+;
+; lswitch => Loopback/12${EXTEN}@othercontext
+;
+; An "eswitch" is like a switch but the evaluation of
+; variable substitution is performed at runtime before
+; being passed to the switch routine.
+;
+; eswitch => IAX2/context@${CURSERVER}
+
+; The following two contexts are a template to enable the ability to dial
+; ISN numbers. For more information about what an ISN number is, please see
+; http://www.freenum.org.
+;
+; This is the dialing hook.  use:
+; include => outbound-freenum
+
+[outbound-freenum]
+; We'll add more digits as needed. The purpose is to dial things
+; like extension numbers at domains (ITAD number) so we're matching
+; on lengths of 1 through 6 prior to the separator (the asterisk [*])
+;
+exten => _X*X!,1,Goto(outbound-freenum2,${EXTEN},1)
+exten => _XX*X!,1,Goto(outbound-freenum2,${EXTEN},1)
+exten => _XXX*X!,1,Goto(outbound-freenum2,${EXTEN},1)
+exten => _XXXX*X!,1,Goto(outbound-freenum2,${EXTEN},1)
+exten => _XXXXX*X!,1,Goto(outbound-freenum2,${EXTEN},1)
+exten => _XXXXXX*X!,1,Goto(outbound-freenum2,${EXTEN},1)
+
+[outbound-freenum2]
+; This is the handler which performs the dialing logic. It is called
+; from the [outbound-freenum] context
+;
+exten => _X!,1,Verbose(2,Performing ISN lookup for ${EXTEN})
+same => n,Set(SUFFIX=${CUT(EXTEN,*,2-)})                                ; make sure the suffix is all digits as well
+same => n,GotoIf($["${FILTER(0-9,${SUFFIX})}" != "${SUFFIX}"]?fn-CONGESTION,1)
+                                                                        ; filter out bad characters per the README-SERIOUSLY.best-practices.txt document
+same => n,Set(TIMEOUT(absolute)=10800)
+same => n,Set(isnresult=${ENUMLOOKUP(${EXTEN},sip,,1,freenum.org)})     ; perform our lookup with freenum.org
+same => n,GotoIf($["${isnresult}" != ""]?from)
+same => n,Set(DIALSTATUS=CONGESTION)
+same => n,Goto(fn-CONGESTION,1)
+same => n(from),Set(__SIPFROMUSER=${CALLERID(num)})
+same => n,GotoIf($["${GLOBAL(FREENUMDOMAIN)}" = ""]?dial)               ; check if we set the FREENUMDOMAIN global variable in [global]
+same => n,Set(__SIPFROMDOMAIN=${GLOBAL(FREENUMDOMAIN)})                 ;    if we did set it, then we'll use it for our outbound dialing domain
+same => n(dial),Dial(SIP/${isnresult},40)
+same => n,Goto(fn-${DIALSTATUS},1)
+
+exten => fn-BUSY,1,Busy()
+
+exten => _f[n]-.,1,NoOp(ISN: ${DIALSTATUS})
+same => n,Congestion()
+
+[macro-trunkdial]
+;
+; Standard trunk dial macro (hangs up on a dialstatus that should
+; terminate call)
+;   ${ARG1} - What to dial
+;
+exten => s,1,Dial(${ARG1})
+exten => s,n,Goto(s-${DIALSTATUS},1)
+exten => s-NOANSWER,1,Hangup
+exten => s-BUSY,1,Hangup
+exten => _s-.,1,NoOp
+
+[stdexten]
+;
+; Standard extension subroutine:
+;   ${EXTEN} - Extension
+;   ${ARG1} - Device(s) to ring
+;   ${ARG2} - Optional context in Voicemail
+;
+; Note that the current version will drop through to the next priority in the
+; case of their pressing '#'.  This gives more flexibility in what do to next:
+; you can prompt for a new extension, or drop the call, or send them to a
+; general delivery mailbox, or...
+;
+; The use of the LOCAL() function is purely for convenience.  Any variable
+; initially declared as LOCAL() will disappear when the innermost Gosub context
+; in which it was declared returns.  Note also that you can declare a LOCAL()
+; variable on top of an existing variable, and its value will revert to its
+; previous value (before being declared as LOCAL()) upon Return.
+;
+exten => _X.,50000(stdexten),NoOp(Start stdexten)
+exten => _X.,n,Set(LOCAL(ext)=${EXTEN})
+exten => _X.,n,Set(LOCAL(dev)=${ARG1})
+exten => _X.,n,Set(LOCAL(cntx)=${ARG2})
+exten => _X.,n,Set(LOCAL(mbx)=${ext}${IF($[!${ISNULL(${cntx})}]?@${cntx})})
+exten => _X.,n,Dial(${dev},20)				; Ring the interface, 20 seconds maximum
+exten => _X.,n,Goto(stdexten-${DIALSTATUS},1)		; Jump based on status (NOANSWER,BUSY,CHANUNAVAIL,CONGESTION,ANSWER)
+
+exten => stdexten-NOANSWER,1,Voicemail(${mbx},u)	; If unavailable, send to voicemail w/ unavail announce
+exten => stdexten-NOANSWER,n,Return()			; If they press #, return to start
+
+exten => stdexten-BUSY,1,Voicemail(${mbx},b)		; If busy, send to voicemail w/ busy announce
+exten => stdexten-BUSY,n,Return()			; If they press #, return to start
+
+exten => _stde[x]te[n]-.,1,Goto(stdexten-NOANSWER,1)	; Treat anything else as no answer
+
+exten => a,1,VoicemailMain(${mbx})			; If they press *, send the user into VoicemailMain
+exten => a,n,Return()
+
+[stdPrivacyexten]
+;
+; Standard extension subroutine:
+;   ${ARG1} - Extension
+;   ${ARG2} - Device(s) to ring
+;   ${ARG3} - Optional DONTCALL context name to jump to (assumes the s,1 extension-priority)
+;   ${ARG4} - Optional TORTURE context name to jump to (assumes the s,1 extension-priority)`
+;   ${ARG5} - Context in voicemail (if empty, then "default")
+;
+; See above note in stdexten about priority handling on exit.
+;
+exten => _X.,60000(stdPrivacyexten),NoOp(Start stdPrivacyexten)
+exten => _X.,n,Set(LOCAL(ext)=${ARG1})
+exten => _X.,n,Set(LOCAL(dev)=${ARG2})
+exten => _X.,n,Set(LOCAL(dontcntx)=${ARG3})
+exten => _X.,n,Set(LOCAL(tortcntx)=${ARG4})
+exten => _X.,n,Set(LOCAL(cntx)=${ARG5})
+
+exten => _X.,n,Set(LOCAL(mbx)="${ext}"$["${cntx}" ? "@${cntx}" :: ""])
+exten => _X.,n,Dial(${dev},20,p)			; Ring the interface, 20 seconds maximum, call screening
+						; option (or use P for databased call _X.creening)
+exten => _X.,n,Goto(stdexten-${DIALSTATUS},1)		; Jump based on status (NOANSWER,BUSY,CHANUNAVAIL,CONGESTION,ANSWER)
+
+exten => stdexten-NOANSWER,1,Voicemail(${mbx},u)	; If unavailable, send to voicemail w/ unavail announce
+exten => stdexten-NOANSWER,n,NoOp(Finish stdPrivacyexten NOANSWER)
+exten => stdexten-NOANSWER,n,Return()			; If they press #, return to start
+
+exten => stdexten-BUSY,1,Voicemail(${mbx},b)		; If busy, send to voicemail w/ busy announce
+exten => stdexten-BUSY,n,NoOp(Finish stdPrivacyexten BUSY)
+exten => stdexten-BUSY,n,Return()			; If they press #, return to start
+
+exten => stdexten-DONTCALL,1,Goto(${dontcntx},s,1)	; Callee chose to send this call to a polite "Don't call again" script.
+
+exten => stdexten-TORTURE,1,Goto(${tortcntx},s,1)	; Callee chose to send this call to a telemarketer torture script.
+
+exten => _stde[x]te[n]-.,1,Goto(stdexten-NOANSWER,1)	; Treat anything else as no answer
+
+exten => a,1,VoicemailMain(${mbx})		; If they press *, send the user into VoicemailMain
+exten => a,n,Return
+
+[macro-page];
+;
+; Paging macro:
+;
+;       Check to see if SIP device is in use and DO NOT PAGE if they are
+;
+;   ${ARG1} - Device to page
+
+exten => s,1,ChanIsAvail(${ARG1},s)			; s is for ANY call
+exten => s,n,GoToIf($[${AVAILSTATUS} = "1"]?autoanswer:fail)
+exten => s,n(autoanswer),Set(_ALERT_INFO="RA")			; This is for the PolyComs
+exten => s,n,SIPAddHeader(Call-Info: Answer-After=0)	; This is for the Grandstream, Snoms, and Others
+exten => s,n,NoOp()					; Add others here and Post on the Wiki!!!!
+exten => s,n,Dial(${ARG1})
+exten => s,n(fail),Hangup
+
+
+[demo]
+include => stdexten
+;
+; We start with what to do when a call first comes in.
+;
+exten => s,1,Wait(1)			; Wait a second, just for fun
+exten => s,n,Answer			; Answer the line
+exten => s,n,Set(TIMEOUT(digit)=5)	; Set Digit Timeout to 5 seconds
+exten => s,n,Set(TIMEOUT(response)=10)	; Set Response Timeout to 10 seconds
+exten => s,n(restart),BackGround(demo-congrats)	; Play a congratulatory message
+exten => s,n(instruct),BackGround(demo-instruct)	; Play some instructions
+exten => s,n,WaitExten			; Wait for an extension to be dialed.
+
+exten => 2,1,BackGround(demo-moreinfo)	; Give some more information.
+exten => 2,n,Goto(s,instruct)
+
+exten => 3,1,Set(LANGUAGE()=fr)		; Set language to french
+exten => 3,n,Goto(s,restart)		; Start with the congratulations
+
+exten => 1000,1,Goto(default,s,1)
+;
+; We also create an example user, 1234, who is on the console and has
+; voicemail, etc.
+;
+exten => 1234,1,Playback(transfer,skip)		; "Please hold while..."
+					; (but skip if channel is not up)
+exten => 1234,n,Gosub(${EXTEN},stdexten(${GLOBAL(CONSOLE)}))
+exten => 1234,n,Goto(default,s,1)		; exited Voicemail
+
+exten => 1235,1,Voicemail(1234,u)		; Right to voicemail
+
+exten => 1236,1,Dial(Console/dsp)		; Ring forever
+exten => 1236,n,Voicemail(1234,b)		; Unless busy
+
+;
+; # for when they're done with the demo
+;
+exten => #,1,Playback(demo-thanks)	; "Thanks for trying the demo"
+exten => #,n,Hangup			; Hang them up.
+
+;
+; A timeout and "invalid extension rule"
+;
+exten => t,1,Goto(#,1)			; If they take too long, give up
+exten => i,1,Playback(invalid)		; "That's not valid, try again"
+
+;
+; Create an extension, 500, for dialing the
+; Asterisk demo.
+;
+exten => 500,1,Playback(demo-abouttotry); Let them know what's going on
+exten => 500,n,Dial(IAX2/guest@pbx.digium.com/s@default)	; Call the Asterisk demo
+exten => 500,n,Playback(demo-nogo)	; Couldn't connect to the demo site
+exten => 500,n,Goto(s,6)		; Return to the start over message.
+
+;
+; Create an extension, 600, for evaluating echo latency.
+;
+exten => 600,1,Playback(demo-echotest)	; Let them know what's going on
+exten => 600,n,Echo			; Do the echo test
+exten => 600,n,Playback(demo-echodone)	; Let them know it's over
+exten => 600,n,Goto(s,6)		; Start over
+
+;
+;	You can use the Macro Page to intercom a individual user
+exten => 76245,1,Macro(page,SIP/Grandstream1)
+; or if your peernames are the same as extensions
+exten => _7XXX,1,Macro(page,SIP/${EXTEN})
+;
+;
+; System Wide Page at extension 7999
+;
+exten => 7999,1,Set(TIMEOUT(absolute)=60)
+exten => 7999,2,Page(Local/Grandstream1@page&Local/Xlite1@page&Local/1234@page/n,d)
+
+; Give voicemail at extension 8500
+;
+exten => 8500,1,VoicemailMain
+exten => 8500,n,Goto(s,6)
+;
+; Here's what a phone entry would look like (IXJ for example)
+;
+;exten => 1265,1,Dial(Phone/phone0,15)
+;exten => 1265,n,Goto(s,5)
+
+;
+;	The page context calls up the page macro that sets variables needed for auto-answer
+;	It is in is own context to make calling it from the Page() application as simple as
+;	Local/{peername}@page
+;
+[page]
+exten => _X.,1,Macro(page,SIP/${EXTEN})
+
+;[mainmenu]
+;
+; Example "main menu" context with submenu
+;
+;exten => s,1,Answer
+;exten => s,n,Background(thanks)		; "Thanks for calling press 1 for sales, 2 for support, ..."
+;exten => s,n,WaitExten
+;exten => 1,1,Goto(submenu,s,1)
+;exten => 2,1,Hangup
+;include => default
+;
+;[submenu]
+;exten => s,1,Ringing					; Make them comfortable with 2 seconds of ringback
+;exten => s,n,Wait,2
+;exten => s,n,Background(submenuopts)	; "Thanks for calling the sales department.  Press 1 for steve, 2 for..."
+;exten => s,n,WaitExten
+;exten => 1,1,Goto(default,steve,1)
+;exten => 2,1,Goto(default,mark,2)
+
+[default]
+;
+; By default we include the demo.  In a production system, you
+; probably don't want to have the demo there.
+;
+include => demo
+
+exten => 100,1,Dial(SIP/100)
+exten => 200,1,Dial(SIP/200)
+exten => 300,1,Dial(SIP/300)
+
+;
+; An extension like the one below can be used for FWD, Nikotel, sipgate etc.
+; Note that you must have a [sipprovider] section in sip.conf
+;
+;exten => _41X.,1,Dial(SIP/${FILTER(0-9,${EXTEN:2})}@sipprovider,,r)
+
+; Real extensions would go here. Generally you want real extensions to be
+; 4 or 5 digits long (although there is no such requirement) and start with a
+; single digit that is fairly large (like 6 or 7) so that you have plenty of
+; room to overlap extensions and menu options without conflict.  You can alias
+; them with names, too, and use global variables
+
+;exten => 6245,hint,SIP/Grandstream1&SIP/Xlite1(Joe Schmoe) ; Channel hints for presence
+;exten => 6245,1,Dial(SIP/Grandstream1,20,rt)	; permit transfer
+;exten => 6245,n(dial),Dial(${HINT},20,rtT)	; Use hint as listed
+;exten => 6245,n,Voicemail(6245,u)		; Voicemail (unavailable)
+;exten => 6245,s+1,Hangup			; s+1, same as n
+;exten => 6245,dial+101,Voicemail(6245,b)	; Voicemail (busy)
+;exten => 6361,1,Dial(IAX2/JaneDoe,,rm)		; ring without time limit
+;exten => 6389,1,Dial(MGCP/aaln/1@192.168.0.14)
+;exten => 6390,1,Dial(JINGLE/caller/callee) ; Dial via jingle using labels
+;exten => 6391,1,Dial(JINGLE/asterisk@digium.com/mogorman@astjab.org) ;Dial via jingle using asterisk as the transport and calling mogorman.
+;exten => 6394,1,Dial(Local/6275/n)		; this will dial ${MARK}
+
+;exten => 6275,1,Gosub(${EXTEN},stdexten(${MARK}))
+						; assuming ${MARK} is something like DAHDI/2
+;exten => 6275,n,Goto(default,s,1)		; exited Voicemail
+;exten => mark,1,Goto(6275,1)			; alias mark to 6275
+;exten => 6536,1,Gosub(${EXTEN},stdexten(${WIL}))
+						; Ditto for wil
+;exten => 6536,n,Goto(default,s,1)		; exited Voicemail
+;exten => wil,1,Goto(6236,1)
+
+;If you want to subscribe to the status of a parking space, this is
+;how you do it. Subscribe to extension 6600 in sip, and you will see
+;the status of the first parking lot with this extensions' help
+;exten => 6600,hint,park:701@parkedcalls
+;exten => 6600,1,noop
+;
+; Some other handy things are an extension for checking voicemail via
+; voicemailmain
+;
+;exten => 8500,1,VoicemailMain
+;exten => 8500,n,Hangup
+;
+; Or a conference room (you'll need to edit meetme.conf to enable this room)
+;
+;exten => 8600,1,Meetme(1234)
+;
+; Or playing an announcement to the called party, as soon it answers
+;
+;exten = 8700,1,Dial(${MARK},30,A(/path/to/my/announcemsg))
+;
+
+; example of a compartmentalized company called "acme"
+;
+; this is the context that your incoming IAX/SIP trunk dumps you in...
+;[acme-incoming]
+;exten => s,1,Wait(1)
+;exten => s,n,Answer()
+;exten => s,n(menu),Playback(acme/vm-brief-menu)
+;exten => s,n(exten),Background(vm-enter-num-to-call)
+;exten => s,n,WaitExten(5)
+;exten => s,n(goodbye),Playback(vm-goodbye)
+;exten => s,n(end),Hangup()
+;
+;include  => acme-extens
+;
+;exten => i,1,Playback(vm-invalid)
+;exten => i,n,Goto(s,exten)			; optionally, transfer to operator
+;
+;exten => t,1,Goto(s,goodbye)
+;
+; this is the context our internal SIP hardphones use (see sip.conf)
+;
+;[acme-internal]
+;exten => s,1,Answer()
+;exten => s,n(exten),Background(vm-enter-num-to-call)
+;exten => s,n,WaitExten(5)
+;exten => s,n(goodbye),Playback(vm-goodbye)
+;exten => s,n(end),Hangup()
+;
+;include => trunkint
+;include => trunkld
+;include => trunklocal
+;
+;include => acme-extens
+;
+; you can test what your system sounds like to outside callers by dialing this
+;exten => 777,1,DISA(no-password,acme-incoming)
+;
+; grouping of acme's extensions... never used directly, always included.
+;
+;[acme-extens]
+;include => stdexten
+;exten => 111,1,Gosub(111,stdexten(SIP/pete_1,acme))
+;exten => 111,n,Goto(s,exten)
+;
+;exten => 112,1,Gosub(112,stdexten(SIP/nancy_1,acme))
+;exten => 112,n,Goto(s,end)
+;
+; end of acme example
+
+;
+; Time context: you can patch this in via the following.
+;
+; [acme-internal]
+; ...
+; exten => 777,1,Gosub(time)
+; exten => 777,n,Hangup()
+;
+; ...
+; include => time
+;
+; Note: if you're geographically spread out, you can have SIP extensions
+; specify their own local timezone in sip.conf as:
+;
+; [boi]
+; type=friend
+; context=acme-internal
+; callerid="Boise Ofc. <2083451111>"
+; ...
+; ; use system-wide default timezone of MST7MDT
+;
+; [lws]
+; type=friend
+; context=acme-internal
+; callerid="Lewiston Ofc. <2087431111>"
+; ...
+; setvar=timezone=PST8PDT
+;
+; "timezone" isn't a 'reserved' name in any way, and other places where
+; the timezone is significant (e.g. calls to "SayUnixTime()", etc) will
+; require modification as well.  Note that voicemail.conf already has
+; a mechanism for timezones.
+;
+
+[time]
+exten => _X.,30000(time),NoOp(Time: ${EXTEN} ${timezone})
+exten => _X.,n,Wait(0.25)
+exten => _X.,n,Answer()
+; the amount of delay is set for English; you may need to adjust this time
+; for other languages if there's no pause before the synchronizing beep.
+exten => _X.,n,Set(FUTURETIME=$[${EPOCH} + 12])
+exten => _X.,n,SayUnixTime(${FUTURETIME},Zulu,HNS)
+exten => _X.,n,SayPhonetic(z)
+; use the timezone associated with the extension (sip only), or system-wide
+; default if one hasn't been set.
+exten => _X.,n,SayUnixTime(${FUTURETIME},${timezone},HNS)
+exten => _X.,n,Playback(spy-local)
+exten => _X.,n,WaitUntil(${FUTURETIME})
+exten => _X.,n,Playback(beep)
+exten => _X.,n,Return()
+
+;
+; ANI context: use in the same way as "time" above
+;
+
+[ani]
+exten => _X.,40000(ani),NoOp(ANI: ${EXTEN})
+exten => _X.,n,Wait(0.25)
+exten => _X.,n,Answer()
+exten => _X.,n,Playback(vm-from)
+exten => _X.,n,SayDigits(${CALLERID(ani)})
+exten => _X.,n,Wait(1.25)
+exten => _X.,n,SayDigits(${CALLERID(ani)})	; playback again in case of missed digit
+exten => _X.,n,Return()
+
+; For more information on applications, just type "core show applications" at your
+; friendly Asterisk CLI prompt.
+;
+; "core show application <command>" will show details of how you
+; use that particular application in this file, the dial plan.
+; "core show functions" will list all dialplan functions
+; "core show function <COMMAND>" will show you more information about
+; one function. Remember that function names are UPPER CASE.
diff --git a/tools/asterisk/keys/asterisk.crt b/tools/asterisk/keys/asterisk.crt
new file mode 100644
index 0000000000000000000000000000000000000000..088853a120ae05be43adcb5bed59341347dd2cca
--- /dev/null
+++ b/tools/asterisk/keys/asterisk.crt
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIDZjCCAU4CAQEwDQYJKoZIhvcNAQEFBQAwQDEcMBoGA1UEAxMTQXN0ZXJpc2sg
+UHJpdmF0ZSBDQTEgMB4GA1UEChMXVGVzdCBTYXZvaXItRmFpcmUgTGludXgwHhcN
+MTIwNDE2MjEwNzU3WhcNMTMwNDE2MjEwNzU3WjA2MRIwEAYDVQQDEwkxMjcuMC4w
+LjExIDAeBgNVBAoTF1Rlc3QgU2F2b2lyLUZhaXJlIExpbnV4MIGfMA0GCSqGSIb3
+DQEBAQUAA4GNADCBiQKBgQCdxgF7K/c/esDIl4NEqlOPghD1UNDejt0miKrkCGmn
+xnWauKY45me+LfRmHqsmFz8F2657/B0Xh1cLD46jYC7vwRrFC7vkkxXaf7/EjLJj
+qNFUl0yjKrBSZOii3goxeekdDFv7MNqZn2dxaJL18jEtbXUBrFBZ5sVN2ftmWqU2
+QwIDAQABMA0GCSqGSIb3DQEBBQUAA4ICAQCGBJTTqtPXDZmqdjp1tt+LiC9Jc4fs
+6ounWAiHKgyboVGCk8ouDeNhbHnAqxkjAFzFPiuhuiYnKHQcOZ71YHHbMO8Mo8xV
+BvT1KGlDSg/BfRkLMzFea3kIomSXUxPPqHx+EVD7HpsZVQ+4LNwAdg+C3S/9JaNE
+7KWY4dXuaIsS51uiNhxwSKuD7Mqp25FH/cIVl6D9m+4l6RHRDSleISv/PKEh4400
+hM4dUe4K7fCziTI0DDDz1WMGrlGg9pq2PGqqMaNg7tog7wyEq5VDZc0CYggEfMO8
+3BK6FLrVOAf6FHOHlzhX/YpFhouaJtIQ+Ke8/X4j8O48nhJN+qvUovEvGRBYF1JC
+NSsH26dAYvFMzwLxc9QIEn/35ygOpH7FV3eTIryZ4qgulQznKtUF8jsnhkQR8S1N
+vTKCr2JkevxU1c24mmBvd+NUYU9JL9BAoAPyCcSzvQf3imnJ3nMhRAG9c0C/7JAI
+IzmRVYBvoeTCYJdEctQX/Y0SaDque2JJVWhGkeeneJirh1LGwH5yEstFp7Rvus+t
+MERVZOupPx9NRc6STfd3TLtNqPuhU5AoLknxtvpyBeWCiwCL1+/NNSAXdUDO0MrF
+UFfAOdKWORTL8p0ZrVcy7N3UwK+P2bkjhrz+3PWh2airczYIycEXeDvmT20/6X/A
+1jHWfYG7WWPECA==
+-----END CERTIFICATE-----
diff --git a/tools/asterisk/keys/asterisk.csr b/tools/asterisk/keys/asterisk.csr
new file mode 100644
index 0000000000000000000000000000000000000000..8d6f41a562210502aa66b5ebe97d7395b60ff26e
--- /dev/null
+++ b/tools/asterisk/keys/asterisk.csr
@@ -0,0 +1,10 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIIBdTCB3wIBADA2MRIwEAYDVQQDEwkxMjcuMC4wLjExIDAeBgNVBAoTF1Rlc3Qg
+U2F2b2lyLUZhaXJlIExpbnV4MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCd
+xgF7K/c/esDIl4NEqlOPghD1UNDejt0miKrkCGmnxnWauKY45me+LfRmHqsmFz8F
+2657/B0Xh1cLD46jYC7vwRrFC7vkkxXaf7/EjLJjqNFUl0yjKrBSZOii3goxeekd
+DFv7MNqZn2dxaJL18jEtbXUBrFBZ5sVN2ftmWqU2QwIDAQABoAAwDQYJKoZIhvcN
+AQEFBQADgYEAnMwWYJhhXUF2pu9YPxrNX7D3/EatZNugzFR1e/BCusH6LXUaGKbD
+ionzVVjkxCBEysK8B4Dcrw1+65mHAQehs3TesaEfZ3ykf9rC8cPY+kwzsqL96H3z
+OOTfz6XuhANUKkSwD3coqauGwIubCCsE2qiBYib5OJwfchbDsIcIBdc=
+-----END CERTIFICATE REQUEST-----
diff --git a/tools/asterisk/keys/asterisk.key b/tools/asterisk/keys/asterisk.key
new file mode 100644
index 0000000000000000000000000000000000000000..3d5bbcb1b691eed25149cabf8316d08d6aea418b
--- /dev/null
+++ b/tools/asterisk/keys/asterisk.key
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICWwIBAAKBgQCdxgF7K/c/esDIl4NEqlOPghD1UNDejt0miKrkCGmnxnWauKY4
+5me+LfRmHqsmFz8F2657/B0Xh1cLD46jYC7vwRrFC7vkkxXaf7/EjLJjqNFUl0yj
+KrBSZOii3goxeekdDFv7MNqZn2dxaJL18jEtbXUBrFBZ5sVN2ftmWqU2QwIDAQAB
+AoGASC+NA+70u+2NAPoZjDQl8TYATk1Ak2NoGbZUAes7dBDgQ/8RxlzcwG3EMWj8
+w3vFUQfXCFEselRo5d2jVGqwbjemjynm9S0bzRdlM2zW3ORv8mKZkKRNVmr5QlJo
+TD9+HbPCFSPEOOYQ2EDITBXvti2Ch16GNgVLZXd+fwePsdkCQQDR8o3HbkteyZsC
+OTi14El04LEE2JLCtPeeeqNYgZw9NrLuS/QInBX0PCN08DY3RemmWsH4/KqFhS/t
+xSMIKJLHAkEAwGGokL0+d1F2eIdQ8BkcpF+AUM7kwSpzTQ2oRSnK+6vj341YAESf
+H4Nki54QHBQiHuFQBiDOCuonX/CBnLCEpQJAByjpcuKtCVeAxMukxncWqji7cLne
+D2vSggIWrf8FkATch0np0Z1ZFlIyt1s1zh7BQB4aPV6IhjMrlkVB05ZmowJAcZT2
+9cWVbNLe1Fhn8+mPnIh59LvCGT3b50FJ+NOs8RvSJPmJXFcnb26e3UOMFVfZsUur
+eILDw3PtnVoc3ArntQJANA/uYKQtNcFuDHPR7mYpLLcAxNW1pNh5Ynq5tSivoXsu
+ED3RTExmskv2sXsjE69K75JD823zdVu0mUmAkYMQiQ==
+-----END RSA PRIVATE KEY-----
diff --git a/tools/asterisk/keys/asterisk.pem b/tools/asterisk/keys/asterisk.pem
new file mode 100644
index 0000000000000000000000000000000000000000..2c43c07fae9e47346531a7d0e14e3181ba9ff963
--- /dev/null
+++ b/tools/asterisk/keys/asterisk.pem
@@ -0,0 +1,36 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICWwIBAAKBgQCdxgF7K/c/esDIl4NEqlOPghD1UNDejt0miKrkCGmnxnWauKY4
+5me+LfRmHqsmFz8F2657/B0Xh1cLD46jYC7vwRrFC7vkkxXaf7/EjLJjqNFUl0yj
+KrBSZOii3goxeekdDFv7MNqZn2dxaJL18jEtbXUBrFBZ5sVN2ftmWqU2QwIDAQAB
+AoGASC+NA+70u+2NAPoZjDQl8TYATk1Ak2NoGbZUAes7dBDgQ/8RxlzcwG3EMWj8
+w3vFUQfXCFEselRo5d2jVGqwbjemjynm9S0bzRdlM2zW3ORv8mKZkKRNVmr5QlJo
+TD9+HbPCFSPEOOYQ2EDITBXvti2Ch16GNgVLZXd+fwePsdkCQQDR8o3HbkteyZsC
+OTi14El04LEE2JLCtPeeeqNYgZw9NrLuS/QInBX0PCN08DY3RemmWsH4/KqFhS/t
+xSMIKJLHAkEAwGGokL0+d1F2eIdQ8BkcpF+AUM7kwSpzTQ2oRSnK+6vj341YAESf
+H4Nki54QHBQiHuFQBiDOCuonX/CBnLCEpQJAByjpcuKtCVeAxMukxncWqji7cLne
+D2vSggIWrf8FkATch0np0Z1ZFlIyt1s1zh7BQB4aPV6IhjMrlkVB05ZmowJAcZT2
+9cWVbNLe1Fhn8+mPnIh59LvCGT3b50FJ+NOs8RvSJPmJXFcnb26e3UOMFVfZsUur
+eILDw3PtnVoc3ArntQJANA/uYKQtNcFuDHPR7mYpLLcAxNW1pNh5Ynq5tSivoXsu
+ED3RTExmskv2sXsjE69K75JD823zdVu0mUmAkYMQiQ==
+-----END RSA PRIVATE KEY-----
+-----BEGIN CERTIFICATE-----
+MIIDZjCCAU4CAQEwDQYJKoZIhvcNAQEFBQAwQDEcMBoGA1UEAxMTQXN0ZXJpc2sg
+UHJpdmF0ZSBDQTEgMB4GA1UEChMXVGVzdCBTYXZvaXItRmFpcmUgTGludXgwHhcN
+MTIwNDE2MjEwNzU3WhcNMTMwNDE2MjEwNzU3WjA2MRIwEAYDVQQDEwkxMjcuMC4w
+LjExIDAeBgNVBAoTF1Rlc3QgU2F2b2lyLUZhaXJlIExpbnV4MIGfMA0GCSqGSIb3
+DQEBAQUAA4GNADCBiQKBgQCdxgF7K/c/esDIl4NEqlOPghD1UNDejt0miKrkCGmn
+xnWauKY45me+LfRmHqsmFz8F2657/B0Xh1cLD46jYC7vwRrFC7vkkxXaf7/EjLJj
+qNFUl0yjKrBSZOii3goxeekdDFv7MNqZn2dxaJL18jEtbXUBrFBZ5sVN2ftmWqU2
+QwIDAQABMA0GCSqGSIb3DQEBBQUAA4ICAQCGBJTTqtPXDZmqdjp1tt+LiC9Jc4fs
+6ounWAiHKgyboVGCk8ouDeNhbHnAqxkjAFzFPiuhuiYnKHQcOZ71YHHbMO8Mo8xV
+BvT1KGlDSg/BfRkLMzFea3kIomSXUxPPqHx+EVD7HpsZVQ+4LNwAdg+C3S/9JaNE
+7KWY4dXuaIsS51uiNhxwSKuD7Mqp25FH/cIVl6D9m+4l6RHRDSleISv/PKEh4400
+hM4dUe4K7fCziTI0DDDz1WMGrlGg9pq2PGqqMaNg7tog7wyEq5VDZc0CYggEfMO8
+3BK6FLrVOAf6FHOHlzhX/YpFhouaJtIQ+Ke8/X4j8O48nhJN+qvUovEvGRBYF1JC
+NSsH26dAYvFMzwLxc9QIEn/35ygOpH7FV3eTIryZ4qgulQznKtUF8jsnhkQR8S1N
+vTKCr2JkevxU1c24mmBvd+NUYU9JL9BAoAPyCcSzvQf3imnJ3nMhRAG9c0C/7JAI
+IzmRVYBvoeTCYJdEctQX/Y0SaDque2JJVWhGkeeneJirh1LGwH5yEstFp7Rvus+t
+MERVZOupPx9NRc6STfd3TLtNqPuhU5AoLknxtvpyBeWCiwCL1+/NNSAXdUDO0MrF
+UFfAOdKWORTL8p0ZrVcy7N3UwK+P2bkjhrz+3PWh2airczYIycEXeDvmT20/6X/A
+1jHWfYG7WWPECA==
+-----END CERTIFICATE-----
diff --git a/tools/asterisk/keys/ca.cfg b/tools/asterisk/keys/ca.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..f362441845dd96792477e6e592f397923b57d711
--- /dev/null
+++ b/tools/asterisk/keys/ca.cfg
@@ -0,0 +1,10 @@
+[req]
+distinguished_name = req_distinguished_name
+prompt = no
+
+[req_distinguished_name]
+CN=Asterisk Private CA
+O=Test Savoir-Faire Linux
+
+[ext]
+basicConstraints=CA:TRUE
diff --git a/tools/asterisk/keys/ca.crt b/tools/asterisk/keys/ca.crt
new file mode 100644
index 0000000000000000000000000000000000000000..bce248b454f3c0b4dfde1ab2762981a60d7caf57
--- /dev/null
+++ b/tools/asterisk/keys/ca.crt
@@ -0,0 +1,29 @@
+-----BEGIN CERTIFICATE-----
+MIIE/DCCAuQCCQCHJx9CtI2lVDANBgkqhkiG9w0BAQUFADBAMRwwGgYDVQQDExNB
+c3RlcmlzayBQcml2YXRlIENBMSAwHgYDVQQKExdUZXN0IFNhdm9pci1GYWlyZSBM
+aW51eDAeFw0xMjA0MTYyMTA3NTJaFw0xMzA0MTYyMTA3NTJaMEAxHDAaBgNVBAMT
+E0FzdGVyaXNrIFByaXZhdGUgQ0ExIDAeBgNVBAoTF1Rlc3QgU2F2b2lyLUZhaXJl
+IExpbnV4MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEArD4kMmNp/EmP
+aqsg9/UWviUXPHjze8TpJfFB4eNJy7HsBHAJSyfrf8NU9Bv8zWsPFs27GKC1EH+N
+i+KIqmz5LZuh6e3q9QwC1ii17ruTZBAAxZXUcH1uX13MhJtaKEvT1pnnGFAA7eRT
+VIvN27R6uTVzBsJKe+qEwxr5ozN5g3JqpM0yF+lQtUWTw9g7JQnw4a/78/qDSnHm
+DnBb8zDccAZiyyhPAzUunrlEIAfTZObrx8xbQRNuRbv55jgcBLwqVUbr0b9Tvx5y
+lM/jqrCYQee1ayNpaHLqYgk8/e2zicM1NBwTLSTITwaaDIJL/YHkDo13UAhGZ3D/
+P9tIGCcGea4zoVhzkakCfSHMR+WUad4Y2sG9wR46S5SDuVUQgrEGgMBFykMYfSCL
+Xs8h6flD5BfaE4FKeQcwfZvaFxieV/5hW6y7splL10pRbmsOleK1rn+aoA9b2Lo7
+HFLbaDMjkOOTGsAxlWMJcbOoPKzsX+4VsUU7/dAMK8QDMGuJOBZ3uX5ESIHj23qv
+oZ3KmreW/VsAlU7J0n7ElQIEbBuqcw/xPZfJpG364Tm9V560JXmNKIlsGbUsT3zA
+NV68EOZlcSXEGOIr8adC7geHtL+cJ8TejiUIFjDWIcJaU0Gg6nFeyY1jhBnEBVxm
+Qg9KT2vKloSlCNyMki0kwXld2l48SG8CAwEAATANBgkqhkiG9w0BAQUFAAOCAgEA
+VkmvTg1DbX0/70A+UijAk+GwJpOak3FaKwgF1zFu1zVQGOnPXxeOa2B7cffgXxSq
+CNccHB3yZyU0skxRkRLjyHRTgtObvH3KmEDMUSBlH06hKzOGbnhhNFkJGmXSEN/Y
+4QytlApqP3Ugpu931xtS3JDfSwwQCbdoUU5Jnn4pRgcGXZI9jTP8wz9w3YVvFUn3
+7bF5WEwtbtMh9Umtx5EpZa9CFAnABY+qU18kucHwu7wtucIaEyPdTT9I0H8Wzn0P
+6elhzJlhru/xaekhZU+Qk1kDwHndLUUfl6/KpLO7gYKqUyAW6rGjgKGuT/0O3Iw6
+yVsz/zmvkUYK6lCMLDY8Kva3Gc0QmRxnO/GcdwAd3WP85V6Nh5bx1Vrsjlro9oZ7
+AZOsUP6ghmNFBGQUl9UsFUNJjYrpZtr8AwYzY4sa46a7nEK1Pe9QxMgGMPXGSwT3
+0PYVXPABgpgEJJTBnejRi7/xsr60qLrEqPlnAWvq8/g6MrEVz2OUPK3c/pBS9xMf
+pgo+adR3zgKHtfE7Ud+Vlw19ASZy/5P7pqkFUuCqOKziJMYSTq92SGqry1svPlqo
+YvpTNBhgCv4WrgdcgceRMOONNyeo55lR417VtY0wiE6pkzcwU5m1O0MceYndk5Tq
+f1fpnAn3GkgKbphiPEU7megH4rdjt2XUa+N/QiRzjyU=
+-----END CERTIFICATE-----
diff --git a/tools/asterisk/keys/ca.key b/tools/asterisk/keys/ca.key
new file mode 100644
index 0000000000000000000000000000000000000000..723a1be63c23af685165d4a153d70a5529cb1f76
--- /dev/null
+++ b/tools/asterisk/keys/ca.key
@@ -0,0 +1,54 @@
+-----BEGIN RSA PRIVATE KEY-----
+Proc-Type: 4,ENCRYPTED
+DEK-Info: DES-EDE3-CBC,2C7C01E8719BBC40
+
+nHi+LlUabC/JCdra5WRyWl2F2Y6O/YpBmekFldvtTMb+4Z2BHE3WDBU+p3VaP+Uw
+vEyKmeKKfGsL5VTVNNZCbbxL5BGy/I/72kO8dhgdy1wwzE84LQjHG6DOBUnr/p2v
+AIlUxzK7KcUbXyJyFlIf+B0pwCaFASh6EXHWA4u6FkhyYY7buaf15mGtQncmvPem
+pVyFyddcPpW7w6+HrSCWr1xBNFw73zlV8sjhxNW1n7+ORNe6yu5lce35nwxsYrAx
+xxul94nNHH7JCbF2rYMIKb+/ycer52Qww4W7fHRJC8odjJy3Np5Bfa1LMvGqHlyq
+tVjR8Bs0feyNlxebqgmiozCJhudBS9P7jbjtp3nbzLxQG/BYlH6jgeD5nhruUS8p
+2nXRZ+oAsnclP9sAHdro1SXsbv9w+cvN9MENoYCSlA/8KUctrjdhLnPCGT20PPMr
+27viMTV4vOEnQwUFVzIE4lvC6X9nqxKHxW2tcoz//A/IN1IcB11nSFH3l1ZdTsd1
+BrfWxW5/gWL4K+wgNEFlm6QG6bDU7Ek+dKeT4e1PzVbM8okqhTzj6KO2rGVcc6WK
+PcVd+Hcq/fvdxUGoFNnfqpmoBSmXiDkoDnkrGluflP8Zi0HpzGnUkN3EA38YnpAW
+fPqqrXjVOtgSvcBD6RJL5/MZn98fMXECNwfZEs8/CMW91whHApjgyQyMmX1MN3xS
+NgkLlBa24rvzBLzaQyCATQ1PKundV8d8NiLIV4V8QL5zxHFG6IQiJJV0+zukdCR6
+0DcH5tfj4almm9w4WbqcUzaAlkW1CQdZDVhK62aVAe7rubG4EPVd6iHUMzOwGHbT
+GB1AdIsAQfN9h46KmNtLu2OBwqzJtBOMeQf0McWvkQeEOQ9VhJL2VvQdHhtYbDb4
+ZS3VkbEvVxUmCO71HeYLQ88nSkS4hhIZ2nfaeOk1BBeFf2tC6P7agq4Dpxp+4vFW
+TqBiJ6lbFJi8DWKlTbjzVu+daX/iFECGm95AZ8DFdWy5O6wiczc1MEkUAzF6pUzz
+WZm671L6UJiPSgEW7kIp8Af/jW8An5mcjGD1IsQurcUdtCcCM2HfA1AVu57O9jfD
+KKsOgLcyJBqneVzeZ1j/WoqKwzElG1nmUnVCoUQa3xAdKUba0BIUduEKoKSD1Amh
+sCKzJxfMDgRdLymfcan4wj89+GkZzAtVLdeVDaUrtNwUIuQf/A3pXeqi/EjFgsaC
+tGSqKA5VghHvaEtE29of0VMkqHH0whP00Mhq6F8wUlvU9WxjTkBg3juUAHsQ0EAy
+KLnrfd2gLDiZ6FtUVlitTuPlD2kPq+RYt+lhK5EYQYJ2Cm31cn/cFJSsGlTybhhj
+hsTfqV3dcVfkEmexhbys6sWtwzHhH/A67UqFWZkytjbhnD1X5Cq7lmMisIoQ3fE2
+945iLyO9ox+IGV7yqq55264Co9Xnw72XnJlNkSiPxIXL6mOzqwQHVB1m4D71Zojk
+vqHnlnKyGinafXsEGh4TTWk/zUJAaZvjwUHl43q7bFwmI3FpKFXpRsDmcVk1YsEl
+2ChEfbNIvbVyECOGJU5evPHwuKirB2OmVOzfxJp39TgEkGDiCSv9PYIwoUY+2Qfg
+ZBW/gTUBGOWMuzDqgqKVpWW53qBb5E6Zp8O7umfbOtw+c5a3vD/Jv8u/zsZwBh0b
+DOK7+tDAR05asleYmieSPpd3Jtfn77HkOWIDT47A8dWzOtDRJNZXOIlJE/tCar5F
+1GNJMr/e/oNZyJ/DrdVHuD9TJrCA8zjqHwk2RMo9wilClgNlsc6m69ipxhG2mzVF
+KlrJQc4pvlYoQp/d5NwEO0t/JGKO5SFlsgL9K7+C6t7eS5EupiAYwYjbH+/rdCBc
+yyWIf4eWLlRssFY3A8QD5LoO6jpt9/oKZe88P2IFNNcKNTWXzHhkx8XskIrqw5tw
+Og7iQiyF64CbAg1I9hDbs8z+pOs47BkHJa6nxbK128ZDj+c0qCCao+GX50Erv0gr
+MhhAgN5XqSrcpr943sS7OzdEppz6lxcxuHDbZywGG4v2smBbzWl4reFk5e8ZyWxf
+ZIOpErx8sLG44neZb4AbNbfVK9JMRvNz/kSjhZXeLvsohkAYomrGi9LUJ6TGjN7i
+MHP9Hsu0nGKd10UZ7t8ZsMrxX0KAsj/Su/qMgfivLjhmj11Uzr48hZob+TaVLuRF
+GAqzZcmIHYA6/NDjp0e/GwDrMd92N8SNfqPdJ0LH2a3b93teh4qlLscE8VoY7XF6
+o85t28DfgpL00+tB3VUWkFCd0f7sOgvA1TYjRITNCVNoSVFzVZjk7r8SiE3bYOd/
+IIjLJMEt2MKVDg7jrIQyMtkpqEVR+83dP3rmMz2utqkTGw33VYqrNdaLikST0nZO
+uaw3RUMFfWXzKFyyVA01RepccAkls6uz/Cf3I8491b06ledxByyazCHkFLGnRuJZ
+/KDfutbStKoqRIQEfHpk43mu4pfT/8xGT5SygAATpIPGstlKOJ7e4/qjex8zmthW
+gUcechy56Fdo5rewG/Qa2uUTv0OsjIjThM98nmWZk8VtWthWi43op2j93tsrQAkh
+bH/3UBgQZ/tROp620lUwAZt2JlT5aVcYtSZvC+iwUd/Pw7ztdyenZGHmBNSq6ggM
+YweVtfubWSsaL09kPEaL4Lsh8OhwIWDpbZ/DsdkDrkeXeInYhNwV3Ilx6zb9HiBk
+y0kMSgro9Ob1vi62liYxN3ziFWSjxr43tjrw83oCBf9m/7o2lIOh3w/7uwXSs8K5
+ehcUEU/UmqjG+VYiu0sQZHoZzORJh5IBfRAIEpWNI53WIEYtNi1mspwWZuKc6B1J
+xXU1Wq6OJwIQzitghA7CHfu7dbYidFKa8Hxv63rp5k7fZpoBWxFDzPzJZToPLfoR
+eUbGWXP0hmSTZw3JHMeP5g6TvpRcvrRntl4wsiGP8HxO/yID//Anvvsaxn8/fVrv
+h0Mjq1gFvzyF0ht3yfk2/MaEtpp9B6H4Y5CQj7M/xAKlCK0xF8lq91Ocxh+0k2Iq
+1qM4rz1okjBwT6zA87dahK7BXY8Nh4LWSDikgzLc0fiWR1DdlGFzDrq060912uNK
+B7pziHHdES0bE/8c7i3V/u4zwbM9Rj36nsC+r8d7BTyOb6Y4wN315IsG9AH8WYvt
+-----END RSA PRIVATE KEY-----
diff --git a/tools/asterisk/keys/testphone1.crt b/tools/asterisk/keys/testphone1.crt
new file mode 100644
index 0000000000000000000000000000000000000000..c4bdbc7b8324219ba403c1cbab7b002b2b569448
--- /dev/null
+++ b/tools/asterisk/keys/testphone1.crt
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIDZjCCAU4CAQEwDQYJKoZIhvcNAQEFBQAwQDEcMBoGA1UEAxMTQXN0ZXJpc2sg
+UHJpdmF0ZSBDQTEgMB4GA1UEChMXVGVzdCBTYXZvaXItRmFpcmUgTGludXgwHhcN
+MTIwNDE2MjExMDQ3WhcNMTMwNDE2MjExMDQ3WjA2MRIwEAYDVQQDEwkxMjcuMC4w
+LjExIDAeBgNVBAoTF1Rlc3QgU2F2b2lyLUZhaXJlIExpbnV4MIGfMA0GCSqGSIb3
+DQEBAQUAA4GNADCBiQKBgQDcD0nVaHoNVpEVLTyN0JOVuEDUZovaMK/XXmQYnP1M
+v9Ru5fU4977DpPQdjqmTSv+VD83QGbUnORdjDSgK8vAmWLnZxJJxxF1pTpbKpKDp
+FO9f74xhh/ekJCWPqfeJqRbjJ5rhXqqbWPtjuI1vXgwBL7MdWQVAuzgz9+kHITxj
+tQIDAQABMA0GCSqGSIb3DQEBBQUAA4ICAQCqs3JJxwXqiRksCf7fGA6mt19Kp6EJ
+kYv7tA2xO0qR6dHX5pE6IQ2bk22jlIHsg269oX4XAtg1OiGMCyLOfrDOve86+qlW
+7+sARNmtDXHT1kQPa8FJbwmdS5Gl4PXzFrRrB6hDlBBtKu5CEMkHuscjpnt9BPA5
+RvXhb3MREs9n0VM0R8hhtgiEVPOLKZpfASSLU8iiTurBdybSAb1hPLRwJF+PIak8
+pohqbEo2lNZq/OdxEIvOnNO7UISfYcojmFFUatPgl35O3hTRA6/RIkPtdXOtTqzX
+agZDgHvn2tnkmSPfO9Zx/8KKa9u1XyXBdNXjdoq0cEaKv7sYCKzPGPbuvoemSbmz
+6u1CrZY+IkFDPLe5mkUBMzNFuHYpy5Xfafs8zo2F+NEpHHKT4PhVFWKQ+FEFoRgi
+P70oA0mXtjoSIhcZiYkbwV5algr7aWP1pAO7A6mjT4SQpk/LSN96eBvy5Llkgety
+Fl+TZizCKMN+PVELgMjQwkHGNDFCyrxGS9j5SSvYj8lIIqlqyOkpsLarfK73JEfZ
+Ad52SK+2/6LamoQbouwVVx7grDEtP+jfqYlr4Mrif8IgoDw9vHSVtlDZ6o5kJh7y
+ZWQz0EDQJXlxnKb4UkftilOUoDPinc1nkRvk6s/DQ6JrHDKYaVyHckjj5xEiqzuP
+USftzxBPTlP4dA==
+-----END CERTIFICATE-----
diff --git a/tools/asterisk/keys/testphone1.csr b/tools/asterisk/keys/testphone1.csr
new file mode 100644
index 0000000000000000000000000000000000000000..7599b6114a5cc643e1f223de57125820635a691f
--- /dev/null
+++ b/tools/asterisk/keys/testphone1.csr
@@ -0,0 +1,10 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIIBdTCB3wIBADA2MRIwEAYDVQQDEwkxMjcuMC4wLjExIDAeBgNVBAoTF1Rlc3Qg
+U2F2b2lyLUZhaXJlIExpbnV4MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc
+D0nVaHoNVpEVLTyN0JOVuEDUZovaMK/XXmQYnP1Mv9Ru5fU4977DpPQdjqmTSv+V
+D83QGbUnORdjDSgK8vAmWLnZxJJxxF1pTpbKpKDpFO9f74xhh/ekJCWPqfeJqRbj
+J5rhXqqbWPtjuI1vXgwBL7MdWQVAuzgz9+kHITxjtQIDAQABoAAwDQYJKoZIhvcN
+AQEFBQADgYEAyqOCNC90ONkad55VRJDnxxhGDtOHlmy/87+5XF09luqF2i2aRjV5
+sY8fkHmkcMH0ppMTakrTxLsfJUJ6k5CCg3zXRzUB8Eg89gmPQuPEbBWEXm5ahZIS
+ceJUoOTSfNAfiYaTTaap2dCTb4ENrOyyu6WMbH22FBgr/OQrRB9NLS8=
+-----END CERTIFICATE REQUEST-----
diff --git a/tools/asterisk/keys/testphone1.key b/tools/asterisk/keys/testphone1.key
new file mode 100644
index 0000000000000000000000000000000000000000..8562655775cc80ae5709620d8e85e17410207436
--- /dev/null
+++ b/tools/asterisk/keys/testphone1.key
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXgIBAAKBgQDcD0nVaHoNVpEVLTyN0JOVuEDUZovaMK/XXmQYnP1Mv9Ru5fU4
+977DpPQdjqmTSv+VD83QGbUnORdjDSgK8vAmWLnZxJJxxF1pTpbKpKDpFO9f74xh
+h/ekJCWPqfeJqRbjJ5rhXqqbWPtjuI1vXgwBL7MdWQVAuzgz9+kHITxjtQIDAQAB
+AoGAEJIaJjbK0gxNuoGAiNFG+8Q3JYdfSpvV8erKsMvJiyj6zysDzzlgpQzb0Qn4
+HP5NxqS9A8mbyYtUBoJsHH70tFrBufsr/ewWL9W/o5SuLOVk4mtGl5aALQSa9OO8
+ue/UwOG5Wnbggdl/RqNlAtqROPfraKmK7RJxHU1MqIUs27UCQQDz2p+y5O8N+NH8
+LRDMK9Y/pk1KAKVwj20escn+Km9NThjAeF6ejhP8RcAXUdxyxPQmktc74udnGlfk
+RqVa68u7AkEA5wVDq8xEaEO08g7F6msiuqImnCfvfn5j52sVXbLEh4fOlHX3gfep
+B0QURCLrsq28ACHaD+AtXzVEr5IaTOi/TwJBALw4PlXdwOre6G2l9zYwi+F7ImMB
+VrEn84jin8+vv1NC+XXuMtJdRe3NhLQ7OlXX0b/ITZtqy0PYoIiRQuaH5CsCQQDB
+tUBQxS523o7SiGCbdsngBCaruTCvt/q9CKUZs9PmcJFfGqs2Zxtr5EG6AC3x3ItO
+8ROPTEG/G0NElBVJd78xAkEAmHAZd/+5qcBlz7BLLcD1Rc598gRxaOnMNkjHw15i
+KOyDNgk5m4OtZ5npbTJDrEW1wjw912ga0jb2J/urCl1X4A==
+-----END RSA PRIVATE KEY-----
diff --git a/tools/asterisk/keys/testphone1.pem b/tools/asterisk/keys/testphone1.pem
new file mode 100644
index 0000000000000000000000000000000000000000..f704ed61e732fc1b0f17608bc01dad82f5a0ec51
--- /dev/null
+++ b/tools/asterisk/keys/testphone1.pem
@@ -0,0 +1,36 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXgIBAAKBgQDcD0nVaHoNVpEVLTyN0JOVuEDUZovaMK/XXmQYnP1Mv9Ru5fU4
+977DpPQdjqmTSv+VD83QGbUnORdjDSgK8vAmWLnZxJJxxF1pTpbKpKDpFO9f74xh
+h/ekJCWPqfeJqRbjJ5rhXqqbWPtjuI1vXgwBL7MdWQVAuzgz9+kHITxjtQIDAQAB
+AoGAEJIaJjbK0gxNuoGAiNFG+8Q3JYdfSpvV8erKsMvJiyj6zysDzzlgpQzb0Qn4
+HP5NxqS9A8mbyYtUBoJsHH70tFrBufsr/ewWL9W/o5SuLOVk4mtGl5aALQSa9OO8
+ue/UwOG5Wnbggdl/RqNlAtqROPfraKmK7RJxHU1MqIUs27UCQQDz2p+y5O8N+NH8
+LRDMK9Y/pk1KAKVwj20escn+Km9NThjAeF6ejhP8RcAXUdxyxPQmktc74udnGlfk
+RqVa68u7AkEA5wVDq8xEaEO08g7F6msiuqImnCfvfn5j52sVXbLEh4fOlHX3gfep
+B0QURCLrsq28ACHaD+AtXzVEr5IaTOi/TwJBALw4PlXdwOre6G2l9zYwi+F7ImMB
+VrEn84jin8+vv1NC+XXuMtJdRe3NhLQ7OlXX0b/ITZtqy0PYoIiRQuaH5CsCQQDB
+tUBQxS523o7SiGCbdsngBCaruTCvt/q9CKUZs9PmcJFfGqs2Zxtr5EG6AC3x3ItO
+8ROPTEG/G0NElBVJd78xAkEAmHAZd/+5qcBlz7BLLcD1Rc598gRxaOnMNkjHw15i
+KOyDNgk5m4OtZ5npbTJDrEW1wjw912ga0jb2J/urCl1X4A==
+-----END RSA PRIVATE KEY-----
+-----BEGIN CERTIFICATE-----
+MIIDZjCCAU4CAQEwDQYJKoZIhvcNAQEFBQAwQDEcMBoGA1UEAxMTQXN0ZXJpc2sg
+UHJpdmF0ZSBDQTEgMB4GA1UEChMXVGVzdCBTYXZvaXItRmFpcmUgTGludXgwHhcN
+MTIwNDE2MjExMDQ3WhcNMTMwNDE2MjExMDQ3WjA2MRIwEAYDVQQDEwkxMjcuMC4w
+LjExIDAeBgNVBAoTF1Rlc3QgU2F2b2lyLUZhaXJlIExpbnV4MIGfMA0GCSqGSIb3
+DQEBAQUAA4GNADCBiQKBgQDcD0nVaHoNVpEVLTyN0JOVuEDUZovaMK/XXmQYnP1M
+v9Ru5fU4977DpPQdjqmTSv+VD83QGbUnORdjDSgK8vAmWLnZxJJxxF1pTpbKpKDp
+FO9f74xhh/ekJCWPqfeJqRbjJ5rhXqqbWPtjuI1vXgwBL7MdWQVAuzgz9+kHITxj
+tQIDAQABMA0GCSqGSIb3DQEBBQUAA4ICAQCqs3JJxwXqiRksCf7fGA6mt19Kp6EJ
+kYv7tA2xO0qR6dHX5pE6IQ2bk22jlIHsg269oX4XAtg1OiGMCyLOfrDOve86+qlW
+7+sARNmtDXHT1kQPa8FJbwmdS5Gl4PXzFrRrB6hDlBBtKu5CEMkHuscjpnt9BPA5
+RvXhb3MREs9n0VM0R8hhtgiEVPOLKZpfASSLU8iiTurBdybSAb1hPLRwJF+PIak8
+pohqbEo2lNZq/OdxEIvOnNO7UISfYcojmFFUatPgl35O3hTRA6/RIkPtdXOtTqzX
+agZDgHvn2tnkmSPfO9Zx/8KKa9u1XyXBdNXjdoq0cEaKv7sYCKzPGPbuvoemSbmz
+6u1CrZY+IkFDPLe5mkUBMzNFuHYpy5Xfafs8zo2F+NEpHHKT4PhVFWKQ+FEFoRgi
+P70oA0mXtjoSIhcZiYkbwV5algr7aWP1pAO7A6mjT4SQpk/LSN96eBvy5Llkgety
+Fl+TZizCKMN+PVELgMjQwkHGNDFCyrxGS9j5SSvYj8lIIqlqyOkpsLarfK73JEfZ
+Ad52SK+2/6LamoQbouwVVx7grDEtP+jfqYlr4Mrif8IgoDw9vHSVtlDZ6o5kJh7y
+ZWQz0EDQJXlxnKb4UkftilOUoDPinc1nkRvk6s/DQ6JrHDKYaVyHckjj5xEiqzuP
+USftzxBPTlP4dA==
+-----END CERTIFICATE-----
diff --git a/tools/asterisk/keys/tmp.cfg b/tools/asterisk/keys/tmp.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..f9d4477e978ba4a795440491b0922beff81e1ab9
--- /dev/null
+++ b/tools/asterisk/keys/tmp.cfg
@@ -0,0 +1,7 @@
+[req]
+distinguished_name = req_distinguished_name
+prompt = no
+
+[req_distinguished_name]
+CN=127.0.0.1
+O=Test Savoir-Faire Linux
diff --git a/tools/asterisk/sip.conf b/tools/asterisk/sip.conf
new file mode 100644
index 0000000000000000000000000000000000000000..5ec53dfb8774ddf14ef30c7515b44efdd7a8cf24
--- /dev/null
+++ b/tools/asterisk/sip.conf
@@ -0,0 +1,1378 @@
+;
+; SIP Configuration example for Asterisk
+;
+; Note: Please read the security documentation for Asterisk in order to
+; 	understand the risks of installing Asterisk with the sample
+;	configuration. If your Asterisk is installed on a public
+;	IP address connected to the Internet, you will want to learn
+;	about the various security settings BEFORE you start
+;	Asterisk.
+;
+;	Especially note the following settings:
+;		- allowguest (default enabled)
+;		- permit/deny - IP address filters
+;		- contactpermit/contactdeny - IP address filters for registrations
+;		- context - Which set of services you offer various users
+;
+; SIP dial strings
+;-----------------------------------------------------------
+; In the dialplan (extensions.conf) you can use several
+; syntaxes for dialing SIP devices.
+;        SIP/devicename
+;        SIP/username@domain   (SIP uri)
+;        SIP/username[:password[:md5secret[:authname[:transport]]]]@host[:port]
+;        SIP/devicename/extension
+;        SIP/devicename/extension/IPorHost
+;        SIP/username@domain//IPorHost
+;
+;
+; Devicename
+;        devicename is defined as a peer in a section below.
+;
+; username@domain
+;        Call any SIP user on the Internet
+;        (Don't forget to enable DNS SRV records if you want to use this)
+;
+; devicename/extension
+;        If you define a SIP proxy as a peer below, you may call
+;        SIP/proxyhostname/user or SIP/user@proxyhostname
+;        where the proxyhostname is defined in a section below
+;        This syntax also works with ATA's with FXO ports
+;
+; SIP/username[:password[:md5secret[:authname]]]@host[:port]
+;        This form allows you to specify password or md5secret and authname
+;        without altering any authentication data in config.
+;        Examples:
+;
+;        SIP/*98@mysipproxy
+;        SIP/sales:topsecret::account02@domain.com:5062
+;        SIP/12345678::bc53f0ba8ceb1ded2b70e05c3f91de4f:myname@192.168.0.1
+;
+; IPorHost
+;        The next server for this call regardless of domain/peer
+;
+; All of these dial strings specify the SIP request URI.
+; In addition, you can specify a specific To: header by adding an
+; exclamation mark after the dial string, like
+;
+;         SIP/sales@mysipproxy!sales@edvina.net
+;
+; A new feature for 1.8 allows one to specify a host or IP address to use
+; when routing the call. This is typically used in tandem with func_srv if
+; multiple methods of reaching the same domain exist. The host or IP address
+; is specified after the third slash in the dialstring. Examples:
+;
+; SIP/devicename/extension/IPorHost
+; SIP/username@domain//IPorHost
+;
+; CLI Commands
+; -------------------------------------------------------------
+; Useful CLI commands to check peers/users:
+;   sip show peers               Show all SIP peers (including friends)
+;   sip show registry            Show status of hosts we register with
+;
+;   sip set debug on             Show all SIP messages
+;
+;   sip reload                   Reload configuration file
+;   sip show settings            Show the current channel configuration
+;
+;------- Naming devices ------------------------------------------------------
+;
+; When naming devices, make sure you understand how Asterisk matches calls
+; that come in.
+;	1. Asterisk checks the SIP From: address username and matches against
+;	   names of devices with type=user
+;	   The name is the text between square brackets [name]
+;	2. Asterisk checks the From: addres and matches the list of devices
+;	   with a type=peer
+;	3. Asterisk checks the IP address (and port number) that the INVITE
+;	   was sent from and matches against any devices with type=peer
+;
+; Don't mix extensions with the names of the devices. Devices need a unique
+; name. The device name is *not* used as phone numbers. Phone numbers are
+; anything you declare as an extension in the dialplan (extensions.conf).
+;
+; When setting up trunks, make sure there's no risk that any From: username
+; (caller ID) will match any of your device names, because then Asterisk
+; might match the wrong device.
+;
+; Note: The parameter "username" is not the username and in most cases is
+;       not needed at all. Check below. In later releases, it's renamed
+;       to "defaultuser" which is a better name, since it is used in
+;       combination with the "defaultip" setting.
+;-----------------------------------------------------------------------------
+
+; ** Old configuration options **
+; The "call-limit" configuation option is considered old is replaced
+; by new functionality. To enable callcounters, you use the new
+; "callcounter" setting (for extension states in queue and subscriptions)
+; You are encouraged to use the dialplan groupcount functionality
+; to enforce call limits instead of using this channel-specific method.
+; You can still set limits per device in sip.conf or in a database by using
+; "setvar" to set variables that can be used in the dialplan for various limits.
+
+[general]
+context=default                 ; Default context for incoming calls
+;allowguest=no                  ; Allow or reject guest calls (default is yes)
+				; If your Asterisk is connected to the Internet
+				; and you have allowguest=yes
+				; you want to check which services you offer everyone
+				; out there, by enabling them in the default context (see below).
+;match_auth_username=yes        ; if available, match user entry using the
+                                ; 'username' field from the authentication line
+                                ; instead of the From: field.
+allowoverlap=no                 ; Disable overlap dialing support. (Default is yes)
+;allowtransfer=no               ; Disable all transfers (unless enabled in peers or users)
+                                ; Default is enabled. The Dial() options 't' and 'T' are not
+                                ; related as to whether SIP transfers are allowed or not.
+;realm=mydomain.tld             ; Realm for digest authentication
+                                ; defaults to "asterisk". If you set a system name in
+                                ; asterisk.conf, it defaults to that system name
+                                ; Realms MUST be globally unique according to RFC 3261
+                                ; Set this to your host name or domain name
+;domainsasrealm=no              ; Use domans list as realms
+                                ; You can serve multiple Realms specifying several
+                                ; 'domain=...' directives (see below).
+                                ; In this case Realm will be based on request 'From'/'To' header
+                                ; and should match one of domain names.
+                                ; Otherwise default 'realm=...' will be used.
+
+; With the current situation, you can do one of four things:
+;  a) Listen on a specific IPv4 address.      Example: bindaddr=192.0.2.1
+;  b) Listen on a specific IPv6 address.      Example: bindaddr=2001:db8::1
+;  c) Listen on the IPv4 wildcard.            Example: bindaddr=0.0.0.0
+;  d) Listen on the IPv4 and IPv6 wildcards.  Example: bindaddr=::
+; (You can choose independently for UDP, TCP, and TLS, by specifying different values for
+; "udpbindaddr", "tcpbindaddr", and "tlsbindaddr".)
+; (Note that using bindaddr=:: will show only a single IPv6 socket in netstat.
+;  IPv4 is supported at the same time using IPv4-mapped IPv6 addresses.)
+;
+; You may optionally add a port number. (The default is port 5060 for UDP and TCP, 5061
+; for TLS).
+;   IPv4 example: bindaddr=0.0.0.0:5062
+;   IPv6 example: bindaddr=[::]:5062
+;
+; The address family of the bound UDP address is used to determine how Asterisk performs
+; DNS lookups. In cases a) and c) above, only A records are considered. In case b), only
+; AAAA records are considered. In case d), both A and AAAA records are considered. Note,
+; however, that Asterisk ignores all records except the first one. In case d), when both A
+; and AAAA records are available, either an A or AAAA record will be first, and which one
+; depends on the operating system. On systems using glibc, AAAA records are given
+; priority.
+
+udpbindaddr=0.0.0.0:5062             ; IP address to bind UDP listen socket to (0.0.0.0 binds to all)
+                                     ; Optionally add a port number, 192.168.1.1:5062 (default is port 5060)
+
+; When a dialog is started with another SIP endpoint, the other endpoint
+; should include an Allow header telling us what SIP methods the endpoint
+; implements. However, some endpoints either do not include an Allow header
+; or lie about what methods they implement. In the former case, Asterisk
+; makes the assumption that the endpoint supports all known SIP methods.
+; If you know that your SIP endpoint does not provide support for a specific
+; method, then you may provide a comma-separated list of methods that your
+; endpoint does not implement in the disallowed_methods option. Note that
+; if your endpoint is truthful with its Allow header, then there is no need
+; to set this option. This option may be set in the general section or may
+; be set per endpoint. If this option is set both in the general section and
+; in a peer section, then the peer setting completely overrides the general
+; setting (i.e. the result is *not* the union of the two options).
+;
+; Note also that while Asterisk currently will parse an Allow header to learn
+; what methods an endpoint supports, the only actual use for this currently
+; is for determining if Asterisk may send connected line UPDATE requests. Its
+; use may be expanded in the future.
+;
+; disallowed_methods = UPDATE
+
+;
+; Note that the TCP and TLS support for chan_sip is currently considered
+; experimental.  Since it is new, all of the related configuration options are
+; subject to change in any release.  If they are changed, the changes will
+; be reflected in this sample configuration file, as well as in the UPGRADE.txt file.
+;
+tcpenable=no                    ; Enable server for incoming TCP connections (default is no)
+tcpbindaddr=0.0.0.0             ; IP address for TCP server to bind to (0.0.0.0 binds to all interfaces)
+                                ; Optionally add a port number, 192.168.1.1:5062 (default is port 5060)
+
+tlsenable=yes                   ; Enable server for incoming TLS (secure) connections (default is no)
+tlsbindaddr=0.0.0.0:5061        ; IP address for TLS server to bind to (0.0.0.0) binds to all interfaces)
+                                ; Optionally add a port number, 192.168.1.1:5063 (default is port 5061)
+                                ; Remember that the IP address must match the common name (hostname) in the
+                                ; certificate, so you don't want to bind a TLS socket to multiple IP addresses.
+                                ; For details how to construct a certificate for SIP see
+                                ; http://tools.ietf.org/html/draft-ietf-sip-domain-certs
+
+;tcpauthtimeout = 30            ; tcpauthtimeout specifies the maximum number
+				; of seconds a client has to authenticate.  If
+				; the client does not authenticate beofre this
+				; timeout expires, the client will be
+                                ; disconnected. (default: 30 seconds)
+
+;tcpauthlimit = 100             ; tcpauthlimit specifies the maximum number of
+				; unauthenticated sessions that will be allowed
+                                ; to connect at any given time. (default: 100)
+
+;srvlookup=yes                   ; Enable DNS SRV lookups on outbound calls
+                                ; Note: Asterisk only uses the first host
+                                ; in SRV records
+                                ; Disabling DNS SRV lookups disables the
+                                ; ability to place SIP calls based on domain
+                                ; names to some other SIP users on the Internet
+                                ; Specifying a port in a SIP peer definition or
+                                ; when dialing outbound calls will supress SRV
+                                ; lookups for that peer or call.
+
+;pedantic=yes                   ; Enable checking of tags in headers,
+                                ; international character conversions in URIs
+                                ; and multiline formatted headers for strict
+                                ; SIP compatibility (defaults to "yes")
+
+; See https://wiki.asterisk.org/wiki/display/AST/IP+Quality+of+Service for a description of these parameters.
+;tos_sip=cs3                    ; Sets TOS for SIP packets.
+;tos_audio=ef                   ; Sets TOS for RTP audio packets.
+;tos_video=af41                 ; Sets TOS for RTP video packets.
+;tos_text=af41                  ; Sets TOS for RTP text packets.
+
+;cos_sip=3                      ; Sets 802.1p priority for SIP packets.
+;cos_audio=5                    ; Sets 802.1p priority for RTP audio packets.
+;cos_video=4                    ; Sets 802.1p priority for RTP video packets.
+;cos_text=3                     ; Sets 802.1p priority for RTP text packets.
+
+;maxexpiry=3600                 ; Maximum allowed time of incoming registrations
+                                ; and subscriptions (seconds)
+;minexpiry=60                   ; Minimum length of registrations/subscriptions (default 60)
+;defaultexpiry=120              ; Default length of incoming/outgoing registration
+;mwiexpiry=3600                 ; Expiry time for outgoing MWI subscriptions
+;maxforwards=70			; Setting for the SIP Max-Forwards: header (loop prevention)
+				; Default value is 70
+;qualifyfreq=60                 ; Qualification: How often to check for the host to be up in seconds
+				; and reported in milliseconds with sip show settings.
+                                ; Set to low value if you use low timeout for NAT of UDP sessions
+				; Default: 60
+;qualifygap=100			; Number of milliseconds between each group of peers being qualified
+				; Default: 100
+;qualifypeers=1			; Number of peers in a group to be qualified at the same time
+				; Default: 1
+;notifymimetype=text/plain      ; Allow overriding of mime type in MWI NOTIFY
+;buggymwi=no                    ; Cisco SIP firmware doesn't support the MWI RFC
+                                ; fully. Enable this option to not get error messages
+                                ; when sending MWI to phones with this bug.
+;mwi_from=asterisk              ; When sending MWI NOTIFY requests, use this setting in
+                                ; the From: header as the "name" portion. Also fill the
+			        ; "user" portion of the URI in the From: header with this
+			        ; value if no fromuser is set
+			        ; Default: empty
+;vmexten=voicemail              ; dialplan extension to reach mailbox sets the
+                                ; Message-Account in the MWI notify message
+                                ; defaults to "asterisk"
+
+; Codec negotiation
+;
+; When Asterisk is receiving a call, the codec will initially be set to the
+; first codec in the allowed codecs defined for the user receiving the call
+; that the caller also indicates that it supports. But, after the caller
+; starts sending RTP, Asterisk will switch to using whatever codec the caller
+; is sending.
+;
+; When Asterisk is placing a call, the codec used will be the first codec in
+; the allowed codecs that the callee indicates that it supports. Asterisk will
+; *not* switch to whatever codec the callee is sending.
+;
+;preferred_codec_only=yes       ; Respond to a SIP invite with the single most preferred codec
+                                ; rather than advertising all joint codec capabilities. This
+                                ; limits the other side's codec choice to exactly what we prefer.
+
+;disallow=all                   ; First disallow all codecs
+;allow=ulaw                     ; Allow codecs in order of preference
+;allow=ilbc                     ; see https://wiki.asterisk.org/wiki/display/AST/RTP+Packetization
+				; for framing options
+;
+; This option specifies a preference for which music on hold class this channel
+; should listen to when put on hold if the music class has not been set on the
+; channel with Set(CHANNEL(musicclass)=whatever) in the dialplan, and the peer
+; channel putting this one on hold did not suggest a music class.
+;
+; This option may be specified globally, or on a per-user or per-peer basis.
+;
+;mohinterpret=default
+;
+; This option specifies which music on hold class to suggest to the peer channel
+; when this channel places the peer on hold. It may be specified globally or on
+; a per-user or per-peer basis.
+;
+;mohsuggest=default
+;
+;parkinglot=plaza               ; Sets the default parking lot for call parking
+                                ; This may also be set for individual users/peers
+                                ; Parkinglots are configured in features.conf
+;language=en                    ; Default language setting for all users/peers
+                                ; This may also be set for individual users/peers
+;relaxdtmf=yes                  ; Relax dtmf handling
+;trustrpid = no                 ; If Remote-Party-ID should be trusted
+;sendrpid = yes                 ; If Remote-Party-ID should be sent (defaults to no)
+;sendrpid = rpid                ; Use the "Remote-Party-ID" header
+                                ; to send the identity of the remote party
+                                ; This is identical to sendrpid=yes
+;sendrpid = pai                 ; Use the "P-Asserted-Identity" header
+                                ; to send the identity of the remote party
+;rpid_update = no               ; In certain cases, the only method by which a connected line
+                                ; change may be immediately transmitted is with a SIP UPDATE request.
+                                ; If communicating with another Asterisk server, and you wish to be able
+                                ; transmit such UPDATE messages to it, then you must enable this option.
+                                ; Otherwise, we will have to wait until we can send a reinvite to
+                                ; transmit the information.
+;prematuremedia=no              ; Some ISDN links send empty media frames before
+                                ; the call is in ringing or progress state. The SIP
+                                ; channel will then send 183 indicating early media
+                                ; which will be empty - thus users get no ring signal.
+                                ; Setting this to "yes" will stop any media before we have
+                                ; call progress (meaning the SIP channel will not send 183 Session
+                                ; Progress for early media). Default is "yes". Also make sure that
+                                ; the SIP peer is configured with progressinband=never.
+                                ;
+                                ; In order for "noanswer" applications to work, you need to run
+                                ; the progress() application in the priority before the app.
+
+;progressinband=never           ; If we should generate in-band ringing always
+                                ; use 'never' to never use in-band signalling, even in cases
+                                ; where some buggy devices might not render it
+                                ; Valid values: yes, no, never Default: never
+;useragent=Asterisk PBX         ; Allows you to change the user agent string
+                                ; The default user agent string also contains the Asterisk
+                                ; version. If you don't want to expose this, change the
+                                ; useragent string.
+;promiscredir = no              ; If yes, allows 302 or REDIR to non-local SIP address
+                                ; Note that promiscredir when redirects are made to the
+                                ; local system will cause loops since Asterisk is incapable
+                                ; of performing a "hairpin" call.
+;usereqphone = no               ; If yes, ";user=phone" is added to uri that contains
+                                ; a valid phone number
+;dtmfmode = rfc2833             ; Set default dtmfmode for sending DTMF. Default: rfc2833
+                                ; Other options:
+                                ; info : SIP INFO messages (application/dtmf-relay)
+                                ; shortinfo : SIP INFO messages (application/dtmf)
+                                ; inband : Inband audio (requires 64 kbit codec -alaw, ulaw)
+                                ; auto : Use rfc2833 if offered, inband otherwise
+
+;compactheaders = yes           ; send compact sip headers.
+;
+;videosupport=yes               ; Turn on support for SIP video. You need to turn this
+                                ; on in this section to get any video support at all.
+                                ; You can turn it off on a per peer basis if the general
+                                ; video support is enabled, but you can't enable it for
+                                ; one peer only without enabling in the general section.
+                                ; If you set videosupport to "always", then RTP ports will
+                                ; always be set up for video, even on clients that don't
+                                ; support it.  This assists callfile-derived calls and
+                                ; certain transferred calls to use always use video when
+                                ; available. [yes|NO|always]
+
+;maxcallbitrate=384             ; Maximum bitrate for video calls (default 384 kb/s)
+                                ; Videosupport and maxcallbitrate is settable
+                                ; for peers and users as well
+;callevents=no                  ; generate manager events when sip ua
+                                ; performs events (e.g. hold)
+;authfailureevents=no           ; generate manager "peerstatus" events when peer can't
+                                ; authenticate with Asterisk. Peerstatus will be "rejected".
+;alwaysauthreject = yes         ; When an incoming INVITE or REGISTER is to be rejected,
+                                ; for any reason, always reject with an identical response
+                                ; equivalent to valid username and invalid password/hash
+                                ; instead of letting the requester know whether there was
+                                ; a matching user or peer for their request.  This reduces
+                                ; the ability of an attacker to scan for valid SIP usernames.
+                                ; This option is set to "yes" by default.
+
+;auth_options_requests = yes    ; Enabling this option will authenticate OPTIONS requests just like
+                                ; INVITE requests are.  By default this option is disabled.
+
+;g726nonstandard = yes          ; If the peer negotiates G726-32 audio, use AAL2 packing
+                                ; order instead of RFC3551 packing order (this is required
+                                ; for Sipura and Grandstream ATAs, among others). This is
+                                ; contrary to the RFC3551 specification, the peer _should_
+                                ; be negotiating AAL2-G726-32 instead :-(
+;outboundproxy=proxy.provider.domain            ; send outbound signaling to this proxy, not directly to the devices
+;outboundproxy=proxy.provider.domain:8080       ; send outbound signaling to this proxy, not directly to the devices
+;outboundproxy=proxy.provider.domain,force      ; Send ALL outbound signalling to proxy, ignoring route: headers
+;outboundproxy=tls://proxy.provider.domain      ; same as '=proxy.provider.domain' except we try to connect with tls
+;outboundproxy=192.0.2.1                        ; IPv4 address literal (default port is 5060)
+;outboundproxy=2001:db8::1                      ; IPv6 address literal (default port is 5060)
+;outboundproxy=192.168.0.2.1:5062               ; IPv4 address literal with explicit port
+;outboundproxy=[2001:db8::1]:5062               ; IPv6 address literal with explicit port
+;                                               ; (could also be tcp,udp) - defining transports on the proxy line only
+;                                               ; applies for the global proxy, otherwise use the transport= option
+;matchexternaddrlocally = yes     ; Only substitute the externaddr or externhost setting if it matches
+                                ; your localnet setting. Unless you have some sort of strange network
+                                ; setup you will not need to enable this.
+
+;dynamic_exclude_static = yes   ; Disallow all dynamic hosts from registering
+                                ; as any IP address used for staticly defined
+                                ; hosts.  This helps avoid the configuration
+                                ; error of allowing your users to register at
+                                ; the same address as a SIP provider.
+
+;contactdeny=0.0.0.0/0.0.0.0           ; Use contactpermit and contactdeny to
+;contactpermit=172.16.0.0/255.255.0.0  ; restrict at what IPs your users may
+                                       ; register their phones.
+
+;engine=asterisk                ; RTP engine to use when communicating with the device
+
+;
+; If regcontext is specified, Asterisk will dynamically create and destroy a
+; NoOp priority 1 extension for a given peer who registers or unregisters with
+; us and have a "regexten=" configuration item.
+; Multiple contexts may be specified by separating them with '&'. The
+; actual extension is the 'regexten' parameter of the registering peer or its
+; name if 'regexten' is not provided.  If more than one context is provided,
+; the context must be specified within regexten by appending the desired
+; context after '@'.  More than one regexten may be supplied if they are
+; separated by '&'.  Patterns may be used in regexten.
+;
+;regcontext=sipregistrations
+;regextenonqualify=yes          ; Default "no"
+                                ; If you have qualify on and the peer becomes unreachable
+                                ; this setting will enforce inactivation of the regexten
+                                ; extension for the peer
+
+; The shrinkcallerid function removes '(', ' ', ')', non-trailing '.', and '-' not
+; in square brackets.  For example, the caller id value 555.5555 becomes 5555555
+; when this option is enabled.  Disabling this option results in no modification
+; of the caller id value, which is necessary when the caller id represents something
+; that must be preserved.  This option can only be used in the [general] section.
+; By default this option is on.
+;
+;shrinkcallerid=yes     ; on by default
+
+
+;use_q850_reason = no ; Default "no"
+                      ; Set to yes add Reason header and use Reason header if it is available.
+;
+;------------------------ TLS settings ------------------------------------------------------------
+tlscertfile=/etc/asterisk/keys/asterisk.pem ; Certificate file (*.pem format only) to use for TLS connections
+                                       ; default is to look for "asterisk.pem" in current directory
+
+; tlsprivatekey=/etc/asterisk/keys/asterisk.key ; Private key file (*.pem format only) for TLS connections.
+                                     ; If no tlsprivatekey is specified, tlscertfile is searched for
+                                     ; for both public and private key.
+
+; tlscafile=/etc/asterisk/keys/ca.crt
+;        If the server your connecting to uses a self signed certificate
+;        you should have their certificate installed here so the code can
+;        verify the authenticity of their certificate.
+
+; tlscapath=/etc/asterisk/keys/
+;        A directory full of CA certificates.  The files must be named with
+;        the CA subject name hash value.
+;        (see man SSL_CTX_load_verify_locations for more info)
+
+; tlsdontverifyserver=[yes|no]
+;        If set to yes, don't verify the servers certificate when acting as
+;        a client.  If you don't have the server's CA certificate you can
+;        set this and it will connect without requiring tlscafile to be set.
+;        Default is no.
+
+; tlscipher=ALL
+;        A string specifying which SSL ciphers to use or not use
+;        A list of valid SSL cipher strings can be found at:
+;                http://www.openssl.org/docs/apps/ciphers.html#CIPHER_STRINGS
+;
+; tlsclientmethod=tlsv1     ; values include tlsv1, sslv3, sslv2.
+                            ; Specify protocol for outbound client connections.
+                            ; If left unspecified, the default is sslv2.
+;
+;--------------------------- SIP timers ----------------------------------------------------
+; These timers are used primarily in INVITE transactions.
+; The default for Timer T1 is 500 ms or the measured run-trip time between
+; Asterisk and the device if you have qualify=yes for the device.
+;
+;t1min=100                      ; Minimum roundtrip time for messages to monitored hosts
+                                ; Defaults to 100 ms
+;timert1=500                    ; Default T1 timer
+                                ; Defaults to 500 ms or the measured round-trip
+                                ; time to a peer (qualify=yes).
+;timerb=32000                   ; Call setup timer. If a provisional response is not received
+                                ; in this amount of time, the call will autocongest
+                                ; Defaults to 64*timert1
+
+;--------------------------- RTP timers ----------------------------------------------------
+; These timers are currently used for both audio and video streams. The RTP timeouts
+; are only applied to the audio channel.
+; The settings are settable in the global section as well as per device
+;
+;rtptimeout=60                  ; Terminate call if 60 seconds of no RTP or RTCP activity
+                                ; on the audio channel
+                                ; when we're not on hold. This is to be able to hangup
+                                ; a call in the case of a phone disappearing from the net,
+                                ; like a powerloss or grandma tripping over a cable.
+;rtpholdtimeout=300             ; Terminate call if 300 seconds of no RTP or RTCP activity
+                                ; on the audio channel
+                                ; when we're on hold (must be > rtptimeout)
+;rtpkeepalive=<secs>            ; Send keepalives in the RTP stream to keep NAT open
+                                ; (default is off - zero)
+
+;--------------------------- SIP Session-Timers (RFC 4028)------------------------------------
+; SIP Session-Timers provide an end-to-end keep-alive mechanism for active SIP sessions.
+; This mechanism can detect and reclaim SIP channels that do not terminate through normal
+; signaling procedures. Session-Timers can be configured globally or at a user/peer level.
+; The operation of Session-Timers is driven by the following configuration parameters:
+;
+; * session-timers    - Session-Timers feature operates in the following three modes:
+;                            originate : Request and run session-timers always
+;                            accept    : Run session-timers only when requested by other UA
+;                            refuse    : Do not run session timers in any case
+;                       The default mode of operation is 'accept'.
+; * session-expires   - Maximum session refresh interval in seconds. Defaults to 1800 secs.
+; * session-minse     - Minimum session refresh interval in seconds. Defualts to 90 secs.
+; * session-refresher - The session refresher (uac|uas). Defaults to 'uas'.
+;
+;session-timers=originate
+;session-expires=600
+;session-minse=90
+;session-refresher=uas
+;
+;--------------------------- SIP DEBUGGING ---------------------------------------------------
+;sipdebug = yes                 ; Turn on SIP debugging by default, from
+                                ; the moment the channel loads this configuration
+;recordhistory=yes              ; Record SIP history by default
+                                ; (see sip history / sip no history)
+;dumphistory=yes                ; Dump SIP history at end of SIP dialogue
+                                ; SIP history is output to the DEBUG logging channel
+
+
+;--------------------------- STATUS NOTIFICATIONS (SUBSCRIPTIONS) ----------------------------
+; You can subscribe to the status of extensions with a "hint" priority
+; (See extensions.conf.sample for examples)
+; chan_sip support two major formats for notifications: dialog-info and SIMPLE
+;
+; You will get more detailed reports (busy etc) if you have a call counter enabled
+; for a device.
+;
+; If you set the busylevel, we will indicate busy when we have a number of calls that
+; matches the busylevel treshold.
+;
+; For queues, you will need this level of detail in status reporting, regardless
+; if you use SIP subscriptions. Queues and manager use the same internal interface
+; for reading status information.
+;
+; Note: Subscriptions does not work if you have a realtime dialplan and use the
+; realtime switch.
+;
+;allowsubscribe=no              ; Disable support for subscriptions. (Default is yes)
+;subscribecontext = default     ; Set a specific context for SUBSCRIBE requests
+                                ; Useful to limit subscriptions to local extensions
+                                ; Settable per peer/user also
+;notifyringing = no             ; Control whether subscriptions already INUSE get sent
+                                ; RINGING when another call is sent (default: yes)
+;notifyhold = yes               ; Notify subscriptions on HOLD state (default: no)
+                                ; Turning on notifyringing and notifyhold will add a lot
+                                ; more database transactions if you are using realtime.
+;notifycid = yes                ; Control whether caller ID information is sent along with
+                                ; dialog-info+xml notifications (supported by snom phones).
+                                ; Note that this feature will only work properly when the
+                                ; incoming call is using the same extension and context that
+                                ; is being used as the hint for the called extension.  This means
+                                ; that it won't work when using subscribecontext for your sip
+                                ; user or peer (if subscribecontext is different than context).
+                                ; This is also limited to a single caller, meaning that if an
+                                ; extension is ringing because multiple calls are incoming,
+                                ; only one will be used as the source of caller ID.  Specify
+                                ; 'ignore-context' to ignore the called context when looking
+                                ; for the caller's channel.  The default value is 'no.' Setting
+                                ; notifycid to 'ignore-context' also causes call-pickups attempted
+                                ; via SNOM's NOTIFY mechanism to set the context for the call pickup
+                                ; to PICKUPMARK.
+;callcounter = yes              ; Enable call counters on devices. This can be set per
+                                ; device too.
+
+;----------------------------------------- T.38 FAX SUPPORT ----------------------------------
+;
+; This setting is available in the [general] section as well as in device configurations.
+; Setting this to yes enables T.38 FAX (UDPTL) on SIP calls; it defaults to off.
+;
+; t38pt_udptl = yes            ; Enables T.38 with FEC error correction.
+; t38pt_udptl = yes,fec        ; Enables T.38 with FEC error correction.
+; t38pt_udptl = yes,redundancy ; Enables T.38 with redundancy error correction.
+; t38pt_udptl = yes,none       ; Enables T.38 with no error correction.
+;
+; In some cases, T.38 endpoints will provide a T38FaxMaxDatagram value (during T.38 setup) that
+; is based on an incorrect interpretation of the T.38 recommendation, and results in failures
+; because Asterisk does not believe it can send T.38 packets of a reasonable size to that
+; endpoint (Cisco media gateways are one example of this situation). In these cases, during a
+; T.38 call you will see warning messages on the console/in the logs from the Asterisk UDPTL
+; stack complaining about lack of buffer space to send T.38 FAX packets. If this occurs, you
+; can set an override (globally, or on a per-device basis) to make Asterisk ignore the
+; T38FaxMaxDatagram value specified by the other endpoint, and use a configured value instead.
+; This can be done by appending 'maxdatagram=<value>' to the t38pt_udptl configuration option,
+; like this:
+;
+; t38pt_udptl = yes,fec,maxdatagram=400 ; Enables T.38 with FEC error correction and overrides
+;                                       ; the other endpoint's provided value to assume we can
+;                                       ; send 400 byte T.38 FAX packets to it.
+;
+; FAX detection will cause the SIP channel to jump to the 'fax' extension (if it exists)
+; based one or more events being detected. The events that can be detected are an incoming
+; CNG tone or an incoming T.38 re-INVITE request.
+;
+; faxdetect = yes		; Default 'no', 'yes' enables both CNG and T.38 detection
+; faxdetect = cng		; Enables only CNG detection
+; faxdetect = t38		; Enables only T.38 detection
+;
+;----------------------------------------- OUTBOUND SIP REGISTRATIONS  ------------------------
+; Asterisk can register as a SIP user agent to a SIP proxy (provider)
+; Format for the register statement is:
+;       register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
+;
+;
+;
+; domain is either
+;	- domain in DNS
+; 	- host name in DNS
+;	- the name of a peer defined below or in realtime
+; The domain is where you register your username, so your SIP uri you are registering to
+; is username@domain
+;
+; If no extension is given, the 's' extension is used. The extension needs to
+; be defined in extensions.conf to be able to accept calls from this SIP proxy
+; (provider).
+;
+; A similar effect can be achieved by adding a "callbackextension" option in a peer section.
+; this is equivalent to having the following line in the general section:
+;
+;        register => username:secret@host/callbackextension
+;
+; and more readable because you don't have to write the parameters in two places
+; (note that the "port" is ignored - this is a bug that should be fixed).
+;
+; Note that a register= line doesn't mean that we will match the incoming call in any
+; other way than described above. If you want to control where the call enters your
+; dialplan, which context, you want to define a peer with the hostname of the provider's
+; server. If the provider has multiple servers to place calls to your system, you need
+; a peer for each server.
+;
+; Beginning with Asterisk version 1.6.2, the "user" portion of the register line may
+; contain a port number. Since the logical separator between a host and port number is a
+; ':' character, and this character is already used to separate between the optional "secret"
+; and "authuser" portions of the line, there is a bit of a hoop to jump through if you wish
+; to use a port here. That is, you must explicitly provide a "secret" and "authuser" even if
+; they are blank. See the third example below for an illustration.
+;
+;
+; Examples:
+;
+;register => 1234:password@mysipprovider.com
+;
+;     This will pass incoming calls to the 's' extension
+;
+;
+;register => 2345:password@sip_proxy/1234
+;
+;    Register 2345 at sip provider 'sip_proxy'.  Calls from this provider
+;    connect to local extension 1234 in extensions.conf, default context,
+;    unless you configure a [sip_proxy] section below, and configure a
+;    context.
+;    Tip 1: Avoid assigning hostname to a sip.conf section like [provider.com]
+;    Tip 2: Use separate inbound and outbound sections for SIP providers
+;           (instead of type=friend) if you have calls in both directions
+;
+;register => 3456@mydomain:5082::@mysipprovider.com
+;
+;    Note that in this example, the optional authuser and secret portions have
+;    been left blank because we have specified a port in the user section
+;
+;register => tls://username:xxxxxx@sip-tls-proxy.example.org
+;
+;    The 'transport' part defaults to 'udp' but may also be 'tcp' or 'tls'.
+;    Using 'udp://' explicitly is also useful in case the username part
+;    contains a '/' ('user/name').
+
+;registertimeout=20             ; retry registration calls every 20 seconds (default)
+;registerattempts=10            ; Number of registration attempts before we give up
+                                ; 0 = continue forever, hammering the other server
+                                ; until it accepts the registration
+                                ; Default is 0 tries, continue forever
+
+;----------------------------------------- OUTBOUND MWI SUBSCRIPTIONS -------------------------
+; Asterisk can subscribe to receive the MWI from another SIP server and store it locally for retrieval
+; by other phones. At this time, you can only subscribe using UDP as the transport.
+; Format for the mwi register statement is:
+;       mwi => user[:secret[:authuser]]@host[:port]/mailbox
+;
+; Examples:
+;mwi => 1234:password@mysipprovider.com/1234
+;mwi => 1234:password@myportprovider.com:6969/1234
+;mwi => 1234:password:authuser@myauthprovider.com/1234
+;mwi => 1234:password:authuser@myauthportprovider.com:6969/1234
+;
+; MWI received will be stored in the 1234 mailbox of the SIP_Remote context. It can be used by other phones by following the below:
+; mailbox=1234@SIP_Remote
+;----------------------------------------- NAT SUPPORT ------------------------
+;
+; WARNING: SIP operation behind a NAT is tricky and you really need
+; to read and understand well the following section.
+;
+; When Asterisk is behind a NAT device, the "local" address (and port) that
+; a socket is bound to has different values when seen from the inside or
+; from the outside of the NATted network. Unfortunately this address must
+; be communicated to the outside (e.g. in SIP and SDP messages), and in
+; order to determine the correct value Asterisk needs to know:
+;
+; + whether it is talking to someone "inside" or "outside" of the NATted network.
+;   This is configured by assigning the "localnet" parameter with a list
+;   of network addresses that are considered "inside" of the NATted network.
+;   IF LOCALNET IS NOT SET, THE EXTERNAL ADDRESS WILL NOT BE SET CORRECTLY.
+;   Multiple entries are allowed, e.g. a reasonable set is the following:
+;
+;      localnet=192.168.0.0/255.255.0.0 ; RFC 1918 addresses
+;      localnet=10.0.0.0/255.0.0.0      ; Also RFC1918
+;      localnet=172.16.0.0/12           ; Another RFC1918 with CIDR notation
+;      localnet=169.254.0.0/255.255.0.0 ; Zero conf local network
+;
+; + the "externally visible" address and port number to be used when talking
+;   to a host outside the NAT. This information is derived by one of the
+;   following (mutually exclusive) config file parameters:
+;
+;   a. "externaddr = hostname[:port]" specifies a static address[:port] to
+;      be used in SIP and SDP messages.
+;      The hostname is looked up only once, when [re]loading sip.conf .
+;      If a port number is not present, use the port specified in the "udpbindaddr"
+;      (which is not guaranteed to work correctly, because a NAT box might remap the
+;      port number as well as the address).
+;      This approach can be useful if you have a NAT device where you can
+;      configure the mapping statically. Examples:
+;
+;        externaddr = 12.34.56.78          ; use this address.
+;        externaddr = 12.34.56.78:9900     ; use this address and port.
+;        externaddr = mynat.my.org:12600   ; Public address of my nat box.
+;        externtcpport = 9900   ; The externally mapped tcp port, when Asterisk is behind a static NAT or PAT.
+;                               ; externtcpport will default to the externaddr or externhost port if either one is set.
+;        externtlsport = 12600  ; The externally mapped tls port, when Asterisk is behind a static NAT or PAT.
+;                               ; externtlsport port will default to the RFC designated port of 5061.
+;
+;   b. "externhost = hostname[:port]" is similar to "externaddr" except
+;      that the hostname is looked up every "externrefresh" seconds
+;      (default 10s). This can be useful when your NAT device lets you choose
+;      the port mapping, but the IP address is dynamic.
+;      Beware, you might suffer from service disruption when the name server
+;      resolution fails. Examples:
+;
+;        externhost=foo.dyndns.net       ; refreshed periodically
+;        externrefresh=180               ; change the refresh interval
+;
+;   Note that at the moment all these mechanism work only for the SIP socket.
+;   The IP address discovered with externaddr/externhost is reused for
+;   media sessions as well, but the port numbers are not remapped so you
+;   may still experience problems.
+;
+; NOTE 1: in some cases, NAT boxes will use different port numbers in
+; the internal<->external mapping. In these cases, the "externaddr" and
+; "externhost" might not help you configure addresses properly.
+;
+; NOTE 2: when using "externaddr" or "externhost", the address part is
+; also used as the external address for media sessions. Thus, the port
+; information in the SDP may be wrong!
+;
+; In addition to the above, Asterisk has an additional "nat" parameter to
+; address NAT-related issues in incoming SIP or media sessions.
+; In particular, depending on the 'nat= ' settings described below, Asterisk
+; may override the address/port information specified in the SIP/SDP messages,
+; and use the information (sender address) supplied by the network stack instead.
+; However, this is only useful if the external traffic can reach us.
+; The following settings are allowed (both globally and in individual sections):
+;
+;        nat = no                ; Default. Use rport if the remote side says to use it.
+;        nat = force_rport       ; Force rport to always be on.
+;        nat = yes               ; Force rport to always be on and perform comedia RTP handling.
+;        nat = comedia           ; Use rport if the remote side says to use it and perform comedia RTP handling.
+;
+; 'comedia RTP handling' refers to the technique of sending RTP to the port that the
+; the other endpoint's RTP arrived from, and means 'connection-oriented media'. This is
+; only partially related to RFC 4145 which was referred to as COMEDIA while it was in
+; draft form. This method is used to accomodate endpoints that may be located behind
+; NAT devices, and as such the port number they tell Asterisk to send RTP packets to
+; for their media streams is not actual port number that will be used on the nearer
+; side of the NAT.
+;
+; In addition to these settings, Asterisk *always* uses 'symmetric RTP' mode as defined by
+; RFC 4961; Asterisk will always send RTP packets from the same port number it expects
+; to receive them on.
+;
+; The IP address used for media (audio, video, and text) in the SDP can also be overridden by using
+; the media_address configuration option. This is only applicable to the general section and
+; can not be set per-user or per-peer.
+;
+; media_address = 172.16.42.1
+;
+; Through the use of the res_stun_monitor module, Asterisk has the ability to detect when the
+; perceived external network address has changed.  When the stun_monitor is installed and
+; configured, chan_sip will renew all outbound registrations when the monitor detects any sort
+; of network change has occurred. By default this option is enabled, but only takes effect once
+; res_stun_monitor is configured.  If res_stun_monitor is enabled and you wish to not
+; generate all outbound registrations on a network change, use the option below to disable
+; this feature.
+;
+; subscribe_network_change_event = yes ; on by default
+
+;----------------------------------- MEDIA HANDLING --------------------------------
+; By default, Asterisk tries to re-invite media streams to an optimal path. If there's
+; no reason for Asterisk to stay in the media path, the media will be redirected.
+; This does not really work well in the case where Asterisk is outside and the
+; clients are on the inside of a NAT. In that case, you want to set directmedia=nonat.
+;
+;directmedia=yes                ; Asterisk by default tries to redirect the
+                                ; RTP media stream to go directly from
+                                ; the caller to the callee.  Some devices do not
+                                ; support this (especially if one of them is behind a NAT).
+                                ; The default setting is YES. If you have all clients
+                                ; behind a NAT, or for some other reason want Asterisk to
+                                ; stay in the audio path, you may want to turn this off.
+
+                                ; This setting also affect direct RTP
+                                ; at call setup (a new feature in 1.4 - setting up the
+                                ; call directly between the endpoints instead of sending
+                                ; a re-INVITE).
+
+                                ; Additionally this option does not disable all reINVITE operations.
+                                ; It only controls Asterisk generating reINVITEs for the specific
+                                ; purpose of setting up a direct media path. If a reINVITE is
+                                ; needed to switch a media stream to inactive (when placed on
+                                ; hold) or to T.38, it will still be done, regardless of this
+                                ; setting. Note that direct T.38 is not supported.
+
+;directmedia=nonat              ; An additional option is to allow media path redirection
+                                ; (reinvite) but only when the peer where the media is being
+                                ; sent is known to not be behind a NAT (as the RTP core can
+                                ; determine it based on the apparent IP address the media
+                                ; arrives from).
+
+;directmedia=update             ; Yet a third option... use UPDATE for media path redirection,
+                                ; instead of INVITE. This can be combined with 'nonat', as
+                                ; 'directmedia=update,nonat'. It implies 'yes'.
+
+;directrtpsetup=yes             ; Enable the new experimental direct RTP setup. This sets up
+                                ; the call directly with media peer-2-peer without re-invites.
+                                ; Will not work for video and cases where the callee sends
+                                ; RTP payloads and fmtp headers in the 200 OK that does not match the
+                                ; callers INVITE. This will also fail if directmedia is enabled when
+                                ; the device is actually behind NAT.
+
+;directmediadeny=0.0.0.0/0      ; Use directmediapermit and directmediadeny to restrict
+;directmediapermit=172.16.0.0/16; which peers should be able to pass directmedia to each other
+                                ; (There is no default setting, this is just an example)
+                                ; Use this if some of your phones are on IP addresses that
+                                ; can not reach each other directly. This way you can force
+                                ; RTP to always flow through asterisk in such cases.
+
+;ignoresdpversion=yes           ; By default, Asterisk will honor the session version
+                                ; number in SDP packets and will only modify the SDP
+                                ; session if the version number changes. This option will
+                                ; force asterisk to ignore the SDP session version number
+                                ; and treat all SDP data as new data.  This is required
+                                ; for devices that send us non standard SDP packets
+                                ; (observed with Microsoft OCS). By default this option is
+                                ; off.
+
+;sdpsession=Asterisk PBX        ; Allows you to change the SDP session name string, (s=)
+                                ; Like the useragent parameter, the default user agent string
+                                ; also contains the Asterisk version.
+;sdpowner=root                  ; Allows you to change the username field in the SDP owner string, (o=)
+                                ; This field MUST NOT contain spaces
+;encryption=no                  ; Whether to offer SRTP encrypted media (and only SRTP encrypted media)
+                                ; on outgoing calls to a peer. Calls will fail with HANGUPCAUSE=58 if
+                                ; the peer does not support SRTP. Defaults to no.
+
+;----------------------------------------- REALTIME SUPPORT ------------------------
+; For additional information on ARA, the Asterisk Realtime Architecture,
+; please read https://wiki.asterisk.org/wiki/display/AST/Realtime+Database+Configuration
+;
+;rtcachefriends=yes             ; Cache realtime friends by adding them to the internal list
+                                ; just like friends added from the config file only on a
+                                ; as-needed basis? (yes|no)
+
+;rtsavesysname=yes              ; Save systemname in realtime database at registration
+                                ; Default= no
+
+;rtupdate=yes                   ; Send registry updates to database using realtime? (yes|no)
+                                ; If set to yes, when a SIP UA registers successfully, the ip address,
+                                ; the origination port, the registration period, and the username of
+                                ; the UA will be set to database via realtime.
+                                ; If not present, defaults to 'yes'. Note: realtime peers will
+                                ; probably not function across reloads in the way that you expect, if
+                                ; you turn this option off.
+;rtautoclear=yes                ; Auto-Expire friends created on the fly on the same schedule
+                                ; as if it had just registered? (yes|no|<seconds>)
+                                ; If set to yes, when the registration expires, the friend will
+                                ; vanish from the configuration until requested again. If set
+                                ; to an integer, friends expire within this number of seconds
+                                ; instead of the registration interval.
+
+;ignoreregexpire=yes            ; Enabling this setting has two functions:
+                                ;
+                                ; For non-realtime peers, when their registration expires, the
+                                ; information will _not_ be removed from memory or the Asterisk database
+                                ; if you attempt to place a call to the peer, the existing information
+                                ; will be used in spite of it having expired
+                                ;
+                                ; For realtime peers, when the peer is retrieved from realtime storage,
+                                ; the registration information will be used regardless of whether
+                                ; it has expired or not; if it expires while the realtime peer
+                                ; is still in memory (due to caching or other reasons), the
+                                ; information will not be removed from realtime storage
+
+;----------------------------------------- SIP DOMAIN SUPPORT ------------------------
+; Incoming INVITE and REFER messages can be matched against a list of 'allowed'
+; domains, each of which can direct the call to a specific context if desired.
+; By default, all domains are accepted and sent to the default context or the
+; context associated with the user/peer placing the call.
+; REGISTER to non-local domains will be automatically denied if a domain
+; list is configured.
+;
+; Domains can be specified using:
+; domain=<domain>[,<context>]
+; Examples:
+; domain=myasterisk.dom
+; domain=customer.com,customer-context
+;
+; In addition, all the 'default' domains associated with a server should be
+; added if incoming request filtering is desired.
+; autodomain=yes
+;
+; To disallow requests for domains not serviced by this server:
+; allowexternaldomains=no
+
+;domain=mydomain.tld,mydomain-incoming
+                                ; Add domain and configure incoming context
+                                ; for external calls to this domain
+;domain=1.2.3.4                 ; Add IP address as local domain
+                                ; You can have several "domain" settings
+;allowexternaldomains=no        ; Disable INVITE and REFER to non-local domains
+                                ; Default is yes
+;autodomain=yes                 ; Turn this on to have Asterisk add local host
+                                ; name and local IP to domain list.
+
+; fromdomain=mydomain.tld       ; When making outbound SIP INVITEs to
+                                ; non-peers, use your primary domain "identity"
+                                ; for From: headers instead of just your IP
+                                ; address. This is to be polite and
+                                ; it may be a mandatory requirement for some
+                                ; destinations which do not have a prior
+                                ; account relationship with your server.
+
+;------------------------------ Advice of Charge CONFIGURATION --------------------------
+; snom_aoc_enabled = yes;     ; This options turns on and off support for sending AOC-D and
+                              ; AOC-E to snom endpoints.  This option can be used both in the
+                              ; peer and global scope.  The default for this option is off.
+
+
+;------------------------------ JITTER BUFFER CONFIGURATION --------------------------
+; jbenable = yes              ; Enables the use of a jitterbuffer on the receiving side of a
+                              ; SIP channel. Defaults to "no". An enabled jitterbuffer will
+                              ; be used only if the sending side can create and the receiving
+                              ; side can not accept jitter. The SIP channel can accept jitter,
+                              ; thus a jitterbuffer on the receive SIP side will be used only
+                              ; if it is forced and enabled.
+
+; jbforce = no                ; Forces the use of a jitterbuffer on the receive side of a SIP
+                              ; channel. Defaults to "no".
+
+; jbmaxsize = 200             ; Max length of the jitterbuffer in milliseconds.
+
+; jbresyncthreshold = 1000    ; Jump in the frame timestamps over which the jitterbuffer is
+                              ; resynchronized. Useful to improve the quality of the voice, with
+                              ; big jumps in/broken timestamps, usually sent from exotic devices
+                              ; and programs. Defaults to 1000.
+
+; jbimpl = fixed              ; Jitterbuffer implementation, used on the receiving side of a SIP
+                              ; channel. Two implementations are currently available - "fixed"
+                              ; (with size always equals to jbmaxsize) and "adaptive" (with
+                              ; variable size, actually the new jb of IAX2). Defaults to fixed.
+
+; jbtargetextra = 40          ; This option only affects the jb when 'jbimpl = adaptive' is set.
+                              ; The option represents the number of milliseconds by which the new jitter buffer
+                              ; will pad its size. the default is 40, so without modification, the new
+                              ; jitter buffer will set its size to the jitter value plus 40 milliseconds.
+                              ; increasing this value may help if your network normally has low jitter,
+                              ; but occasionally has spikes.
+
+; jblog = no                  ; Enables jitterbuffer frame logging. Defaults to "no".
+;-----------------------------------------------------------------------------------
+
+[authentication]
+; Global credentials for outbound calls, i.e. when a proxy challenges your
+; Asterisk server for authentication. These credentials override
+; any credentials in peer/register definition if realm is matched.
+;
+; This way, Asterisk can authenticate for outbound calls to other
+; realms. We match realm on the proxy challenge and pick an set of
+; credentials from this list
+; Syntax:
+;        auth = <user>:<secret>@<realm>
+;        auth = <user>#<md5secret>@<realm>
+; Example:
+;auth=mark:topsecret@digium.com
+;
+; You may also add auth= statements to [peer] definitions
+; Peer auth= override all other authentication settings if we match on realm
+
+;------------------------------------------------------------------------------
+; DEVICE CONFIGURATION
+;
+; The SIP channel has two types of devices, the friend and the peer.
+; * The type=friend is a device type that accepts both incoming and outbound calls,
+;   where Asterisk match on the From: username on incoming calls.
+;   (A synonym for friend is "user"). This is a type you use for your local
+;   SIP phones.
+; * The type=peer also handles both incoming and outbound calls. On inbound calls,
+;   Asterisk only matches on IP/port, not on names. This is mostly used for SIP
+;   trunks.
+;
+; For device names, we recommend using only a-z, numerics (0-9) and underscore
+;
+; For local phones, type=friend works most of the time
+;
+; If you have one-way audio, you probably have NAT problems.
+; If Asterisk is on a public IP, and the phone is inside of a NAT device
+; you will need to configure nat option for those phones.
+; Also, turn on qualify=yes to keep the nat session open
+;
+; Configuration options available
+; --------------------
+; context
+; callingpres
+; permit
+; deny
+; secret
+; md5secret
+; remotesecret
+; transport
+; dtmfmode
+; directmedia
+; nat
+; callgroup
+; pickupgroup
+; language
+; allow
+; disallow
+; insecure
+; trustrpid
+; progressinband
+; promiscredir
+; useclientcode
+; accountcode
+; setvar
+; callerid
+; amaflags
+; callcounter
+; busylevel
+; allowoverlap
+; allowsubscribe
+; allowtransfer
+; ignoresdpversion
+; subscribecontext
+; template
+; videosupport
+; maxcallbitrate
+; rfc2833compensate
+; mailbox
+; session-timers
+; session-expires
+; session-minse
+; session-refresher
+; t38pt_usertpsource
+; regexten
+; fromdomain
+; fromuser
+; host
+; port
+; qualify
+; defaultip
+; defaultuser
+; rtptimeout
+; rtpholdtimeout
+; sendrpid
+; outboundproxy
+; rfc2833compensate
+; callbackextension
+; registertrying
+; timert1
+; timerb
+; qualifyfreq
+; t38pt_usertpsource
+; contactpermit         ; Limit what a host may register as (a neat trick
+; contactdeny           ; is to register at the same IP as a SIP provider,
+;                       ; then call oneself, and get redirected to that
+;                       ; same location).
+; directmediapermit
+; directmediadeny
+; unsolicited_mailbox
+; use_q850_reason
+; maxforwards
+; encryption
+
+;[sip_proxy]
+; For incoming calls only. Example: FWD (Free World Dialup)
+; We match on IP address of the proxy for incoming calls
+; since we can not match on username (caller id)
+;type=peer
+;context=from-fwd
+;host=fwd.pulver.com
+
+;[sip_proxy-out]
+;type=peer                        ; we only want to call out, not be called
+;remotesecret=guessit             ; Our password to their service
+;defaultuser=yourusername         ; Authentication user for outbound proxies
+;fromuser=yourusername            ; Many SIP providers require this!
+;fromdomain=provider.sip.domain
+;host=box.provider.com
+;transport=udp,tcp                ; This sets the default transport type to udp for outgoing, and will
+;                                 ; accept both tcp and udp. The default transport type is only used for
+;                                 ; outbound messages until a Registration takes place.  During the
+;                                 ; peer Registration the transport type may change to another supported
+;                                 ; type if the peer requests so.
+
+;usereqphone=yes                  ; This provider requires ";user=phone" on URI
+;callcounter=yes                  ; Enable call counter
+;busylevel=2                      ; Signal busy at 2 or more calls
+;outboundproxy=proxy.provider.domain  ; send outbound signaling to this proxy, not directly to the peer
+;port=80                          ; The port number we want to connect to on the remote side
+                                  ; Also used as "defaultport" in combination with "defaultip" settings
+
+;--- sample definition for a provider
+;[provider1]
+;type=peer
+;host=sip.provider1.com
+;fromuser=4015552299              ; how your provider knows you
+;remotesecret=youwillneverguessit ; The password we use to authenticate to them
+;secret=gissadetdu                ; The password they use to contact us
+;callbackextension=123            ; Register with this server and require calls coming back to this extension
+;transport=udp,tcp                ; This sets the transport type to udp for outgoing, and will
+;                                 ;   accept both tcp and udp. Default is udp. The first transport
+;                                 ;   listed will always be used for outgoing connections.
+;unsolicited_mailbox=4015552299   ; If the remote SIP server sends an unsolicited MWI NOTIFY message the new/old
+;                                 ;   message count will be stored in the configured virtual mailbox. It can be used
+;                                 ;   by any device supporting MWI by specifying <configured value>@SIP_Remote as the
+;                                 ;   mailbox.
+
+;
+; Because you might have a large number of similar sections, it is generally
+; convenient to use templates for the common parameters, and add them
+; the the various sections. Examples are below, and we can even leave
+; the templates uncommented as they will not harm:
+
+[basic-options](!)                ; a template
+        dtmfmode=rfc2833
+        context=from-office
+        type=friend
+
+[natted-phone](!,basic-options)   ; another template inheriting basic-options
+        nat=yes
+        directmedia=no
+        host=dynamic
+
+[public-phone](!,basic-options)   ; another template inheriting basic-options
+        nat=no
+        directmedia=yes
+
+[my-codecs](!)                    ; a template for my preferred codecs
+        disallow=all
+        allow=ilbc
+        allow=g729
+        allow=gsm
+        allow=g723
+        allow=ulaw
+
+[ulaw-phone](!)                   ; and another one for ulaw-only
+        disallow=all
+        allow=ulaw
+
+; and finally instantiate a few phones
+;
+; [2133](natted-phone,my-codecs)
+;        secret = peekaboo
+; [2134](natted-phone,ulaw-phone)
+;        secret = not_very_secret
+; [2136](public-phone,ulaw-phone)
+;        secret = not_very_secret_either
+; ...
+;
+
+; Standard configurations not using templates look like this:
+;
+;[grandstream1]
+;type=friend
+;context=from-sip                ; Where to start in the dialplan when this phone calls
+;callerid=John Doe <1234>        ; Full caller ID, to override the phones config
+                                 ; on incoming calls to Asterisk
+;host=192.168.0.23               ; we have a static but private IP address
+                                 ; No registration allowed
+;nat=no                          ; there is not NAT between phone and Asterisk
+;directmedia=yes                 ; allow RTP voice traffic to bypass Asterisk
+;dtmfmode=info                   ; either RFC2833 or INFO for the BudgeTone
+;call-limit=1                    ; permit only 1 outgoing call and 1 incoming call at a time
+                                 ; from the phone to asterisk (deprecated)
+                                 ; 1 for the explicit peer, 1 for the explicit user,
+                                 ; remember that a friend equals 1 peer and 1 user in
+                                 ; memory
+                                 ; There is no combined call counter for a "friend"
+                                 ; so there's currently no way in sip.conf to limit
+                                 ; to one inbound or outbound call per phone. Use
+                                 ; the group counters in the dial plan for that.
+                                 ;
+;mailbox=1234@default            ; mailbox 1234 in voicemail context "default"
+;disallow=all                    ; need to disallow=all before we can use allow=
+;allow=ulaw                      ; Note: In user sections the order of codecs
+                                 ; listed with allow= does NOT matter!
+;allow=alaw
+;allow=g723.1                    ; Asterisk only supports g723.1 pass-thru!
+;allow=g729                      ; Pass-thru only unless g729 license obtained
+;callingpres=allowed_passed_screen ; Set caller ID presentation
+                                 ; See README.callingpres for more information
+
+;[xlite1]
+; Turn off silence suppression in X-Lite ("Transmit Silence"=YES)!
+; Note that Xlite sends NAT keep-alive packets, so qualify=yes is not needed
+;type=friend
+;regexten=1234                   ; When they register, create extension 1234
+;callerid="Jane Smith" <5678>
+;host=dynamic                    ; This device needs to register
+;nat=yes                         ; X-Lite is behind a NAT router
+;directmedia=no                  ; Typically set to NO if behind NAT
+;disallow=all
+;allow=gsm                       ; GSM consumes far less bandwidth than ulaw
+;allow=ulaw
+;allow=alaw
+;mailbox=1234@default,1233@default ; Subscribe to status of multiple mailboxes
+;registertrying=yes              ; Send a 100 Trying when the device registers.
+
+;[snom]
+;type=friend                     ; Friends place calls and receive calls
+;context=from-sip                ; Context for incoming calls from this user
+;secret=blah
+;subscribecontext=localextensions ; Only allow SUBSCRIBE for local extensions
+;language=de                     ; Use German prompts for this user
+;host=dynamic                    ; This peer register with us
+;dtmfmode=inband                 ; Choices are inband, rfc2833, or info
+;defaultip=192.168.0.59          ; IP used until peer registers
+;mailbox=1234@context,2345       ; Mailbox(-es) for message waiting indicator
+;subscribemwi=yes                ; Only send notifications if this phone
+                                 ; subscribes for mailbox notification
+;vmexten=voicemail               ; dialplan extension to reach mailbox
+                                 ; sets the Message-Account in the MWI notify message
+                                 ; defaults to global vmexten which defaults to "asterisk"
+;disallow=all
+;allow=ulaw                      ; dtmfmode=inband only works with ulaw or alaw!
+
+
+;[polycom]
+;type=friend                     ; Friends place calls and receive calls
+;context=from-sip                ; Context for incoming calls from this user
+;secret=blahpoly
+;host=dynamic                    ; This peer register with us
+;dtmfmode=rfc2833                ; Choices are inband, rfc2833, or info
+;defaultuser=polly               ; Username to use in INVITE until peer registers
+;defaultip=192.168.40.123
+                                 ; Normally you do NOT need to set this parameter
+;disallow=all
+;allow=ulaw                      ; dtmfmode=inband only works with ulaw or alaw!
+;progressinband=no               ; Polycom phones don't work properly with "never"
+
+
+;[pingtel]
+;type=friend
+;secret=blah
+;host=dynamic
+;insecure=port                   ; Allow matching of peer by IP address without
+                                 ; matching port number
+;insecure=invite                 ; Do not require authentication of incoming INVITEs
+;insecure=port,invite            ; (both)
+;qualify=1000                    ; Consider it down if it's 1 second to reply
+                                 ; Helps with NAT session
+                                 ; qualify=yes uses default value
+;qualifyfreq=60                  ; Qualification: How often to check for the
+                                 ; host to be up in seconds
+                                 ; Set to low value if you use low timeout for
+                                 ; NAT of UDP sessions
+;
+; Call group and Pickup group should be in the range from 0 to 63
+;
+;callgroup=1,3-4                 ; We are in caller groups 1,3,4
+;pickupgroup=1,3-5               ; We can do call pick-p for call group 1,3,4,5
+;defaultip=192.168.0.60          ; IP address to use if peer has not registered
+;deny=0.0.0.0/0.0.0.0            ; ACL: Control access to this account based on IP address
+;permit=192.168.0.60/255.255.255.0
+;permit=192.168.0.60/24          ; we can also use CIDR notation for subnet masks
+;permit=2001:db8::/32            ; IPv6 ACLs can be specified if desired. IPv6 ACLs
+                                 ; apply only to IPv6 addresses, and IPv4 ACLs apply
+                                 ; only to IPv4 addresses.
+
+;[cisco1]
+;type=friend
+;secret=blah
+;qualify=200                     ; Qualify peer is no more than 200ms away
+;nat=yes                         ; This phone may be natted
+                                 ; Send SIP and RTP to the IP address that packet is
+                                 ; received from instead of trusting SIP headers
+;host=dynamic                    ; This device registers with us
+;directmedia=no                  ; Asterisk by default tries to redirect the
+                                 ; RTP media stream (audio) to go directly from
+                                 ; the caller to the callee.  Some devices do not
+                                 ; support this (especially if one of them is
+                                 ; behind a NAT).
+;defaultip=192.168.0.4           ; IP address to use until registration
+;defaultuser=goran               ; Username to use when calling this device before registration
+                                 ; Normally you do NOT need to set this parameter
+;setvar=CUSTID=5678              ; Channel variable to be set for all calls from or to this device
+;setvar=ATTENDED_TRANSFER_COMPLETE_SOUND=beep   ; This channel variable will
+                                                ; cause the given audio file to
+                                                ; be played upon completion of
+                                                ; an attended transfer.
+
+;[pre14-asterisk]
+;type=friend
+;secret=digium
+;host=dynamic
+;rfc2833compensate=yes          ; Compensate for pre-1.4 DTMF transmission from another Asterisk machine.
+                                ; You must have this turned on or DTMF reception will work improperly.
+;t38pt_usertpsource=yes         ; Use the source IP address of RTP as the destination IP address for UDPTL packets
+                                ; if the nat option is enabled. If a single RTP packet is received Asterisk will know the
+                                ; external IP address of the remote device. If port forwarding is done at the client side
+                                ; then UDPTL will flow to the remote device.
+
+[100]
+type=friend
+host=dynamic
+username=100
+secret=password
+canreinvite=no
+allow=all
+
+[200]
+type=friend
+host=dynamic
+username=200
+secret=password
+canreinvite=no
+allow=all
+
+[300]
+type=friend
+host=dynamic
+username=300
+canreinvite=no
+allow=all
+
+[400]
+type=friend
+host=dynamic
+username=400
+canreinvite=no
+allow=all
+
+[testphone1]
+context=default
+type=friend
+secret=savoirfairelinux
+host=dynamic
+insecure=invite,port
+dtmfmode=rfc2833
+transport=tls
+allow=all
+nat=yes
diff --git a/tools/pysflphone/sflphonectrlsimple.py b/tools/pysflphone/sflphonectrl.py
similarity index 73%
rename from tools/pysflphone/sflphonectrlsimple.py
rename to tools/pysflphone/sflphonectrl.py
index 12709ed900ddb56310ed0d4487af2693faa5db98..b6a17226a21ec1a38df9699caf08fb740ec6408b 100755
--- a/tools/pysflphone/sflphonectrlsimple.py
+++ b/tools/pysflphone/sflphonectrl.py
@@ -47,38 +47,49 @@ except ImportError, e:
 	raise SflPhoneError("No python-dbus module found")
 
 
-class SflPhoneCtrlSimple(Thread):
-    """ Simple class for controlling SflPhoned through DBUS
-
-        If option testSuite (ts) is put to true,
-	simple actions are implemented on incoming call.
+class SflPhoneCtrl(Thread):
+    """ class for controlling SflPhoned through DBUS
+
+    Classes deriving this class should reimplement signal handlers,
+    more especially:
+	onIncomingCall_cb
+        onCallHangup_cb
+        onCallRinging_cb
+        onCallHold_cb
+        onCallCurrent_cb
+        onCallBusy_cb
+        onCallFailure_cb
+        onConferenceCreated_cb
     """
 
     # list of active calls (known by the client)
     activeCalls = {}
 
-    def __init__(self, test=False, name=sys.argv[0]):
-        print "Create SFLphone instance"
-	Thread.__init__(self)
-       	# current active account
+    # list of active conferences
+    activeConferences = {}
+
+    def __init__(self, name=sys.argv[0]):
+        Thread.__init__(self)
+
+        # current active account
         self.account = None
+
         # client name
         self.name = name
+
+	self.currentCallId = ""
+        self.currentConfId = ""
+
+	self.isStop = False
+
         # client registered to sflphoned ?
         self.registered = False
         self.register()
-	self.currentCallId = ""
 
+        # Glib MainLoop for processing callbacks
 	self.loop = MainLoop()
 
-	self.isStop = False
-
-	self.test = test
-	self.onIncomingCall_cb = None
-	self.event = Event()
-
 	gobject.threads_init()
-	
 
 
     def __del__(self):
@@ -88,9 +99,7 @@ class SflPhoneCtrlSimple(Thread):
 
 
     def stopThread(self):
-        print "Stop PySFLphone"
         self.isStop = True
-	
 
 
     def register(self):
@@ -141,18 +150,15 @@ class SflPhoneCtrlSimple(Thread):
             print "Adding Incoming call method"
             proxy_callmgr.connect_to_signal('incomingCall', self.onIncomingCall)
             proxy_callmgr.connect_to_signal('callStateChanged', self.onCallStateChanged)
+            proxy_callmgr.connect_to_signal('conferenceCreated', self.onConferenceCreated)
         except dbus.DBusException, e:
             print e
 
 
-
     def unregister(self):
 
-        print "Unregister"
-
         if not self.registered:
             return
-            #raise SflPhoneError("Not registered !")
         try:
             self.instance.Unregister(os.getpid())
             self.registered = False
@@ -164,66 +170,122 @@ class SflPhoneCtrlSimple(Thread):
         return self.registered
 
 
-    def getEvent(self):
-        return self.event
+    #
+    # Signal handling
+    #
 
-    def wait(self):
-        self.event.wait()
+    def onIncomingCall_cb(self):
+        pass
 
-    def isSet(self):
-        self.event.isSet()
+    def onCallHangup_cb(self, callId):
+        pass
 
-    def set(self):
-        self.event.set()
+    def onCallRinging_cb(self):
+        pass
 
-    def clear(self):
-        self.event.clear()
+    def onCallHold_cb(self):
+        pass
 
-    #
-    # Signal handling
-    #
+    def onCallCurrent_cb(self):
+        pass
+
+    def onCallBusy_cb(self):
+        pass
+
+    def onCallFailure_cb(self):
+        pass
 
-    # On incoming call event, add the call to the list of active calls
     def onIncomingCall(self, account, callid, to):
-        print "Incoming call: " + account + ", " + callid + ", " + to
-        self.activeCalls[callid] = {'Account': account, 'To': to, 'State': '' }
+        """ On incoming call event, add the call to the list of active calls """
+
+        self.activeCalls[callid] = {'Account': account,
+                                         'To': to,
+                                      'State': ''}
 	self.currentCallId = callid
+	self.onIncomingCall_cb()
 
-	if(self.test):
-            # TODO fix this bug in daemon, cannot answer too fast
-            time.sleep(0.5)
-	    if self.onIncomingCall_cb(self) is not None:
-                self.onIncomingCall_cb(self)
-	
+
+    def onCallHangUp(self, callid):
+        """ Remove callid from call list """
+
+        self.onCallHangup_cb(callid)
+	self.currentCallId = ""
+        del self.activeCalls[callid]
+
+
+    def onCallRinging(self, callid, state):
+        """ Update state for this call to Ringing """
+
+        self.activeCalls[callid]['State'] = state
+        self.onCallRinging_cb()
+
+
+    def onCallHold(self, callid, state):
+        """ Update state for this call to Hold """
+
+        self.activeCalls[callid]['State'] = state
+        self.onCallHold_cb()
+
+
+    def onCallCurrent(self, callid, state):
+        """ Update state for this call to current """
+
+        self.activeCalls[callid]['State'] = state
+        self.onCallCurrent_cb()
+
+
+    def onCallBusy(self, callid, state):
+        """ Update state for this call to busy """
+
+        self.activeCalls[callid]['State'] = state
+        self.onCallBusy_cb()
+
+
+    def onCallFailure(self, callid, state):
+        """ Handle call failure """
+
+        self.onCallFailure_cb(self)
+        del self.activeCalls[callid]
 
 
-    # On call state changed event, set the values for new calls,
-    # or delete the call from the list of active calls
     def onCallStateChanged(self, callid, state):
-        print "Call state changed: " + callid + ", " + state
+        """ On call state changed event, set the values for new calls,
+        or delete the call from the list of active calls
+        """
+
+        print "On call state changed " + callid + " " + state
+
+        if callid not in self.activeCalls:
+            print "This call didn't exist!: " + callid + ". Adding it to the list."
+            callDetails = self.getCallDetails(callid)
+            self.activeCalls[callid] = {'Account': callDetails['ACCOUNTID'],
+                                             'To': callDetails['PEER_NUMBER'],
+                                          'State': state }
+
+
+        self.currentCallId = callid
+
         if state == "HUNGUP":
-            try:
-                del self.activeCalls[callid]
-            except KeyError:
-                print "Call " + callid + " didn't exist. Cannot delete."
-
-        elif state in [ "RINGING", "CURRENT", "INCOMING", "HOLD" ]:
-            try:
-                self.activeCalls[callid]['State'] = state
-            except KeyError, e:
-                print "This call didn't exist!: " + callid + ". Adding it to the list."
-                callDetails = self.getCallDetails(callid)
-                self.activeCalls[callid] = {'Account': callDetails['ACCOUNTID'],
-					    'To': callDetails['PEER_NUMBER'], 'State': state }
-        elif state in [ "BUSY", "FAILURE" ]:
-            try:
-                del self.activeCalls[callid]
-            except KeyError, e:
-                print "This call didn't exist!: " + callid
-
-#		elif state == "UNHOLD_CURRENT":
-#			self.activeCalls[callid]['State'] = "UNHOLD_CURRENT"
+            self.onCallHangUp(callid)
+        elif state == "RINGING":
+            self.onCallRinging(callid, state)
+        elif state == "CURRENT":
+            self.onCallCurrent(callid, state)
+        elif state == "HOLD":
+            self.onCallHold(callid, state)
+        elif state == "BUSY":
+            self.onCallBusy(callid, state)
+        elif state == "FAILURE":
+            self.onCallFailure(self, callid, state)
+        else:
+            print "unknown state"
+
+    def onConferenceCreated_cb(self):
+        pass
 
+    def onConferenceCreated(self, confId):
+        self.currentConfId = confId
+        self.onConferenceCreated_cb()
 
     #
     # Account management
@@ -237,7 +299,7 @@ class SflPhoneCtrlSimple(Thread):
 	Required parameters are type, alias, hostname, username and password
 
 	input details
-	
+
 	"""
 
 	if details is None:
@@ -247,6 +309,7 @@ class SflPhoneCtrlSimple(Thread):
 
 	return self.configurationmanager.addAccount(details)
 
+
     def removeAccount(self, accountID=None):
         """Remove an account from internal list"""
 
@@ -255,13 +318,16 @@ class SflPhoneCtrlSimple(Thread):
 
         self.configurationmanager.removeAccount(accountID)
 
+
     def getAllAccounts(self):
         """Return a list with all accounts"""
+
         return self.configurationmanager.getAccountList()
 
 
     def getAllEnabledAccounts(self):
         """Return a list with all enabled accounts"""
+
         accounts = self.getAllAccounts()
         activeaccounts = []
         for testedaccount in accounts:
@@ -306,6 +372,7 @@ class SflPhoneCtrlSimple(Thread):
 
         raise SPaccountError("No account matched with alias")
 
+
     def setAccount(self, account):
         """Define the active account
 
@@ -318,6 +385,7 @@ class SflPhoneCtrlSimple(Thread):
             print account
             raise SflPhoneError("Not a valid account")
 
+
     def setFirstRegisteredAccount(self):
         """Find the first enabled account and define it as active"""
 
@@ -326,6 +394,7 @@ class SflPhoneCtrlSimple(Thread):
             raise SflPhoneError("No registered account !")
         self.account = rAccounts[0]
 
+
     def setFirstActiveAccount(self):
         """Find the first enabled account and define it as active"""
 
@@ -348,40 +417,44 @@ class SflPhoneCtrlSimple(Thread):
                 if self.account is None:
                         raise SflPhoneError("No provided or current account !")
                 account = self.account
-        return self.getAccountDetails(account)['Status'] == "REGISTERED"
+        return self.getAccountDetails(account)['Registration.Status'] == "REGISTERED"
 
 
     def isAccountEnable(self, account=None):
         """Return True if the account is enabled. If no account is provided, active account is used"""
 
         if account is None:
-	       	if self.account is None:
-		       	raise SflPhoneError("No provided or current account !")
+            if self.account is None:
+                raise SflPhoneError("No provided or current account !")
                 account = self.account
         return self.getAccountDetails(account)['Account.enable'] == "TRUE"
 
+
     def setAccountEnable(self, account=None, enable=False):
-       	"""Set account enabled"""
+        """Set account enabled"""
         if account is None:
-	       	if self.account is None:
-		       	raise SflPhoneError("No provided or current account !")
+            if self.account is None:
+                raise SflPhoneError("No provided or current account !")
                 account = self.account
 
-       	if enable == True:
-	       	details = self.getAccountDetails(account)
-                details['Account.enable'] = "TRUE"
-                self.configurationmanager.setAccountDetails(account, details)
+        if enable == True:
+	    details = self.getAccountDetails(account)
+            details['Account.enable'] = "true"
+            self.configurationmanager.setAccountDetails(account, details)
         else:
-	       	details = self.getAccountDetails(account)
-                details['Account.enable'] = "FALSE"
-                self.configurationmanager.setAccountDetails(account, details)
+            details = self.getAccountDetails(account)
+            details['Account.enable'] = "false"
+            self.configurationmanager.setAccountDetails(account, details)
+
 
     def checkAccountExists(self, account=None):
         """ Checks if the account exists """
+
         if account is None:
             raise SflPhoneError("No provided or current account !")
         return account in self.getAllAccounts()
-			
+
+
     def getAllRegisteredAccounts(self):
         """Return a list of registered accounts"""
 
@@ -392,6 +465,7 @@ class SflPhoneCtrlSimple(Thread):
 
         return registeredAccountsList
 
+
     def getAllEnabledAccounts(self):
         """Return a list of enabled accounts"""
 
@@ -402,8 +476,10 @@ class SflPhoneCtrlSimple(Thread):
 
         return enabledAccountsList
 
+
     def getAllSipAccounts(self):
         """Return a list of SIP accounts"""
+
         sipAccountsList = []
         for accountName in self.getAllAccounts():
             if  self.getAccountDetails(accountName)['Account.type'] == "SIP":
@@ -411,6 +487,7 @@ class SflPhoneCtrlSimple(Thread):
 
         return sipAccountsList
 
+
     def getAllIaxAccounts(self):
         """Return a list of IAX accounts"""
 
@@ -421,23 +498,22 @@ class SflPhoneCtrlSimple(Thread):
 
         return iaxAccountsList
 
+
     def setAccountRegistered(self, account=None, register=False):
-       	""" Tries to register the account """
-
-       	if account is None:
-       		if self.account is None:
-       			raise SflPhoneError("No provided or current account !")
-       		account = self.account
-
-       	try:
-       		if register:
-       			self.configurationmanager.sendRegister(account, int(1))
-       			#self.setAccount(account)
-       		else:
-       			self.configurationmanager.sendRegister(account, int(0))
-       			#self.setFirstRegisteredAccount()
+        """ Tries to register the account """
+
+        if account is None:
+            if self.account is None:
+                raise SflPhoneError("No provided or current account !")
+            account = self.account
+
+        try:
+            if register:
+                self.configurationmanager.sendRegister(account, int(1))
+            else:
+                self.configurationmanager.sendRegister(account, int(0))
         except SflPhoneError, e:
-       		print e
+            print e
 
     #
     # Codec manager
@@ -445,12 +521,14 @@ class SflPhoneCtrlSimple(Thread):
 
     def getCodecList(self):
         """ Return the codec list """
+
         return self.configurationmanager.getCodecList()
 
+
     def getActiveCodecList(self):
         """ Return the active codec list """
-        return self.configurationmanager.getActiveCodecList()
 
+        return self.configurationmanager.getActiveCodecList()
 
 
     #
@@ -479,9 +557,6 @@ class SflPhoneCtrlSimple(Thread):
         for call in self.activeCalls:
             print "\t" + call
 
-    #
-    # Action
-    #
     def Call(self, dest):
         """Start a call and return a CallID
 
@@ -496,7 +571,7 @@ class SflPhoneCtrlSimple(Thread):
 
 	if dest is None or dest == "":
             raise SflPhoneError("Invalid call destination")
-	
+
         # Set the account to be used for this call
 	if dest.find('sip:') is 0 or dest.find('sips:') is 0:
             print "Ip 2 IP call"
@@ -508,7 +583,7 @@ class SflPhoneCtrlSimple(Thread):
             raise SflPhoneError("Can't place a call without a registered account")
 
         # Generate a call ID for this call
-        callid = self.GenerateCallID()	
+        callid = self.GenerateCallID()
 
         # Add the call to the list of active calls and set status to SENT
         self.activeCalls[callid] = {'Account': self.account, 'To': dest, 'State': 'SENT' }
@@ -521,26 +596,18 @@ class SflPhoneCtrlSimple(Thread):
 
     def HangUp(self, callid):
         """End a call identified by a CallID"""
+
         if not self.account:
             self.setFirstRegisteredAccount()
 
-        # if not self.isAccountRegistered() and self.accout is not "IP2IP":
-        #    raise SflPhoneError("Can't hangup a call without a registered account")
-
         if callid is None or callid == "":
             pass # just to see
-            #raise SflPhoneError("Invalid callID")
 
 	self.callmanager.hangUp(callid)
 
 
     def Transfer(self, callid, to):
         """Transfert a call identified by a CallID"""
-        # if not self.account:
-        #    self.setFirstRegisteredAccount()
-
-        # if not self.isAccountRegistered():
-        #     raise SflPhoneError("Can't transfert a call without a registered account")
 
         if callid is None or callid == "":
             raise SflPhoneError("Invalid callID")
@@ -553,12 +620,6 @@ class SflPhoneCtrlSimple(Thread):
 
 	print "Refuse call " + callid
 
-        # if not self.account:
-        #     self.setFirstRegisteredAccount()
-
-        # if not self.isAccountRegistered():
-        #     raise SflPhoneError("Can't refuse a call without a registered account")
-
         if callid is None or callid == "":
             raise SflPhoneError("Invalid callID")
 
@@ -567,26 +628,22 @@ class SflPhoneCtrlSimple(Thread):
 
     def Accept(self, callid):
         """Accept an incoming call identified by a CallID"""
+
 	print "Accept call " + callid
         if not self.account:
             self.setFirstRegisteredAccount()
 
-       	if not self.isAccountRegistered():
+        if not self.isAccountRegistered():
             raise SflPhoneError("Can't accept a call without a registered account")
 
         if callid is None or callid == "":
             raise SflPhoneError("Invalid callID")
-	
+
         self.callmanager.accept(callid)
 
 
     def Hold(self, callid):
         """Hold a call identified by a CallID"""
-        # if not self.account:
-        #    self.setFirstRegisteredAccount()
-
-        # if not self.isAccountRegistered():
-        #    raise SflPhoneError("Can't hold a call without a registered account")
 
         if callid is None or callid == "":
             raise SflPhoneError("Invalid callID")
@@ -596,11 +653,6 @@ class SflPhoneCtrlSimple(Thread):
 
     def UnHold(self, callid):
         """Unhold an incoming call identified by a CallID"""
-        # if not self.account:
-        #    self.setFirstRegisteredAccount()
-
-        # if not self.isAccountRegistered():
-        #    raise SflPhoneError("Can't unhold a call without a registered account")
 
         if callid is None or callid == "":
             raise SflPhoneError("Invalid callID")
@@ -610,11 +662,13 @@ class SflPhoneCtrlSimple(Thread):
 
     def Dtmf(self, key):
         """Send a DTMF"""
+
         self.callmanager.playDTMF(key)
 
 
     def GenerateCallID(self):
         """Generate Call ID"""
+
 	m = hashlib.md5()
         t = long( time.time() * 1000 )
         r = long( random.random()*100000000000000000L )
@@ -622,13 +676,30 @@ class SflPhoneCtrlSimple(Thread):
         callid = m.hexdigest()
 	return callid
 
+
+    def createConference(self, call1Id, call2Id):
+        """ Create a conference given the two call ids """
+
+        self.callmanager.joinParticipant(call1Id, call2Id)
+
+
+    def hangupConference(self, confId):
+        """ Hang up each call for this conference """
+
+        self.callmanager.hangUpConference(confId)
+
+
     def run(self):
         """Processing method for this thread"""
 
-	context = self.loop.get_context()
+        context = self.loop.get_context()
 
 	while True:
             context.iteration(True)
 
 	    if self.isStop:
-	        return
+                print "++++++++++++++++++++++++++++++++++++++++"
+                print "++++++++++++++++++++++++++++++++++++++++"
+                print "++++++++++++++++++++++++++++++++++++++++"
+                print "++++++++++++++++++++++++++++++++++++++++"
+                return
diff --git a/tools/pysflphone/sflphoned.functest.yml b/tools/pysflphone/sflphoned.functest.yml
new file mode 100644
index 0000000000000000000000000000000000000000..926a0506b642f640a7dbf57396e85f8757051a3b
--- /dev/null
+++ b/tools/pysflphone/sflphoned.functest.yml
@@ -0,0 +1,208 @@
+---
+accounts:
+- alias: 100
+  codecs: 0/3/8/9/110/111/112/
+  credential:
+  - Account.password: password
+    Account.realm: '*'
+    Account.username: 100
+  displayName:
+  dtmfType: overrtp
+  enable: true
+  hostname: 127.0.0.1:5062
+  id: Account:1334024061
+  interface: default
+  mailbox:
+  port: 5060
+  publishAddr: 0.0.0.0
+  publishPort: 5060
+  registrationexpire: 600
+  ringtoneEnabled: true
+  ringtonePath: /home/alexandresavard/Development/sflphone/gnome
+  sameasLocal: true
+  serviceRoute:
+  srtp:
+    enable: false
+    keyExchange:
+    rtpFallback: false
+  stunEnabled: false
+  stunServer: stun.sflphone.org
+  tls:
+    calist:
+    certificate:
+    ciphers:
+    enable: false
+    method: TLSv1
+    password:
+    privateKey:
+    requireCertif: true
+    server:
+    timeout: 2
+    tlsPort: 5061
+    verifyClient: true
+    verifyServer: true
+  type: SIP
+  updateContact: false
+  username: 100
+  zrtp:
+    displaySas: true
+    displaySasOnce: false
+    helloHashEnabled: true
+    notSuppWarning: true
+- alias: 200
+  codecs: 0/3/8/9/110/111/112/
+  credential:
+  - Account.password: password
+    Account.realm: '*'
+    Account.username: 200
+  displayName:
+  dtmfType: overrtp
+  enable: true
+  hostname: 127.0.0.1:5062
+  id: Account:1334024356
+  interface: default
+  mailbox:
+  port: 5060
+  publishAddr: 0.0.0.0
+  publishPort: 5060
+  registrationexpire: 600
+  ringtoneEnabled: true
+  ringtonePath: /home/alexandresavard/Development/sflphone/gnome
+  sameasLocal: true
+  serviceRoute:
+  srtp:
+    enable: false
+    keyExchange:
+    rtpFallback: false
+  stunEnabled: false
+  stunServer: stun.sflphone.org
+  tls:
+    calist:
+    certificate:
+    ciphers:
+    enable: false
+    method: TLSv1
+    password:
+    privateKey:
+    requireCertif: true
+    server:
+    timeout: 2
+    tlsPort: 5061
+    verifyClient: true
+    verifyServer: true
+  type: SIP
+  updateContact: false
+  username: 200
+  zrtp:
+    displaySas: true
+    displaySasOnce: false
+    helloHashEnabled: true
+    notSuppWarning: true
+- alias:
+  codecs: 0/3/8/9/110/111/112/
+  credential:
+  - Account.password:
+    Account.realm: '*'
+    Account.username:
+  displayName:
+  dtmfType: overrtp
+  enable: true
+  hostname:
+  id: IP2IP
+  interface: default
+  mailbox:
+  port: 5060
+  publishAddr:
+  publishPort: 5060
+  registrationexpire: 600
+  ringtoneEnabled: true
+  ringtonePath: /usr/share/sflphone/ringtones/konga.ul
+  sameasLocal: true
+  serviceRoute:
+  srtp:
+    enable: false
+    keyExchange: sdes
+    rtpFallback: false
+  stunEnabled: false
+  stunServer: stun.sflphone.org
+  tls:
+    calist:
+    certificate:
+    ciphers:
+    enable: false
+    method: TLSv1
+    password:
+    privateKey:
+    requireCertif: true
+    server:
+    timeout: 2
+    tlsPort: 5061
+    verifyClient: true
+    verifyServer: true
+  type: SIP
+  updateContact: false
+  username:
+  zrtp:
+    displaySas: true
+    displaySasOnce: false
+    helloHashEnabled: true
+    notSuppWarning: true
+preferences:
+  historyLimit: 30
+  historyMaxCalls: 20
+  md5Hash: false
+  notifyMails: false
+  order: Account:1334024356/Account:1334024061/
+  portNum: 5060
+  registrationexpire: 180
+  searchBarDisplay: true
+  zeroConfenable: false
+  zoneToneChoice: North America
+voipPreferences:
+  playDtmf: true
+  playTones: true
+  pulseLength: 250
+  symmetric: true
+  zidFile: true
+addressbook:
+  business: true
+  enabled: true
+  home: true
+  list:
+  maxResults: 25
+  mobile: true
+  photo: true
+hooks:
+  iax2Enabled: false
+  numberAddPrefix:
+  numberEnabled: false
+  sipEnabled: false
+  urlCommand: x-www-browser
+  urlSipField: X-sflphone-url
+audio:
+  alsa:
+    cardIn: 0
+    cardOut: 0
+    cardRing: 0
+    plugin: default
+    smplRate: 44100
+  alwaysRecording: false
+  audioApi: pulseaudio
+  echoCancel: false
+  echoDelayLength: 0
+  echoTailLength: 100
+  noiseReduce: true
+  pulse:
+    devicePlayback: alsa_output.pci-0000_00_1b.0.analog-stereo
+    deviceRecord: alsa_input.pci-0000_00_1b.0.analog-stereo
+    deviceRingtone: alsa_output.pci-0000_00_1b.0.analog-stereo
+  recordPath:
+  volumeMic: 100
+  volumeSpkr: 100
+shortcuts:
+  hangUp:
+  pickUp:
+  popupWindow:
+  toggleHold:
+  togglePickupHangup:
+...
diff --git a/tools/pysflphone/sippwrap.py b/tools/pysflphone/sippwrap.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bdc07355893fca4a475267d00707323b3e84f97
--- /dev/null
+++ b/tools/pysflphone/sippwrap.py
@@ -0,0 +1,160 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2012 by the Free Software Foundation, Inc.
+#
+# Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+import os
+
+class SippWrapper:
+    """ Wrapper taht allow for managing sipp command line easily """
+
+    def __init__(self):
+        self.commandLine = "./sipp"
+        self.remoteServer = ""
+        self.remotePort = ""
+        self.localInterface = ""
+        self.localPort = ""
+        self.customScenarioFile = ""
+        self.isUserAgenClient = True
+        self.launchInBackground = False
+        self.numberOfCall = 0
+        self.numberOfSimultaneousCall = 0
+        self.enableTraceMsg = False
+        self.enableTraceShormsg = False
+        self.enableTraceScreen = False
+        self.enableTraceError = False
+        self.enableTraceStat = False
+        self.enableTraceCounts = False
+        self.enableTraceRtt = False
+        self.enableTraceLogs = False
+
+    def buildCommandLine(self, port):
+	""" Fill the command line arguments based on specified parameters """
+
+        self.localPort = str(port)
+
+        if not self.remotePort and not self.remoteServer:
+            self.isUserAgentClient = False
+        elif self.remotePort and not self.remoteServer:
+	    print "Error cannot have remote port specified with no server"
+            return
+
+        if self.remoteServer:
+            self.commandLine += " " + self.remoteServer
+
+        if self.remotePort:
+            self.commandLine += ":" + self.remotePort
+
+        if self.localInterface:
+            self.commandLine += " -i " + self.localInterface
+
+        if self.localPort:
+            self.commandLine += " -p " + self.localPort
+
+        if self.customScenarioFile:
+            self.commandLine += " -sf " + self.customScenarioFile
+        elif self.isUserAgentClient is True:
+            self.commandLine += " -sn uac"
+        elif self.isUserAgentClient is False:
+            self.commandLine += " -sn uas"
+
+        if self.launchInBackground:
+            self.commandLine += " -bg"
+
+        if self.numberOfCall:
+            self.commandLine += " -m " + str(self.numberOfCall)
+
+        if self.numberOfSimultaneousCall:
+            self.commandLine += " -l " + str(self.numberOfSimultaneousCall)
+
+        if self.enableTraceMsg:
+            self.commandLine += " -trace_msg"
+
+        if self.enableTraceShormsg:
+            self.commandLine += " -trace_shortmsg"
+
+        if self.enableTraceScreen:
+            self.commandLine += " -trace_screen"
+
+        if self.enableTraceError:
+            self.commandLine += " -trace_err"
+
+        if self.enableTraceStat:
+            self.commandLine += " -trace_stat"
+
+        if self.enableTraceCounts:
+            self.commandLine += " -trace_counts"
+
+        if self.enableTraceRtt:
+            self.commandLine += " -trace_rtt"
+
+        if self.enableTraceLogs:
+            self.commandLine += " -trace_logs"
+
+
+    def launch(self):
+        """ Launch the sipp instance using the specified arguments """
+
+        print self.commandLine
+        return os.system(self.commandLine + " 2>&1 > /dev/null")
+
+
+class SippScreenStatParser:
+    """ Class that parse statistic reported by a sipp instance
+        report some of the most important value """
+
+    def __init__(self, filename):
+        print "Opening " + filename
+        self.logfile = open(filename, "r").readlines()
+        print self.logfile[39]
+        print self.logfile[40]
+
+    def isAnyFailedCall(self):
+        """ Look for any failed call
+            Return true if there are failed call, false elsewhere """
+
+        # TODO: Find a better way to determine which line to consider
+        if "Failed call" not in self.logfile[40]:
+            print "Error: Could not find 'Failed call' statistics"
+            # We consider this as a failure
+            return True
+
+        return "1" in self.logfile[40]
+
+    def isAnySuccessfulCall(self):
+        """ Look for any successful call
+            Return true if there are successful call, false elsewhere """
+
+        # TODO: Find a better way to determine which line to consider
+        if "Successful call" not in self.logfile[39]:
+            print "Error: Could not find 'Successful call' statistics"
+            return False
+
+        return "1" in self.logfile[39]
+
+
+
+def test_result_parsing():
+    dirlist = os.listdir("./")
+
+    logfile = [x for x in dirlist if "screen.log" in x]
+    testResult = SippScreenStatParser(logfile[0])
+
+    assert(not testResult.isAnyFailedCall())
+
+    assert(testResult.isAnySuccessfulCall())
diff --git a/tools/pysflphone/test_sflphone_dbus_interface.py b/tools/pysflphone/test_sflphone_dbus_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..34dfee8a274b084c99b72b520f0b27f6eb31902e
--- /dev/null
+++ b/tools/pysflphone/test_sflphone_dbus_interface.py
@@ -0,0 +1,412 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2012 by the Free Software Foundation, Inc.
+#
+# Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+import os
+import time
+import yaml
+import logging
+import multiprocessing
+from sippwrap import SippWrapper
+from sippwrap import SippScreenStatParser
+from sflphonectrl import SflPhoneCtrl
+
+from nose.tools import nottest
+
+###
+### function starting with 'test' are executed.
+###
+
+SCENARIO_PATH = "../sippxml/"
+
+class SippCtrl:
+
+    def __init__(self):
+        self.remoteServer = "127.0.0.1"
+        self.remotePort = str(5062)
+        self.localInterface = "127.0.0.1"
+        self.localPort = str(5060)
+
+    def initialize_sipp_registration_instance(self, instance, xmlScenario):
+        instance.remoteServer = self.remoteServer
+        instance.remotePort = self.remotePort
+        instance.localInterface = self.localInterface
+        instance.localPort = self.localPort
+        instance.customScenarioFile = SCENARIO_PATH + xmlScenario
+        instance.numberOfCall = 1
+        instance.numberOfSimultaneousCall = 1
+
+    def initialize_sipp_call_instance(self, instance):
+        instance.localInterface = self.localInterface
+        instance.localPort = self.localPort
+        instance.numberOfCall = 1
+        instance.numberOfSimultaneousCall = 1
+        instance.enableTraceScreen = True
+
+    def launchSippProcess(self, sippInstance, localPort):
+        sippInstance.buildCommandLine(localPort)
+        sippInstance.launch()
+
+    def find_sipp_pid(self):
+        # Retreive the PID of the last
+        # The /proc/PID/cmdline contain the command line from
+        pids = [int(x) for x in os.listdir("/proc") if x.isdigit()]
+        sippPid = [pid for pid in pids if "sipp" in open("/proc/" + str(pid) + "/cmdline").readline()]
+
+        return sippPid[0]
+
+    def clean_log_directory(self):
+        dirlist = os.listdir("./")
+        files = [x for x in dirlist if "screen.log" in x]
+        for f in files:
+	    os.remove(f)
+
+    def parse_results(self):
+        dirlist = os.listdir("./")
+        logfile = [x for x in dirlist if "screen.log" in x]
+
+        fullpath = os.path.dirname(os.path.realpath(__file__)) + "/"
+
+        # there should be only one screen.log file (see clean_log_directory)
+        resultParser = SippScreenStatParser(fullpath + logfile[0])
+
+        assert(not resultParser.isAnyFailedCall())
+        assert(resultParser.isAnySuccessfulCall())
+
+class TestSFLPhoneAccountConfig(SflPhoneCtrl):
+    """ The test suite for account configuration """
+
+    def __init__(self):
+        SflPhoneCtrl.__init__(self)
+
+        self.logger = logging.getLogger("TestSFLPhoneAccountConfig")
+        filehdlr = logging.FileHandler("/tmp/sflphonedbustest.log")
+        formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
+        filehdlr.setFormatter(formatter)
+        self.logger.addHandler(filehdlr)
+        self.logger.setLevel(logging.INFO)
+
+
+    def get_config(self):
+        """ Parsse configuration file and return a dictionary """
+        config = {}
+        with open("sflphoned.functest.yml","r") as stream:
+            config = yaml.load(stream)
+
+        return config
+
+
+    def get_account_list_from_config(self):
+        """ Get the accout list from config and add IP2IP """
+
+        config = self.get_config()
+
+        accounts = config["preferences"]["order"]
+        accountList = accounts.split('/')
+        del accountList[len(accountList)-1]
+        accountList.append("IP2IP")
+
+        return accountList
+
+
+    def test_get_account_list(self):
+        self.logger.info("Test get account list")
+
+        accountList = self.get_account_list_from_config()
+
+        # make sure that the intersection between the list is of same size
+        accList = self.getAllAccounts()
+        listIntersection = set(accList) & set(accountList)
+        assert len(listIntersection) == len(accountList)
+
+
+    def test_account_registration(self):
+        self.logger.info("Test account registration")
+        accList = [x for x in self.getAllAccounts() if x != "IP2IP"]
+        for acc in accList:
+	    self.logger.info("Registering account " + acc)
+
+            if self.isAccountEnable(acc):
+               self.setAccountEnable(acc, False)
+               time.sleep(2)
+
+            # Account should not be registered
+            assert self.isAccountRegistered(acc)
+
+            self.setAccountEnable(acc, True)
+            time.sleep(2)
+
+            assert self.isAccountRegistered(acc)
+
+
+    @nottest
+    def test_get_account_details(self):
+        self.logger.info("Test account details")
+
+        accList = [x for x in self.getAllAccounts() if x != "IP2IP"]
+
+        config = self.get_config()
+
+        accountDetails = {}
+        for acc in accList:
+            accountDetails[acc] = self.getAccountDetails(acc)
+
+        accountConfDetails = {}
+        for accConf in config["accounts"]:
+            accountConfDetails[accConf["id"]] = accConf
+
+
+    @nottest
+    def test_add_remove_account(self):
+        self.logger.info("Test add/remove account")
+        accountDetails = {}
+        newAccList = []
+
+        # consider only true accounts
+        accList = [x for x in self.getAllAccounts() if x != "IP2IP"]
+
+        # Store the account details localy
+        for acc in accList:
+            accountDetails[acc] = self.getAccountDetails(acc)
+
+        # Remove all accounts from sflphone
+        for acc in accountDetails:
+            self.removeAccount(acc)
+
+        # Recreate all accounts
+        for acc in accountDetails:
+            newAccList.append(self.addAccount(accountDetails[acc]))
+
+        # New accounts should be automatically registered
+        for acc in newAccList:
+            assert self.isAccountRegistered(acc)
+
+
+
+class TestSFLPhoneRegisteredCalls(SflPhoneCtrl, SippCtrl):
+    """ The test suite for call interaction """
+
+    def __init__(self):
+        SflPhoneCtrl.__init__(self)
+        SippCtrl.__init__(self)
+
+        self.logger = logging.getLogger("TestSFLPhoneRegisteredCalls")
+        filehdlr = logging.FileHandler("/tmp/sfltestregisteredcall.log")
+        formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
+        filehdlr.setFormatter(formatter)
+        self.logger.addHandler(filehdlr)
+        self.logger.setLevel(logging.INFO)
+        self.sippRegistrationInstance = SippWrapper()
+        self.sippCallInstance = SippWrapper()
+
+        # Make sure the test directory is populated with most recent log files
+        self.clean_log_directory()
+
+
+    def onCallCurrent_cb(self):
+        """ On incoming call, answer the callm, then hangup """
+
+        print "Hangup Call with id " + self.currentCallId
+        self.HangUp(self.currentCallId)
+
+        print "Stopping Thread"
+        self.stopThread()
+
+
+    def onCallRinging_cb(self):
+        """ Display messages when call is ringing """
+
+        print "The call is ringing"
+
+
+    def onCallFailure_cb(self):
+        """ If a failure occurs duing the call, just leave the running thread """
+
+        print "Stopping Thread"
+        self.stopThread()
+
+
+    def test_registered_call(self):
+        self.logger.info("Test Registered Call")
+
+        # Launch a sipp instance for account registration on asterisk
+        # this account will then be used to receive call from sflphone
+        self.initialize_sipp_registration_instance(self.sippRegistrationInstance, "uac_register_no_cvs_300.xml")
+        regd = multiprocessing.Process(name='sipp1register', target=self.launchSippProcess,
+                                                          args=(self.sippRegistrationInstance, 5064,))
+        regd.start()
+
+        # wait for the registration to complete
+        regd.join()
+
+        # Launch a sipp instance waiting for a call from previously registered account
+        self.initialize_sipp_call_instance(self.sippCallInstance)
+        calld = multiprocessing.Process(name='sipp1call', target=self.launchSippProcess,
+                                                      args=(self.sippCallInstance, 5064,))
+        calld.start()
+
+        # Make sure every account are enabled
+        accList = [x for x in self.getAllAccounts() if x != "IP2IP"]
+        for acc in accList:
+            if not self.isAccountRegistered(acc):
+                self.setAccountEnable(acc, True)
+
+        # Make a call to the SIPP instance
+        self.Call("300")
+
+        # Start the threaded loop to handle GLIB cllbacks
+        self.start()
+
+        # Wait for the sipp instance to dump log files
+        calld.join()
+
+        self.stopThread()
+        self.parse_results()
+
+
+class TestSFLPhoneConferenceCalls(SflPhoneCtrl, SippCtrl):
+    """ Test Conference calls """
+
+    def __init__(self):
+        SflPhoneCtrl.__init__(self)
+        SippCtrl.__init__(self)
+
+        self.logger = logging.getLogger("TestSFLPhoneRegisteredCalls")
+        filehdlr = logging.FileHandler("/tmp/sfltestregisteredcall.log")
+        formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
+        filehdlr.setFormatter(formatter)
+        self.logger.addHandler(filehdlr)
+        self.logger.setLevel(logging.INFO)
+        self.sippRegistrationInstanceA = SippWrapper()
+        self.sippRegistrationInstanceB = SippWrapper()
+        self.sippCallInstanceA = SippWrapper()
+        self.sippCallInstanceB = SippWrapper()
+        self.localPortCallA = str(5064)
+        self.localPortCallB = str(5066)
+        self.callCount = 0
+        self.accountCalls = []
+
+        # Make sure the test directory is populated with most recent log files
+        # self.clean_log_directory()
+
+
+    def onCallCurrent_cb(self):
+        """ On incoming call, answer the call, then hangup """
+
+        self.callCount += 1
+
+        self.accountCalls.append(self.currentCallId)
+        print "Account List: ", str(self.accountCalls)
+
+        if self.callCount == 2:
+            self.createConference(self.accountCalls[0], self.accountCalls[1])
+
+
+    def onCallRinging_cb(self):
+        """ Display messages when call is ringing """
+
+        print "The call is ringing"
+
+
+    def onCallHangup_cb(self, callId):
+        """ Exit thread when all call are finished """
+
+        if callId in self.accountCalls:
+            self.accountCalls.remove(callId)
+
+            self.callCount -= 1
+            if self.callCount == 0:
+                self.stopThread()
+
+
+    def onCallFailure_cb(self):
+        """ If a failure occurs duing the call, just leave the running thread """
+
+        print "Stopping Thread"
+        self.stopThread()
+
+
+    def onConferenceCreated_cb(self):
+        """ Called once the conference is created """
+
+        print "Conference Created ", self.currentConfId
+        print "Conference Hangup ", self.currentConfId
+
+        self.hangupConference(self.currentConfId)
+
+
+    def test_conference_call(self):
+        self.logger.info("Test Registered Call")
+
+        # launch the sipp instance to register the first participant to astersik
+        self.initialize_sipp_registration_instance(self.sippRegistrationInstanceA, "uac_register_no_cvs_300.xml")
+        regd = multiprocessing.Process(name='sipp1register', target=self.launchSippProcess,
+                                                                 args=(self.sippRegistrationInstanceA, 5064,))
+        regd.start()
+        regd.join()
+
+        # launch the sipp instance to register the second participant to asterisk
+        self.initialize_sipp_registration_instance(self.sippRegistrationInstanceB, "uac_register_no_cvs_400.xml")
+        regd = multiprocessing.Process(name='sipp2register', target=self.launchSippProcess,
+                                                                 args=(self.sippRegistrationInstanceB, 5066,))
+        regd.start()
+        regd.join()
+
+        # launch the sipp instance waining for call as the first participant
+        self.initialize_sipp_call_instance(self.sippCallInstanceA)
+        calldA = multiprocessing.Process(name='sipp1call', target=self.launchSippProcess,
+                                                              args=(self.sippCallInstanceA, 5064,))
+        calldA.start()
+
+
+        # launch the sipp instance waiting for call as the second particpant
+        self.initialize_sipp_call_instance(self.sippCallInstanceB)
+        calldB = multiprocessing.Process(name='sipp2call', target=self.launchSippProcess,
+                                                               args=(self.sippCallInstanceB, 5066,))
+        calldB.start()
+
+        # make sure every account are enabled
+        accList = [x for x in self.getAllAccounts() if x != "IP2IP"]
+        for acc in accList:
+            if not self.isAccountRegistered(acc):
+                self.setAccountEnable(acc, True)
+
+        # make a call to the SIPP instance
+        self.Call("300")
+        self.Call("400")
+
+        # start the main loop for processing glib callbacks
+        self.start()
+
+        print "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-"
+        calldA.join()
+        print "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+"
+        calldB.join()
+
+        print "====================================================="
+
+        self.stopThread()
+        self.parse_results()
+
+
+# callInstance = TestSFLPhoneRegisteredCalls()
+# callInstance.test_registered_call()
+
+confInstance = TestSFLPhoneConferenceCalls()
+confInstance.test_conference_call()
diff --git a/tools/sippxml/uac_register_no_cvs_300.xml b/tools/sippxml/uac_register_no_cvs_300.xml
new file mode 100644
index 0000000000000000000000000000000000000000..f22ae377a8df43ddbcd8800e4d1f57d49765d306
--- /dev/null
+++ b/tools/sippxml/uac_register_no_cvs_300.xml
@@ -0,0 +1,110 @@
+<?xml version="1.0" encoding="ISO-8859-2" ?>
+
+<!--  Use with CSV file struct like: 3000;192.168.1.106;[authentication username=3000 password=3000];
+      (user part of uri, server address, auth tag in each line)
+-->
+
+<scenario name="register_client">
+  <send retrans="500">
+    <![CDATA[
+
+      REGISTER sip:127.0.0.1 SIP/2.0
+      Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
+      From: <sip:300@127.0.0.1>;tag=[call_number]
+      To: <sip:300@127.0.0.1>
+      Call-ID: [call_id]
+      CSeq: [cseq] REGISTER
+      Contact: sip:300@[local_ip]:[local_port]
+      Max-Forwards: 10
+      Expires: 120
+      User-Agent: SIPp/Win32
+      Content-Length: 0
+
+    ]]>
+  </send>
+
+  <!-- asterisk -->
+  <recv response="200">
+  <!--
+    <action>
+      <ereg regexp=".*" search_in="hdr" header="Contact:" check_it="true" assign_to="1" />
+    </action>
+  -->
+  </recv>
+
+  <!--
+  <recv request="INVITE" crlf="true">
+  </recv>
+
+  <send>
+    <![CDATA[
+
+      SIP/2.0 180 Ringing
+      [last_Via:]
+      [last_From:]
+      [last_To:];tag=[pid]SIPpTag01[call_number]
+      [last_Call-ID:]
+      [last_CSeq:]
+      Contact: <sip:[local_ip]:[local_port];transport=[transport]>
+      Content-Length: 0
+
+    ]]>
+  </send>
+
+  <send retrans="500">
+    <![CDATA[
+
+      SIP/2.0 200 OK
+      [last_Via:]
+      [last_From:]
+      [last_To:];tag=[pid]SIPpTag01[call_number]
+      [last_Call-ID:]
+      [last_CSeq:]
+      Contact: <sip:[local_ip]:[local_port];transport=[transport]>
+      Content-Type: application/sdp
+      Content-Length: [len]
+
+      v=0
+      o=user1 53655765 2353687637 IN IP[local_ip_type] [local_ip]
+      s=-
+      c=IN IP[media_ip_type] [media_ip]
+      t=0 0
+      m=audio [media_port] RTP/AVP 0
+      a=rtpmap:0 PCMU/8000
+
+    ]]>
+  </send>
+
+  <recv request="ACK"
+        optional="true"
+        rtd="true"
+        crlf="true">
+  </recv>
+
+  <recv request="BYE">
+  </recv>
+
+  <send>
+    <![CDATA[
+
+      SIP/2.0 200 OK
+      [last_Via:]
+      [last_From:]
+      [last_To:]
+      [last_Call-ID:]
+      [last_CSeq:]
+      Contact: <sip:[local_ip]:[local_port];transport=[transport]>
+      Content-Length: 0
+
+    ]]>
+  </send>
+
+  <timewait milliseconds="4000"/>
+
+
+  <ResponseTimeRepartition value="10, 20, 30, 40, 50, 100, 150, 200"/>
+
+  <CallLengthRepartition value="10, 50, 100, 500, 1000, 5000, 10000"/>
+  -->
+
+</scenario>
diff --git a/tools/sippxml/uac_register_no_cvs_400.xml b/tools/sippxml/uac_register_no_cvs_400.xml
new file mode 100644
index 0000000000000000000000000000000000000000..ccceacdf7748bbe490cfe306222724e4dfe93c99
--- /dev/null
+++ b/tools/sippxml/uac_register_no_cvs_400.xml
@@ -0,0 +1,110 @@
+<?xml version="1.0" encoding="ISO-8859-2" ?>
+
+<!--  Use with CSV file struct like: 3000;192.168.1.106;[authentication username=3000 password=3000];
+      (user part of uri, server address, auth tag in each line)
+-->
+
+<scenario name="register_client">
+  <send retrans="500">
+    <![CDATA[
+
+      REGISTER sip:127.0.0.1 SIP/2.0
+      Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
+      From: <sip:300@127.0.0.1>;tag=[call_number]
+      To: <sip:400@127.0.0.1>
+      Call-ID: [call_id]
+      CSeq: [cseq] REGISTER
+      Contact: sip:300@[local_ip]:[local_port]
+      Max-Forwards: 10
+      Expires: 120
+      User-Agent: SIPp/Win32
+      Content-Length: 0
+
+    ]]>
+  </send>
+
+  <!-- asterisk -->
+  <recv response="200">
+  <!--
+    <action>
+      <ereg regexp=".*" search_in="hdr" header="Contact:" check_it="true" assign_to="1" />
+    </action>
+  -->
+  </recv>
+
+  <!--
+  <recv request="INVITE" crlf="true">
+  </recv>
+
+  <send>
+    <![CDATA[
+
+      SIP/2.0 180 Ringing
+      [last_Via:]
+      [last_From:]
+      [last_To:];tag=[pid]SIPpTag01[call_number]
+      [last_Call-ID:]
+      [last_CSeq:]
+      Contact: <sip:[local_ip]:[local_port];transport=[transport]>
+      Content-Length: 0
+
+    ]]>
+  </send>
+
+  <send retrans="500">
+    <![CDATA[
+
+      SIP/2.0 200 OK
+      [last_Via:]
+      [last_From:]
+      [last_To:];tag=[pid]SIPpTag01[call_number]
+      [last_Call-ID:]
+      [last_CSeq:]
+      Contact: <sip:[local_ip]:[local_port];transport=[transport]>
+      Content-Type: application/sdp
+      Content-Length: [len]
+
+      v=0
+      o=user1 53655765 2353687637 IN IP[local_ip_type] [local_ip]
+      s=-
+      c=IN IP[media_ip_type] [media_ip]
+      t=0 0
+      m=audio [media_port] RTP/AVP 0
+      a=rtpmap:0 PCMU/8000
+
+    ]]>
+  </send>
+
+  <recv request="ACK"
+        optional="true"
+        rtd="true"
+        crlf="true">
+  </recv>
+
+  <recv request="BYE">
+  </recv>
+
+  <send>
+    <![CDATA[
+
+      SIP/2.0 200 OK
+      [last_Via:]
+      [last_From:]
+      [last_To:]
+      [last_Call-ID:]
+      [last_CSeq:]
+      Contact: <sip:[local_ip]:[local_port];transport=[transport]>
+      Content-Length: 0
+
+    ]]>
+  </send>
+
+  <timewait milliseconds="4000"/>
+
+
+  <ResponseTimeRepartition value="10, 20, 30, 40, 50, 100, 150, 200"/>
+
+  <CallLengthRepartition value="10, 50, 100, 500, 1000, 5000, 10000"/>
+  -->
+
+</scenario>